Install.php 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128
  1. <?php
  2. Lib::loadClass('RouteBase');
  3. Lib::loadClass('UI');
  4. //TODO install nie kopiuje aktualnej /config/.config_base_structure.php @2017-09-24 bindera - sprawdzone na medicalu
  5. class Route_Install extends RouteBase {
  6. public function __construct() {
  7. $this->sshArgsSkipHostKey = ' -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no ';
  8. }
  9. public function handleAuth() {
  10. if (!User::logged()) {
  11. throw new HttpException('Unauthorized', 401);
  12. }
  13. if (!User::isAdmin()) {
  14. throw new HttpException('Unauthorized - only for administrators', 401);
  15. }
  16. }
  17. public function defaultAction() {
  18. UI::gora();
  19. UI::menu();
  20. $this->menu();
  21. UI::setTitleJsTag("Install");
  22. UI::dol();
  23. }
  24. public function menu() {
  25. $serversList = $this->fetchActiveLicences();
  26. ?>
  27. <div class="jumbotron">
  28. <div class="container">
  29. <form class="form-inline" method="GET">
  30. <input type="hidden" name="_route" value="Install" />
  31. <input type="hidden" name="_task" value="createApp" />
  32. <label>Przygotuj kod źródłowy do aktualizacji na serwerze klienta:</label>
  33. <select id="servers_list" class="form-control" name="licence_id">
  34. <?php foreach ($serversList as $srv) : ?>
  35. <option value="<?php echo $srv->ID; ?>">[<?php echo $srv->ID; ?>] <?php echo $srv->domain; ?></option>
  36. <?php endforeach; ?>
  37. </select>
  38. <button type="submit" id="fldSbmtBtn" class="btn btn-primary" autocomplete="off">
  39. Generuj
  40. </button>
  41. <div id="servers_list_react"></div>
  42. </form>
  43. </div>
  44. </div>
  45. <script type="text/javascript">
  46. jQuery(document).ready(function () {
  47. jQuery('#fldSbmtBtn').on('click', function () {
  48. jQuery(this).text(jQuery(this).text() + '...').attr('disabled', 'disabled');
  49. jQuery(this).parent().submit();
  50. })
  51. });
  52. </script>
  53. <?php
  54. echo UI::h('script', ['src'=>"static/vendor.js", 'type'=>"text/javascript"]);
  55. // echo UI::h('script', ['src'=>"https://cdnjs.cloudflare.com/ajax/libs/react/15.4.2/react.js", 'type'=>"text/javascript"]);
  56. // echo UI::h('script', ['src'=>"https://cdnjs.cloudflare.com/ajax/libs/react/15.4.2/react-dom.js", 'type'=>"text/javascript"]);
  57. // echo UI::h('script', ['src'=>"https://cdnjs.cloudflare.com/ajax/libs/react-bootstrap-typeahead/0.10.4/react-bootstrap-typeahead.js", 'type'=>"text/javascript"]);
  58. $jsonServersList = array_values(array_map(
  59. function ($srv) {
  60. return [
  61. 'id' => $srv->ID,
  62. 'label' => "{$srv->domain} [{$srv->ID}]"
  63. ];
  64. },
  65. $serversList
  66. ));
  67. echo UI::h('script', ['type'=>"text/javascript"], "
  68. (function(global){
  69. if (!global.p5VendorJs) { console.warn('Brak p5VendorJs'); return; }
  70. if (!global.p5VendorJs.React) { console.warn('Brak p5VendorJs.React'); return; }
  71. if (!global.p5VendorJs.ReactDOM) { console.warn('Brak p5VendorJs.ReactDOM'); return; }
  72. if (!global.p5VendorJs.Typeahead) { console.warn('Brak p5VendorJs.Typeahead'); return; }
  73. const React = global.p5VendorJs.React;
  74. const ReactDOM = global.p5VendorJs.ReactDOM;
  75. const Typeahead = global.p5VendorJs.Typeahead;
  76. var options = ".json_encode($jsonServersList).";
  77. var selected = [];
  78. var onInputChange = function (query) {
  79. // console.log('onInputChange:: query', query);
  80. }
  81. var onChange = function (value) {
  82. // console.log('onChange:: value', value);
  83. if (value.length > 0) {
  84. var id = value[0]['id'];
  85. if (id > 0) {
  86. document.getElementById('servers_list').value = id;
  87. }
  88. }
  89. }
  90. ReactDOM.render(
  91. React.createElement(Typeahead, {
  92. options: options,
  93. emptyLabel: 'Brak danych',
  94. placeholder: 'Wybierz serwer',
  95. selected: selected,
  96. // onInputChange: onInputChange,
  97. onChange: onChange,
  98. }, null),
  99. document.getElementById('servers_list_react')
  100. );
  101. })(window);
  102. ");
  103. }
  104. public function createAppAction() {
  105. session_write_close();
  106. $args = array();
  107. $args['licence_id'] = V::get('licence_id', 0, $_REQUEST, 'int');
  108. UI::gora();
  109. UI::menu();
  110. UI::setTitleJsTag("Install");
  111. //$this->menu($args['licence_id']);// TODO: GO BACK BTN
  112. try {
  113. $appLicenceInfo = $this->getAppLicenceInfo($args['licence_id']);
  114. $this->validateAppLicenceInfo($appLicenceInfo);
  115. } catch (Exception $e) {
  116. $this->_endWithException($e);
  117. }
  118. // $this->generateApp($appLicenceInfo->installPath, $appLicenceInfo->domains);
  119. //DBG::_(true, true, "appLicenceInfo", $appLicenceInfo, __CLASS__, __FUNCTION__, __LINE__);
  120. if ('_generateEncryptedSource' === V::get('_postTask', '', $_POST)) {
  121. echo '<div class="container">';
  122. echo '<h4>' . "Generowanie..." . '</h4>';
  123. echo '<div style="border:1px solid silver; max-height:400px; overflow-y:scroll">';
  124. try {
  125. $this->validateAppLicenceInfo($appLicenceInfo);
  126. $this->generateApp($appLicenceInfo->installPath, $appLicenceInfo->domains);
  127. // TODO: $this->configGenerate(...);
  128. } catch (Exception $e) {
  129. echo '</div></div>';// .container/ scroll
  130. $this->_endWithException($e);
  131. }
  132. echo '</div>';// .container
  133. UI::alert('success', "<strong>Gotowe</strong> Aplikacja znajduje się w katalogu {$appLicenceInfo->installFolderName}");
  134. $appLicenceInfo = $this->getAppLicenceInfo($args['licence_id']);
  135. }
  136. if ('newGenerateApp' === V::get('_postTask', '', $_POST)) {
  137. $this->newGenerateApp($appLicenceInfo);
  138. }
  139. if ('updateAndSendToRemoteTestDir' === V::get('_postTask', '', $_POST)) {
  140. echo '<details><summary style="cursor:pointer">aktualizuj werjsę, szyfruj i wyślij do testowego katalogu na serwerze</summary>';
  141. try {
  142. $idLicence = V::get('licence_id', 0, $_POST, 'int');
  143. $appLicenceInfo = $this->getAppLicenceInfo($idLicence);
  144. $this->validateAppLicenceInfo($appLicenceInfo);
  145. $this->gitResetHard($appLicenceInfo->installPath, $appLicenceInfo->projects);
  146. flush();
  147. $this->_encodeSource($appLicenceInfo->installPath, $appLicenceInfo->domains);
  148. flush();
  149. $this->_sendToRemoteTestDir($appLicenceInfo);
  150. } catch (Exception $e) {
  151. DBG::log($e);
  152. UI::alert('danger', $e->getMessage());
  153. }
  154. echo '</details>';
  155. $testDirUrl = "https://{$appLicenceInfo->mainServer}/se.encrypted.upgrade/";
  156. UI::alert('info', UI::h('p', [], [
  157. "testowy katalog zaktualizowany - ",
  158. UI::h('a', [ 'href' => $testDirUrl, 'target' => "_blank" ], $testDirUrl),
  159. ]));
  160. flush();
  161. }
  162. // echo UI::hButtonPost("TODO: Generuj z p5.git", [
  163. // 'class' => "btn btn-md btn-primary",
  164. // 'data' => [
  165. // '_postTask' => "newGenerateApp",
  166. // 'licence_id' => $appLicenceInfo->ID,
  167. // ],
  168. // ]);
  169. echo UI::h('div', [ 'class' => "jumbotron" ], [
  170. UI::h('div', [ 'class' => "container" ], [
  171. UI::h('h3', [], "Generowanie aplikacji dla licencji {$appLicenceInfo->ID}"),
  172. UI::h('p', [], "Licencja dla domen: " . implode(', ', $appLicenceInfo->domains)),
  173. UI::h('p', [], "Katalog z zakodowanymi plikami: {$appLicenceInfo->installFolderName}"),
  174. UI::hButtonPost("Generuj", [
  175. 'class' => "btn btn-primary",
  176. 'data' => [
  177. '_postTask' => '_generateEncryptedSource',
  178. 'licence_id' => $appLicenceInfo->ID,
  179. ]
  180. ]),
  181. (!$appLicenceInfo->installFolderGitExists)
  182. ? UI::h('div', [ 'class' => "alert alert-info" ], "Katalog nie istnieje - wygeneruj aplikację")
  183. : UI::h('div', [ 'class' => "alert alert-info", 'style' => "margin-top:10px" ], [
  184. UI::h('p', [], "Katalog istnieje i zawiera już repozytorium git: "),
  185. UI::h('p', [], [
  186. UI::hButtonPost("aktualizuj werjsę, szyfruj i wyślij do testowego katalogu na serwerze", [
  187. 'class' => "btn btn-xs btn-primary",
  188. 'data' => [
  189. '_postTask' => "updateAndSendToRemoteTestDir",
  190. 'licence_id' => $appLicenceInfo->ID,
  191. ],
  192. ]),
  193. ]),
  194. UI::h('p', [ 'style' => "margin-left:20px" ], [
  195. UI::h('a', [
  196. 'href' => "index.php?_route=Install&_task=gitResetHard&licence_id={$appLicenceInfo->ID}",
  197. 'target' => "_blank",
  198. 'class' => "btn btn-xs btn-default"
  199. ], "aktualizuj werjsę"),
  200. " (git reset --hard, git pull, set SE/VERSION - tak samo co 'rm -rf; git clone', ale szybciej)",
  201. ]),
  202. UI::h('p', [ 'style' => "margin-left:20px" ], [
  203. UI::h('a', [
  204. 'href' => "index.php?_route=Install&_task=configGenerate&licence_id={$appLicenceInfo->ID}",
  205. 'target' => "_blank",
  206. 'class' => "btn btn-xs btn-default"
  207. ], "generuj pliki konfiguracyjne"),
  208. ]),
  209. UI::h('p', [ 'style' => "margin-left:20px" ], [
  210. UI::h('a', [
  211. 'href' => "index.php?_route=Install&_task=encodeSource&licence_id={$appLicenceInfo->ID}",
  212. 'target' => "_blank",
  213. 'class' => "btn btn-xs btn-default"
  214. ], "encode files"),
  215. ]),
  216. UI::h('p', [ 'style' => "margin-left:20px" ], [
  217. UI::h('a', [
  218. 'href' => "index.php?_route=Install&_task=sendToRemoteTestDir&licence_id={$appLicenceInfo->ID}",
  219. 'target' => "_blank",
  220. 'class' => "btn btn-xs btn-default"
  221. ], "send encoded files to remote server test folder (generates ssh key if not set)"),
  222. ]),
  223. UI::h('p', [ 'style' => "margin-left:20px" ], [
  224. UI::h('a', [
  225. 'href' => "index.php?_route=Install&_task=generateUpgradeScript&licence_id={$appLicenceInfo->ID}",
  226. 'target' => "_blank",
  227. 'class' => "btn btn-xs btn-warning"
  228. ], "generuj skrypt aktualizacji"),
  229. ]),
  230. UI::h('p', [ 'style' => "margin-top:30px" ], [
  231. "Test online: ",
  232. UI::h('a', [
  233. 'target' => "_blank",
  234. 'href' => "https://{$appLicenceInfo->mainServer}/se.encrypted.upgrade/"
  235. ], "https://{$appLicenceInfo->mainServer}/se.encrypted.upgrade/"),
  236. ]),
  237. "<br> - ",
  238. UI::h('a', [
  239. 'href' => "index.php?_route=Install&_task=upgradeRemoteFromTestDir&licence_id={$appLicenceInfo->ID}",
  240. 'onclick' => "return confirm('Uruchomić aktualizację SE na https://{$appLicenceInfo->mainServer}/SE/?')",
  241. 'target' => "_blank",
  242. 'class' => "btn btn-xs btn-warning"
  243. ], "UPGRADE Production folder from uploaded dir: ~/se.encrypted.upgrade/"),
  244. ]),
  245. ]),
  246. ]);
  247. ?>
  248. <script type="text/javascript">
  249. jQuery(document).ready(function () {
  250. jQuery('#fldSbmtBtn').on('click', function () {
  251. jQuery(this).text(jQuery(this).text() + '...').attr('disabled', 'disabled');
  252. jQuery(this).parent().submit();
  253. })
  254. });
  255. </script>
  256. <?php
  257. UI::dol();
  258. }
  259. public function generateUpgradeScriptAction() {
  260. session_write_close();
  261. $args = array();
  262. $args['licence_id'] = V::get('licence_id', 0, $_REQUEST, 'int');
  263. UI::gora();
  264. UI::menu();
  265. //$this->menu($args['licence_id']);// TODO: GO BACK BTN
  266. try {
  267. $appLicenceInfo = $this->getAppLicenceInfo($args['licence_id']);
  268. $this->validateAppLicenceInfo($appLicenceInfo);
  269. UI::startContainer();
  270. $this->generateUpgradeScript($appLicenceInfo);
  271. UI::endContainer();
  272. } catch (Exception $e) {
  273. $this->_endWithException($e);
  274. }
  275. UI::dol();
  276. }
  277. public function generateUpgradeScript($appLicenceInfo) {
  278. $cmds = [];
  279. //
  280. $cmds[] = "# TODO: commands from remote upgrade";
  281. $cmds[] = "# cp -r {UPDATE_ZIP_PATH_SE} {public_html}/se.encrypted.upgrade";
  282. $cmds[] = "# rm -rf {public_html}/se.encrypted.upgrade";
  283. // '[ ! -d ~/se.encrypted.upgrade ] && mkdir ~/se.encrypted.upgrade || echo 1';
  284. // 'rm -rf ~/se.encrypted.upgrade/SE';
  285. // 'cp -r /Library/Server/Web/Data/Sites/Default/SE ~/se.encrypted.upgrade/SE';
  286. // 'rm -rf ~/se.encrypted.upgrade/SE/config';
  287. // rsync --archive --times --delete --compress --one-file-system --omit-dir-times --no-g --no-perms {$dryRunOnly} \
  288. // --verbose {$rsyncSshPort} \
  289. // --exclude='schema/default_db.instance.xml' \
  290. // --exclude='schema/default_db.instance.xml/**' \
  291. // '{$appLicenceInfo->installPath}/SE/' {$sshHostUsr}:~/se.encrypted.upgrade/SE/;
  292. // 'cp -r /Library/Server/Web/Data/Sites/Default/SE/config ~/se.encrypted.upgrade/SE/';
  293. // 'rm /Library/Server/Web/Data/Sites/Default/se.encrypted.upgrade'
  294. // 'ln -s ~/se.encrypted.upgrade/SE /Library/Server/Web/Data/Sites/Default/se.encrypted.upgrade'
  295. // scp {$this->sshArgsSkipHostKey} {$scpArgs} /Library/Server/Web/Data/Sites/SE-production-git/SE/config/.config_base_structure.php {$sshHostUsr}:
  296. // 'mv ~/.config_base_structure.php /Library/Server/Web/Data/Sites/Default/se.encrypted.upgrade/config'
  297. // config
  298. // $cmds[] = "TODO cp -r from {SE}/config";
  299. $cmds[] = "rm ~/se.encrypted.upgrade/.*.inc.php";
  300. $cmds[] = "cp -r {UPDATE_ZIP_PATH_SE}/.*.inc.php ~/se.encrypted.upgrade/";
  301. // $domainList = INSTALL_SES_PROCESY_A::fetch_same_domains_for_install($SERVER_ADDRESS_SHORT, $SERVER_ADDRESS);// [ $SERVER_ADDRESS, localhost, 127.0.0.1, ... ]
  302. DBG::nicePrint($appLicenceInfo, '$appLicenceInfo');
  303. $mainDomain = $appLicenceInfo->mainServer;
  304. $additionalDomains = array_filter($appLicenceInfo->domains, function ($domain) use ($mainDomain) {
  305. return ($mainDomain != $domain);
  306. });
  307. foreach ($additionalDomains as $domain) {
  308. if ('localhost' == $domain) continue;// skip localhost (127.0.0.1)
  309. $cmds[] = ' test -f /Library/Server/Web/Data/Sites/Default/SE/config/.cnf--default_db-'.$domain.'.ini.php || ln -s /Library/Server/Web/Data/Sites/Default/SE/config/.cnf--default_db-'.$mainDomain.'.inc.php /Library/Server/Web/Data/Sites/Default/SE/config/.cnf--default_db-'.$domain.'.inc.php';
  310. $cmds[] = ' test -f /Library/Server/Web/Data/Sites/Default/SE/config/.cnf--zasob_2-'.$domain.'.inc.php || ln -s /Library/Server/Web/Data/Sites/Default/SE/config/.cnf--zasob_2-'.$mainDomain.'.inc.php /Library/Server/Web/Data/Sites/Default/SE/config/.cnf--zasob_2-'.$domain.'.inc.php';
  311. // $cmds[] = ' test -f /Library/Server/Web/Data/Sites/Default/SE/config/.cnf--import_db-'.$domain.'.inc.php || ln -s /Library/Server/Web/Data/Sites/Default/SE/config/.cnf--import_db-'.$mainDomain.'.inc.php /Library/Server/Web/Data/Sites/Default/SE/config/.cnf--import_db-'.$domain.'.inc.php';
  312. $cmds[] = ' test -f /Library/Server/Web/Data/Sites/Default/SE/config/.cnf--folders-'.$domain.'.inc.php || ln -s /Library/Server/Web/Data/Sites/Default/SE/config/.cnf--folders-'.$mainDomain.'.inc.php /Library/Server/Web/Data/Sites/Default/SE/config/.cnf--folders-'.$domain.'.inc.php';
  313. $cmds[] = ' test -f /Library/Server/Web/Data/Sites/Default/SE/config/.cnf--default_ldap-'.$domain.'.inc.php || ln -s /Library/Server/Web/Data/Sites/Default/SE/config/.cnf--default_ldap-'.$mainDomain.'.inc.php /Library/Server/Web/Data/Sites/Default/SE/config/.cnf--default_ldap-'.$domain.'.inc.php';
  314. }
  315. DBG::nicePrint($cmds, "\$cmds");
  316. }
  317. public function configGenerateAction() {
  318. session_write_close();
  319. $args = array();
  320. $args['licence_id'] = V::get('licence_id', 0, $_REQUEST, 'int');
  321. UI::gora();
  322. UI::menu();
  323. //$this->menu($args['licence_id']);// TODO: GO BACK BTN
  324. try {
  325. $appLicenceInfo = $this->getAppLicenceInfo($args['licence_id']);
  326. $this->validateAppLicenceInfo($appLicenceInfo);
  327. UI::startContainer();
  328. $this->configGenerate($appLicenceInfo->configPath, $appLicenceInfo->mainServer, $appLicenceInfo->domains, $appLicenceInfo->rootPassword
  329. , $appLicenceInfo->ldapUser, $appLicenceInfo->ldapPass, $appLicenceInfo->ldapBaseDN
  330. );
  331. UI::endContainer();
  332. } catch (Exception $e) {
  333. $this->_endWithException($e);
  334. }
  335. UI::dol();
  336. }
  337. public function configGenerate($configPath, $mainServer, $domains, $rootPassword, $ldapUser, $ldapPass, $ldapBaseDN) {
  338. if (empty($configPath)) throw new Exception("Install path not found");
  339. $cmds = array();
  340. $cmds[] = "if [ -d {$configPath} ] ; then rm -rf '{$configPath}'; fi";
  341. $cmds[] = "mkdir {$configPath}";
  342. $REMOTE_FOLDER_ROOT = str_replace([ ".", "-" ], '_', $mainServer);
  343. $cmds[] = ' echo "' . V::quoteBashEcho(
  344. Config::generateDefaultDbConfigFile(
  345. [
  346. 'database' => $REMOTE_FOLDER_ROOT,
  347. 'password' => $rootPassword,
  348. ],
  349. $outputFormat = 'inc'
  350. )
  351. ) . '" > ' . $configPath . '/.cnf--default_db-' . $mainServer . '.inc.php';
  352. $cmds[] = ' echo "' . V::quoteBashEcho(
  353. Config::generateDefaultDbConfigFile(
  354. [
  355. 'database' => $REMOTE_FOLDER_ROOT,
  356. 'password' => $rootPassword,
  357. ],
  358. $outputFormat = 'inc'
  359. )
  360. ) . '" > ' . $configPath . '/.cnf--zasob_2-' . $mainServer . '.inc.php';
  361. $cmds[] = ' echo "' . V::quoteBashEcho(
  362. Config::generateDefaultLdapConfigFile(
  363. [
  364. 'user' => $ldapUser,
  365. 'pass' => $ldapPass,
  366. 'base_dn' => $ldapBaseDN,
  367. ],
  368. $outputFormat = 'inc'
  369. )
  370. ) . '" > ' . $configPath . '/.cnf--default_ldap-' . $mainServer . '.inc.php';
  371. $cmds[] = ' echo "' . V::quoteBashEcho(
  372. Config::generateDefaultFoldersConfigFile(
  373. [
  374. 'remote_folder_root' => str_replace([ '.', '-' ], '_', $mainServer),
  375. 'server_address' => $mainServer,
  376. ],
  377. $outputFormat = 'ini'
  378. )
  379. ) . '" > ' . $configPath . '/.cnf--folders-' . $mainServer . '.ini.php';
  380. $additionalDomains = array_filter($domains, function ($domain) use ($mainServer) {
  381. return ($mainServer != $domain);
  382. });
  383. foreach ($additionalDomains as $domain) {
  384. if ('localhost' == $domain) continue;// skip localhost (127.0.0.1)
  385. $cmds[] = "cd {$configPath} && ln -s .cnf--default_db-{$mainServer}.inc.php .cnf--default_db-{$domain}.inc.php";
  386. $cmds[] = "cd {$configPath} && ln -s .cnf--zasob_2-{$mainServer}.inc.php .cnf--zasob_2-{$domain}.inc.php";
  387. // $cmds[] = "cd {$configPath} && ln -s .cnf--import_db-{$mainServer}.inc.php .cnf--import_db-{$domain}.inc.php";
  388. $cmds[] = "cd {$configPath} && ln -s .cnf--default_ldap-{$mainServer}.inc.php .cnf--default_ldap-{$domain}.inc.php";
  389. switch ($domain) {
  390. case '127.0.0.1': // alias for mainServer
  391. case "{$mainServer}.procesy5.pl": // alias for mainServer
  392. {
  393. $cmds[] = ' echo "' . V::quoteBashEcho(
  394. Config::generateDefaultFoldersConfigFile(
  395. [
  396. 'remote_folder_root' => str_replace([ '.', '-' ], '_', $mainServer),
  397. 'server_address' => $domain,
  398. ],
  399. $outputFormat = 'ini'
  400. )
  401. ) . '" > ' . $configPath . '/.cnf--folders-' . $domain . '.ini.php';
  402. } break;
  403. default:
  404. $cmds[] = ' echo "' . V::quoteBashEcho(
  405. Config::generateDefaultFoldersConfigFile(
  406. [
  407. 'remote_folder_root' => str_replace([ '.', '-' ], '_', $domain),
  408. 'server_address' => $domain,
  409. ],
  410. $outputFormat = 'ini'
  411. )
  412. ) . '" > ' . $configPath . '/.cnf--folders-' . $domain . '.ini.php';
  413. }
  414. }
  415. $hasError = false;
  416. foreach ($cmds as $cmd) {
  417. V::exec($cmd, $out, $ret);
  418. if (0 !== $ret) $hasError = true;
  419. DBG::nicePrint(array_merge([ "CMD: {$cmd}", "OUTPUT:" ], $out), "cmd: `" . htmlspecialchars(V::strShort($cmd, 20)) . "` (return:{$ret})");
  420. }
  421. if (!$hasError) {
  422. UI::alert('success', "OK");
  423. } else {
  424. UI::alert('danger', "errors");
  425. }
  426. }
  427. public function gitResetHardAction() {
  428. session_write_close();
  429. $args = array();
  430. $args['licence_id'] = V::get('licence_id', 0, $_REQUEST, 'int');
  431. UI::gora();
  432. UI::menu();
  433. //$this->menu($args['licence_id']);// TODO: GO BACK BTN
  434. try {
  435. $appLicenceInfo = $this->getAppLicenceInfo($args['licence_id']);
  436. $this->validateAppLicenceInfo($appLicenceInfo);
  437. UI::startContainer();
  438. $this->gitResetHard($appLicenceInfo->installPath, $appLicenceInfo->projects);
  439. UI::endContainer();
  440. } catch (Exception $e) {
  441. $this->_endWithException($e);
  442. }
  443. UI::dol();
  444. }
  445. public function gitResetHard($installPath, $projects = []) {
  446. if (empty($installPath)) throw new Exception("Install path not found");
  447. $cmds = array();
  448. $cmds[] = "git reset --hard";
  449. $cmds[] = "git pull";
  450. $cmds[] = "echo `git show-ref --head|head -1|head -c 8` > SE/VERSION ";
  451. $hasError = false;
  452. foreach ($cmds as $cmd) {
  453. V::exec("cd {$installPath} && {$cmd}", $out, $ret);
  454. if (0 !== $ret) $hasError = true;
  455. DBG::nicePrint($out, "cmd: `{$cmd}` (return:{$ret})");
  456. }
  457. foreach ($projects as $projectName) {
  458. $cmd = "ls -l SE/projects/{$projectName} | wc -l";
  459. V::exec("cd {$installPath} && {$cmd}", $out, $ret);
  460. DBG::nicePrint([ 'cmd' => $cmd, 'output' => $out ], "return: {$ret}");
  461. if (!empty($out) && '0' !== trim($out[0])) {
  462. // $cmd = "git submodule update SE/projects/{$projectName}";
  463. $cmd = "cd SE/projects/{$projectName} && git reset --hard"; // revert encode source - checkout to last commit (need update)
  464. V::exec("cd {$installPath} && {$cmd}", $out, $ret);
  465. DBG::nicePrint([ 'cmd' => $cmd, 'output' => $out ], "return: {$ret}");
  466. }
  467. $cmd = "git submodule update --init SE/projects/{$projectName}"; // checkout to current commit
  468. V::exec("cd {$installPath} && {$cmd}", $out, $ret);
  469. DBG::nicePrint([ 'cmd' => $cmd, 'output' => $out ], "return: {$ret}");
  470. }
  471. if (!$hasError) {
  472. UI::alert('success', "OK");
  473. } else {
  474. UI::alert('danger', "errors");
  475. }
  476. }
  477. public function encodeSourceAction() {
  478. session_write_close();
  479. $args = array();
  480. $args['licence_id'] = V::get('licence_id', 0, $_REQUEST, 'int');
  481. UI::gora();
  482. UI::menu();
  483. //$this->menu($args['licence_id']);// TODO: GO BACK BTN
  484. try {
  485. $appLicenceInfo = $this->getAppLicenceInfo($args['licence_id']);
  486. $this->validateAppLicenceInfo($appLicenceInfo);
  487. $this->_encodeSource($appLicenceInfo->installPath, $appLicenceInfo->domains);
  488. $this->_encodeConfigs($appLicenceInfo->configPath);
  489. } catch (Exception $e) {
  490. $this->_endWithException($e);
  491. }
  492. UI::dol();
  493. }
  494. public function _encodeSource($installPath, $domains) {
  495. UI::startContainer();
  496. $this->encodeSourceFiles($installPath, $domains, $dbg = true);
  497. // try {
  498. // $this->encodeSourceFiles($appLicenceInfo->installPath, $appLicenceInfo->domains, $dbg = false);
  499. // UI::alert('success', "OK");
  500. // } catch (Exception $e) {
  501. // UI::alert('danger', $e->getMessage());
  502. // }
  503. UI::endContainer();
  504. }
  505. // @usage: Router::getRoute('Install')->encodeSourceFiles($installPath = '/path_to_git_repo', $domains = [ 'domain.com', 'localhost' ], $dbg = false);
  506. public function encodeSourceFiles($installPath, $domains, $dbg = false) {
  507. if (empty($installPath)) throw new Exception("Install path not found");
  508. if (empty($domains)) throw new Exception("Domains not found");
  509. $phpVersionsForSgencoder = '--phpversion 5.5 --phpversion 5.6';// encode for PHP 5.x (currently supported PHP 5.0-5.6)
  510. if ('1' == V::get('DBG_ENCODER_HELP', '', $_REQUEST)) {// encoder help
  511. $cmd = "cd {$installPath}/SE && /Applications/SourceGuardian.app/Contents/MacOS/sgencoder --help ";
  512. $out = ''; $ret = '';
  513. V::exec($cmd, $out, $ret);
  514. DBG::nicePrint($out, "cmd: `{$cmd}` (return:{$ret})");
  515. exit;
  516. }
  517. $domainEncodePhpFiles = [
  518. 'ant.php',
  519. 'api.php',
  520. 'budynki.php',
  521. 'index-ajax.php',
  522. 'index.php',
  523. 'procesy5.php',
  524. 'session-expire.php',
  525. 'test-sync.php',
  526. 'wfs-data.php',
  527. 'wfs-qgis.php',
  528. 'wfs.php',
  529. ];
  530. $cmd = "find . -name '*.php' ";
  531. $out = ''; $ret = '';
  532. V::exec("cd {$installPath}/SE && {$cmd}", $out, $ret);
  533. if ($dbg) DBG::nicePrint($out, "cmd: `{$cmd}` (return:{$ret})");
  534. else DBG::log($out, 'array', "cmd: `{$cmd}` (return:{$ret})");
  535. if (0 !== $ret) throw new Exception("Error at find php files");
  536. if (empty($out)) throw new Exception("No php files found");
  537. $allPhpFiles = array_map(function ($phpFilePath) {
  538. return ('./' == substr($phpFilePath, 0, 2))? substr($phpFilePath, 2) : $phpFilePath;
  539. }, $out);
  540. $freeEncodePhpFiles = array_filter($allPhpFiles, function ($phpFilePath) use ($domainEncodePhpFiles) {
  541. if ('se-lib/Vendor/' === substr($phpFilePath, 0, strlen('se-lib/Vendor/'))) return false; // SKIP se-lib/Vendor/*
  542. if ('.ini.php' === substr($phpFilePath, -1 * strlen('.ini.php'))) return false; // SKIP *.ini.php
  543. return (!in_array($phpFilePath, $domainEncodePhpFiles));
  544. });
  545. DBG::log($freeEncodePhpFiles, 'array', "\$freeEncodePhpFiles");
  546. if (empty($freeEncodePhpFiles)) throw new Exception("No php files to encode");
  547. $cmdTempl = "cd {$installPath}/SE && /Applications/SourceGuardian.app/Contents/MacOS/sgencoder {$phpVersionsForSgencoder} -b- ";
  548. $cmdDomainEncodeDomainsTempl = " --domain " . implode(" --domain ", $domains);
  549. $cmdDomainEncodeFilesTempl = " " . implode(" ", $domainEncodePhpFiles);
  550. $cmdFreeEncodeFilesTempl = " " . implode(" ", $freeEncodePhpFiles);
  551. $cmds = [
  552. $cmdTempl . $cmdDomainEncodeDomainsTempl . $cmdDomainEncodeFilesTempl,
  553. $cmdTempl . $cmdFreeEncodeFilesTempl,
  554. ];
  555. $returnValues = [];
  556. foreach ($cmds as $cmd) {
  557. $out = ''; $ret = '';
  558. V::exec($cmd, $out, $ret);
  559. $encoderSummaryLine = end($out);
  560. $returnValues[] = $encoderSummaryLine;
  561. if ($dbg) {
  562. DBG::nicePrint([$cmd], "cmd");
  563. DBG::nicePrint($out, "return: '{$ret}'");
  564. // DBG::nicePrint([$encoderSummaryLine], "cmd last line");
  565. }
  566. else DBG::log([$cmd, $out], 'array', "cmd return:'{$ret}'");
  567. // if (0 !== $ret) throw new Exception("Error at encode files");
  568. if (empty($out)) throw new Exception("No output for encode files command");
  569. }
  570. $statusInfo = array_reduce($returnValues, function ($ret, $encoderSummaryLine) {
  571. DBG::log([$ret, $encoderSummaryLine], 'array', "DBG reduce [\$ret, \$encoderSummaryLine]");
  572. $matches = [];
  573. preg_match_all('/(\d+) files, (\d+) encoded, (\d+) skipped, (\d+) errors/', $encoderSummaryLine, $matches, PREG_SET_ORDER, 0);
  574. return [
  575. 'files' => $ret['files'] + (int)$matches[0][1],
  576. 'encoded' => $ret['encoded'] + (int)$matches[0][2],
  577. 'skipped' => $ret['skipped'] + (int)$matches[0][3],
  578. 'errors' => $ret['errors'] + (int)$matches[0][4],
  579. ];
  580. }, [
  581. 'files' => 0,
  582. 'encoded' => 0,
  583. 'skipped' => 0,
  584. 'errors' => 0,
  585. ]);
  586. if ($statusInfo['errors'] === 0 && $statusInfo['files'] > 0) {
  587. if ($dbg) UI::alert('success', "{$statusInfo['files']} files, {$statusInfo['encoded']} encoded, {$statusInfo['skipped']} skipped, {$statusInfo['errors']} errors");
  588. } else {
  589. if ($dbg) UI::alert('danger', "{$statusInfo['files']} files, {$statusInfo['encoded']} encoded, {$statusInfo['skipped']} skipped, {$statusInfo['errors']} errors");
  590. else throw new Exception("{$statusInfo['files']} files, {$statusInfo['encoded']} encoded, {$statusInfo['skipped']} skipped, {$statusInfo['errors']} errors");
  591. }
  592. }
  593. public function _encodeConfigs($configPath) {
  594. $cmd = "find . -name '*.inc.php' ";
  595. $out = ''; $ret = '';
  596. V::exec("cd {$configPath} && {$cmd}", $out, $ret);
  597. DBG::nicePrint($out, "cmd: `{$cmd}` (return:{$ret})");
  598. $freeEncodePhpFiles = $out;
  599. $phpVersionsForSgencoder = '--phpversion 5.5 --phpversion 5.6';// encode for PHP 5.x (currently supported PHP 5.0-5.6)
  600. $cmdTempl = "cd {$configPath} && /Applications/SourceGuardian.app/Contents/MacOS/sgencoder {$phpVersionsForSgencoder} -b- ";
  601. $cmdDomainEncodeDomainsTempl = " --domain " . implode(" --domain ", array_merge($domains, ['localhost']));
  602. // $cmdDomainEncodeFilesTempl = " " . implode(" ", $domainEncodePhpFiles);
  603. $cmdFreeEncodeFilesTempl = " " . implode(" ", $freeEncodePhpFiles);
  604. $cmds = [
  605. // $cmdTempl . $cmdDomainEncodeDomainsTempl . $cmdDomainEncodeFilesTempl,
  606. $cmdTempl . $cmdFreeEncodeFilesTempl,
  607. ];
  608. $dbg = true;
  609. $returnValues = [];
  610. foreach ($cmds as $cmd) {
  611. $out = ''; $ret = '';
  612. V::exec($cmd, $out, $ret);
  613. $encoderSummaryLine = end($out);
  614. $returnValues[] = $encoderSummaryLine;
  615. if ($dbg) {
  616. DBG::nicePrint([$cmd], "cmd");
  617. DBG::nicePrint($out, "return: '{$ret}'");
  618. // DBG::nicePrint([$encoderSummaryLine], "cmd last line");
  619. }
  620. else DBG::log([$cmd, $out], 'array', "cmd return:'{$ret}'");
  621. // if (0 !== $ret) throw new Exception("Error at encode files");
  622. if (empty($out)) throw new Exception("No output for encode files command");
  623. }
  624. $statusInfo = array_reduce($returnValues, function ($ret, $encoderSummaryLine) {
  625. DBG::log([$ret, $encoderSummaryLine], 'array', "DBG reduce [\$ret, \$encoderSummaryLine]");
  626. $matches = [];
  627. preg_match_all('/(\d+) files, (\d+) encoded, (\d+) skipped, (\d+) errors/', $encoderSummaryLine, $matches, PREG_SET_ORDER, 0);
  628. return [
  629. 'files' => $ret['files'] + (int)$matches[0][1],
  630. 'encoded' => $ret['encoded'] + (int)$matches[0][2],
  631. 'skipped' => $ret['skipped'] + (int)$matches[0][3],
  632. 'errors' => $ret['errors'] + (int)$matches[0][4],
  633. ];
  634. }, [
  635. 'files' => 0,
  636. 'encoded' => 0,
  637. 'skipped' => 0,
  638. 'errors' => 0,
  639. ]);
  640. if ($statusInfo['errors'] === 0 && $statusInfo['files'] > 0) {
  641. if ($dbg) UI::alert('success', "{$statusInfo['files']} files, {$statusInfo['encoded']} encoded, {$statusInfo['skipped']} skipped, {$statusInfo['errors']} errors");
  642. } else {
  643. if ($dbg) UI::alert('danger', "{$statusInfo['files']} files, {$statusInfo['encoded']} encoded, {$statusInfo['skipped']} skipped, {$statusInfo['errors']} errors");
  644. else throw new Exception("{$statusInfo['files']} files, {$statusInfo['encoded']} encoded, {$statusInfo['skipped']} skipped, {$statusInfo['errors']} errors");
  645. }
  646. }
  647. public function getAppLicenceInfo($idLicence) {
  648. $idLicence = intval($idLicence);
  649. if (empty($idLicence)) throw new Exception("Nie wybrano serwera/licencji.");
  650. //DBG::_(true, true, 'idLicence', $idLicence, __CLASS__, __FUNCTION__, __LINE__);
  651. $appLicenceInfo = (object)$this->fetchAppLicenceInfo($idLicence);
  652. $appLicenceInfo->domains = $this->fetchDomainsByLicenceId($idLicence);
  653. $installRootPath = '/Library/Server/Web/Data/Sites/Default/PLIKI/SES_PROCESY5_A';
  654. $appLicenceInfo->installFolderName = "{$idLicence}_upgrade_SE_source_encrypted";
  655. $appLicenceInfo->configFolderName = "{$idLicence}_upgrade_SE_config_encrypted";
  656. $appLicenceInfo->installPath = "{$installRootPath}/{$appLicenceInfo->installFolderName}";
  657. $appLicenceInfo->configPath = "{$installRootPath}/{$appLicenceInfo->configFolderName}";
  658. //DBG::_(true, true, 'appLicenceInfo', $appLicenceInfo, __CLASS__, __FUNCTION__, __LINE__);
  659. if (empty($appLicenceInfo->domains)) throw new Exception("Domains not found."); // TODO: mv to validate
  660. $appLicenceInfo->installFolderExists = file_exists("{$appLicenceInfo->installPath}/SE");
  661. $appLicenceInfo->installFolderGitExists = file_exists("{$appLicenceInfo->installPath}/.git");
  662. $appLicenceInfo->projects = []; // TODO: get from db
  663. if (!empty($appLicenceInfo->project)) {
  664. $appLicenceInfo->projects = [ $appLicenceInfo->project ];
  665. }
  666. else if (79 == $idLicence) { // bravecom.procesy5.pl
  667. $appLicenceInfo->projects = [ 'bravecare' ];
  668. } else if (80 == $idLicence) { // bravecom.yellowgroup.pl
  669. $appLicenceInfo->projects = [ 'bocian' ];
  670. } else if (81 == $idLicence) { // bocian.procesy5.pl
  671. $appLicenceInfo->projects = [ 'bocian' ];
  672. } else if (67 == $idLicence) { // bocian.procesy5.pl
  673. $appLicenceInfo->projects = [ 'bocian' ];
  674. } else if (82 == $idLicence) { // bocian-energa.procesy5.pl
  675. $appLicenceInfo->projects = [ 'bocian' ];
  676. } else if (4 == $idLicence) { // bzyk.procesy5.pl
  677. $appLicenceInfo->projects = [ 'bocian' ];
  678. }
  679. return $appLicenceInfo;
  680. }
  681. public function validateAppLicenceInfo($appLicenceInfo) {
  682. if (empty($appLicenceInfo->ID)) throw new Exception("Nie wybrano serwera/licencji.");
  683. if (empty($appLicenceInfo->domains)) throw new Exception("Domains not found");
  684. if (empty($appLicenceInfo->installPath)) throw new Exception("Install path not found");
  685. }
  686. public function generateApp($installPath, $domains, $projects = []) {
  687. $cmds = array();
  688. $cmds[] = "if [ -d {$installPath} ] ; then rm -rf '{$installPath}'; fi";
  689. $cmds[] = "mkdir {$installPath}";
  690. $cmds[] = "cd {$installPath} && git clone --depth 1 ssh://git@biuro.biall-net.pl:2222/plabudda/se.git .";
  691. $cmds[] = "cd {$installPath} && echo `git show-ref --head|head -1|head -c 8` > SE/VERSION ";
  692. foreach ($cmds as $cmd) {
  693. V::exec($cmd, $out, $ret);
  694. DBG::nicePrint([ 'cmd' => $cmd, 'output' => $out ], "return: {$ret}");
  695. }
  696. foreach ($projects as $projectName) {
  697. $cmd = "ls -l SE/projects/{$projectName} | wc -l";
  698. V::exec("cd {$installPath} && {$cmd}", $out, $ret);
  699. DBG::nicePrint([ 'cmd' => $cmd, 'output' => $out ], "return: {$ret}");
  700. if (!empty($out) && '0' !== trim($out[0])) {
  701. // $cmd = "git submodule update SE/projects/{$projectName}";
  702. $cmd = "cd SE/projects/{$projectName} && git reset --hard"; // revert encode source - checkout to last commit (need update)
  703. V::exec("cd {$installPath} && {$cmd}", $out, $ret);
  704. DBG::nicePrint([ 'cmd' => $cmd, 'output' => $out ], "return: {$ret}");
  705. }
  706. $cmd = "git submodule update --init SE/projects/{$projectName}"; // checkout to current commit
  707. V::exec("cd {$installPath} && {$cmd}", $out, $ret);
  708. DBG::nicePrint([ 'cmd' => $cmd, 'output' => $out ], "return: {$ret}");
  709. }
  710. $this->_encodeSource($installPath, $domains);
  711. $this->configGenerate($appLicenceInfo->configPath, $appLicenceInfo->mainServer, $appLicenceInfo->domains, $appLicenceInfo->rootPassword
  712. , $appLicenceInfo->ldapUser, $appLicenceInfo->ldapPass, $appLicenceInfo->ldapBaseDN
  713. );
  714. $this->_encodeConfigs($appLicenceInfo->configPath);
  715. // 1763: $exec='cd '.$installer_dir.' && /Applications/SourceGuardian.app/Contents/MacOS/sgencoder -b-
  716. // '.INSTALL_SES_PROCESY_A::get_same_domains_for_install($h->SERVER_ADDRESS_SHORT).'
  717. // -r *.php
  718. // -x superedit-DB_PROCEDURES_CREATE.php
  719. // -x INI.php
  720. // -x .config_base_structure.php
  721. // ';
  722. //
  723. // INSTALL_SES_PROCESY_A::get_same_domains_for_install($h->SERVER_ADDRESS_SHORT):
  724. // $res2=DB::query("select SERVER_ADDRESS_SHORT from SES_PROCESY5_A where SERVER_ADDRESS_IP='".$h->SERVER_ADDRESS_IP."'");
  725. // while($h2=DB::fetch($res2)) {
  726. // $domain[]=' --domain '.$h2->SERVER_ADDRESS_SHORT;
  727. // ssh server@biuro.galeriaprzymorze.eu: PHP 5.5.20
  728. // ssh server@biuro.biall-net.pl
  729. // cd /Users/plabudda/procesy5-install-galeriaprzymorze.eu/
  730. // sudo chown -R server:admin SE/
  731. // /Applications/SourceGuardian.app/Contents/MacOS/sgencoder --phpversion 5.5 -b- --domain galeriaprzymorze.eu -r SE/*.php SE/se-lib/*.php SE/se-lib/*/*.php SE/se-lib/*/*/*.php SE/procesy/*.php SE/odt2xhtml/*.php -x superedit-DB_PROCEDURES_CREATE.php -x INI.php -x .config_base_structure.php
  732. }
  733. public function fetchActiveLicences() {
  734. $activeLic = array();
  735. $sql = "
  736. select l.`ID`
  737. , l.`SERVER_ADDRESS`
  738. , l.`SERVER_ADDRESS_SHORT` as domain -- domain for sgencoder
  739. , l.`SERVER_ADDRESS_IP`
  740. from `SES_PROCESY5_A` l
  741. where 1=1
  742. -- TODO: and l.`A_STATUS` in('NORMAL','WAITING')
  743. order by l.`ID` DESC
  744. ";
  745. $rows = DB::getPDO()->fetchAll($sql);
  746. foreach ($rows as $row) {
  747. $r = (object)$row;
  748. $activeLic[$r->ID] = $r;
  749. }
  750. return $activeLic;
  751. }
  752. public function fetchDomainsByLicenceId($licenceId) {
  753. $domains = array();
  754. $sql = "
  755. select g.ID, g.`SERVER_ADDRESS_SHORT`, g.`SERVER_ADDRESS`
  756. from `SES_PROCESY5_A` g
  757. where g.`SERVER_ADDRESS_IP`=(select l.`SERVER_ADDRESS_IP`
  758. from `SES_PROCESY5_A` l
  759. where l.`ID`='{$licenceId}'
  760. -- TODO: and l.`A_STATUS` in('NORMAL','WAITING')
  761. )
  762. -- TODO: and g.`A_STATUS` in('NORMAL','WAITING')
  763. ";
  764. $rows = DB::getPDO()->fetchAll($sql);
  765. $mainDomain = null;
  766. foreach ($rows as $row) {
  767. if ($licenceId == $row['ID']) $mainDomain = $row['SERVER_ADDRESS'];
  768. }
  769. foreach ($rows as $row) {
  770. $r = (object)$row;
  771. $domains[] = $r->SERVER_ADDRESS_SHORT;
  772. if ($r->SERVER_ADDRESS != $r->SERVER_ADDRESS_SHORT) {
  773. $domains[] = $r->SERVER_ADDRESS;
  774. }
  775. }
  776. if ($mainDomain && (!preg_match('/^(.*)\.procesy5\.pl$/', $mainDomain))) {
  777. $subDomainP5 = '' . $mainDomain . '.procesy5.pl';
  778. if (!in_array($subDomainP5, $domains)) $domains[] = $subDomainP5;
  779. }
  780. $domains[] = '127.0.0.1';
  781. $domains[] = 'localhost';
  782. return $domains;
  783. }
  784. public function fetchMainServerByLicenceId($licenceId) {
  785. return DB::getPDO()->fetchValue("
  786. select g.`SERVER_ADDRESS`
  787. from `SES_PROCESY5_A` g
  788. where g.`ID`='{$licenceId}'
  789. -- TODO: and g.`A_STATUS` in('NORMAL','WAITING')
  790. ");
  791. }
  792. public function fetchAppLicenceInfo($licenceId) {
  793. $licenceInfo = null;
  794. $sql = "
  795. select g.ID
  796. , g.SERVER_ADDRESS as mainServer
  797. , g.ADMIN_USERNAME as rootLogin
  798. , g.ADMIN_USERNAME_PASSWD as rootPassword
  799. , g.SSH_PORT as sshPort
  800. , g.VERSION_GIT as project
  801. , g.ADMIN_USERNAME_DIRECTORY as ldapUser
  802. , g.ADMIN_USERNAME_PASSWD as ldapPass
  803. , g.SERVER_ADDRESS_LDAP_DC as ldapBaseDN
  804. , g.VERSION_GIT as project
  805. from SES_PROCESY5_A g
  806. where g.`ID`=:id_licence
  807. -- TODO: and g.A_STATUS in('NORMAL','WAITING')
  808. ";
  809. $all = DB::getPDO()->fetchAll($sql, [ ':id_licence' => $licenceId ]);
  810. if (empty($all)) throw new Exception("Brak licencji o nr '{$licenceId}'");
  811. $licenceInfo = reset($all);
  812. if (!$licenceInfo['sshPort']) $licenceInfo['sshPort'] = 22;
  813. return $licenceInfo;
  814. }
  815. public function _endWithException($e) {
  816. echo UI::h('div', ['class'=>"container"], [
  817. UI::h('div', ['class' => "alert alert-danger"], "#" . $e->getLine() . ": " . $e->getMessage()),
  818. UI::h('p', [], [
  819. "Wróć do ",
  820. UI::h('a', ['href'=>"index.php?_route=Install"], "menu")
  821. ])
  822. ]);
  823. UI::dol();
  824. exit;
  825. }
  826. public function sendToRemoteTestDirAction() {
  827. session_write_close();
  828. $args = array();
  829. $args['licence_id'] = V::get('licence_id', 0, $_REQUEST, 'int');
  830. UI::gora();
  831. //UI::menu();
  832. //$this->menu($args['licence_id']);// TODO: GO BACK BTN
  833. try {
  834. $appLicenceInfo = $this->getAppLicenceInfo($args['licence_id']);
  835. $this->validateAppLicenceInfo($appLicenceInfo);
  836. // TODO: if (59 ) => baratosz.sledz - na lokalnym kompie
  837. // bn:~/$ scp -r SE server@192.168.61.153:~/se.encrypted.upgrade
  838. // remote SE.git = '/Users/bartoszsledz/Desktop/production-se'
  839. // remote:~/$ mv SE ~/SE.bup.2017-07-03
  840. // remote:~/$ mv ~/se.encrypted.upgrade/SE SE
  841. // remote:~/$ cp -r ~/SE.bup.2017-07-03/config SE/
  842. // remote:~/$ sudo chown -R bartoszsledz:staff SE/
  843. $this->_sendToRemoteTestDir($appLicenceInfo);
  844. echo "Test online: ";
  845. echo UI::h('a', ['target'=>"_blank", 'href'=>"https://{$appLicenceInfo->mainServer}/se.encrypted.upgrade/"], "https://{$appLicenceInfo->mainServer}/se.encrypted.upgrade/");
  846. } catch (Exception $e) {
  847. $this->_endWithException($e);
  848. }
  849. UI::dol();
  850. }
  851. public function _fetchRemoteHomeDir($appLicenceInfo) {
  852. $this->_assertRsaKeyExists($appLicenceInfo);
  853. $sshHostUsr = "{$appLicenceInfo->rootLogin}@{$appLicenceInfo->mainServer}";
  854. $sshArgs = (22 != $appLicenceInfo->sshPort)? "-p {$appLicenceInfo->sshPort}" : '';
  855. $scpArgs = (22 != $appLicenceInfo->sshPort)? "-P {$appLicenceInfo->sshPort}" : '';
  856. $rsyncSshPort = (22 != $appLicenceInfo->sshPort)? "-e 'ssh -p {$appLicenceInfo->sshPort}'" : '';
  857. if (V::get('DBG_REMOTE', '', $_GET)) {// DBG
  858. $cmd = "echo ~";
  859. V::exec("ssh {$sshArgs} {$sshHostUsr} '{$cmd}'", $out, $ret);
  860. DBG::log([ 'cmd-remote' => $cmd, 'output' => $out ], 'array', "return: {$ret}");
  861. V::execRemote($appLicenceInfo->mainServer, $appLicenceInfo->rootLogin, $appLicenceInfo->rootPassword, $cmd, $out, $ret, $appLicenceInfo->sshPort);
  862. DBG::log([ 'cmd-remote' => $cmd, 'output' => $out ], 'array', "return: {$ret}");
  863. V::execRootRemote($appLicenceInfo->mainServer, $appLicenceInfo->rootLogin, $appLicenceInfo->rootPassword, $cmd, $out, $ret, $appLicenceInfo->sshPort);
  864. DBG::log([ 'cmd-remote' => $cmd, 'output' => $out ], 'array', "return: {$ret}");
  865. }
  866. $cmd = "echo ~";
  867. V::exec("ssh {$sshArgs} {$this->sshArgsSkipHostKey} {$sshHostUsr} '{$cmd}'", $out, $ret);
  868. DBG::log([ 'cmd-remote' => $cmd, 'output' => $out ], 'array', "return: {$ret}");
  869. if (empty($out) || empty($out[0])) throw new Exception("Cannot fetch remote home dir");
  870. return $out[0];
  871. }
  872. public function _sendToRemoteTestDir($appLicenceInfo) {
  873. $cmd = ''; $out = ''; $ret = '';
  874. $dryRunOnly = (V::get('dry-run', '', $_REQUEST)) ? "--dry-run" : "";
  875. $this->_assertRsaKeyExists($appLicenceInfo);
  876. $sshHostUsr = "{$appLicenceInfo->rootLogin}@{$appLicenceInfo->mainServer}";
  877. $sshArgs = (22 != $appLicenceInfo->sshPort)? "-p {$appLicenceInfo->sshPort}" : '';
  878. $rsyncSshPort = (22 != $appLicenceInfo->sshPort)? "-e 'ssh -p {$appLicenceInfo->sshPort}'" : '';
  879. $scpArgs = (22 != $appLicenceInfo->sshPort)? "-P {$appLicenceInfo->sshPort}" : '';
  880. // $appLicenceInfo->sshPort
  881. /* rsync options:
  882. -a, --archive archive mode; same as -rlptgoD (no -H)
  883. -u, --update skip files that are newer on the receiver
  884. -t, --times preserve times
  885. --delete delete extraneous files from dest dirs
  886. */
  887. $remoteDir = $this->_fetchRemoteHomeDir($appLicenceInfo);
  888. DBG::log($remoteDir, 'array', "remote home dir:");
  889. $cmd = "
  890. ssh {$sshArgs} {$this->sshArgsSkipHostKey} {$sshHostUsr} '[ ! -d ~/se.encrypted.upgrade ] && mkdir ~/se.encrypted.upgrade || echo 1';
  891. ssh {$sshArgs} {$this->sshArgsSkipHostKey} {$sshHostUsr} 'rm -rf ~/se.encrypted.upgrade/SE';
  892. ssh {$sshArgs} {$this->sshArgsSkipHostKey} {$sshHostUsr} 'cp -r /Library/Server/Web/Data/Sites/Default/SE ~/se.encrypted.upgrade/SE';
  893. ssh {$sshArgs} {$this->sshArgsSkipHostKey} {$sshHostUsr} 'rm -rf ~/se.encrypted.upgrade/SE/config';
  894. rsync --archive --times --delete --compress --one-file-system --omit-dir-times --no-g --no-perms {$dryRunOnly} \
  895. --verbose {$rsyncSshPort} \
  896. --exclude='schema/default_db.instance.xml' \
  897. --exclude='schema/default_db.instance.xml/**' \
  898. '{$appLicenceInfo->installPath}/SE/' {$sshHostUsr}:~/se.encrypted.upgrade/SE/;
  899. ssh {$sshArgs} {$this->sshArgsSkipHostKey} {$sshHostUsr} 'cp -r /Library/Server/Web/Data/Sites/Default/SE/config ~/se.encrypted.upgrade/SE/';
  900. ssh {$sshArgs} {$this->sshArgsSkipHostKey} {$sshHostUsr} 'rm /Library/Server/Web/Data/Sites/Default/se.encrypted.upgrade'
  901. ssh {$sshArgs} {$this->sshArgsSkipHostKey} {$sshHostUsr} 'ln -s ~/se.encrypted.upgrade/SE /Library/Server/Web/Data/Sites/Default/se.encrypted.upgrade'
  902. scp {$this->sshArgsSkipHostKey} {$scpArgs} /Library/Server/Web/Data/Sites/SE-production-git/SE/config/.config_base_structure.php {$sshHostUsr}:
  903. ssh {$sshArgs} {$this->sshArgsSkipHostKey} {$sshHostUsr} 'mv ~/.config_base_structure.php /Library/Server/Web/Data/Sites/Default/se.encrypted.upgrade/config'
  904. ssh {$sshArgs} {$this->sshArgsSkipHostKey} {$sshHostUsr} 'cp /Users/server/se.encrypted.upgrade/SE/stuff/SourceGuardian/Loaders/Mac\ OS\ X/ixed.5.6.dar /opt/local/lib/php56/extensions/no-debug-non-zts-20131226/'
  905. "; //todo rsync ... -e \"{$this->sshArgsSkipHostKey}\" - maybe not working
  906. // --exclude='schema/default_db_xml_cache.public' \
  907. // --exclude='stuff' \
  908. // --exclude='stuff/**' \
  909. //--exclude='schema/default_db_xml_cache.public/**' \
  910. //TODO @2018-02-09 - check if ssh {$sshArgs} {$this->sshArgsSkipHostKey} {$sshHostUsr} 'cp /Applications/SourceGuardian.app/Contents/MacOS/Loaders/Mac\ OS\ X/ixed.5.6.dar /opt/local/lib/php56/extensions/no-debug-non-zts-20131226/'
  911. //IS WORKING WELL!
  912. V::exec("$cmd 2>&1", $out, $ret);
  913. DBG::log([ 'cmd-remote' => $cmd, 'output' => $out ], 'array', "return: {$ret}");
  914. if (0 !== $ret) throw new Exception("Cannot run remote command using rsa key! #{$ret}. cmd: {$cmd} . out: {$out}");
  915. }
  916. public function upgradeRemoteFromTestDirAction() {
  917. session_write_close();
  918. $args = array();
  919. $args['licence_id'] = V::get('licence_id', 0, $_REQUEST, 'int');
  920. UI::gora();
  921. //UI::menu();
  922. //$this->menu($args['licence_id']);// TODO: GO BACK BTN
  923. try {
  924. $appLicenceInfo = $this->getAppLicenceInfo($args['licence_id']);
  925. $this->validateAppLicenceInfo($appLicenceInfo);
  926. $this->_upgradeRemoteFromTestDir($appLicenceInfo);
  927. echo "Test online: ";
  928. echo UI::h('a', ['target'=>"_blank", 'href'=>"https://{$appLicenceInfo->mainServer}/SE/"], "https://{$appLicenceInfo->mainServer}/SE/");
  929. } catch (Exception $e) {
  930. $this->_endWithException($e);
  931. }
  932. UI::dol();
  933. }
  934. public function _upgradeRemoteFromTestDir($appLicenceInfo) {
  935. $cmd = ''; $out = ''; $ret = '';
  936. $this->_assertRsaKeyExists($appLicenceInfo);
  937. $dateStr = date("Y-m-d_H-i-s");
  938. // $remoteHomeDir = "/Users/{$appLicenceInfo->rootLogin}";// BUG: alias like in ams - login = prezes is alias for arkadiuszbinder
  939. $remoteHomeDir = $this->_fetchRemoteHomeDir($appLicenceInfo);
  940. $cmd = "
  941. rm -rf /Library/Server/Web/Data/Sites/Default/SE.test 2>&1
  942. cp -r {$remoteHomeDir}/se.encrypted.upgrade/SE /Library/Server/Web/Data/Sites/Default/SE.test 2>&1
  943. [ ! -d {$remoteHomeDir}/bup.se.upgrade ] && mkdir {$remoteHomeDir}/bup.se.upgrade || echo 1
  944. [ ! -d {$remoteHomeDir}/bup.se.upgrade ] && exit 1
  945. [ ! -d {$remoteHomeDir}/bup.se.upgrade-testttttt ] && exit 1
  946. [ ! -f /Library/Server/Web/Data/Sites/Default/SE.test/VERSION ] && echo \"Error: plik VERSION nie istnieje\" || echo \"check VERSION OK\"
  947. [ ! -f /Library/Server/Web/Data/Sites/Default/SE.test/VERSION ] && exit 1
  948. [ ! -f /Library/Server/Web/Data/Sites/Default/SE.test/index.php ] && echo \"Error: plik index.php nie istnieje\" || echo \"check index.php OK\"
  949. [ ! -f /Library/Server/Web/Data/Sites/Default/SE.test/index.php ] && exit 1
  950. [ ! -d /Library/Server/Web/Data/Sites/Default/SE.test/se-lib ] && echo \"Error: plik se-lib nie istnieje\" || echo \"check se-lib OK\"
  951. [ ! -d /Library/Server/Web/Data/Sites/Default/SE.test/se-lib ] && exit 1
  952. exit 0
  953. ";
  954. V::execRootRemote($appLicenceInfo->mainServer, $appLicenceInfo->rootLogin, $appLicenceInfo->rootPassword, $cmd, $out, $ret, $appLicenceInfo->sshPort);
  955. $cmd = "
  956. mv /Library/Server/Web/Data/Sites/Default/SE {$remoteHomeDir}/bup.se.upgrade/bup.{$dateStr} 2>&1
  957. mv /Library/Server/Web/Data/Sites/Default/SE.test /Library/Server/Web/Data/Sites/Default/SE 2>&1
  958. exit 0
  959. ";
  960. V::execRootRemote($appLicenceInfo->mainServer, $appLicenceInfo->rootLogin, $appLicenceInfo->rootPassword, $cmd, $out, $ret, $appLicenceInfo->sshPort);
  961. DBG::_(true, true, "cmd: {$cmd} (return: {$ret})", $out, __CLASS__, __FUNCTION__, __LINE__);
  962. if (0 !== $ret) throw new Exception("Cannot run remote command as root! #{$ret}");
  963. // TODO: SE/bash_install_check.php requires $domain!
  964. // $cmd = "/usr/bin/php /Library/Server/Web/Data/Sites/Default/SE/bash_install_check.php {$domain}";
  965. // V::execRootRemote($appLicenceInfo->mainServer, $appLicenceInfo->rootLogin, $appLicenceInfo->rootPassword, $cmd, $out, $ret, $appLicenceInfo->sshPort);
  966. // DBG::_(true, true, "cmd: {$cmd} (return: {$ret})", $out, __CLASS__, __FUNCTION__, __LINE__);
  967. // if (0 !== $ret) throw new Exception("Cannot run remote command as root! #{$ret}");
  968. }
  969. public function _assertRsaKeyExists($appLicenceInfo) {
  970. $cmd = ''; $out = ''; $ret = '';
  971. $cmd = "echo ~ && pwd";// /Library/WebServer
  972. $cmd = "ls -1 ~/.ssh/";
  973. //$cmd = "rm /tmp/id_rsa";
  974. //$cmd = "rm /tmp/id_rsa.pub";
  975. //$cmd = "ssh-keygen -t rsa -N '' -C '_www@biuro.biall-net.pl' -f /tmp/id_rsa";
  976. //$cmd = "ssh-keygen -t rsa -N '' -C '_www@biuro.biall-net.pl' -f /tmp/id_rsa";
  977. V::exec($cmd, $out, $ret);
  978. DBG::_(true, true, "cmd: {$cmd} (return: {$ret})", $out, __CLASS__, __FUNCTION__, __LINE__);
  979. if (0 !== $ret) {// no ~/.ssh directory
  980. $rsaKeyPath = "~/.ssh";
  981. $cmds = array();
  982. $cmds[] = "mkdir {$rsaKeyPath}";
  983. $cmds[] = "ssh-keygen -t rsa -N '' -C '_www@biuro.biall-net.pl' -f {$rsaKeyPath}/id_rsa 2>&1";
  984. $cmds[] = "ls -1 $rsaKeyPath";
  985. foreach ($cmds as $cmd) {
  986. V::exec($cmd, $out, $ret);
  987. DBG::_(true, true, "cmd: {$cmd} (return: {$ret})", $out, __CLASS__, __FUNCTION__, __LINE__);
  988. if (0 !== $ret) throw new Exception("Error '{$ret}' cmd({$cmd}): " . implode("\n", $out));
  989. }
  990. }
  991. $cmd = "cat ~/.ssh/id_rsa.pub";
  992. V::exec($cmd, $out, $ret);
  993. DBG::_(true, true, "cmd: {$cmd} (return: {$ret})", $out, __CLASS__, __FUNCTION__, __LINE__);
  994. if (0 !== $ret || empty($out) || empty($out[0])) throw new Exception("Cannot read rsa public key");
  995. $rsaPubKey = $out[0];
  996. $cmd = 'ls -1a';
  997. $cmd = "
  998. [ ! -d ~/.ssh ] && mkdir ~/.ssh;
  999. [ ! -d ~/.ssh ] && echo 'ERROR ~/.ssh not exists and cannot be created';
  1000. [ ! -f ~/.ssh/authorized_keys ] && echo '{$rsaPubKey}' > ~/.ssh/authorized_keys;
  1001. [ ! -f ~/.ssh/authorized_keys ] && echo 'ERROR ~/.ssh/authorized_keys not exists and cannot be created';
  1002. cat ~/.ssh/authorized_keys| grep '{$rsaPubKey}' && echo 'OK' || echo '{$rsaPubKey}' >> ~/.ssh/authorized_keys;
  1003. chmod 600 ~/.ssh/authorized_keys;
  1004. ";
  1005. V::execRemote($appLicenceInfo->mainServer, $appLicenceInfo->rootLogin, $appLicenceInfo->rootPassword, $cmd, $out, $ret, $appLicenceInfo->sshPort);
  1006. DBG::_(true, true, "remote cmd: {$cmd} (return: {$ret})", $out, __CLASS__, __FUNCTION__, __LINE__);
  1007. //$cmd = "ssh server@{$appLicenceInfo->mainServer} 'ls -1 .ssh/'";
  1008. //$cmd = "ssh -i ~/.ssh/id_rsa server@{$appLicenceInfo->mainServer} 'ls -1'";
  1009. $sshPort = (22 != $appLicenceInfo->sshPort)? "-p {$appLicenceInfo->sshPort}" : '';
  1010. $cmd = "ssh {$sshPort} {$this->sshArgsSkipHostKey} {$appLicenceInfo->rootLogin}@{$appLicenceInfo->mainServer} 'ls -1'";
  1011. V::exec("$cmd 2>&1", $out, $ret); // http://php.net/manual/pl/function.exec.php says I saw the exec, system, shell_exec and passthru functions,
  1012. //and deduced that the solution was to
  1013. //redirect the standard error (stderr) to the standard output (stdout). It's not very clean, since it mixes stderr with stdout, and I only wanted to log the stderr.
  1014. //But it seems to be the only solution (suggestions are welcome).
  1015. DBG::_(true, true, "cmd: {$cmd} (return: {$ret})", $out, __CLASS__, __FUNCTION__, __LINE__);
  1016. if (0 !== $ret) throw new Exception("Cannot run remote command using rsa key! #{$ret}; Out: ".implode($out)."; Cmd: {$cmd};");
  1017. }
  1018. public function newGenerateApp($appLicenceInfo) {
  1019. if (empty($appLicenceInfo->ID)) throw new Exception("Nie wybrano serwera/licencji.");
  1020. if (empty($appLicenceInfo->domains)) throw new Exception("Domains not found");
  1021. $installPath = $appLicenceInfo->installPath;
  1022. if (empty($installPath)) throw new Exception("Install path not found");
  1023. $installPath .= '-p5';
  1024. $cmds = array();
  1025. $cmds[] = "if [ -d {$installPath} ] ; then rm -rf '{$installPath}'; fi";
  1026. $cmds[] = "mkdir {$installPath}";
  1027. $cmds[] = "cd {$installPath} && git clone --depth 1 ssh://git@biuro.biall-net.pl:2222/p5/p5.git .";
  1028. $cmds[] = "cd {$installPath} && echo `git show-ref --head|head -1|head -c 8` > SE/VERSION ";
  1029. // TODO: fetch from DB
  1030. {
  1031. foreach ($appLicenceInfo->projects as $projectName) {
  1032. $cmds[] = "cd {$installPath} && git submodule update --init SE/projects/{$projectName}";
  1033. }
  1034. }
  1035. foreach ($cmds as $cmd) {
  1036. $out = ''; $ret = '';
  1037. V::exec($cmd, $out, $ret);
  1038. DBG::nicePrint([ 'cmd' => $cmd, 'output' => $out ], "return: {$ret}");
  1039. }
  1040. // $this->_encodeSource($appLicenceInfo->installPath, $appLicenceInfo->domains);
  1041. }
  1042. }