Install.php 29 KB

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