Install.php 29 KB

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