Install.php 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812
  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 handleAuth() {
  7. if (!User::logged()) {
  8. throw new HttpException('Unauthorized', 401);
  9. }
  10. if (!User::isAdmin()) {
  11. throw new HttpException('Unauthorized - only for administrators', 401);
  12. }
  13. }
  14. public function defaultAction() {
  15. UI::gora();
  16. UI::menu();
  17. $this->menu();
  18. UI::setTitleJsTag("Install");
  19. UI::dol();
  20. }
  21. public function menu() {
  22. $serversList = $this->fetchActiveLicences();
  23. ?>
  24. <div class="jumbotron">
  25. <div class="container">
  26. <form class="form-inline" method="GET">
  27. <input type="hidden" name="_route" value="Install" />
  28. <input type="hidden" name="_task" value="createApp" />
  29. <label>Przygotuj kod źródłowy do aktualizacji na serwerze klienta:</label>
  30. <select id="servers_list" class="form-control" name="licence_id">
  31. <?php foreach ($serversList as $srv) : ?>
  32. <option value="<?php echo $srv->ID; ?>">[<?php echo $srv->ID; ?>] <?php echo $srv->domain; ?></option>
  33. <?php endforeach; ?>
  34. </select>
  35. <button type="submit" id="fldSbmtBtn" class="btn btn-primary" autocomplete="off">
  36. Generuj
  37. </button>
  38. <div id="servers_list_react"></div>
  39. </form>
  40. </div>
  41. </div>
  42. <script type="text/javascript">
  43. jQuery(document).ready(function () {
  44. jQuery('#fldSbmtBtn').on('click', function () {
  45. jQuery(this).text(jQuery(this).text() + '...').attr('disabled', 'disabled');
  46. jQuery(this).parent().submit();
  47. })
  48. });
  49. </script>
  50. <?php
  51. echo UI::h('script', ['src'=>"static/vendor.js", 'type'=>"text/javascript"]);
  52. // echo UI::h('script', ['src'=>"https://cdnjs.cloudflare.com/ajax/libs/react/15.4.2/react.js", 'type'=>"text/javascript"]);
  53. // echo UI::h('script', ['src'=>"https://cdnjs.cloudflare.com/ajax/libs/react/15.4.2/react-dom.js", 'type'=>"text/javascript"]);
  54. // echo UI::h('script', ['src'=>"https://cdnjs.cloudflare.com/ajax/libs/react-bootstrap-typeahead/0.10.4/react-bootstrap-typeahead.js", 'type'=>"text/javascript"]);
  55. $jsonServersList = array_values(array_map(
  56. function ($srv) {
  57. return [
  58. 'id' => $srv->ID,
  59. 'label' => "{$srv->domain} [{$srv->ID}]"
  60. ];
  61. },
  62. $serversList
  63. ));
  64. echo UI::h('script', ['type'=>"text/javascript"], "
  65. (function(global){
  66. if (!global.p5VendorJs) { console.warn('Brak p5VendorJs'); return; }
  67. if (!global.p5VendorJs.React) { console.warn('Brak p5VendorJs.React'); return; }
  68. if (!global.p5VendorJs.ReactDOM) { console.warn('Brak p5VendorJs.ReactDOM'); return; }
  69. if (!global.p5VendorJs.Typeahead) { console.warn('Brak p5VendorJs.Typeahead'); return; }
  70. const React = global.p5VendorJs.React;
  71. const ReactDOM = global.p5VendorJs.ReactDOM;
  72. const Typeahead = global.p5VendorJs.Typeahead;
  73. var options = ".json_encode($jsonServersList).";
  74. var selected = [];
  75. var onInputChange = function (query) {
  76. // console.log('onInputChange:: query', query);
  77. }
  78. var onChange = function (value) {
  79. // console.log('onChange:: value', value);
  80. if (value.length > 0) {
  81. var id = value[0]['id'];
  82. if (id > 0) {
  83. document.getElementById('servers_list').value = id;
  84. }
  85. }
  86. }
  87. ReactDOM.render(
  88. React.createElement(Typeahead, {
  89. options: options,
  90. emptyLabel: 'Brak danych',
  91. placeholder: 'Wybierz serwer',
  92. selected: selected,
  93. // onInputChange: onInputChange,
  94. onChange: onChange,
  95. }, null),
  96. document.getElementById('servers_list_react')
  97. );
  98. })(window);
  99. ");
  100. }
  101. public function createAppAction() {
  102. session_write_close();
  103. $args = array();
  104. $args['licence_id'] = V::get('licence_id', 0, $_REQUEST, 'int');
  105. UI::gora();
  106. UI::menu();
  107. UI::setTitleJsTag("Install");
  108. //$this->menu($args['licence_id']);// TODO: GO BACK BTN
  109. try {
  110. $appLicenceInfo = $this->getAppLicenceInfo($args['licence_id']);
  111. $this->validateAppLicenceInfo($appLicenceInfo);
  112. } catch (Exception $e) {
  113. $this->_endWithException($e);
  114. }
  115. // $this->generateApp($appLicenceInfo->installPath, $appLicenceInfo->domains);
  116. //DBG::_(true, true, "appLicenceInfo", $appLicenceInfo, __CLASS__, __FUNCTION__, __LINE__);
  117. if ('_generateEncryptedSource' === V::get('_postTask', '', $_POST)) {
  118. echo '<div class="container">';
  119. echo '<h4>' . "Generowanie..." . '</h4>';
  120. echo '<div style="border:1px solid silver; max-height:400px; overflow-y:scroll">';
  121. try {
  122. $this->validateAppLicenceInfo($appLicenceInfo);
  123. $this->generateApp($appLicenceInfo->installPath, $appLicenceInfo->domains);
  124. } catch (Exception $e) {
  125. echo '</div></div>';// .container/ scroll
  126. $this->_endWithException($e);
  127. }
  128. echo '</div>';// .container
  129. UI::alert('success', "<strong>Gotowe</strong> Aplikacja znajduje się w katalogu {$appLicenceInfo->installFolderName}");
  130. $appLicenceInfo = $this->getAppLicenceInfo($args['licence_id']);
  131. }
  132. if ('newGenerateApp' === V::get('_postTask', '', $_POST)) {
  133. $this->newGenerateApp($appLicenceInfo);
  134. }
  135. if ('updateAndSendToRemoteTestDir' === V::get('_postTask', '', $_POST)) {
  136. echo '<details><summary style="cursor:pointer">aktualizuj werjsę, szyfruj i wyślij do testowego katalogu na serwerze</summary>';
  137. try {
  138. $idLicence = V::get('licence_id', 0, $_POST, 'int');
  139. $appLicenceInfo = $this->getAppLicenceInfo($idLicence);
  140. $this->validateAppLicenceInfo($appLicenceInfo);
  141. $projects = [ 'bravecare' ]; // TODO: fetch from $appLicenceInfo->projects = [ ... ]
  142. $this->gitResetHard($appLicenceInfo->installPath, $projects);
  143. flush();
  144. $this->_encodeSource($appLicenceInfo->installPath, $appLicenceInfo->domains);
  145. flush();
  146. $this->_sendToRemoteTestDir($appLicenceInfo);
  147. } catch (Exception $e) {
  148. DBG::log($e);
  149. UI::alert('danger', $e->getMessage());
  150. }
  151. echo '</details>';
  152. $testDirUrl = "https://{$appLicenceInfo->mainServer}/se.encrypted.upgrade/";
  153. UI::alert('info', UI::h('p', [], [
  154. "testowy katalog zaktualizowany - ",
  155. UI::h('a', [ 'href' => $testDirUrl, 'target' => "_blank" ], $testDirUrl),
  156. ]));
  157. flush();
  158. }
  159. // echo UI::hButtonPost("TODO: Generuj z p5.git", [
  160. // 'class' => "btn btn-md btn-primary",
  161. // 'data' => [
  162. // '_postTask' => "newGenerateApp",
  163. // 'licence_id' => $appLicenceInfo->ID,
  164. // ],
  165. // ]);
  166. echo UI::h('div', [ 'class' => "jumbotron" ], [
  167. UI::h('div', [ 'class' => "container" ], [
  168. UI::h('h3', [], "Generowanie aplikacji dla licencji {$appLicenceInfo->ID}"),
  169. UI::h('p', [], "Licencja dla domen: " . implode(', ', $appLicenceInfo->domains)),
  170. UI::h('p', [], "Katalog z zakodowanymi plikami: {$appLicenceInfo->installFolderName}"),
  171. UI::hButtonPost("Generuj", [
  172. 'class' => "btn btn-primary",
  173. 'data' => [
  174. '_postTask' => '_generateEncryptedSource',
  175. 'licence_id' => $appLicenceInfo->ID,
  176. ]
  177. ]),
  178. (!$appLicenceInfo->installFolderGitExists)
  179. ? UI::h('div', [ 'class' => "alert alert-info" ], "Katalog nie istnieje - wygeneruj aplikację")
  180. : UI::h('div', [ 'class' => "alert alert-info", 'style' => "margin-top:10px" ], [
  181. UI::h('p', [], "Katalog istnieje i zawiera już repozytorium git: "),
  182. UI::h('p', [], [
  183. UI::hButtonPost("aktualizuj werjsę, szyfruj i wyślij do testowego katalogu na serwerze", [
  184. 'class' => "btn btn-xs btn-primary",
  185. 'data' => [
  186. '_postTask' => "updateAndSendToRemoteTestDir",
  187. 'licence_id' => $appLicenceInfo->ID,
  188. ],
  189. ]),
  190. ]),
  191. UI::h('p', [ 'style' => "margin-left:20px" ], [
  192. UI::h('a', [
  193. 'href' => "index.php?_route=Install&_task=gitResetHard&licence_id={$appLicenceInfo->ID}",
  194. 'target' => "_blank",
  195. 'class' => "btn btn-xs btn-default"
  196. ], "aktualizuj werjsę</a> (git reset --hard, git pull, set SE/VERSION - tak samo co 'rm -rf; git clone', ale szybciej)"),
  197. ]),
  198. UI::h('p', [ 'style' => "margin-left:20px" ], [
  199. UI::h('a', [
  200. 'href' => "index.php?_route=Install&_task=encodeSource&licence_id={$appLicenceInfo->ID}",
  201. 'target' => "_blank",
  202. 'class' => "btn btn-xs btn-default"
  203. ], "encode files"),
  204. ]),
  205. UI::h('p', [ 'style' => "margin-left:20px" ], [
  206. UI::h('a', [
  207. 'href' => "index.php?_route=Install&_task=sendToRemoteTestDir&licence_id={$appLicenceInfo->ID}",
  208. 'target' => "_blank",
  209. 'class' => "btn btn-xs btn-default"
  210. ], "send encoded files to remote server test folder (generates ssh key if not set)"),
  211. ]),
  212. UI::h('p', [ 'style' => "margin-top:30px" ], [
  213. "Test online: ",
  214. UI::h('a', [
  215. 'target' => "_blank",
  216. 'href' => "https://{$appLicenceInfo->mainServer}/se.encrypted.upgrade/"
  217. ], "https://{$appLicenceInfo->mainServer}/se.encrypted.upgrade/"),
  218. ]),
  219. "<br> - ",
  220. UI::h('a', [
  221. 'href' => "index.php?_route=Install&_task=upgradeRemoteFromTestDir&licence_id={$appLicenceInfo->ID}",
  222. 'onclick' => "return confirm('Uruchomić aktualizację SE na https://{$appLicenceInfo->mainServer}/SE/?')",
  223. 'target' => "_blank",
  224. 'class' => "btn btn-xs btn-warning"
  225. ], "UPGRADE Production folder from uploaded dir: ~/se.encrypted.upgrade/"),
  226. ]),
  227. ]),
  228. ]);
  229. ?>
  230. <script type="text/javascript">
  231. jQuery(document).ready(function () {
  232. jQuery('#fldSbmtBtn').on('click', function () {
  233. jQuery(this).text(jQuery(this).text() + '...').attr('disabled', 'disabled');
  234. jQuery(this).parent().submit();
  235. })
  236. });
  237. </script>
  238. <?php
  239. UI::dol();
  240. }
  241. public function gitResetHardAction() {
  242. session_write_close();
  243. $args = array();
  244. $args['licence_id'] = V::get('licence_id', 0, $_REQUEST, 'int');
  245. UI::gora();
  246. UI::menu();
  247. //$this->menu($args['licence_id']);// TODO: GO BACK BTN
  248. try {
  249. $appLicenceInfo = $this->getAppLicenceInfo($args['licence_id']);
  250. $this->validateAppLicenceInfo($appLicenceInfo);
  251. UI::startContainer();
  252. $projects = [ 'bravecare' ]; // TODO: fetch from $appLicenceInfo->projects = [ ... ]
  253. $this->gitResetHard($appLicenceInfo->installPath, $projects);
  254. UI::endContainer();
  255. } catch (Exception $e) {
  256. $this->_endWithException($e);
  257. }
  258. UI::dol();
  259. }
  260. public function gitResetHard($installPath, $projects = []) {
  261. if (empty($installPath)) throw new Exception("Install path not found");
  262. $cmds = array();
  263. $cmds[] = "git reset --hard";
  264. $cmds[] = "git pull";
  265. $cmds[] = "echo `git show-ref --head|head -1|head -c 8` > SE/VERSION ";
  266. $hasError = false;
  267. foreach ($cmds as $cmd) {
  268. $out = ''; $ret = '';
  269. exec("cd {$installPath} && {$cmd}", $out, $ret);
  270. if (0 !== $ret) $hasError = true;
  271. DBG::nicePrint($out, "cmd: `{$cmd}` (return:{$ret})");
  272. }
  273. foreach ($projects as $projectName) {
  274. $cmd = "ls -l SE/projects/{$projectName} | wc -l";
  275. V::exec("cd {$installPath} && {$cmd}", $out, $ret);
  276. DBG::nicePrint([ 'cmd' => $cmd, 'output' => $out ], "return: {$ret}");
  277. if (!empty($out) && '0' !== trim($out[0])) {
  278. // $cmd = "git submodule update SE/projects/{$projectName}";
  279. $cmd = "cd SE/projects/{$projectName} && git reset --hard"; // revert encode source - checkout to last commit (need update)
  280. V::exec("cd {$installPath} && {$cmd}", $out, $ret);
  281. DBG::nicePrint([ 'cmd' => $cmd, 'output' => $out ], "return: {$ret}");
  282. }
  283. $cmd = "git submodule update --init SE/projects/{$projectName}"; // checkout to current commit
  284. V::exec("cd {$installPath} && {$cmd}", $out, $ret);
  285. DBG::nicePrint([ 'cmd' => $cmd, 'output' => $out ], "return: {$ret}");
  286. }
  287. if (!$hasError) {
  288. UI::alert('success', "OK");
  289. } else {
  290. UI::alert('danger', "errors");
  291. }
  292. }
  293. public function encodeSourceAction() {
  294. session_write_close();
  295. $args = array();
  296. $args['licence_id'] = V::get('licence_id', 0, $_REQUEST, 'int');
  297. UI::gora();
  298. UI::menu();
  299. //$this->menu($args['licence_id']);// TODO: GO BACK BTN
  300. try {
  301. $appLicenceInfo = $this->getAppLicenceInfo($args['licence_id']);
  302. $this->validateAppLicenceInfo($appLicenceInfo);
  303. $this->_encodeSource($appLicenceInfo->installPath, $appLicenceInfo->domains);
  304. } catch (Exception $e) {
  305. $this->_endWithException($e);
  306. }
  307. UI::dol();
  308. }
  309. public function _encodeSource($installPath, $domains) {
  310. UI::startContainer();
  311. $this->encodeSourceFiles($installPath, $domains, $dbg = true);
  312. // try {
  313. // $this->encodeSourceFiles($appLicenceInfo->installPath, $appLicenceInfo->domains, $dbg = false);
  314. // UI::alert('success', "OK");
  315. // } catch (Exception $e) {
  316. // UI::alert('danger', $e->getMessage());
  317. // }
  318. UI::endContainer();
  319. }
  320. // @usage: Router::getRoute('Install')->encodeSourceFiles($installPath = '/path_to_git_repo', $domains = [ 'domain.com', 'localhost' ], $dbg = false);
  321. public function encodeSourceFiles($installPath, $domains, $dbg = false) {
  322. if (empty($installPath)) throw new Exception("Install path not found");
  323. if (empty($domains)) throw new Exception("Domains not found");
  324. $phpVersionsForSgencoder = '--phpversion 5.5 --phpversion 5.6';// encode for PHP 5.x (currently supported PHP 5.0-5.6)
  325. if ('1' == V::get('DBG_ENCODER_HELP', '', $_REQUEST)) {// encoder help
  326. $cmd = "cd {$installPath}/SE && /Applications/SourceGuardian.app/Contents/MacOS/sgencoder --help ";
  327. $out = ''; $ret = '';
  328. exec($cmd, $out, $ret);
  329. DBG::nicePrint($out, "cmd: `{$cmd}` (return:{$ret})");
  330. exit;
  331. }
  332. $domainEncodePhpFiles = [
  333. 'ant.php',
  334. 'api.php',
  335. 'budynki.php',
  336. 'index-ajax.php',
  337. 'index.php',
  338. 'procesy5.php',
  339. 'session-expire.php',
  340. 'test-sync.php',
  341. 'wfs-data.php',
  342. 'wfs-qgis.php',
  343. 'wfs.php',
  344. ];
  345. $cmd = "find . -name '*.php' ";
  346. $out = ''; $ret = '';
  347. exec("cd {$installPath}/SE && {$cmd}", $out, $ret);
  348. if ($dbg) DBG::nicePrint($out, "cmd: `{$cmd}` (return:{$ret})");
  349. else DBG::log($out, 'array', "cmd: `{$cmd}` (return:{$ret})");
  350. if (0 !== $ret) throw new Exception("Error at find php files");
  351. if (empty($out)) throw new Exception("No php files found");
  352. $allPhpFiles = array_map(function ($phpFilePath) {
  353. return ('./' == substr($phpFilePath, 0, 2))? substr($phpFilePath, 2) : $phpFilePath;
  354. }, $out);
  355. $freeEncodePhpFiles = array_filter($allPhpFiles, function ($phpFilePath) use ($domainEncodePhpFiles) {
  356. if ('se-lib/Vendor/' === substr($phpFilePath, 0, strlen('se-lib/Vendor/'))) return false; // SKIP se-lib/Vendor/*
  357. if ('.ini.php' === substr($phpFilePath, -1 * strlen('.ini.php'))) return false; // SKIP *.ini.php
  358. return (!in_array($phpFilePath, $domainEncodePhpFiles));
  359. });
  360. DBG::log($freeEncodePhpFiles, 'array', "\$freeEncodePhpFiles");
  361. if (empty($freeEncodePhpFiles)) throw new Exception("No php files to encode");
  362. $cmdTempl = "cd {$installPath}/SE && /Applications/SourceGuardian.app/Contents/MacOS/sgencoder {$phpVersionsForSgencoder} -b- ";
  363. $cmdDomainEncodeDomainsTempl = " --domain " . implode(" --domain ", array_merge($domains, ['localhost']));
  364. $cmdDomainEncodeFilesTempl = " " . implode(" ", $domainEncodePhpFiles);
  365. $cmdFreeEncodeFilesTempl = " " . implode(" ", $freeEncodePhpFiles);
  366. $cmds = [
  367. $cmdTempl . $cmdDomainEncodeDomainsTempl . $cmdDomainEncodeFilesTempl,
  368. $cmdTempl . $cmdFreeEncodeFilesTempl,
  369. ];
  370. $returnValues = [];
  371. foreach ($cmds as $cmd) {
  372. $out = ''; $ret = '';
  373. exec($cmd, $out, $ret);
  374. $encoderSummaryLine = end($out);
  375. $returnValues[] = $encoderSummaryLine;
  376. if ($dbg) {
  377. DBG::nicePrint([$cmd], "cmd");
  378. DBG::nicePrint($out, "return: '{$ret}'");
  379. // DBG::nicePrint([$encoderSummaryLine], "cmd last line");
  380. }
  381. else DBG::log([$cmd, $out], 'array', "cmd return:'{$ret}'");
  382. // if (0 !== $ret) throw new Exception("Error at encode files");
  383. if (empty($out)) throw new Exception("No output for encode files command");
  384. }
  385. $statusInfo = array_reduce($returnValues, function ($ret, $encoderSummaryLine) {
  386. DBG::log([$ret, $encoderSummaryLine], 'array', "DBG reduce [\$ret, \$encoderSummaryLine]");
  387. $matches = [];
  388. preg_match_all('/(\d+) files, (\d+) processed, (\d+) errors/', $encoderSummaryLine, $matches, PREG_SET_ORDER, 0);
  389. return [
  390. 'files' => $ret['files'] + (int)$matches[0][1],
  391. 'processed' => $ret['processed'] + (int)$matches[0][2],
  392. 'errors' => $ret['errors'] + (int)$matches[0][3],
  393. ];
  394. }, [
  395. 'files' => 0,
  396. 'processed' => 0,
  397. 'errors' => 0,
  398. ]);
  399. if ($statusInfo['errors'] === 0 && $statusInfo['files'] > 0) {
  400. if ($dbg) UI::alert('success', "{$statusInfo['files']} files, {$statusInfo['processed']} processed, {$statusInfo['errors']} errors");
  401. } else {
  402. if ($dbg) UI::alert('danger', "{$statusInfo['files']} files, {$statusInfo['processed']} processed, {$statusInfo['errors']} errors");
  403. else throw new Exception("{$statusInfo['files']} files, {$statusInfo['processed']} processed, {$statusInfo['errors']} errors");
  404. }
  405. }
  406. public function getAppLicenceInfo($idLicence) {
  407. $idLicence = intval($idLicence);
  408. if (empty($idLicence)) throw new Exception("Nie wybrano serwera/licencji.");
  409. //DBG::_(true, true, 'idLicence', $idLicence, __CLASS__, __FUNCTION__, __LINE__);
  410. $appLicenceInfo = (object)$this->fetchAppLicenceInfo($idLicence);
  411. $appLicenceInfo->domains = $this->fetchDomainsByLicenceId($idLicence);
  412. $installRootPath = '/Library/Server/Web/Data/Sites/Default/PLIKI/SES_PROCESY5_A';
  413. $appLicenceInfo->installFolderName = "{$idLicence}_upgrade_SE_source_encrypted";
  414. $appLicenceInfo->installPath = "{$installRootPath}/{$appLicenceInfo->installFolderName}";
  415. //DBG::_(true, true, 'appLicenceInfo', $appLicenceInfo, __CLASS__, __FUNCTION__, __LINE__);
  416. if (empty($appLicenceInfo->domains)) throw new Exception("Domains not found."); // TODO: mv to validate
  417. $appLicenceInfo->installFolderExists = file_exists("{$appLicenceInfo->installPath}/SE");
  418. $appLicenceInfo->installFolderGitExists = file_exists("{$appLicenceInfo->installPath}/.git");
  419. return $appLicenceInfo;
  420. }
  421. public function validateAppLicenceInfo($appLicenceInfo) {
  422. if (empty($appLicenceInfo->ID)) throw new Exception("Nie wybrano serwera/licencji.");
  423. if (empty($appLicenceInfo->domains)) throw new Exception("Domains not found");
  424. if (empty($appLicenceInfo->installPath)) throw new Exception("Install path not found");
  425. }
  426. public function generateApp($installPath, $domains, $projects = []) {
  427. $cmds = array();
  428. $cmds[] = "if [ -d {$installPath} ] ; then rm -rf '{$installPath}'; fi";
  429. $cmds[] = "mkdir {$installPath}";
  430. $cmds[] = "cd {$installPath} && git clone --depth 1 ssh://git@biuro.biall-net.pl:2222/plabudda/se.git .";
  431. $cmds[] = "cd {$installPath} && echo `git show-ref --head|head -1|head -c 8` > SE/VERSION ";
  432. foreach ($cmds as $cmd) {
  433. V::exec($cmd, $out, $ret);
  434. DBG::nicePrint([ 'cmd' => $cmd, 'output' => $out ], "return: {$ret}");
  435. }
  436. foreach ($projects as $projectName) {
  437. $cmd = "ls -l SE/projects/{$projectName} | wc -l";
  438. V::exec("cd {$installPath} && {$cmd}", $out, $ret);
  439. DBG::nicePrint([ 'cmd' => $cmd, 'output' => $out ], "return: {$ret}");
  440. if (!empty($out) && '0' !== trim($out[0])) {
  441. // $cmd = "git submodule update SE/projects/{$projectName}";
  442. $cmd = "cd SE/projects/{$projectName} && git reset --hard"; // revert encode source - checkout to last commit (need update)
  443. V::exec("cd {$installPath} && {$cmd}", $out, $ret);
  444. DBG::nicePrint([ 'cmd' => $cmd, 'output' => $out ], "return: {$ret}");
  445. }
  446. $cmd = "git submodule update --init SE/projects/{$projectName}"; // checkout to current commit
  447. V::exec("cd {$installPath} && {$cmd}", $out, $ret);
  448. DBG::nicePrint([ 'cmd' => $cmd, 'output' => $out ], "return: {$ret}");
  449. }
  450. $this->_encodeSource($installPath, $domains);
  451. // 1763: $exec='cd '.$installer_dir.' && /Applications/SourceGuardian.app/Contents/MacOS/sgencoder -b-
  452. // '.INSTALL_SES_PROCESY_A::get_same_domains_for_install($h->SERVER_ADDRESS_SHORT).'
  453. // -r *.php
  454. // -x superedit-DB_PROCEDURES_CREATE.php
  455. // -x INI.php
  456. // -x .config_base_structure.php
  457. // ';
  458. //
  459. // INSTALL_SES_PROCESY_A::get_same_domains_for_install($h->SERVER_ADDRESS_SHORT):
  460. // $res2=DB::query("select SERVER_ADDRESS_SHORT from SES_PROCESY5_A where SERVER_ADDRESS_IP='".$h->SERVER_ADDRESS_IP."'");
  461. // while($h2=DB::fetch($res2)) {
  462. // $domain[]=' --domain '.$h2->SERVER_ADDRESS_SHORT;
  463. // ssh server@biuro.galeriaprzymorze.eu: PHP 5.5.20
  464. // ssh server@biuro.biall-net.pl
  465. // cd /Users/plabudda/procesy5-install-galeriaprzymorze.eu/
  466. // sudo chown -R server:admin SE/
  467. // /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
  468. }
  469. public function fetchActiveLicences() {
  470. $activeLic = array();
  471. $sql = "
  472. select l.`ID`
  473. , l.`SERVER_ADDRESS`
  474. , l.`SERVER_ADDRESS_SHORT` as domain -- domain for sgencoder
  475. , l.`SERVER_ADDRESS_IP`
  476. from `SES_PROCESY5_A` l
  477. where 1=1
  478. -- TODO: and l.`A_STATUS` in('NORMAL','WAITING')
  479. order by l.`ID` DESC
  480. ";
  481. $rows = DB::getPDO()->fetchAll($sql);
  482. foreach ($rows as $row) {
  483. $r = (object)$row;
  484. $activeLic[$r->ID] = $r;
  485. }
  486. return $activeLic;
  487. }
  488. public function fetchDomainsByLicenceId($licenceId) {
  489. $domains = array();
  490. $sql = "
  491. select g.`SERVER_ADDRESS_SHORT`, g.`SERVER_ADDRESS`
  492. from `SES_PROCESY5_A` g
  493. where g.`SERVER_ADDRESS_IP`=(select l.`SERVER_ADDRESS_IP`
  494. from `SES_PROCESY5_A` l
  495. where l.`ID`='{$licenceId}'
  496. -- TODO: and l.`A_STATUS` in('NORMAL','WAITING')
  497. )
  498. -- TODO: and g.`A_STATUS` in('NORMAL','WAITING')
  499. ";
  500. $rows = DB::getPDO()->fetchAll($sql);
  501. foreach ($rows as $row) {
  502. $r = (object)$row;
  503. $domains[] = $r->SERVER_ADDRESS_SHORT;
  504. if ($r->SERVER_ADDRESS != $r->SERVER_ADDRESS_SHORT) {
  505. $domains[] = $r->SERVER_ADDRESS;
  506. }
  507. }
  508. return $domains;
  509. }
  510. public function fetchMainServerByLicenceId($licenceId) {
  511. return DB::getPDO()->fetchValue("
  512. select g.`SERVER_ADDRESS`
  513. from `SES_PROCESY5_A` g
  514. where g.`ID`='{$licenceId}'
  515. -- TODO: and g.`A_STATUS` in('NORMAL','WAITING')
  516. ");
  517. }
  518. public function fetchAppLicenceInfo($licenceId) {
  519. $licenceInfo = null;
  520. $sql = "
  521. select g.ID
  522. , g.SERVER_ADDRESS as mainServer
  523. , g.ADMIN_USERNAME as rootLogin
  524. , g.ADMIN_USERNAME_PASSWD as rootPassword
  525. , g.SSH_PORT as sshPort
  526. from SES_PROCESY5_A g
  527. where g.`ID`=:id_licence
  528. -- TODO: and g.A_STATUS in('NORMAL','WAITING')
  529. ";
  530. $all = DB::getPDO()->fetchAll($sql, [ ':id_licence' => $licenceId ]);
  531. if (empty($all)) throw new Exception("Brak licencji o nr '{$licenceId}'");
  532. $licenceInfo = reset($all);
  533. if (!$licenceInfo['sshPort']) $licenceInfo['sshPort'] = 22;
  534. return $licenceInfo;
  535. }
  536. public function _endWithException($e) {
  537. echo UI::h('div', ['class'=>"container"], [
  538. UI::h('div', ['class' => "alert alert-danger"], "#" . $e->getLine() . ": " . $e->getMessage()),
  539. UI::h('p', [], [
  540. "Wróć do ",
  541. UI::h('a', ['href'=>"index.php?_route=Install"], "menu")
  542. ])
  543. ]);
  544. UI::dol();
  545. exit;
  546. }
  547. public function sendToRemoteTestDirAction() {
  548. session_write_close();
  549. $args = array();
  550. $args['licence_id'] = V::get('licence_id', 0, $_REQUEST, 'int');
  551. UI::gora();
  552. //UI::menu();
  553. //$this->menu($args['licence_id']);// TODO: GO BACK BTN
  554. try {
  555. $appLicenceInfo = $this->getAppLicenceInfo($args['licence_id']);
  556. $this->validateAppLicenceInfo($appLicenceInfo);
  557. // TODO: if (59 ) => baratosz.sledz - na lokalnym kompie
  558. // bn:~/$ scp -r SE server@192.168.61.153:~/se.encrypted.upgrade
  559. // remote SE.git = '/Users/bartoszsledz/Desktop/production-se'
  560. // remote:~/$ mv SE ~/SE.bup.2017-07-03
  561. // remote:~/$ mv ~/se.encrypted.upgrade/SE SE
  562. // remote:~/$ cp -r ~/SE.bup.2017-07-03/config SE/
  563. // remote:~/$ sudo chown -R bartoszsledz:staff SE/
  564. $this->_sendToRemoteTestDir($appLicenceInfo);
  565. echo "Test online: ";
  566. echo UI::h('a', ['target'=>"_blank", 'href'=>"https://{$appLicenceInfo->mainServer}/se.encrypted.upgrade/"], "https://{$appLicenceInfo->mainServer}/se.encrypted.upgrade/");
  567. } catch (Exception $e) {
  568. $this->_endWithException($e);
  569. }
  570. UI::dol();
  571. }
  572. public function _fetchRemoteHomeDir($appLicenceInfo) {
  573. $this->_assertRsaKeyExists($appLicenceInfo);
  574. $sshHostUsr = "{$appLicenceInfo->rootLogin}@{$appLicenceInfo->mainServer}";
  575. $sshArgs = (22 != $appLicenceInfo->sshPort)? "-p {$appLicenceInfo->sshPort}" : '';
  576. $rsyncSshPort = (22 != $appLicenceInfo->sshPort)? "-e 'ssh -p {$appLicenceInfo->sshPort}'" : '';
  577. if (V::get('DBG_REMOTE', '', $_GET)) {// DBG
  578. $cmd = "echo ~";
  579. V::exec("ssh {$sshArgs} {$sshHostUsr} '{$cmd}'", $out, $ret);
  580. DBG::log([ 'cmd-remote' => $cmd, 'output' => $out ], 'array', "return: {$ret}");
  581. V::execRemote($appLicenceInfo->mainServer, $appLicenceInfo->rootLogin, $appLicenceInfo->rootPassword, $cmd, $out, $ret, $appLicenceInfo->sshPort);
  582. DBG::log([ 'cmd-remote' => $cmd, 'output' => $out ], 'array', "return: {$ret}");
  583. V::execRootRemote($appLicenceInfo->mainServer, $appLicenceInfo->rootLogin, $appLicenceInfo->rootPassword, $cmd, $out, $ret, $appLicenceInfo->sshPort);
  584. DBG::log([ 'cmd-remote' => $cmd, 'output' => $out ], 'array', "return: {$ret}");
  585. }
  586. $cmd = "echo ~";
  587. V::exec("ssh {$sshArgs} {$sshHostUsr} '{$cmd}'", $out, $ret);
  588. DBG::log([ 'cmd-remote' => $cmd, 'output' => $out ], 'array', "return: {$ret}");
  589. if (empty($out) || empty($out[0])) throw new Exception("Cannot fetch remote home dir");
  590. return $out[0];
  591. }
  592. public function _sendToRemoteTestDir($appLicenceInfo) {
  593. $cmd = ''; $out = ''; $ret = '';
  594. $dryRunOnly = (V::get('dry-run', '', $_REQUEST)) ? "--dry-run" : "";
  595. $this->_assertRsaKeyExists($appLicenceInfo);
  596. $sshHostUsr = "{$appLicenceInfo->rootLogin}@{$appLicenceInfo->mainServer}";
  597. $sshArgs = (22 != $appLicenceInfo->sshPort)? "-p {$appLicenceInfo->sshPort}" : '';
  598. $rsyncSshPort = (22 != $appLicenceInfo->sshPort)? "-e 'ssh -p {$appLicenceInfo->sshPort}'" : '';
  599. // $appLicenceInfo->sshPort
  600. /* rsync options:
  601. -a, --archive archive mode; same as -rlptgoD (no -H)
  602. -u, --update skip files that are newer on the receiver
  603. -t, --times preserve times
  604. --delete delete extraneous files from dest dirs
  605. */
  606. $remoteDir = $this->_fetchRemoteHomeDir($appLicenceInfo);
  607. DBG::log($remoteDir, 'array', "remote home dir:");
  608. $cmd = "
  609. ssh {$sshArgs} {$sshHostUsr} '[ ! -d ~/se.encrypted.upgrade ] && mkdir ~/se.encrypted.upgrade || echo 1';
  610. ssh {$sshArgs} {$sshHostUsr} 'rm -rf ~/se.encrypted.upgrade/SE';
  611. ssh {$sshArgs} {$sshHostUsr} 'cp -r /Library/Server/Web/Data/Sites/Default/SE ~/se.encrypted.upgrade/SE';
  612. ssh {$sshArgs} {$sshHostUsr} 'rm -rf ~/se.encrypted.upgrade/SE/config';
  613. rsync --archive --times --delete --compress --one-file-system --omit-dir-times --no-g --no-perms {$dryRunOnly} \
  614. --verbose {$rsyncSshPort} \
  615. --exclude='stuff' \
  616. --exclude='stuff/**' \
  617. --exclude='schema/default_db.instance.xml' \
  618. --exclude='schema/default_db_xml_cache.public' \
  619. --exclude='schema/default_db.instance.xml/**' \
  620. --exclude='schema/default_db_xml_cache.public/**' \
  621. '{$appLicenceInfo->installPath}/SE/' {$sshHostUsr}:~/se.encrypted.upgrade/SE/;
  622. ssh {$sshArgs} {$sshHostUsr} 'cp -r /Library/Server/Web/Data/Sites/Default/SE/config ~/se.encrypted.upgrade/SE/';
  623. ssh {$sshArgs} {$sshHostUsr} 'rm /Library/Server/Web/Data/Sites/Default/se.encrypted.upgrade'
  624. ssh {$sshArgs} {$sshHostUsr} 'ln -s ~/se.encrypted.upgrade/SE /Library/Server/Web/Data/Sites/Default/se.encrypted.upgrade'
  625. ";
  626. V::exec($cmd, $out, $ret);
  627. DBG::log([ 'cmd-remote' => $cmd, 'output' => $out ], 'array', "return: {$ret}");
  628. if (0 !== $ret) throw new Exception("Cannot run remote command using rsa key! #{$ret}");
  629. }
  630. public function upgradeRemoteFromTestDirAction() {
  631. session_write_close();
  632. $args = array();
  633. $args['licence_id'] = V::get('licence_id', 0, $_REQUEST, 'int');
  634. UI::gora();
  635. //UI::menu();
  636. //$this->menu($args['licence_id']);// TODO: GO BACK BTN
  637. try {
  638. $appLicenceInfo = $this->getAppLicenceInfo($args['licence_id']);
  639. $this->validateAppLicenceInfo($appLicenceInfo);
  640. $this->_upgradeRemoteFromTestDir($appLicenceInfo);
  641. echo "Test online: ";
  642. echo UI::h('a', ['target'=>"_blank", 'href'=>"https://{$appLicenceInfo->mainServer}/SE/"], "https://{$appLicenceInfo->mainServer}/SE/");
  643. } catch (Exception $e) {
  644. $this->_endWithException($e);
  645. }
  646. UI::dol();
  647. }
  648. public function _upgradeRemoteFromTestDir($appLicenceInfo) {
  649. $cmd = ''; $out = ''; $ret = '';
  650. $this->_assertRsaKeyExists($appLicenceInfo);
  651. $dateStr = date("Y-m-d_H-i-s");
  652. // $remoteHomeDir = "/Users/{$appLicenceInfo->rootLogin}";// BUG: alias like in ams - login = prezes is alias for arkadiuszbinder
  653. $remoteHomeDir = $this->_fetchRemoteHomeDir($appLicenceInfo);
  654. $cmd = "
  655. rm -rf /Library/Server/Web/Data/Sites/Default/SE.test 2>&1
  656. cp -r {$remoteHomeDir}/se.encrypted.upgrade/SE /Library/Server/Web/Data/Sites/Default/SE.test 2>&1
  657. [ ! -d {$remoteHomeDir}/bup.se.upgrade ] && mkdir {$remoteHomeDir}/bup.se.upgrade || echo 1
  658. [ ! -d {$remoteHomeDir}/bup.se.upgrade ] && exit 1
  659. [ ! -d {$remoteHomeDir}/bup.se.upgrade-testttttt ] && exit 1
  660. [ ! -f /Library/Server/Web/Data/Sites/Default/SE.test/VERSION ] && echo \"Error: plik VERSION nie istnieje\" || echo \"check VERSION OK\"
  661. [ ! -f /Library/Server/Web/Data/Sites/Default/SE.test/VERSION ] && exit 1
  662. [ ! -f /Library/Server/Web/Data/Sites/Default/SE.test/index.php ] && echo \"Error: plik index.php nie istnieje\" || echo \"check index.php OK\"
  663. [ ! -f /Library/Server/Web/Data/Sites/Default/SE.test/index.php ] && exit 1
  664. [ ! -d /Library/Server/Web/Data/Sites/Default/SE.test/se-lib ] && echo \"Error: plik se-lib nie istnieje\" || echo \"check se-lib OK\"
  665. [ ! -d /Library/Server/Web/Data/Sites/Default/SE.test/se-lib ] && exit 1
  666. exit 0
  667. ";
  668. V::execRootRemote($appLicenceInfo->mainServer, $appLicenceInfo->rootLogin, $appLicenceInfo->rootPassword, $cmd, $out, $ret, $appLicenceInfo->sshPort);
  669. $cmd = "
  670. mv /Library/Server/Web/Data/Sites/Default/SE {$remoteHomeDir}/bup.se.upgrade/bup.{$dateStr} 2>&1
  671. mv /Library/Server/Web/Data/Sites/Default/SE.test /Library/Server/Web/Data/Sites/Default/SE 2>&1
  672. exit 0
  673. ";
  674. V::execRootRemote($appLicenceInfo->mainServer, $appLicenceInfo->rootLogin, $appLicenceInfo->rootPassword, $cmd, $out, $ret, $appLicenceInfo->sshPort);
  675. DBG::_(true, true, "cmd: {$cmd} (return: {$ret})", $out, __CLASS__, __FUNCTION__, __LINE__);
  676. if (0 !== $ret) throw new Exception("Cannot run remote command as root! #{$ret}");
  677. // TODO: SE/bash_install_check.php requires $domain!
  678. // $cmd = "/usr/bin/php /Library/Server/Web/Data/Sites/Default/SE/bash_install_check.php {$domain}";
  679. // V::execRootRemote($appLicenceInfo->mainServer, $appLicenceInfo->rootLogin, $appLicenceInfo->rootPassword, $cmd, $out, $ret, $appLicenceInfo->sshPort);
  680. // DBG::_(true, true, "cmd: {$cmd} (return: {$ret})", $out, __CLASS__, __FUNCTION__, __LINE__);
  681. // if (0 !== $ret) throw new Exception("Cannot run remote command as root! #{$ret}");
  682. }
  683. public function _assertRsaKeyExists($appLicenceInfo) {
  684. $cmd = ''; $out = ''; $ret = '';
  685. $cmd = "echo ~ && pwd";// /Library/WebServer
  686. $cmd = "ls -1 ~/.ssh/";
  687. //$cmd = "rm /tmp/id_rsa";
  688. //$cmd = "rm /tmp/id_rsa.pub";
  689. //$cmd = "ssh-keygen -t rsa -N '' -C '_www@biuro.biall-net.pl' -f /tmp/id_rsa";
  690. //$cmd = "ssh-keygen -t rsa -N '' -C '_www@biuro.biall-net.pl' -f /tmp/id_rsa";
  691. V::exec($cmd, $out, $ret);
  692. DBG::_(true, true, "cmd: {$cmd} (return: {$ret})", $out, __CLASS__, __FUNCTION__, __LINE__);
  693. if (0 !== $ret) {// no ~/.ssh directory
  694. $rsaKeyPath = "~/.ssh";
  695. $cmds = array();
  696. $cmds[] = "mkdir {$rsaKeyPath}";
  697. $cmds[] = "ssh-keygen -t rsa -N '' -C '_www@biuro.biall-net.pl' -f {$rsaKeyPath}/id_rsa 2>&1";
  698. $cmds[] = "ls -1 $rsaKeyPath";
  699. foreach ($cmds as $cmd) {
  700. V::exec($cmd, $out, $ret);
  701. DBG::_(true, true, "cmd: {$cmd} (return: {$ret})", $out, __CLASS__, __FUNCTION__, __LINE__);
  702. if (0 !== $ret) throw new Exception("Error '{$ret}' cmd({$cmd}): " . implode("\n", $out));
  703. }
  704. }
  705. $cmd = "cat ~/.ssh/id_rsa.pub";
  706. V::exec($cmd, $out, $ret);
  707. DBG::_(true, true, "cmd: {$cmd} (return: {$ret})", $out, __CLASS__, __FUNCTION__, __LINE__);
  708. if (0 !== $ret || empty($out) || empty($out[0])) throw new Exception("Cannot read rsa public key");
  709. $rsaPubKey = $out[0];
  710. $cmd = 'ls -1a';
  711. $cmd = "
  712. [ ! -d ~/.ssh ] && mkdir ~/.ssh;
  713. [ ! -d ~/.ssh ] && echo 'ERROR ~/.ssh not exists and cannot be created';
  714. [ ! -f ~/.ssh/authorized_keys ] && echo '{$rsaPubKey}' > ~/.ssh/authorized_keys;
  715. [ ! -f ~/.ssh/authorized_keys ] && echo 'ERROR ~/.ssh/authorized_keys not exists and cannot be created';
  716. cat ~/.ssh/authorized_keys| grep '{$rsaPubKey}' && echo 'OK' || echo '{$rsaPubKey}' >> ~/.ssh/authorized_keys;
  717. chmod 600 ~/.ssh/authorized_keys;
  718. ";
  719. V::execRemote($appLicenceInfo->mainServer, $appLicenceInfo->rootLogin, $appLicenceInfo->rootPassword, $cmd, $out, $ret, $appLicenceInfo->sshPort);
  720. DBG::_(true, true, "remote cmd: {$cmd} (return: {$ret})", $out, __CLASS__, __FUNCTION__, __LINE__);
  721. //$cmd = "ssh server@{$appLicenceInfo->mainServer} 'ls -1 .ssh/'";
  722. //$cmd = "ssh -i ~/.ssh/id_rsa server@{$appLicenceInfo->mainServer} 'ls -1'";
  723. $sshPort = (22 != $appLicenceInfo->sshPort)? "-p {$appLicenceInfo->sshPort}" : '';
  724. $cmd = "ssh {$sshPort} {$appLicenceInfo->rootLogin}@{$appLicenceInfo->mainServer} 'ls -1'";
  725. V::exec($cmd, $out, $ret);
  726. DBG::_(true, true, "cmd: {$cmd} (return: {$ret})", $out, __CLASS__, __FUNCTION__, __LINE__);
  727. if (0 !== $ret) throw new Exception("Cannot run remote command using rsa key! #{$ret}");
  728. }
  729. public function newGenerateApp($appLicenceInfo) {
  730. if (empty($appLicenceInfo->ID)) throw new Exception("Nie wybrano serwera/licencji.");
  731. if (empty($appLicenceInfo->domains)) throw new Exception("Domains not found");
  732. $installPath = $appLicenceInfo->installPath;
  733. if (empty($installPath)) throw new Exception("Install path not found");
  734. $installPath .= '-p5';
  735. $cmds = array();
  736. $cmds[] = "if [ -d {$installPath} ] ; then rm -rf '{$installPath}'; fi";
  737. $cmds[] = "mkdir {$installPath}";
  738. $cmds[] = "cd {$installPath} && git clone --depth 1 ssh://git@biuro.biall-net.pl:2222/p5/p5.git .";
  739. $cmds[] = "cd {$installPath} && echo `git show-ref --head|head -1|head -c 8` > SE/VERSION ";
  740. // TODO: fetch from DB
  741. {
  742. $projectName = "bravecare";
  743. $cmds[] = "cd {$installPath} && git submodule update --init SE/projects/{$projectName}";
  744. }
  745. foreach ($cmds as $cmd) {
  746. $out = ''; $ret = '';
  747. exec($cmd, $out, $ret);
  748. DBG::nicePrint([ 'cmd' => $cmd, 'output' => $out ], "return: {$ret}");
  749. }
  750. // $this->_encodeSource($appLicenceInfo->installPath, $appLicenceInfo->domains);
  751. }
  752. }