Install.php 28 KB

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