Install.php 31 KB

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