Install.php 29 KB

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