Install.php 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989
  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->generateConfigs($appLicenceInfo->installPath, $appLicenceInfo->domains);
  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-top:30px" ], [
  224. "Test online: ",
  225. UI::h('a', [
  226. 'target' => "_blank",
  227. 'href' => "https://{$appLicenceInfo->mainServer}/se.encrypted.upgrade/"
  228. ], "https://{$appLicenceInfo->mainServer}/se.encrypted.upgrade/"),
  229. ]),
  230. "<br> - ",
  231. UI::h('a', [
  232. 'href' => "index.php?_route=Install&_task=upgradeRemoteFromTestDir&licence_id={$appLicenceInfo->ID}",
  233. 'onclick' => "return confirm('Uruchomić aktualizację SE na https://{$appLicenceInfo->mainServer}/SE/?')",
  234. 'target' => "_blank",
  235. 'class' => "btn btn-xs btn-warning"
  236. ], "UPGRADE Production folder from uploaded dir: ~/se.encrypted.upgrade/"),
  237. ]),
  238. ]),
  239. ]);
  240. ?>
  241. <script type="text/javascript">
  242. jQuery(document).ready(function () {
  243. jQuery('#fldSbmtBtn').on('click', function () {
  244. jQuery(this).text(jQuery(this).text() + '...').attr('disabled', 'disabled');
  245. jQuery(this).parent().submit();
  246. })
  247. });
  248. </script>
  249. <?php
  250. UI::dol();
  251. }
  252. public function configGenerateAction() {
  253. session_write_close();
  254. $args = array();
  255. $args['licence_id'] = V::get('licence_id', 0, $_REQUEST, 'int');
  256. UI::gora();
  257. UI::menu();
  258. //$this->menu($args['licence_id']);// TODO: GO BACK BTN
  259. try {
  260. $appLicenceInfo = $this->getAppLicenceInfo($args['licence_id']);
  261. $this->validateAppLicenceInfo($appLicenceInfo);
  262. UI::startContainer();
  263. $this->configGenerate($appLicenceInfo->configPath, $appLicenceInfo->mainServer, $appLicenceInfo->rootPassword
  264. , $appLicenceInfo->ldapUser, $appLicenceInfo->ldapPass, $appLicenceInfo->ldapBaseDN
  265. );
  266. UI::endContainer();
  267. } catch (Exception $e) {
  268. $this->_endWithException($e);
  269. }
  270. UI::dol();
  271. }
  272. public function configGenerate($configPath, $mainServer, $rootPassword, $ldapUser, $ldapPass, $ldapBaseDN) {
  273. if (empty($configPath)) throw new Exception("Install path not found");
  274. $cmds = array();
  275. $cmds[] = "mkdir '{$configPath}'";
  276. $REMOTE_FOLDER_ROOT = str_replace([ ".", "-" ], '_', $mainServer);
  277. $cmds[] = ' echo "' . V::quoteBashEcho(
  278. Config::generateDefaultDbConfigFile(
  279. [
  280. 'database' => $REMOTE_FOLDER_ROOT,
  281. 'password' => $rootPassword,
  282. ],
  283. $outputFormat = 'inc'
  284. )
  285. ) . '" > ' . $configPath . '/.cnf--default_db-' . $mainServer . '.inc.php';
  286. $cmds[] = ' echo "' . V::quoteBashEcho(
  287. Config::generateDefaultDbConfigFile(
  288. [
  289. 'database' => $REMOTE_FOLDER_ROOT,
  290. 'password' => $rootPassword,
  291. ],
  292. $outputFormat = 'inc'
  293. )
  294. ) . '" > ' . $configPath . '/.cnf--zasob_2-' . $mainServer . '.inc.php';
  295. $cmds[] = ' echo "' . V::quoteBashEcho(
  296. Config::generateDefaultLdapConfigFile(
  297. [
  298. 'user' => $ldapUser,
  299. 'pass' => $ldapPass,
  300. 'base_dn' => $ldapBaseDN,
  301. ],
  302. $outputFormat = 'inc'
  303. )
  304. ) . '" > ' . $configPath . '/.cnf--default_ldap-' . $mainServer . '.inc.php';
  305. $hasError = false;
  306. foreach ($cmds as $cmd) {
  307. V::exec($cmd, $out, $ret);
  308. if (0 !== $ret) $hasError = true;
  309. DBG::nicePrint($out, "cmd: `{$cmd}` (return:{$ret})");
  310. }
  311. if (!$hasError) {
  312. UI::alert('success', "OK");
  313. } else {
  314. UI::alert('danger', "errors");
  315. }
  316. }
  317. public function gitResetHardAction() {
  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->gitResetHard($appLicenceInfo->installPath, $appLicenceInfo->projects);
  329. UI::endContainer();
  330. } catch (Exception $e) {
  331. $this->_endWithException($e);
  332. }
  333. UI::dol();
  334. }
  335. public function gitResetHard($installPath, $projects = []) {
  336. if (empty($installPath)) throw new Exception("Install path not found");
  337. $cmds = array();
  338. $cmds[] = "git reset --hard";
  339. $cmds[] = "git pull";
  340. $cmds[] = "echo `git show-ref --head|head -1|head -c 8` > SE/VERSION ";
  341. $hasError = false;
  342. foreach ($cmds as $cmd) {
  343. V::exec("cd {$installPath} && {$cmd}", $out, $ret);
  344. if (0 !== $ret) $hasError = true;
  345. DBG::nicePrint($out, "cmd: `{$cmd}` (return:{$ret})");
  346. }
  347. foreach ($projects as $projectName) {
  348. $cmd = "ls -l SE/projects/{$projectName} | wc -l";
  349. V::exec("cd {$installPath} && {$cmd}", $out, $ret);
  350. DBG::nicePrint([ 'cmd' => $cmd, 'output' => $out ], "return: {$ret}");
  351. if (!empty($out) && '0' !== trim($out[0])) {
  352. // $cmd = "git submodule update SE/projects/{$projectName}";
  353. $cmd = "cd SE/projects/{$projectName} && git reset --hard"; // revert encode source - checkout to last commit (need update)
  354. V::exec("cd {$installPath} && {$cmd}", $out, $ret);
  355. DBG::nicePrint([ 'cmd' => $cmd, 'output' => $out ], "return: {$ret}");
  356. }
  357. $cmd = "git submodule update --init SE/projects/{$projectName}"; // checkout to current commit
  358. V::exec("cd {$installPath} && {$cmd}", $out, $ret);
  359. DBG::nicePrint([ 'cmd' => $cmd, 'output' => $out ], "return: {$ret}");
  360. }
  361. if (!$hasError) {
  362. UI::alert('success', "OK");
  363. } else {
  364. UI::alert('danger', "errors");
  365. }
  366. }
  367. public function encodeSourceAction() {
  368. session_write_close();
  369. $args = array();
  370. $args['licence_id'] = V::get('licence_id', 0, $_REQUEST, 'int');
  371. UI::gora();
  372. UI::menu();
  373. //$this->menu($args['licence_id']);// TODO: GO BACK BTN
  374. try {
  375. $appLicenceInfo = $this->getAppLicenceInfo($args['licence_id']);
  376. $this->validateAppLicenceInfo($appLicenceInfo);
  377. $this->_encodeSource($appLicenceInfo->installPath, $appLicenceInfo->domains);
  378. $this->_encodeConfigs($appLicenceInfo->configPath);
  379. } catch (Exception $e) {
  380. $this->_endWithException($e);
  381. }
  382. UI::dol();
  383. }
  384. public function _encodeSource($installPath, $domains) {
  385. UI::startContainer();
  386. $this->encodeSourceFiles($installPath, $domains, $dbg = true);
  387. // try {
  388. // $this->encodeSourceFiles($appLicenceInfo->installPath, $appLicenceInfo->domains, $dbg = false);
  389. // UI::alert('success', "OK");
  390. // } catch (Exception $e) {
  391. // UI::alert('danger', $e->getMessage());
  392. // }
  393. UI::endContainer();
  394. }
  395. // @usage: Router::getRoute('Install')->encodeSourceFiles($installPath = '/path_to_git_repo', $domains = [ 'domain.com', 'localhost' ], $dbg = false);
  396. public function encodeSourceFiles($installPath, $domains, $dbg = false) {
  397. if (empty($installPath)) throw new Exception("Install path not found");
  398. if (empty($domains)) throw new Exception("Domains not found");
  399. $phpVersionsForSgencoder = '--phpversion 5.5 --phpversion 5.6';// encode for PHP 5.x (currently supported PHP 5.0-5.6)
  400. if ('1' == V::get('DBG_ENCODER_HELP', '', $_REQUEST)) {// encoder help
  401. $cmd = "cd {$installPath}/SE && /Applications/SourceGuardian.app/Contents/MacOS/sgencoder --help ";
  402. $out = ''; $ret = '';
  403. V::exec($cmd, $out, $ret);
  404. DBG::nicePrint($out, "cmd: `{$cmd}` (return:{$ret})");
  405. exit;
  406. }
  407. $domainEncodePhpFiles = [
  408. 'ant.php',
  409. 'api.php',
  410. 'budynki.php',
  411. 'index-ajax.php',
  412. 'index.php',
  413. 'procesy5.php',
  414. 'session-expire.php',
  415. 'test-sync.php',
  416. 'wfs-data.php',
  417. 'wfs-qgis.php',
  418. 'wfs.php',
  419. ];
  420. $cmd = "find . -name '*.php' ";
  421. $out = ''; $ret = '';
  422. V::exec("cd {$installPath}/SE && {$cmd}", $out, $ret);
  423. if ($dbg) DBG::nicePrint($out, "cmd: `{$cmd}` (return:{$ret})");
  424. else DBG::log($out, 'array', "cmd: `{$cmd}` (return:{$ret})");
  425. if (0 !== $ret) throw new Exception("Error at find php files");
  426. if (empty($out)) throw new Exception("No php files found");
  427. $allPhpFiles = array_map(function ($phpFilePath) {
  428. return ('./' == substr($phpFilePath, 0, 2))? substr($phpFilePath, 2) : $phpFilePath;
  429. }, $out);
  430. $freeEncodePhpFiles = array_filter($allPhpFiles, function ($phpFilePath) use ($domainEncodePhpFiles) {
  431. if ('se-lib/Vendor/' === substr($phpFilePath, 0, strlen('se-lib/Vendor/'))) return false; // SKIP se-lib/Vendor/*
  432. if ('.ini.php' === substr($phpFilePath, -1 * strlen('.ini.php'))) return false; // SKIP *.ini.php
  433. return (!in_array($phpFilePath, $domainEncodePhpFiles));
  434. });
  435. DBG::log($freeEncodePhpFiles, 'array', "\$freeEncodePhpFiles");
  436. if (empty($freeEncodePhpFiles)) throw new Exception("No php files to encode");
  437. $cmdTempl = "cd {$installPath}/SE && /Applications/SourceGuardian.app/Contents/MacOS/sgencoder {$phpVersionsForSgencoder} -b- ";
  438. $cmdDomainEncodeDomainsTempl = " --domain " . implode(" --domain ", array_merge($domains, ['localhost']));
  439. $cmdDomainEncodeFilesTempl = " " . implode(" ", $domainEncodePhpFiles);
  440. $cmdFreeEncodeFilesTempl = " " . implode(" ", $freeEncodePhpFiles);
  441. $cmds = [
  442. $cmdTempl . $cmdDomainEncodeDomainsTempl . $cmdDomainEncodeFilesTempl,
  443. $cmdTempl . $cmdFreeEncodeFilesTempl,
  444. ];
  445. $returnValues = [];
  446. foreach ($cmds as $cmd) {
  447. $out = ''; $ret = '';
  448. V::exec($cmd, $out, $ret);
  449. $encoderSummaryLine = end($out);
  450. $returnValues[] = $encoderSummaryLine;
  451. if ($dbg) {
  452. DBG::nicePrint([$cmd], "cmd");
  453. DBG::nicePrint($out, "return: '{$ret}'");
  454. // DBG::nicePrint([$encoderSummaryLine], "cmd last line");
  455. }
  456. else DBG::log([$cmd, $out], 'array', "cmd return:'{$ret}'");
  457. // if (0 !== $ret) throw new Exception("Error at encode files");
  458. if (empty($out)) throw new Exception("No output for encode files command");
  459. }
  460. $statusInfo = array_reduce($returnValues, function ($ret, $encoderSummaryLine) {
  461. DBG::log([$ret, $encoderSummaryLine], 'array', "DBG reduce [\$ret, \$encoderSummaryLine]");
  462. $matches = [];
  463. preg_match_all('/(\d+) files, (\d+) processed, (\d+) errors/', $encoderSummaryLine, $matches, PREG_SET_ORDER, 0);
  464. return [
  465. 'files' => $ret['files'] + (int)$matches[0][1],
  466. 'processed' => $ret['processed'] + (int)$matches[0][2],
  467. 'errors' => $ret['errors'] + (int)$matches[0][3],
  468. ];
  469. }, [
  470. 'files' => 0,
  471. 'processed' => 0,
  472. 'errors' => 0,
  473. ]);
  474. if ($statusInfo['errors'] === 0 && $statusInfo['files'] > 0) {
  475. if ($dbg) UI::alert('success', "{$statusInfo['files']} files, {$statusInfo['processed']} processed, {$statusInfo['errors']} errors");
  476. } else {
  477. if ($dbg) UI::alert('danger', "{$statusInfo['files']} files, {$statusInfo['processed']} processed, {$statusInfo['errors']} errors");
  478. else throw new Exception("{$statusInfo['files']} files, {$statusInfo['processed']} processed, {$statusInfo['errors']} errors");
  479. }
  480. }
  481. public function _encodeConfigs($configPath) {
  482. $cmd = "find . -name '*.inc.php' ";
  483. $out = ''; $ret = '';
  484. V::exec("cd {$configPath} && {$cmd}", $out, $ret);
  485. DBG::nicePrint($out, "cmd: `{$cmd}` (return:{$ret})");
  486. $freeEncodePhpFiles = $out;
  487. $phpVersionsForSgencoder = '--phpversion 5.5 --phpversion 5.6';// encode for PHP 5.x (currently supported PHP 5.0-5.6)
  488. $cmdTempl = "cd {$configPath} && /Applications/SourceGuardian.app/Contents/MacOS/sgencoder {$phpVersionsForSgencoder} -b- ";
  489. $cmdDomainEncodeDomainsTempl = " --domain " . implode(" --domain ", array_merge($domains, ['localhost']));
  490. // $cmdDomainEncodeFilesTempl = " " . implode(" ", $domainEncodePhpFiles);
  491. $cmdFreeEncodeFilesTempl = " " . implode(" ", $freeEncodePhpFiles);
  492. $cmds = [
  493. // $cmdTempl . $cmdDomainEncodeDomainsTempl . $cmdDomainEncodeFilesTempl,
  494. $cmdTempl . $cmdFreeEncodeFilesTempl,
  495. ];
  496. $dbg = true;
  497. $returnValues = [];
  498. foreach ($cmds as $cmd) {
  499. $out = ''; $ret = '';
  500. V::exec($cmd, $out, $ret);
  501. $encoderSummaryLine = end($out);
  502. $returnValues[] = $encoderSummaryLine;
  503. if ($dbg) {
  504. DBG::nicePrint([$cmd], "cmd");
  505. DBG::nicePrint($out, "return: '{$ret}'");
  506. // DBG::nicePrint([$encoderSummaryLine], "cmd last line");
  507. }
  508. else DBG::log([$cmd, $out], 'array', "cmd return:'{$ret}'");
  509. // if (0 !== $ret) throw new Exception("Error at encode files");
  510. if (empty($out)) throw new Exception("No output for encode files command");
  511. }
  512. $statusInfo = array_reduce($returnValues, function ($ret, $encoderSummaryLine) {
  513. DBG::log([$ret, $encoderSummaryLine], 'array', "DBG reduce [\$ret, \$encoderSummaryLine]");
  514. $matches = [];
  515. preg_match_all('/(\d+) files, (\d+) processed, (\d+) errors/', $encoderSummaryLine, $matches, PREG_SET_ORDER, 0);
  516. return [
  517. 'files' => $ret['files'] + (int)$matches[0][1],
  518. 'processed' => $ret['processed'] + (int)$matches[0][2],
  519. 'errors' => $ret['errors'] + (int)$matches[0][3],
  520. ];
  521. }, [
  522. 'files' => 0,
  523. 'processed' => 0,
  524. 'errors' => 0,
  525. ]);
  526. if ($statusInfo['errors'] === 0 && $statusInfo['files'] > 0) {
  527. if ($dbg) UI::alert('success', "{$statusInfo['files']} files, {$statusInfo['processed']} processed, {$statusInfo['errors']} errors");
  528. } else {
  529. if ($dbg) UI::alert('danger', "{$statusInfo['files']} files, {$statusInfo['processed']} processed, {$statusInfo['errors']} errors");
  530. else throw new Exception("{$statusInfo['files']} files, {$statusInfo['processed']} processed, {$statusInfo['errors']} errors");
  531. }
  532. }
  533. public function getAppLicenceInfo($idLicence) {
  534. $idLicence = intval($idLicence);
  535. if (empty($idLicence)) throw new Exception("Nie wybrano serwera/licencji.");
  536. //DBG::_(true, true, 'idLicence', $idLicence, __CLASS__, __FUNCTION__, __LINE__);
  537. $appLicenceInfo = (object)$this->fetchAppLicenceInfo($idLicence);
  538. $appLicenceInfo->domains = $this->fetchDomainsByLicenceId($idLicence);
  539. $installRootPath = '/Library/Server/Web/Data/Sites/Default/PLIKI/SES_PROCESY5_A';
  540. $appLicenceInfo->installFolderName = "{$idLicence}_upgrade_SE_source_encrypted";
  541. $appLicenceInfo->configFolderName = "{$idLicence}_upgrade_SE_config_encrypted";
  542. $appLicenceInfo->installPath = "{$installRootPath}/{$appLicenceInfo->installFolderName}";
  543. $appLicenceInfo->configPath = "{$installRootPath}/{$appLicenceInfo->configFolderName}";
  544. //DBG::_(true, true, 'appLicenceInfo', $appLicenceInfo, __CLASS__, __FUNCTION__, __LINE__);
  545. if (empty($appLicenceInfo->domains)) throw new Exception("Domains not found."); // TODO: mv to validate
  546. $appLicenceInfo->installFolderExists = file_exists("{$appLicenceInfo->installPath}/SE");
  547. $appLicenceInfo->installFolderGitExists = file_exists("{$appLicenceInfo->installPath}/.git");
  548. // 'user' => $ADMIN_USERNAME_DIRECTORY,
  549. // 'pass' => $ADMIN_USERNAME_PASSWD,
  550. // 'base_dn' => $SERVER_ADDRESS_LDAP_DC,
  551. $appLicenceInfo->projects = []; // TODO: get from db
  552. if (!empty($appLicenceInfo->projects)) {
  553. $appLicenceInfo->projects = [ $appLicenceInfo->project ];
  554. }
  555. else if (79 == $idLicence) { // bravecom.procesy5.pl
  556. $appLicenceInfo->projects = [ 'bravecare' ];
  557. } else if (80 == $idLicence) { // bravecom.yellowgroup.pl
  558. $appLicenceInfo->projects = [ 'bocian' ];
  559. } else if (81 == $idLicence) { // bocian.procesy5.pl
  560. $appLicenceInfo->projects = [ 'bocian' ];
  561. } else if (67 == $idLicence) { // bocian.procesy5.pl
  562. $appLicenceInfo->projects = [ 'bocian' ];
  563. } else if (82 == $idLicence) { // bocian-energa.procesy5.pl
  564. $appLicenceInfo->projects = [ 'bocian' ];
  565. } else if (4 == $idLicence) { // bzyk.procesy5.pl
  566. $appLicenceInfo->projects = [ 'bocian' ];
  567. }
  568. return $appLicenceInfo;
  569. }
  570. public function validateAppLicenceInfo($appLicenceInfo) {
  571. if (empty($appLicenceInfo->ID)) throw new Exception("Nie wybrano serwera/licencji.");
  572. if (empty($appLicenceInfo->domains)) throw new Exception("Domains not found");
  573. if (empty($appLicenceInfo->installPath)) throw new Exception("Install path not found");
  574. }
  575. public function generateApp($installPath, $domains, $projects = []) {
  576. $cmds = array();
  577. $cmds[] = "if [ -d {$installPath} ] ; then rm -rf '{$installPath}'; fi";
  578. $cmds[] = "mkdir {$installPath}";
  579. $cmds[] = "cd {$installPath} && git clone --depth 1 ssh://git@biuro.biall-net.pl:2222/plabudda/se.git .";
  580. $cmds[] = "cd {$installPath} && echo `git show-ref --head|head -1|head -c 8` > SE/VERSION ";
  581. foreach ($cmds as $cmd) {
  582. V::exec($cmd, $out, $ret);
  583. DBG::nicePrint([ 'cmd' => $cmd, 'output' => $out ], "return: {$ret}");
  584. }
  585. foreach ($projects as $projectName) {
  586. $cmd = "ls -l SE/projects/{$projectName} | wc -l";
  587. V::exec("cd {$installPath} && {$cmd}", $out, $ret);
  588. DBG::nicePrint([ 'cmd' => $cmd, 'output' => $out ], "return: {$ret}");
  589. if (!empty($out) && '0' !== trim($out[0])) {
  590. // $cmd = "git submodule update SE/projects/{$projectName}";
  591. $cmd = "cd SE/projects/{$projectName} && git reset --hard"; // revert encode source - checkout to last commit (need update)
  592. V::exec("cd {$installPath} && {$cmd}", $out, $ret);
  593. DBG::nicePrint([ 'cmd' => $cmd, 'output' => $out ], "return: {$ret}");
  594. }
  595. $cmd = "git submodule update --init SE/projects/{$projectName}"; // checkout to current commit
  596. V::exec("cd {$installPath} && {$cmd}", $out, $ret);
  597. DBG::nicePrint([ 'cmd' => $cmd, 'output' => $out ], "return: {$ret}");
  598. }
  599. $this->_encodeSource($installPath, $domains);
  600. // 1763: $exec='cd '.$installer_dir.' && /Applications/SourceGuardian.app/Contents/MacOS/sgencoder -b-
  601. // '.INSTALL_SES_PROCESY_A::get_same_domains_for_install($h->SERVER_ADDRESS_SHORT).'
  602. // -r *.php
  603. // -x superedit-DB_PROCEDURES_CREATE.php
  604. // -x INI.php
  605. // -x .config_base_structure.php
  606. // ';
  607. //
  608. // INSTALL_SES_PROCESY_A::get_same_domains_for_install($h->SERVER_ADDRESS_SHORT):
  609. // $res2=DB::query("select SERVER_ADDRESS_SHORT from SES_PROCESY5_A where SERVER_ADDRESS_IP='".$h->SERVER_ADDRESS_IP."'");
  610. // while($h2=DB::fetch($res2)) {
  611. // $domain[]=' --domain '.$h2->SERVER_ADDRESS_SHORT;
  612. // ssh server@biuro.galeriaprzymorze.eu: PHP 5.5.20
  613. // ssh server@biuro.biall-net.pl
  614. // cd /Users/plabudda/procesy5-install-galeriaprzymorze.eu/
  615. // sudo chown -R server:admin SE/
  616. // /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
  617. }
  618. public function fetchActiveLicences() {
  619. $activeLic = array();
  620. $sql = "
  621. select l.`ID`
  622. , l.`SERVER_ADDRESS`
  623. , l.`SERVER_ADDRESS_SHORT` as domain -- domain for sgencoder
  624. , l.`SERVER_ADDRESS_IP`
  625. from `SES_PROCESY5_A` l
  626. where 1=1
  627. -- TODO: and l.`A_STATUS` in('NORMAL','WAITING')
  628. order by l.`ID` DESC
  629. ";
  630. $rows = DB::getPDO()->fetchAll($sql);
  631. foreach ($rows as $row) {
  632. $r = (object)$row;
  633. $activeLic[$r->ID] = $r;
  634. }
  635. return $activeLic;
  636. }
  637. public function fetchDomainsByLicenceId($licenceId) {
  638. $domains = array();
  639. $sql = "
  640. select g.`SERVER_ADDRESS_SHORT`, g.`SERVER_ADDRESS`
  641. from `SES_PROCESY5_A` g
  642. where g.`SERVER_ADDRESS_IP`=(select l.`SERVER_ADDRESS_IP`
  643. from `SES_PROCESY5_A` l
  644. where l.`ID`='{$licenceId}'
  645. -- TODO: and l.`A_STATUS` in('NORMAL','WAITING')
  646. )
  647. -- TODO: and g.`A_STATUS` in('NORMAL','WAITING')
  648. ";
  649. $rows = DB::getPDO()->fetchAll($sql);
  650. foreach ($rows as $row) {
  651. $r = (object)$row;
  652. $domains[] = $r->SERVER_ADDRESS_SHORT;
  653. if ($r->SERVER_ADDRESS != $r->SERVER_ADDRESS_SHORT) {
  654. $domains[] = $r->SERVER_ADDRESS;
  655. }
  656. }
  657. return $domains;
  658. }
  659. public function fetchMainServerByLicenceId($licenceId) {
  660. return DB::getPDO()->fetchValue("
  661. select g.`SERVER_ADDRESS`
  662. from `SES_PROCESY5_A` g
  663. where g.`ID`='{$licenceId}'
  664. -- TODO: and g.`A_STATUS` in('NORMAL','WAITING')
  665. ");
  666. }
  667. public function fetchAppLicenceInfo($licenceId) {
  668. $licenceInfo = null;
  669. $sql = "
  670. select g.ID
  671. , g.SERVER_ADDRESS as mainServer
  672. , g.ADMIN_USERNAME as rootLogin
  673. , g.ADMIN_USERNAME_PASSWD as rootPassword
  674. , g.SSH_PORT as sshPort
  675. , g.VERSION_GIT as project
  676. , g.ADMIN_USERNAME_DIRECTORY as ldapUser
  677. , g.ADMIN_USERNAME_PASSWD as ldapPass
  678. , g.SERVER_ADDRESS_LDAP_DC as ldapBaseDN
  679. from SES_PROCESY5_A g
  680. where g.`ID`=:id_licence
  681. -- TODO: and g.A_STATUS in('NORMAL','WAITING')
  682. ";
  683. $all = DB::getPDO()->fetchAll($sql, [ ':id_licence' => $licenceId ]);
  684. if (empty($all)) throw new Exception("Brak licencji o nr '{$licenceId}'");
  685. $licenceInfo = reset($all);
  686. if (!$licenceInfo['sshPort']) $licenceInfo['sshPort'] = 22;
  687. return $licenceInfo;
  688. }
  689. public function _endWithException($e) {
  690. echo UI::h('div', ['class'=>"container"], [
  691. UI::h('div', ['class' => "alert alert-danger"], "#" . $e->getLine() . ": " . $e->getMessage()),
  692. UI::h('p', [], [
  693. "Wróć do ",
  694. UI::h('a', ['href'=>"index.php?_route=Install"], "menu")
  695. ])
  696. ]);
  697. UI::dol();
  698. exit;
  699. }
  700. public function sendToRemoteTestDirAction() {
  701. session_write_close();
  702. $args = array();
  703. $args['licence_id'] = V::get('licence_id', 0, $_REQUEST, 'int');
  704. UI::gora();
  705. //UI::menu();
  706. //$this->menu($args['licence_id']);// TODO: GO BACK BTN
  707. try {
  708. $appLicenceInfo = $this->getAppLicenceInfo($args['licence_id']);
  709. $this->validateAppLicenceInfo($appLicenceInfo);
  710. // TODO: if (59 ) => baratosz.sledz - na lokalnym kompie
  711. // bn:~/$ scp -r SE server@192.168.61.153:~/se.encrypted.upgrade
  712. // remote SE.git = '/Users/bartoszsledz/Desktop/production-se'
  713. // remote:~/$ mv SE ~/SE.bup.2017-07-03
  714. // remote:~/$ mv ~/se.encrypted.upgrade/SE SE
  715. // remote:~/$ cp -r ~/SE.bup.2017-07-03/config SE/
  716. // remote:~/$ sudo chown -R bartoszsledz:staff SE/
  717. $this->_sendToRemoteTestDir($appLicenceInfo);
  718. echo "Test online: ";
  719. echo UI::h('a', ['target'=>"_blank", 'href'=>"https://{$appLicenceInfo->mainServer}/se.encrypted.upgrade/"], "https://{$appLicenceInfo->mainServer}/se.encrypted.upgrade/");
  720. } catch (Exception $e) {
  721. $this->_endWithException($e);
  722. }
  723. UI::dol();
  724. }
  725. public function _fetchRemoteHomeDir($appLicenceInfo) {
  726. $this->_assertRsaKeyExists($appLicenceInfo);
  727. $sshHostUsr = "{$appLicenceInfo->rootLogin}@{$appLicenceInfo->mainServer}";
  728. $sshArgs = (22 != $appLicenceInfo->sshPort)? "-p {$appLicenceInfo->sshPort}" : '';
  729. $scpArgs = (22 != $appLicenceInfo->sshPort)? "-P {$appLicenceInfo->sshPort}" : '';
  730. $rsyncSshPort = (22 != $appLicenceInfo->sshPort)? "-e 'ssh -p {$appLicenceInfo->sshPort}'" : '';
  731. if (V::get('DBG_REMOTE', '', $_GET)) {// DBG
  732. $cmd = "echo ~";
  733. V::exec("ssh {$sshArgs} {$sshHostUsr} '{$cmd}'", $out, $ret);
  734. DBG::log([ 'cmd-remote' => $cmd, 'output' => $out ], 'array', "return: {$ret}");
  735. V::execRemote($appLicenceInfo->mainServer, $appLicenceInfo->rootLogin, $appLicenceInfo->rootPassword, $cmd, $out, $ret, $appLicenceInfo->sshPort);
  736. DBG::log([ 'cmd-remote' => $cmd, 'output' => $out ], 'array', "return: {$ret}");
  737. V::execRootRemote($appLicenceInfo->mainServer, $appLicenceInfo->rootLogin, $appLicenceInfo->rootPassword, $cmd, $out, $ret, $appLicenceInfo->sshPort);
  738. DBG::log([ 'cmd-remote' => $cmd, 'output' => $out ], 'array', "return: {$ret}");
  739. }
  740. $cmd = "echo ~";
  741. V::exec("ssh {$sshArgs} {$this->sshArgsSkipHostKey} {$sshHostUsr} '{$cmd}'", $out, $ret);
  742. DBG::log([ 'cmd-remote' => $cmd, 'output' => $out ], 'array', "return: {$ret}");
  743. if (empty($out) || empty($out[0])) throw new Exception("Cannot fetch remote home dir");
  744. return $out[0];
  745. }
  746. public function _sendToRemoteTestDir($appLicenceInfo) {
  747. $cmd = ''; $out = ''; $ret = '';
  748. $dryRunOnly = (V::get('dry-run', '', $_REQUEST)) ? "--dry-run" : "";
  749. $this->_assertRsaKeyExists($appLicenceInfo);
  750. $sshHostUsr = "{$appLicenceInfo->rootLogin}@{$appLicenceInfo->mainServer}";
  751. $sshArgs = (22 != $appLicenceInfo->sshPort)? "-p {$appLicenceInfo->sshPort}" : '';
  752. $rsyncSshPort = (22 != $appLicenceInfo->sshPort)? "-e 'ssh -p {$appLicenceInfo->sshPort}'" : '';
  753. $scpArgs = (22 != $appLicenceInfo->sshPort)? "-P {$appLicenceInfo->sshPort}" : '';
  754. // $appLicenceInfo->sshPort
  755. /* rsync options:
  756. -a, --archive archive mode; same as -rlptgoD (no -H)
  757. -u, --update skip files that are newer on the receiver
  758. -t, --times preserve times
  759. --delete delete extraneous files from dest dirs
  760. */
  761. $remoteDir = $this->_fetchRemoteHomeDir($appLicenceInfo);
  762. DBG::log($remoteDir, 'array', "remote home dir:");
  763. $cmd = "
  764. ssh {$sshArgs} {$this->sshArgsSkipHostKey} {$sshHostUsr} '[ ! -d ~/se.encrypted.upgrade ] && mkdir ~/se.encrypted.upgrade || echo 1';
  765. ssh {$sshArgs} {$this->sshArgsSkipHostKey} {$sshHostUsr} 'rm -rf ~/se.encrypted.upgrade/SE';
  766. ssh {$sshArgs} {$this->sshArgsSkipHostKey} {$sshHostUsr} 'cp -r /Library/Server/Web/Data/Sites/Default/SE ~/se.encrypted.upgrade/SE';
  767. ssh {$sshArgs} {$this->sshArgsSkipHostKey} {$sshHostUsr} 'rm -rf ~/se.encrypted.upgrade/SE/config';
  768. rsync --archive --times --delete --compress --one-file-system --omit-dir-times --no-g --no-perms {$dryRunOnly} \
  769. --verbose {$rsyncSshPort} \
  770. --exclude='schema/default_db.instance.xml' \
  771. --exclude='schema/default_db.instance.xml/**' \
  772. '{$appLicenceInfo->installPath}/SE/' {$sshHostUsr}:~/se.encrypted.upgrade/SE/;
  773. ssh {$sshArgs} {$this->sshArgsSkipHostKey} {$sshHostUsr} 'cp -r /Library/Server/Web/Data/Sites/Default/SE/config ~/se.encrypted.upgrade/SE/';
  774. ssh {$sshArgs} {$this->sshArgsSkipHostKey} {$sshHostUsr} 'rm /Library/Server/Web/Data/Sites/Default/se.encrypted.upgrade'
  775. ssh {$sshArgs} {$this->sshArgsSkipHostKey} {$sshHostUsr} 'ln -s ~/se.encrypted.upgrade/SE /Library/Server/Web/Data/Sites/Default/se.encrypted.upgrade'
  776. scp {$this->sshArgsSkipHostKey} {$scpArgs} /Library/Server/Web/Data/Sites/SE-production-git/SE/config/.config_base_structure.php {$sshHostUsr}:
  777. ssh {$sshArgs} {$this->sshArgsSkipHostKey} {$sshHostUsr} 'mv ~/.config_base_structure.php /Library/Server/Web/Data/Sites/Default/se.encrypted.upgrade/config'
  778. "; //todo rsync ... -e \"{$this->sshArgsSkipHostKey}\" - maybe not working
  779. // --exclude='schema/default_db_xml_cache.public' \
  780. // --exclude='stuff' \
  781. // --exclude='stuff/**' \
  782. //--exclude='schema/default_db_xml_cache.public/**' \
  783. V::exec("$cmd 2>&1", $out, $ret);
  784. DBG::log([ 'cmd-remote' => $cmd, 'output' => $out ], 'array', "return: {$ret}");
  785. if (0 !== $ret) throw new Exception("Cannot run remote command using rsa key! #{$ret}. cmd: {$cmd} . out: {$out}");
  786. }
  787. public function upgradeRemoteFromTestDirAction() {
  788. session_write_close();
  789. $args = array();
  790. $args['licence_id'] = V::get('licence_id', 0, $_REQUEST, 'int');
  791. UI::gora();
  792. //UI::menu();
  793. //$this->menu($args['licence_id']);// TODO: GO BACK BTN
  794. try {
  795. $appLicenceInfo = $this->getAppLicenceInfo($args['licence_id']);
  796. $this->validateAppLicenceInfo($appLicenceInfo);
  797. $this->_upgradeRemoteFromTestDir($appLicenceInfo);
  798. echo "Test online: ";
  799. echo UI::h('a', ['target'=>"_blank", 'href'=>"https://{$appLicenceInfo->mainServer}/SE/"], "https://{$appLicenceInfo->mainServer}/SE/");
  800. } catch (Exception $e) {
  801. $this->_endWithException($e);
  802. }
  803. UI::dol();
  804. }
  805. public function _upgradeRemoteFromTestDir($appLicenceInfo) {
  806. $cmd = ''; $out = ''; $ret = '';
  807. $this->_assertRsaKeyExists($appLicenceInfo);
  808. $dateStr = date("Y-m-d_H-i-s");
  809. // $remoteHomeDir = "/Users/{$appLicenceInfo->rootLogin}";// BUG: alias like in ams - login = prezes is alias for arkadiuszbinder
  810. $remoteHomeDir = $this->_fetchRemoteHomeDir($appLicenceInfo);
  811. $cmd = "
  812. rm -rf /Library/Server/Web/Data/Sites/Default/SE.test 2>&1
  813. cp -r {$remoteHomeDir}/se.encrypted.upgrade/SE /Library/Server/Web/Data/Sites/Default/SE.test 2>&1
  814. [ ! -d {$remoteHomeDir}/bup.se.upgrade ] && mkdir {$remoteHomeDir}/bup.se.upgrade || echo 1
  815. [ ! -d {$remoteHomeDir}/bup.se.upgrade ] && exit 1
  816. [ ! -d {$remoteHomeDir}/bup.se.upgrade-testttttt ] && exit 1
  817. [ ! -f /Library/Server/Web/Data/Sites/Default/SE.test/VERSION ] && echo \"Error: plik VERSION nie istnieje\" || echo \"check VERSION OK\"
  818. [ ! -f /Library/Server/Web/Data/Sites/Default/SE.test/VERSION ] && exit 1
  819. [ ! -f /Library/Server/Web/Data/Sites/Default/SE.test/index.php ] && echo \"Error: plik index.php nie istnieje\" || echo \"check index.php OK\"
  820. [ ! -f /Library/Server/Web/Data/Sites/Default/SE.test/index.php ] && exit 1
  821. [ ! -d /Library/Server/Web/Data/Sites/Default/SE.test/se-lib ] && echo \"Error: plik se-lib nie istnieje\" || echo \"check se-lib OK\"
  822. [ ! -d /Library/Server/Web/Data/Sites/Default/SE.test/se-lib ] && exit 1
  823. exit 0
  824. ";
  825. V::execRootRemote($appLicenceInfo->mainServer, $appLicenceInfo->rootLogin, $appLicenceInfo->rootPassword, $cmd, $out, $ret, $appLicenceInfo->sshPort);
  826. $cmd = "
  827. mv /Library/Server/Web/Data/Sites/Default/SE {$remoteHomeDir}/bup.se.upgrade/bup.{$dateStr} 2>&1
  828. mv /Library/Server/Web/Data/Sites/Default/SE.test /Library/Server/Web/Data/Sites/Default/SE 2>&1
  829. exit 0
  830. ";
  831. V::execRootRemote($appLicenceInfo->mainServer, $appLicenceInfo->rootLogin, $appLicenceInfo->rootPassword, $cmd, $out, $ret, $appLicenceInfo->sshPort);
  832. DBG::_(true, true, "cmd: {$cmd} (return: {$ret})", $out, __CLASS__, __FUNCTION__, __LINE__);
  833. if (0 !== $ret) throw new Exception("Cannot run remote command as root! #{$ret}");
  834. // TODO: SE/bash_install_check.php requires $domain!
  835. // $cmd = "/usr/bin/php /Library/Server/Web/Data/Sites/Default/SE/bash_install_check.php {$domain}";
  836. // V::execRootRemote($appLicenceInfo->mainServer, $appLicenceInfo->rootLogin, $appLicenceInfo->rootPassword, $cmd, $out, $ret, $appLicenceInfo->sshPort);
  837. // DBG::_(true, true, "cmd: {$cmd} (return: {$ret})", $out, __CLASS__, __FUNCTION__, __LINE__);
  838. // if (0 !== $ret) throw new Exception("Cannot run remote command as root! #{$ret}");
  839. }
  840. public function _assertRsaKeyExists($appLicenceInfo) {
  841. $cmd = ''; $out = ''; $ret = '';
  842. $cmd = "echo ~ && pwd";// /Library/WebServer
  843. $cmd = "ls -1 ~/.ssh/";
  844. //$cmd = "rm /tmp/id_rsa";
  845. //$cmd = "rm /tmp/id_rsa.pub";
  846. //$cmd = "ssh-keygen -t rsa -N '' -C '_www@biuro.biall-net.pl' -f /tmp/id_rsa";
  847. //$cmd = "ssh-keygen -t rsa -N '' -C '_www@biuro.biall-net.pl' -f /tmp/id_rsa";
  848. V::exec($cmd, $out, $ret);
  849. DBG::_(true, true, "cmd: {$cmd} (return: {$ret})", $out, __CLASS__, __FUNCTION__, __LINE__);
  850. if (0 !== $ret) {// no ~/.ssh directory
  851. $rsaKeyPath = "~/.ssh";
  852. $cmds = array();
  853. $cmds[] = "mkdir {$rsaKeyPath}";
  854. $cmds[] = "ssh-keygen -t rsa -N '' -C '_www@biuro.biall-net.pl' -f {$rsaKeyPath}/id_rsa 2>&1";
  855. $cmds[] = "ls -1 $rsaKeyPath";
  856. foreach ($cmds as $cmd) {
  857. V::exec($cmd, $out, $ret);
  858. DBG::_(true, true, "cmd: {$cmd} (return: {$ret})", $out, __CLASS__, __FUNCTION__, __LINE__);
  859. if (0 !== $ret) throw new Exception("Error '{$ret}' cmd({$cmd}): " . implode("\n", $out));
  860. }
  861. }
  862. $cmd = "cat ~/.ssh/id_rsa.pub";
  863. V::exec($cmd, $out, $ret);
  864. DBG::_(true, true, "cmd: {$cmd} (return: {$ret})", $out, __CLASS__, __FUNCTION__, __LINE__);
  865. if (0 !== $ret || empty($out) || empty($out[0])) throw new Exception("Cannot read rsa public key");
  866. $rsaPubKey = $out[0];
  867. $cmd = 'ls -1a';
  868. $cmd = "
  869. [ ! -d ~/.ssh ] && mkdir ~/.ssh;
  870. [ ! -d ~/.ssh ] && echo 'ERROR ~/.ssh not exists and cannot be created';
  871. [ ! -f ~/.ssh/authorized_keys ] && echo '{$rsaPubKey}' > ~/.ssh/authorized_keys;
  872. [ ! -f ~/.ssh/authorized_keys ] && echo 'ERROR ~/.ssh/authorized_keys not exists and cannot be created';
  873. cat ~/.ssh/authorized_keys| grep '{$rsaPubKey}' && echo 'OK' || echo '{$rsaPubKey}' >> ~/.ssh/authorized_keys;
  874. chmod 600 ~/.ssh/authorized_keys;
  875. ";
  876. V::execRemote($appLicenceInfo->mainServer, $appLicenceInfo->rootLogin, $appLicenceInfo->rootPassword, $cmd, $out, $ret, $appLicenceInfo->sshPort);
  877. DBG::_(true, true, "remote cmd: {$cmd} (return: {$ret})", $out, __CLASS__, __FUNCTION__, __LINE__);
  878. //$cmd = "ssh server@{$appLicenceInfo->mainServer} 'ls -1 .ssh/'";
  879. //$cmd = "ssh -i ~/.ssh/id_rsa server@{$appLicenceInfo->mainServer} 'ls -1'";
  880. $sshPort = (22 != $appLicenceInfo->sshPort)? "-p {$appLicenceInfo->sshPort}" : '';
  881. $cmd = "ssh {$sshPort} {$this->sshArgsSkipHostKey} {$appLicenceInfo->rootLogin}@{$appLicenceInfo->mainServer} 'ls -1'";
  882. 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,
  883. //and deduced that the solution was to
  884. //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.
  885. //But it seems to be the only solution (suggestions are welcome).
  886. DBG::_(true, true, "cmd: {$cmd} (return: {$ret})", $out, __CLASS__, __FUNCTION__, __LINE__);
  887. if (0 !== $ret) throw new Exception("Cannot run remote command using rsa key! #{$ret}; Out: ".implode($out)."; Cmd: {$cmd};");
  888. }
  889. public function newGenerateApp($appLicenceInfo) {
  890. if (empty($appLicenceInfo->ID)) throw new Exception("Nie wybrano serwera/licencji.");
  891. if (empty($appLicenceInfo->domains)) throw new Exception("Domains not found");
  892. $installPath = $appLicenceInfo->installPath;
  893. if (empty($installPath)) throw new Exception("Install path not found");
  894. $installPath .= '-p5';
  895. $cmds = array();
  896. $cmds[] = "if [ -d {$installPath} ] ; then rm -rf '{$installPath}'; fi";
  897. $cmds[] = "mkdir {$installPath}";
  898. $cmds[] = "cd {$installPath} && git clone --depth 1 ssh://git@biuro.biall-net.pl:2222/p5/p5.git .";
  899. $cmds[] = "cd {$installPath} && echo `git show-ref --head|head -1|head -c 8` > SE/VERSION ";
  900. // TODO: fetch from DB
  901. {
  902. foreach ($appLicenceInfo->projects as $projectName) {
  903. $cmds[] = "cd {$installPath} && git submodule update --init SE/projects/{$projectName}";
  904. }
  905. }
  906. foreach ($cmds as $cmd) {
  907. $out = ''; $ret = '';
  908. V::exec($cmd, $out, $ret);
  909. DBG::nicePrint([ 'cmd' => $cmd, 'output' => $out ], "return: {$ret}");
  910. }
  911. // $this->_encodeSource($appLicenceInfo->installPath, $appLicenceInfo->domains);
  912. }
  913. }