Install.php 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690
  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. $installPath = $appLicenceInfo->installPath;
  226. if (empty($installPath)) throw new Exception("Install path not found");
  227. $phpVersionsForSgencoder = '--phpversion 5.5 --phpversion 5.6';// encode for PHP 5.x (currently supported PHP 5.0-5.6)
  228. if ('1' == V::get('DBG_ENCODER_HELP', '', $_REQUEST)) {// encoder help
  229. $cmd = "cd {$installPath}/SE && /Applications/SourceGuardian.app/Contents/MacOS/sgencoder --help ";
  230. $out = ''; $ret = '';
  231. exec($cmd, $out, $ret);
  232. echo'<pre>cmd: '. $cmd . ': (return:'.$ret.')'."\n";print_r($out);echo'</pre>';
  233. exit;
  234. }
  235. if (0) {//'1' == V::get('DBG_ENCODER_TEST_IP', '', $_REQUEST)) {
  236. $phpFiles = array();
  237. $phpFiles[] = 't.php';
  238. $cmd = "cd {$installPath}/SE && echo '<?php' > t.php ; echo 'echo \"test\\n\";' >> t.php ";
  239. //$cmd = "cd {$installPath}/SE && rm t.php ";
  240. V::exec($cmd, $out, $ret);
  241. DBG::_(true, true, "cmd: {$cmd} (return: {$ret})", $out, __CLASS__, __FUNCTION__, __LINE__);
  242. $cmd = "cd {$installPath}/SE && /Applications/SourceGuardian.app/Contents/MacOS/sgencoder {$phpVersionsForSgencoder} -b- ";
  243. //$mac = '38:c9:86:31:80:77';
  244. //$cmd .= " --mac {$mac}";
  245. foreach ($appLicenceInfo->domains as $domain) {
  246. $cmd .= " --domain {$domain} ";
  247. }
  248. $cmd .= " " . implode(" ", $phpFiles);
  249. V::exec($cmd, $out, $ret);
  250. DBG::_(true, true, "cmd: {$cmd} (return: {$ret})", $out, __CLASS__, __FUNCTION__, __LINE__);
  251. if (0 !== $ret) throw new Exception("Error at encode files");
  252. if (empty($out)) throw new Exception("No output for encode files command");
  253. exit;
  254. }
  255. {
  256. $phpFiles = array();
  257. $skipPhpFiles = array();
  258. $skipPhpFiles[] = 'bash_sync_perms.php';
  259. $skipPhpFiles[] = 'bash_install_check.php';
  260. $skipPhpFiles[] = '.config.php';
  261. $skipPhpFiles[] = '.config_base_structure.php';
  262. $skipPhpFiles[] = 'se-lib/V.php';
  263. $skipPhpFiles[] = 'se-lib/Lib.php';
  264. $skipPhpFiles[] = 'se-lib/DB.php';
  265. $skipPhpFiles[] = 'se-lib/DBG.php';
  266. $skipPhpFiles[] = 'se-lib/User.php';
  267. $skipPhpFiles[] = 'se-lib/UserProfile.php';
  268. $skipPhpFiles[] = 'se-lib/Config.php';
  269. $skipPhpFiles[] = 'se-lib/Config/INI.php';
  270. $skipPhpFiles[] = 'se-lib/FoldersConfig.php';
  271. $skipPhpFiles[] = 'se-lib/FileUploader.php';
  272. $skipPhpFiles[] = 'se-lib/Route/Budget.php';
  273. $skipPhpFiles[] = 'se-lib/Route/FixCrmProcesInitIdx.php';
  274. $skipPhpFiles[] = 'se-lib/Route/FixProjectPath.php';
  275. $skipPhpFiles[] = 'se-lib/Route/FixZasobPath.php';
  276. //$skipPhpFiles[] = 'se-lib/Route/Install.php';
  277. $skipPhpFiles[] = 'se-lib/Route/Msgs.php';
  278. $skipPhpFiles[] = 'se-lib/Route/UrlAction/WmsGenerate.php';
  279. $skipPhpFiles[] = 'se-lib/Route/UrlAction/BiAuditGenerate.php';
  280. $skipPhpFiles[] = 'superedit-DB_PROCEDURES_CREATE.php';
  281. //$skipPhpFiles[] = '';
  282. $skipPhpFiles[] = 'se-lib/DataSourceException.php';
  283. $skipPhpFiles[] = 'se-lib/Core/Pdo.php';
  284. $skipPhpFiles[] = 'se-lib/Cron.php';
  285. $skipPhpFiles[] = 'se-lib/Router.php';
  286. $skipPhpFiles[] = 'se-lib/RouteBase.php';
  287. $skipPhpFiles[] = 'se-lib/HttpException.php';
  288. $skipPhpFiles[] = 'se-lib/DebugExecutionTime.php';
  289. $skipPhpFiles[] = 'se-lib/UI.php';
  290. $skipPhpFiles[] = 'se-lib/Request.php';
  291. $cmd = "cd {$installPath}/SE && find . -name '*.php' ";
  292. $out = ''; $ret = '';
  293. exec($cmd, $out, $ret);
  294. echo'<pre>cmd: '. $cmd . ': (return:'.$ret.')'."\n";print_r($out);echo'</pre>';
  295. if (0 !== $ret) throw new Exception("Error at find php files");
  296. if (empty($out)) throw new Exception("No php files found");
  297. foreach ($out as $phpFilePath) {
  298. $phpFilePath = ('./' == substr($phpFilePath, 0, 2))? substr($phpFilePath, 2) : $phpFilePath;
  299. if (in_array($phpFilePath, $skipPhpFiles)) continue;
  300. if ('schema/' == substr($phpFilePath, 0, 7)) continue;
  301. $phpFiles[] = $phpFilePath;
  302. }
  303. DBG::_(true, true, 'phpFiles', $phpFiles, __CLASS__, __FUNCTION__, __LINE__);
  304. if (empty($phpFiles)) throw new Exception("No php files to encode");
  305. }
  306. {
  307. $cmd = "cd {$installPath}/SE && /Applications/SourceGuardian.app/Contents/MacOS/sgencoder {$phpVersionsForSgencoder} -b- ";
  308. foreach ($appLicenceInfo->domains as $domain) {
  309. $cmd .= " --domain {$domain} ";
  310. }
  311. $cmd .= " " . implode(" ", $phpFiles);
  312. $out = ''; $ret = '';
  313. exec($cmd, $out, $ret);
  314. echo'<pre>cmd: '. $cmd . ': (return:'.$ret.')'."\n";print_r($out);echo'</pre>';
  315. if (0 !== $ret) throw new Exception("Error at encode files");
  316. if (empty($out)) throw new Exception("No output for encode files command");
  317. }
  318. }
  319. public function getAppLicenceInfo($idLicence) {
  320. $idLicence = intval($idLicence);
  321. if (empty($idLicence)) throw new Exception("Nie wybrano serwera/licencji.");
  322. //DBG::_(true, true, 'idLicence', $idLicence, __CLASS__, __FUNCTION__, __LINE__);
  323. $appLicenceInfo = (object)$this->fetchAppLicenceInfo($idLicence);
  324. $appLicenceInfo->domains = $this->fetchDomainsByLicenceId($idLicence);
  325. $installRootPath = '/Library/Server/Web/Data/Sites/Default/PLIKI/SES_PROCESY5_A';
  326. $appLicenceInfo->installFolderName = "{$idLicence}_upgrade_SE_source_encrypted";
  327. $appLicenceInfo->installPath = "{$installRootPath}/{$appLicenceInfo->installFolderName}";
  328. //DBG::_(true, true, 'appLicenceInfo', $appLicenceInfo, __CLASS__, __FUNCTION__, __LINE__);
  329. if (empty($appLicenceInfo->domains)) throw new Exception("Domains not found.");
  330. $appLicenceInfo->installFolderExists = file_exists("{$appLicenceInfo->installPath}/SE");
  331. $appLicenceInfo->installFolderGitExists = file_exists("{$appLicenceInfo->installPath}/.git");
  332. return $appLicenceInfo;
  333. }
  334. public function generateApp($appLicenceInfo) {
  335. if (empty($appLicenceInfo->ID)) throw new Exception("Nie wybrano serwera/licencji.");
  336. if (empty($appLicenceInfo->domains)) throw new Exception("Domains not found");
  337. $installPath = $appLicenceInfo->installPath;
  338. if (empty($installPath)) throw new Exception("Install path not found");
  339. $cmds = array();
  340. $cmds[] = "if [ -d {$installPath} ] ; then rm -rf '{$installPath}'; fi";
  341. $cmds[] = "mkdir {$installPath}";
  342. $cmds[] = "cd {$installPath} && git clone ssh://git@biuro.biall-net.pl:2222/plabudda/se.git .";
  343. $cmds[] = "cd {$installPath} && echo `git show-ref --head|head -1|head -c 8` > SE/VERSION ";
  344. //echo'<pre>cmds: ';print_r($cmds);echo'</pre>';
  345. foreach ($cmds as $cmd) {
  346. $out = ''; $ret = '';
  347. exec($cmd, $out, $ret);
  348. echo'<pre>cmd: '. $cmd . ': (return:'.$ret.')'."\n";print_r($out);echo'</pre>';
  349. }
  350. $this->_encodeSource($appLicenceInfo);
  351. // 1763: $exec='cd '.$installer_dir.' && /Applications/SourceGuardian.app/Contents/MacOS/sgencoder -b-
  352. // '.INSTALL_SES_PROCESY_A::get_same_domains_for_install($h->SERVER_ADDRESS_SHORT).'
  353. // -r *.php
  354. // -x superedit-DB_PROCEDURES_CREATE.php
  355. // -x INI.php
  356. // -x .config_base_structure.php
  357. // ';
  358. //
  359. // INSTALL_SES_PROCESY_A::get_same_domains_for_install($h->SERVER_ADDRESS_SHORT):
  360. // $res2=DB::query("select SERVER_ADDRESS_SHORT from SES_PROCESY5_A where SERVER_ADDRESS_IP='".$h->SERVER_ADDRESS_IP."'");
  361. // while($h2=DB::fetch($res2)) {
  362. // $domain[]=' --domain '.$h2->SERVER_ADDRESS_SHORT;
  363. // ssh server@biuro.galeriaprzymorze.eu: PHP 5.5.20
  364. // ssh server@biuro.biall-net.pl
  365. // cd /Users/plabudda/procesy5-install-galeriaprzymorze.eu/
  366. // sudo chown -R server:admin SE/
  367. // /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
  368. }
  369. public function fetchActiveLicences() {
  370. $activeLic = array();
  371. $db = DB::getDB();
  372. $sql = "select l.`ID`
  373. , l.`SERVER_ADDRESS`
  374. , l.`SERVER_ADDRESS_SHORT` as domain -- domain for sgencoder
  375. , l.`SERVER_ADDRESS_IP`
  376. from `SES_PROCESY5_A` l
  377. where 1=1
  378. -- TODO: and l.`A_STATUS` in('NORMAL','WAITING')
  379. order by l.`ID` DESC
  380. ";
  381. $res = $db->query($sql);
  382. while ($r = $db->fetch($res)) {
  383. $activeLic[$r->ID] = $r;
  384. }
  385. return $activeLic;
  386. }
  387. public function fetchDomainsByLicenceId($licenceId) {
  388. $domains = array();
  389. $db = DB::getDB();
  390. $sql = "select g.`SERVER_ADDRESS_SHORT`, g.`SERVER_ADDRESS`
  391. from `SES_PROCESY5_A` g
  392. where g.`SERVER_ADDRESS_IP`=(select l.`SERVER_ADDRESS_IP`
  393. from `SES_PROCESY5_A` l
  394. where l.`ID`='{$licenceId}'
  395. -- TODO: and l.`A_STATUS` in('NORMAL','WAITING')
  396. )
  397. -- TODO: and g.`A_STATUS` in('NORMAL','WAITING')
  398. ";
  399. $res = $db->query($sql);
  400. while ($r = $db->fetch($res)) {
  401. $domains[] = $r->SERVER_ADDRESS_SHORT;
  402. if ($r->SERVER_ADDRESS != $r->SERVER_ADDRESS_SHORT) {
  403. $domains[] = $r->SERVER_ADDRESS;
  404. }
  405. }
  406. return $domains;
  407. }
  408. public function fetchMainServerByLicenceId($licenceId) {
  409. $mainServer = null;
  410. $db = DB::getDB();
  411. $sql = "select g.`SERVER_ADDRESS`
  412. from `SES_PROCESY5_A` g
  413. where g.`ID`='{$licenceId}'
  414. -- TODO: and g.`A_STATUS` in('NORMAL','WAITING')
  415. ";
  416. $res = $db->query($sql);
  417. while ($r = $db->fetch($res)) {
  418. $mainServer = $r->SERVER_ADDRESS;
  419. }
  420. return $mainServer;
  421. }
  422. public function fetchAppLicenceInfo($licenceId) {
  423. $licenceInfo = null;
  424. $sth = DB::getPDO()->prepare("
  425. select g.ID
  426. , g.SERVER_ADDRESS as mainServer
  427. , g.ADMIN_USERNAME as rootLogin
  428. , g.ADMIN_USERNAME_PASSWD as rootPassword
  429. , g.SSH_PORT as sshPort
  430. from SES_PROCESY5_A g
  431. where g.`ID`=:id_licence
  432. -- TODO: and g.A_STATUS in('NORMAL','WAITING')
  433. ");
  434. $sth->bindValue('id_licence', $licenceId, PDO::PARAM_INT);
  435. $sth->execute();
  436. $all = $sth->fetchAll();
  437. if (empty($all)) throw new Exception("Brak licencji o nr '{$licenceId}'");
  438. $licenceInfo = reset($all);
  439. if (!$licenceInfo['sshPort']) $licenceInfo['sshPort'] = 22;
  440. return $licenceInfo;
  441. }
  442. public function _endWithException($e) {
  443. echo UI::h('div', ['class'=>"container"], [
  444. UI::h('div', ['class' => "alert alert-danger"], "#" . $e->getLine() . ": " . $e->getMessage()),
  445. UI::h('p', [], [
  446. "Wróć do ",
  447. UI::h('a', ['href'=>"index.php?_route=Install"], "menu")
  448. ])
  449. ]);
  450. UI::dol();
  451. exit;
  452. }
  453. public function sendToRemoteTestDirAction() {
  454. session_write_close();
  455. $args = array();
  456. $args['licence_id'] = V::get('licence_id', 0, $_REQUEST, 'int');
  457. UI::gora();
  458. //UI::menu();
  459. //$this->menu($args['licence_id']);// TODO: GO BACK BTN
  460. try {
  461. $appLicenceInfo = $this->getAppLicenceInfo($args['licence_id']);
  462. // TODO: if (59 ) => baratosz.sledz - na lokalnym kompie
  463. // bn:~/$ scp -r SE server@192.168.61.153:~/se.encrypted.upgrade
  464. // remote SE.git = '/Users/bartoszsledz/Desktop/production-se'
  465. // remote:~/$ mv SE ~/SE.bup.2017-07-03
  466. // remote:~/$ mv ~/se.encrypted.upgrade/SE SE
  467. // remote:~/$ cp -r ~/SE.bup.2017-07-03/config SE/
  468. // remote:~/$ sudo chown -R bartoszsledz:staff SE/
  469. $this->_sendToRemoteTestDir($appLicenceInfo);
  470. echo "Test online: ";
  471. echo UI::h('a', ['target'=>"_blank", 'href'=>"https://{$appLicenceInfo->mainServer}/se.encrypted.upgrade/"], "https://{$appLicenceInfo->mainServer}/se.encrypted.upgrade/");
  472. } catch (Exception $e) {
  473. $this->_endWithException($e);
  474. }
  475. UI::dol();
  476. }
  477. public function _fetchRemoteHomeDir($appLicenceInfo) {
  478. $this->_assertRsaKeyExists($appLicenceInfo);
  479. $sshHostUsr = "{$appLicenceInfo->rootLogin}@{$appLicenceInfo->mainServer}";
  480. $sshArgs = (22 != $appLicenceInfo->sshPort)? "-p {$appLicenceInfo->sshPort}" : '';
  481. $rsyncSshPort = (22 != $appLicenceInfo->sshPort)? "-e 'ssh -p {$appLicenceInfo->sshPort}'" : '';
  482. if (V::get('DBG_REMOTE', '', $_GET)) {// DBG
  483. $cmd = "echo ~";
  484. V::exec("ssh {$sshArgs} {$sshHostUsr} '{$cmd}'", $out, $ret);
  485. DBG::_(true, true, "exec(ssh ... 'cmd'): {$cmd} (return: {$ret})", $out, __CLASS__, __FUNCTION__, __LINE__);
  486. V::execRemote($appLicenceInfo->mainServer, $appLicenceInfo->rootLogin, $appLicenceInfo->rootPassword, $cmd, $out, $ret, $appLicenceInfo->sshPort);
  487. DBG::_(true, true, "execRemote(cmd): {$cmd} (return: {$ret})", $out, __CLASS__, __FUNCTION__, __LINE__);
  488. V::execRootRemote($appLicenceInfo->mainServer, $appLicenceInfo->rootLogin, $appLicenceInfo->rootPassword, $cmd, $out, $ret, $appLicenceInfo->sshPort);
  489. DBG::_(true, true, "execRootRemote(cmd): {$cmd} (return: {$ret})", $out, __CLASS__, __FUNCTION__, __LINE__);
  490. }
  491. $cmd = "echo ~";
  492. V::exec("ssh {$sshArgs} {$sshHostUsr} '{$cmd}'", $out, $ret);
  493. DBG::_(true, true, "exec(ssh ... '{$cmd}') (return: {$ret})", $out, __CLASS__, __FUNCTION__, __LINE__);
  494. if (empty($out) || empty($out[0])) throw new Exception("Cannot fetch remote home dir");
  495. return $out[0];
  496. }
  497. public function _sendToRemoteTestDir($appLicenceInfo) {
  498. $cmd = ''; $out = ''; $ret = '';
  499. $this->_assertRsaKeyExists($appLicenceInfo);
  500. $sshHostUsr = "{$appLicenceInfo->rootLogin}@{$appLicenceInfo->mainServer}";
  501. $sshArgs = (22 != $appLicenceInfo->sshPort)? "-p {$appLicenceInfo->sshPort}" : '';
  502. $rsyncSshPort = (22 != $appLicenceInfo->sshPort)? "-e 'ssh -p {$appLicenceInfo->sshPort}'" : '';
  503. // $appLicenceInfo->sshPort
  504. /* rsync options:
  505. -a, --archive archive mode; same as -rlptgoD (no -H)
  506. -u, --update skip files that are newer on the receiver
  507. -t, --times preserve times
  508. --delete delete extraneous files from dest dirs
  509. */
  510. DBG::_(true, true, "remote home dir:", $this->_fetchRemoteHomeDir($appLicenceInfo), __CLASS__, __FUNCTION__, __LINE__);
  511. $cmd = "
  512. ssh {$sshArgs} {$sshHostUsr} '[ ! -d ~/se.encrypted.upgrade ] && mkdir ~/se.encrypted.upgrade || echo 1';
  513. ssh {$sshArgs} {$sshHostUsr} 'rm -rf ~/se.encrypted.upgrade/SE';
  514. ssh {$sshArgs} {$sshHostUsr} 'cp -r /Library/Server/Web/Data/Sites/Default/SE ~/se.encrypted.upgrade/SE';
  515. ssh {$sshArgs} {$sshHostUsr} 'rm -rf ~/se.encrypted.upgrade/SE/config';
  516. rsync --archive --times --delete --compress --one-file-system --omit-dir-times --no-g --no-perms \
  517. --verbose {$rsyncSshPort} \
  518. --exclude='stuff/qgis__kyngchaos.com' \
  519. --exclude='stuff/qgis__kyngchaos.com/QGIS-2.14.3-1.dmg' \
  520. --exclude='stuff/postgis' \
  521. --exclude='stuff/postgis2' \
  522. --exclude='stuff/KindleGen_Mac_i386_v2_9' \
  523. --exclude='stuff/jdk-8u121-macosx-x64.dmg' \
  524. --exclude='stuff/jre-8u112-macosx-x64.tar.gz' \
  525. --exclude='stuff/jre-8u121-macosx-x64.dmg' \
  526. --exclude='schema/default_db.instance.xml' \
  527. --exclude='schema/default_db_xml_cache.public' \
  528. --exclude='schema/default_db.instance.xml/**' \
  529. --exclude='schema/default_db_xml_cache.public/**' \
  530. '{$appLicenceInfo->installPath}/SE/' {$sshHostUsr}:~/se.encrypted.upgrade/SE/;
  531. ssh {$sshArgs} {$sshHostUsr} 'cp -r /Library/Server/Web/Data/Sites/Default/SE/config ~/se.encrypted.upgrade/SE/';
  532. ssh {$sshArgs} {$sshHostUsr} 'rm /Library/Server/Web/Data/Sites/Default/se.encrypted.upgrade'
  533. ssh {$sshArgs} {$sshHostUsr} 'ln -s ~/se.encrypted.upgrade/SE /Library/Server/Web/Data/Sites/Default/se.encrypted.upgrade'
  534. ";
  535. // --dry-run \
  536. V::exec($cmd, $out, $ret);
  537. DBG::_(true, true, "cmd: {$cmd} (return: {$ret})", $out, __CLASS__, __FUNCTION__, __LINE__);
  538. if (0 !== $ret) throw new Exception("Cannot run remote command using rsa key! #{$ret}");
  539. }
  540. public function upgradeRemoteFromTestDirAction() {
  541. session_write_close();
  542. $args = array();
  543. $args['licence_id'] = V::get('licence_id', 0, $_REQUEST, 'int');
  544. UI::gora();
  545. //UI::menu();
  546. //$this->menu($args['licence_id']);// TODO: GO BACK BTN
  547. try {
  548. $appLicenceInfo = $this->getAppLicenceInfo($args['licence_id']);
  549. $this->_upgradeRemoteFromTestDir($appLicenceInfo);
  550. echo "Test online: ";
  551. echo UI::h('a', ['target'=>"_blank", 'href'=>"https://{$appLicenceInfo->mainServer}/SE/"], "https://{$appLicenceInfo->mainServer}/SE/");
  552. } catch (Exception $e) {
  553. $this->_endWithException($e);
  554. }
  555. UI::dol();
  556. }
  557. public function _upgradeRemoteFromTestDir($appLicenceInfo) {
  558. $cmd = ''; $out = ''; $ret = '';
  559. $this->_assertRsaKeyExists($appLicenceInfo);
  560. $dateStr = date("Y-m-d_H-i-s");
  561. // $remoteHomeDir = "/Users/{$appLicenceInfo->rootLogin}";// BUG: alias like in ams - login = prezes is alias for arkadiuszbinder
  562. $remoteHomeDir = $this->_fetchRemoteHomeDir($appLicenceInfo);
  563. $cmd = "
  564. rm -rf /Library/Server/Web/Data/Sites/Default/SE.test 2>&1
  565. cp -r {$remoteHomeDir}/se.encrypted.upgrade/SE /Library/Server/Web/Data/Sites/Default/SE.test 2>&1
  566. [ ! -d {$remoteHomeDir}/bup.se.upgrade ] && mkdir {$remoteHomeDir}/bup.se.upgrade || echo 1
  567. [ ! -d {$remoteHomeDir}/bup.se.upgrade ] && exit 1
  568. [ ! -d {$remoteHomeDir}/bup.se.upgrade-testttttt ] && exit 1
  569. [ ! -f /Library/Server/Web/Data/Sites/Default/SE.test/VERSION ] && echo \"Error: plik VERSION nie istnieje\" || echo \"check VERSION OK\"
  570. [ ! -f /Library/Server/Web/Data/Sites/Default/SE.test/VERSION ] && exit 1
  571. [ ! -f /Library/Server/Web/Data/Sites/Default/SE.test/index.php ] && echo \"Error: plik index.php nie istnieje\" || echo \"check index.php OK\"
  572. [ ! -f /Library/Server/Web/Data/Sites/Default/SE.test/index.php ] && exit 1
  573. [ ! -d /Library/Server/Web/Data/Sites/Default/SE.test/se-lib ] && echo \"Error: plik se-lib nie istnieje\" || echo \"check se-lib OK\"
  574. [ ! -d /Library/Server/Web/Data/Sites/Default/SE.test/se-lib ] && exit 1
  575. exit 0
  576. ";
  577. V::execRootRemote($appLicenceInfo->mainServer, $appLicenceInfo->rootLogin, $appLicenceInfo->rootPassword, $cmd, $out, $ret, $appLicenceInfo->sshPort);
  578. $cmd = "
  579. mv /Library/Server/Web/Data/Sites/Default/SE {$remoteHomeDir}/bup.se.upgrade/bup.{$dateStr} 2>&1
  580. mv /Library/Server/Web/Data/Sites/Default/SE.test /Library/Server/Web/Data/Sites/Default/SE 2>&1
  581. exit 0
  582. ";
  583. V::execRootRemote($appLicenceInfo->mainServer, $appLicenceInfo->rootLogin, $appLicenceInfo->rootPassword, $cmd, $out, $ret, $appLicenceInfo->sshPort);
  584. DBG::_(true, true, "cmd: {$cmd} (return: {$ret})", $out, __CLASS__, __FUNCTION__, __LINE__);
  585. if (0 !== $ret) throw new Exception("Cannot run remote command as root! #{$ret}");
  586. // TODO: SE/bash_install_check.php requires $domain!
  587. // $cmd = "/usr/bin/php /Library/Server/Web/Data/Sites/Default/SE/bash_install_check.php {$domain}";
  588. // V::execRootRemote($appLicenceInfo->mainServer, $appLicenceInfo->rootLogin, $appLicenceInfo->rootPassword, $cmd, $out, $ret, $appLicenceInfo->sshPort);
  589. // DBG::_(true, true, "cmd: {$cmd} (return: {$ret})", $out, __CLASS__, __FUNCTION__, __LINE__);
  590. // if (0 !== $ret) throw new Exception("Cannot run remote command as root! #{$ret}");
  591. }
  592. public function _assertRsaKeyExists($appLicenceInfo) {
  593. $cmd = ''; $out = ''; $ret = '';
  594. $cmd = "echo ~ && pwd";// /Library/WebServer
  595. $cmd = "ls -1 ~/.ssh/";
  596. //$cmd = "rm /tmp/id_rsa";
  597. //$cmd = "rm /tmp/id_rsa.pub";
  598. //$cmd = "ssh-keygen -t rsa -N '' -C '_www@biuro.biall-net.pl' -f /tmp/id_rsa";
  599. //$cmd = "ssh-keygen -t rsa -N '' -C '_www@biuro.biall-net.pl' -f /tmp/id_rsa";
  600. V::exec($cmd, $out, $ret);
  601. DBG::_(true, true, "cmd: {$cmd} (return: {$ret})", $out, __CLASS__, __FUNCTION__, __LINE__);
  602. if (0 !== $ret) {// no ~/.ssh directory
  603. $rsaKeyPath = "~/.ssh";
  604. $cmds = array();
  605. $cmds[] = "mkdir {$rsaKeyPath}";
  606. $cmds[] = "ssh-keygen -t rsa -N '' -C '_www@biuro.biall-net.pl' -f {$rsaKeyPath}/id_rsa 2>&1";
  607. $cmds[] = "ls -1 $rsaKeyPath";
  608. foreach ($cmds as $cmd) {
  609. V::exec($cmd, $out, $ret);
  610. DBG::_(true, true, "cmd: {$cmd} (return: {$ret})", $out, __CLASS__, __FUNCTION__, __LINE__);
  611. if (0 !== $ret) throw new Exception("Error '{$ret}' cmd({$cmd}): " . implode("\n", $out));
  612. }
  613. }
  614. $cmd = "cat ~/.ssh/id_rsa.pub";
  615. V::exec($cmd, $out, $ret);
  616. DBG::_(true, true, "cmd: {$cmd} (return: {$ret})", $out, __CLASS__, __FUNCTION__, __LINE__);
  617. if (0 !== $ret || empty($out) || empty($out[0])) throw new Exception("Cannot read rsa public key");
  618. $rsaPubKey = $out[0];
  619. $cmd = 'ls -1a';
  620. $cmd = "
  621. [ ! -d ~/.ssh ] && mkdir ~/.ssh;
  622. [ ! -d ~/.ssh ] && echo 'ERROR ~/.ssh not exists and cannot be created';
  623. [ ! -f ~/.ssh/authorized_keys ] && echo '{$rsaPubKey}' > ~/.ssh/authorized_keys;
  624. [ ! -f ~/.ssh/authorized_keys ] && echo 'ERROR ~/.ssh/authorized_keys not exists and cannot be created';
  625. cat ~/.ssh/authorized_keys| grep '{$rsaPubKey}' && echo 'OK' || echo '{$rsaPubKey}' >> ~/.ssh/authorized_keys;
  626. chmod 600 ~/.ssh/authorized_keys;
  627. ";
  628. V::execRemote($appLicenceInfo->mainServer, $appLicenceInfo->rootLogin, $appLicenceInfo->rootPassword, $cmd, $out, $ret, $appLicenceInfo->sshPort);
  629. DBG::_(true, true, "remote cmd: {$cmd} (return: {$ret})", $out, __CLASS__, __FUNCTION__, __LINE__);
  630. //$cmd = "ssh server@{$appLicenceInfo->mainServer} 'ls -1 .ssh/'";
  631. //$cmd = "ssh -i ~/.ssh/id_rsa server@{$appLicenceInfo->mainServer} 'ls -1'";
  632. $sshPort = (22 != $appLicenceInfo->sshPort)? "-p {$appLicenceInfo->sshPort}" : '';
  633. $cmd = "ssh {$sshPort} {$appLicenceInfo->rootLogin}@{$appLicenceInfo->mainServer} 'ls -1'";
  634. V::exec($cmd, $out, $ret);
  635. DBG::_(true, true, "cmd: {$cmd} (return: {$ret})", $out, __CLASS__, __FUNCTION__, __LINE__);
  636. if (0 !== $ret) throw new Exception("Cannot run remote command using rsa key! #{$ret}");
  637. }
  638. }