Install.php 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932
  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 __construct() {
  7. $this->sshArgsSkipHostKey = ' -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no ';
  8. }
  9. public function handleAuth() {
  10. if (!User::logged()) {
  11. throw new HttpException('Unauthorized', 401);
  12. }
  13. if (!User::isAdmin()) {
  14. throw new HttpException('Unauthorized - only for administrators', 401);
  15. }
  16. }
  17. public function defaultAction() {
  18. UI::gora();
  19. UI::menu();
  20. $this->menu();
  21. UI::setTitleJsTag("Install");
  22. UI::dol();
  23. }
  24. public function menu() {
  25. $serversList = $this->fetchActiveLicences();
  26. ?>
  27. <div class="jumbotron">
  28. <div class="container">
  29. <form class="form-inline" method="GET">
  30. <input type="hidden" name="_route" value="Install" />
  31. <input type="hidden" name="_task" value="createApp" />
  32. <label>Przygotuj kod źródłowy do aktualizacji na serwerze klienta:</label>
  33. <select id="servers_list" class="form-control" name="licence_id">
  34. <?php foreach ($serversList as $srv) : ?>
  35. <option value="<?php echo $srv->ID; ?>">[<?php echo $srv->ID; ?>] <?php echo $srv->domain; ?></option>
  36. <?php endforeach; ?>
  37. </select>
  38. <button type="submit" id="fldSbmtBtn" class="btn btn-primary" autocomplete="off">
  39. Generuj
  40. </button>
  41. <div id="servers_list_react"></div>
  42. </form>
  43. </div>
  44. </div>
  45. <script type="text/javascript">
  46. jQuery(document).ready(function () {
  47. jQuery('#fldSbmtBtn').on('click', function () {
  48. jQuery(this).text(jQuery(this).text() + '...').attr('disabled', 'disabled');
  49. jQuery(this).parent().submit();
  50. })
  51. });
  52. </script>
  53. <?php
  54. echo UI::h('script', ['src'=>"static/vendor.js", 'type'=>"text/javascript"]);
  55. // echo UI::h('script', ['src'=>"https://cdnjs.cloudflare.com/ajax/libs/react/15.4.2/react.js", 'type'=>"text/javascript"]);
  56. // echo UI::h('script', ['src'=>"https://cdnjs.cloudflare.com/ajax/libs/react/15.4.2/react-dom.js", 'type'=>"text/javascript"]);
  57. // echo UI::h('script', ['src'=>"https://cdnjs.cloudflare.com/ajax/libs/react-bootstrap-typeahead/0.10.4/react-bootstrap-typeahead.js", 'type'=>"text/javascript"]);
  58. $jsonServersList = array_values(array_map(
  59. function ($srv) {
  60. return [
  61. 'id' => $srv->ID,
  62. 'label' => "{$srv->domain} [{$srv->ID}]"
  63. ];
  64. },
  65. $serversList
  66. ));
  67. echo UI::h('script', ['type'=>"text/javascript"], "
  68. (function(global){
  69. if (!global.p5VendorJs) { console.warn('Brak p5VendorJs'); return; }
  70. if (!global.p5VendorJs.React) { console.warn('Brak p5VendorJs.React'); return; }
  71. if (!global.p5VendorJs.ReactDOM) { console.warn('Brak p5VendorJs.ReactDOM'); return; }
  72. if (!global.p5VendorJs.Typeahead) { console.warn('Brak p5VendorJs.Typeahead'); return; }
  73. const React = global.p5VendorJs.React;
  74. const ReactDOM = global.p5VendorJs.ReactDOM;
  75. const Typeahead = global.p5VendorJs.Typeahead;
  76. var options = ".json_encode($jsonServersList).";
  77. var selected = [];
  78. var onInputChange = function (query) {
  79. // console.log('onInputChange:: query', query);
  80. }
  81. var onChange = function (value) {
  82. // console.log('onChange:: value', value);
  83. if (value.length > 0) {
  84. var id = value[0]['id'];
  85. if (id > 0) {
  86. document.getElementById('servers_list').value = id;
  87. }
  88. }
  89. }
  90. ReactDOM.render(
  91. React.createElement(Typeahead, {
  92. options: options,
  93. emptyLabel: 'Brak danych',
  94. placeholder: 'Wybierz serwer',
  95. selected: selected,
  96. // onInputChange: onInputChange,
  97. onChange: onChange,
  98. }, null),
  99. document.getElementById('servers_list_react')
  100. );
  101. })(window);
  102. ");
  103. }
  104. public function createAppAction() {
  105. session_write_close();
  106. $args = array();
  107. $args['licence_id'] = V::get('licence_id', 0, $_REQUEST, 'int');
  108. UI::gora();
  109. UI::menu();
  110. UI::setTitleJsTag("Install");
  111. //$this->menu($args['licence_id']);// TODO: GO BACK BTN
  112. try {
  113. $appLicenceInfo = $this->getAppLicenceInfo($args['licence_id']);
  114. $this->validateAppLicenceInfo($appLicenceInfo);
  115. } catch (Exception $e) {
  116. $this->_endWithException($e);
  117. }
  118. // $this->generateApp($appLicenceInfo->installPath, $appLicenceInfo->domains);
  119. //DBG::_(true, true, "appLicenceInfo", $appLicenceInfo, __CLASS__, __FUNCTION__, __LINE__);
  120. if ('_generateEncryptedSource' === V::get('_postTask', '', $_POST)) {
  121. echo '<div class="container">';
  122. echo '<h4>' . "Generowanie..." . '</h4>';
  123. echo '<div style="border:1px solid silver; max-height:400px; overflow-y:scroll">';
  124. try {
  125. $this->validateAppLicenceInfo($appLicenceInfo);
  126. $this->generateApp($appLicenceInfo->installPath, $appLicenceInfo->domains);
  127. // TODO: $this->generateConfigs($appLicenceInfo->installPath, $appLicenceInfo->domains);
  128. } catch (Exception $e) {
  129. echo '</div></div>';// .container/ scroll
  130. $this->_endWithException($e);
  131. }
  132. echo '</div>';// .container
  133. UI::alert('success', "<strong>Gotowe</strong> Aplikacja znajduje się w katalogu {$appLicenceInfo->installFolderName}");
  134. $appLicenceInfo = $this->getAppLicenceInfo($args['licence_id']);
  135. }
  136. if ('newGenerateApp' === V::get('_postTask', '', $_POST)) {
  137. $this->newGenerateApp($appLicenceInfo);
  138. }
  139. if ('updateAndSendToRemoteTestDir' === V::get('_postTask', '', $_POST)) {
  140. echo '<details><summary style="cursor:pointer">aktualizuj werjsę, szyfruj i wyślij do testowego katalogu na serwerze</summary>';
  141. try {
  142. $idLicence = V::get('licence_id', 0, $_POST, 'int');
  143. $appLicenceInfo = $this->getAppLicenceInfo($idLicence);
  144. $this->validateAppLicenceInfo($appLicenceInfo);
  145. $this->gitResetHard($appLicenceInfo->installPath, $appLicenceInfo->projects);
  146. flush();
  147. $this->_encodeSource($appLicenceInfo->installPath, $appLicenceInfo->domains);
  148. flush();
  149. $this->_sendToRemoteTestDir($appLicenceInfo);
  150. } catch (Exception $e) {
  151. DBG::log($e);
  152. UI::alert('danger', $e->getMessage());
  153. }
  154. echo '</details>';
  155. $testDirUrl = "https://{$appLicenceInfo->mainServer}/se.encrypted.upgrade/";
  156. UI::alert('info', UI::h('p', [], [
  157. "testowy katalog zaktualizowany - ",
  158. UI::h('a', [ 'href' => $testDirUrl, 'target' => "_blank" ], $testDirUrl),
  159. ]));
  160. flush();
  161. }
  162. // echo UI::hButtonPost("TODO: Generuj z p5.git", [
  163. // 'class' => "btn btn-md btn-primary",
  164. // 'data' => [
  165. // '_postTask' => "newGenerateApp",
  166. // 'licence_id' => $appLicenceInfo->ID,
  167. // ],
  168. // ]);
  169. echo UI::h('div', [ 'class' => "jumbotron" ], [
  170. UI::h('div', [ 'class' => "container" ], [
  171. UI::h('h3', [], "Generowanie aplikacji dla licencji {$appLicenceInfo->ID}"),
  172. UI::h('p', [], "Licencja dla domen: " . implode(', ', $appLicenceInfo->domains)),
  173. UI::h('p', [], "Katalog z zakodowanymi plikami: {$appLicenceInfo->installFolderName}"),
  174. UI::hButtonPost("Generuj", [
  175. 'class' => "btn btn-primary",
  176. 'data' => [
  177. '_postTask' => '_generateEncryptedSource',
  178. 'licence_id' => $appLicenceInfo->ID,
  179. ]
  180. ]),
  181. (!$appLicenceInfo->installFolderGitExists)
  182. ? UI::h('div', [ 'class' => "alert alert-info" ], "Katalog nie istnieje - wygeneruj aplikację")
  183. : UI::h('div', [ 'class' => "alert alert-info", 'style' => "margin-top:10px" ], [
  184. UI::h('p', [], "Katalog istnieje i zawiera już repozytorium git: "),
  185. UI::h('p', [], [
  186. UI::hButtonPost("aktualizuj werjsę, szyfruj i wyślij do testowego katalogu na serwerze", [
  187. 'class' => "btn btn-xs btn-primary",
  188. 'data' => [
  189. '_postTask' => "updateAndSendToRemoteTestDir",
  190. 'licence_id' => $appLicenceInfo->ID,
  191. ],
  192. ]),
  193. ]),
  194. UI::h('p', [ 'style' => "margin-left:20px" ], [
  195. UI::h('a', [
  196. 'href' => "index.php?_route=Install&_task=gitResetHard&licence_id={$appLicenceInfo->ID}",
  197. 'target' => "_blank",
  198. 'class' => "btn btn-xs btn-default"
  199. ], "aktualizuj werjsę"),
  200. " (git reset --hard, git pull, set SE/VERSION - tak samo co 'rm -rf; git clone', ale szybciej)",
  201. ]),
  202. UI::h('p', [ 'style' => "margin-left:20px" ], [
  203. UI::h('a', [
  204. 'href' => "index.php?_route=Install&_task=configGenerate&licence_id={$appLicenceInfo->ID}",
  205. 'target' => "_blank",
  206. 'class' => "btn btn-xs btn-default"
  207. ], "generuj pliki konfiguracyjne"),
  208. ]),
  209. UI::h('p', [ 'style' => "margin-left:20px" ], [
  210. UI::h('a', [
  211. 'href' => "index.php?_route=Install&_task=encodeSource&licence_id={$appLicenceInfo->ID}",
  212. 'target' => "_blank",
  213. 'class' => "btn btn-xs btn-default"
  214. ], "encode files"),
  215. ]),
  216. UI::h('p', [ 'style' => "margin-left:20px" ], [
  217. UI::h('a', [
  218. 'href' => "index.php?_route=Install&_task=sendToRemoteTestDir&licence_id={$appLicenceInfo->ID}",
  219. 'target' => "_blank",
  220. 'class' => "btn btn-xs btn-default"
  221. ], "send encoded files to remote server test folder (generates ssh key if not set)"),
  222. ]),
  223. UI::h('p', [ 'style' => "margin-top:30px" ], [
  224. "Test online: ",
  225. UI::h('a', [
  226. 'target' => "_blank",
  227. 'href' => "https://{$appLicenceInfo->mainServer}/se.encrypted.upgrade/"
  228. ], "https://{$appLicenceInfo->mainServer}/se.encrypted.upgrade/"),
  229. ]),
  230. "<br> - ",
  231. UI::h('a', [
  232. 'href' => "index.php?_route=Install&_task=upgradeRemoteFromTestDir&licence_id={$appLicenceInfo->ID}",
  233. 'onclick' => "return confirm('Uruchomić aktualizację SE na https://{$appLicenceInfo->mainServer}/SE/?')",
  234. 'target' => "_blank",
  235. 'class' => "btn btn-xs btn-warning"
  236. ], "UPGRADE Production folder from uploaded dir: ~/se.encrypted.upgrade/"),
  237. ]),
  238. ]),
  239. ]);
  240. ?>
  241. <script type="text/javascript">
  242. jQuery(document).ready(function () {
  243. jQuery('#fldSbmtBtn').on('click', function () {
  244. jQuery(this).text(jQuery(this).text() + '...').attr('disabled', 'disabled');
  245. jQuery(this).parent().submit();
  246. })
  247. });
  248. </script>
  249. <?php
  250. UI::dol();
  251. }
  252. public function configGenerateAction() {
  253. session_write_close();
  254. $args = array();
  255. $args['licence_id'] = V::get('licence_id', 0, $_REQUEST, 'int');
  256. UI::gora();
  257. UI::menu();
  258. //$this->menu($args['licence_id']);// TODO: GO BACK BTN
  259. try {
  260. $appLicenceInfo = $this->getAppLicenceInfo($args['licence_id']);
  261. $this->validateAppLicenceInfo($appLicenceInfo);
  262. UI::startContainer();
  263. $this->configGenerate($appLicenceInfo->configPath, $appLicenceInfo->mainServer, $appLicenceInfo->rootPassword
  264. , $appLicenceInfo->ldapUser, $appLicenceInfo->ldapPass, $appLicenceInfo->ldapBaseDN
  265. );
  266. UI::endContainer();
  267. } catch (Exception $e) {
  268. $this->_endWithException($e);
  269. }
  270. UI::dol();
  271. }
  272. public function configGenerate($configPath, $mainServer, $rootPassword, $ldapUser, $ldapPass, $ldapBaseDN) {
  273. if (empty($configPath)) throw new Exception("Install path not found");
  274. $cmds = array();
  275. $cmds[] = "mkdir '{$configPath}'";
  276. $REMOTE_FOLDER_ROOT = str_replace([ ".", "-" ], '_', $mainServer);
  277. $cmds[] = ' echo "' . V::quoteBashEcho(
  278. Config::generateDefaultDbConfigFile(
  279. [
  280. 'database' => $REMOTE_FOLDER_ROOT,
  281. 'password' => $rootPassword,
  282. ],
  283. $outputFormat = 'inc'
  284. )
  285. ) . '" > ' . $configPath . '/.cnf--default_db-' . $mainServer . '.inc.php';
  286. $cmds[] = ' echo "' . V::quoteBashEcho(
  287. Config::generateDefaultDbConfigFile(
  288. [
  289. 'database' => $REMOTE_FOLDER_ROOT,
  290. 'password' => $rootPassword,
  291. ],
  292. $outputFormat = 'inc'
  293. )
  294. ) . '" > ' . $configPath . '/.cnf--zasob_2-' . $mainServer . '.inc.php';
  295. $cmds[] = ' echo "' . V::quoteBashEcho(
  296. Config::generateDefaultLdapConfigFile(
  297. [
  298. 'user' => $ldapUser,
  299. 'pass' => $ldapPass,
  300. 'base_dn' => $ldapBaseDN,
  301. ],
  302. $outputFormat = 'inc'
  303. )
  304. ) . '" > ' . $configPath . '/.cnf--default_ldap-' . $mainServer . '.inc.php';
  305. $hasError = false;
  306. foreach ($cmds as $cmd) {
  307. V::exec($cmd, $out, $ret);
  308. if (0 !== $ret) $hasError = true;
  309. DBG::nicePrint($out, "cmd: `{$cmd}` (return:{$ret})");
  310. }
  311. if (!$hasError) {
  312. UI::alert('success', "OK");
  313. } else {
  314. UI::alert('danger', "errors");
  315. }
  316. }
  317. public function gitResetHardAction() {
  318. session_write_close();
  319. $args = array();
  320. $args['licence_id'] = V::get('licence_id', 0, $_REQUEST, 'int');
  321. UI::gora();
  322. UI::menu();
  323. //$this->menu($args['licence_id']);// TODO: GO BACK BTN
  324. try {
  325. $appLicenceInfo = $this->getAppLicenceInfo($args['licence_id']);
  326. $this->validateAppLicenceInfo($appLicenceInfo);
  327. UI::startContainer();
  328. $this->gitResetHard($appLicenceInfo->installPath, $appLicenceInfo->projects);
  329. UI::endContainer();
  330. } catch (Exception $e) {
  331. $this->_endWithException($e);
  332. }
  333. UI::dol();
  334. }
  335. public function gitResetHard($installPath, $projects = []) {
  336. if (empty($installPath)) throw new Exception("Install path not found");
  337. $cmds = array();
  338. $cmds[] = "git reset --hard";
  339. $cmds[] = "git pull";
  340. $cmds[] = "echo `git show-ref --head|head -1|head -c 8` > SE/VERSION ";
  341. $hasError = false;
  342. foreach ($cmds as $cmd) {
  343. V::exec("cd {$installPath} && {$cmd}", $out, $ret);
  344. if (0 !== $ret) $hasError = true;
  345. DBG::nicePrint($out, "cmd: `{$cmd}` (return:{$ret})");
  346. }
  347. foreach ($projects as $projectName) {
  348. $cmd = "ls -l SE/projects/{$projectName} | wc -l";
  349. V::exec("cd {$installPath} && {$cmd}", $out, $ret);
  350. DBG::nicePrint([ 'cmd' => $cmd, 'output' => $out ], "return: {$ret}");
  351. if (!empty($out) && '0' !== trim($out[0])) {
  352. // $cmd = "git submodule update SE/projects/{$projectName}";
  353. $cmd = "cd SE/projects/{$projectName} && git reset --hard"; // revert encode source - checkout to last commit (need update)
  354. V::exec("cd {$installPath} && {$cmd}", $out, $ret);
  355. DBG::nicePrint([ 'cmd' => $cmd, 'output' => $out ], "return: {$ret}");
  356. }
  357. $cmd = "git submodule update --init SE/projects/{$projectName}"; // checkout to current commit
  358. V::exec("cd {$installPath} && {$cmd}", $out, $ret);
  359. DBG::nicePrint([ 'cmd' => $cmd, 'output' => $out ], "return: {$ret}");
  360. }
  361. if (!$hasError) {
  362. UI::alert('success', "OK");
  363. } else {
  364. UI::alert('danger', "errors");
  365. }
  366. }
  367. public function encodeSourceAction() {
  368. session_write_close();
  369. $args = array();
  370. $args['licence_id'] = V::get('licence_id', 0, $_REQUEST, 'int');
  371. UI::gora();
  372. UI::menu();
  373. //$this->menu($args['licence_id']);// TODO: GO BACK BTN
  374. try {
  375. $appLicenceInfo = $this->getAppLicenceInfo($args['licence_id']);
  376. $this->validateAppLicenceInfo($appLicenceInfo);
  377. $this->_encodeSource($appLicenceInfo->installPath, $appLicenceInfo->domains);
  378. } catch (Exception $e) {
  379. $this->_endWithException($e);
  380. }
  381. UI::dol();
  382. }
  383. public function _encodeSource($installPath, $domains) {
  384. UI::startContainer();
  385. $this->encodeSourceFiles($installPath, $domains, $dbg = true);
  386. // try {
  387. // $this->encodeSourceFiles($appLicenceInfo->installPath, $appLicenceInfo->domains, $dbg = false);
  388. // UI::alert('success', "OK");
  389. // } catch (Exception $e) {
  390. // UI::alert('danger', $e->getMessage());
  391. // }
  392. UI::endContainer();
  393. }
  394. // @usage: Router::getRoute('Install')->encodeSourceFiles($installPath = '/path_to_git_repo', $domains = [ 'domain.com', 'localhost' ], $dbg = false);
  395. public function encodeSourceFiles($installPath, $domains, $dbg = false) {
  396. if (empty($installPath)) throw new Exception("Install path not found");
  397. if (empty($domains)) throw new Exception("Domains not found");
  398. $phpVersionsForSgencoder = '--phpversion 5.5 --phpversion 5.6';// encode for PHP 5.x (currently supported PHP 5.0-5.6)
  399. if ('1' == V::get('DBG_ENCODER_HELP', '', $_REQUEST)) {// encoder help
  400. $cmd = "cd {$installPath}/SE && /Applications/SourceGuardian.app/Contents/MacOS/sgencoder --help ";
  401. $out = ''; $ret = '';
  402. V::exec($cmd, $out, $ret);
  403. DBG::nicePrint($out, "cmd: `{$cmd}` (return:{$ret})");
  404. exit;
  405. }
  406. $domainEncodePhpFiles = [
  407. 'ant.php',
  408. 'api.php',
  409. 'budynki.php',
  410. 'index-ajax.php',
  411. 'index.php',
  412. 'procesy5.php',
  413. 'session-expire.php',
  414. 'test-sync.php',
  415. 'wfs-data.php',
  416. 'wfs-qgis.php',
  417. 'wfs.php',
  418. ];
  419. $cmd = "find . -name '*.php' ";
  420. $out = ''; $ret = '';
  421. V::exec("cd {$installPath}/SE && {$cmd}", $out, $ret);
  422. if ($dbg) DBG::nicePrint($out, "cmd: `{$cmd}` (return:{$ret})");
  423. else DBG::log($out, 'array', "cmd: `{$cmd}` (return:{$ret})");
  424. if (0 !== $ret) throw new Exception("Error at find php files");
  425. if (empty($out)) throw new Exception("No php files found");
  426. $allPhpFiles = array_map(function ($phpFilePath) {
  427. return ('./' == substr($phpFilePath, 0, 2))? substr($phpFilePath, 2) : $phpFilePath;
  428. }, $out);
  429. $freeEncodePhpFiles = array_filter($allPhpFiles, function ($phpFilePath) use ($domainEncodePhpFiles) {
  430. if ('se-lib/Vendor/' === substr($phpFilePath, 0, strlen('se-lib/Vendor/'))) return false; // SKIP se-lib/Vendor/*
  431. if ('.ini.php' === substr($phpFilePath, -1 * strlen('.ini.php'))) return false; // SKIP *.ini.php
  432. return (!in_array($phpFilePath, $domainEncodePhpFiles));
  433. });
  434. DBG::log($freeEncodePhpFiles, 'array', "\$freeEncodePhpFiles");
  435. if (empty($freeEncodePhpFiles)) throw new Exception("No php files to encode");
  436. $cmdTempl = "cd {$installPath}/SE && /Applications/SourceGuardian.app/Contents/MacOS/sgencoder {$phpVersionsForSgencoder} -b- ";
  437. $cmdDomainEncodeDomainsTempl = " --domain " . implode(" --domain ", array_merge($domains, ['localhost']));
  438. $cmdDomainEncodeFilesTempl = " " . implode(" ", $domainEncodePhpFiles);
  439. $cmdFreeEncodeFilesTempl = " " . implode(" ", $freeEncodePhpFiles);
  440. $cmds = [
  441. $cmdTempl . $cmdDomainEncodeDomainsTempl . $cmdDomainEncodeFilesTempl,
  442. $cmdTempl . $cmdFreeEncodeFilesTempl,
  443. ];
  444. $returnValues = [];
  445. foreach ($cmds as $cmd) {
  446. $out = ''; $ret = '';
  447. V::exec($cmd, $out, $ret);
  448. $encoderSummaryLine = end($out);
  449. $returnValues[] = $encoderSummaryLine;
  450. if ($dbg) {
  451. DBG::nicePrint([$cmd], "cmd");
  452. DBG::nicePrint($out, "return: '{$ret}'");
  453. // DBG::nicePrint([$encoderSummaryLine], "cmd last line");
  454. }
  455. else DBG::log([$cmd, $out], 'array', "cmd return:'{$ret}'");
  456. // if (0 !== $ret) throw new Exception("Error at encode files");
  457. if (empty($out)) throw new Exception("No output for encode files command");
  458. }
  459. $statusInfo = array_reduce($returnValues, function ($ret, $encoderSummaryLine) {
  460. DBG::log([$ret, $encoderSummaryLine], 'array', "DBG reduce [\$ret, \$encoderSummaryLine]");
  461. $matches = [];
  462. preg_match_all('/(\d+) files, (\d+) processed, (\d+) errors/', $encoderSummaryLine, $matches, PREG_SET_ORDER, 0);
  463. return [
  464. 'files' => $ret['files'] + (int)$matches[0][1],
  465. 'processed' => $ret['processed'] + (int)$matches[0][2],
  466. 'errors' => $ret['errors'] + (int)$matches[0][3],
  467. ];
  468. }, [
  469. 'files' => 0,
  470. 'processed' => 0,
  471. 'errors' => 0,
  472. ]);
  473. if ($statusInfo['errors'] === 0 && $statusInfo['files'] > 0) {
  474. if ($dbg) UI::alert('success', "{$statusInfo['files']} files, {$statusInfo['processed']} processed, {$statusInfo['errors']} errors");
  475. } else {
  476. if ($dbg) UI::alert('danger', "{$statusInfo['files']} files, {$statusInfo['processed']} processed, {$statusInfo['errors']} errors");
  477. else throw new Exception("{$statusInfo['files']} files, {$statusInfo['processed']} processed, {$statusInfo['errors']} errors");
  478. }
  479. }
  480. public function getAppLicenceInfo($idLicence) {
  481. $idLicence = intval($idLicence);
  482. if (empty($idLicence)) throw new Exception("Nie wybrano serwera/licencji.");
  483. //DBG::_(true, true, 'idLicence', $idLicence, __CLASS__, __FUNCTION__, __LINE__);
  484. $appLicenceInfo = (object)$this->fetchAppLicenceInfo($idLicence);
  485. $appLicenceInfo->domains = $this->fetchDomainsByLicenceId($idLicence);
  486. $installRootPath = '/Library/Server/Web/Data/Sites/Default/PLIKI/SES_PROCESY5_A';
  487. $appLicenceInfo->installFolderName = "{$idLicence}_upgrade_SE_source_encrypted";
  488. $appLicenceInfo->configFolderName = "{$idLicence}_upgrade_SE_config_encrypted";
  489. $appLicenceInfo->installPath = "{$installRootPath}/{$appLicenceInfo->installFolderName}";
  490. $appLicenceInfo->configPath = "{$installRootPath}/{$appLicenceInfo->configFolderName}";
  491. //DBG::_(true, true, 'appLicenceInfo', $appLicenceInfo, __CLASS__, __FUNCTION__, __LINE__);
  492. if (empty($appLicenceInfo->domains)) throw new Exception("Domains not found."); // TODO: mv to validate
  493. $appLicenceInfo->installFolderExists = file_exists("{$appLicenceInfo->installPath}/SE");
  494. $appLicenceInfo->installFolderGitExists = file_exists("{$appLicenceInfo->installPath}/.git");
  495. // 'user' => $ADMIN_USERNAME_DIRECTORY,
  496. // 'pass' => $ADMIN_USERNAME_PASSWD,
  497. // 'base_dn' => $SERVER_ADDRESS_LDAP_DC,
  498. $appLicenceInfo->projects = []; // TODO: get from db
  499. if (!empty($appLicenceInfo->projects)) {
  500. $appLicenceInfo->projects = [ $appLicenceInfo->project ];
  501. }
  502. else if (79 == $idLicence) { // bravecom.procesy5.pl
  503. $appLicenceInfo->projects = [ 'bravecare' ];
  504. } else if (80 == $idLicence) { // bravecom.yellowgroup.pl
  505. $appLicenceInfo->projects = [ 'bocian' ];
  506. } else if (81 == $idLicence) { // bocian.procesy5.pl
  507. $appLicenceInfo->projects = [ 'bocian' ];
  508. } else if (67 == $idLicence) { // bocian.procesy5.pl
  509. $appLicenceInfo->projects = [ 'bocian' ];
  510. } else if (82 == $idLicence) { // bocian-energa.procesy5.pl
  511. $appLicenceInfo->projects = [ 'bocian' ];
  512. } else if (4 == $idLicence) { // bzyk.procesy5.pl
  513. $appLicenceInfo->projects = [ 'bocian' ];
  514. }
  515. return $appLicenceInfo;
  516. }
  517. public function validateAppLicenceInfo($appLicenceInfo) {
  518. if (empty($appLicenceInfo->ID)) throw new Exception("Nie wybrano serwera/licencji.");
  519. if (empty($appLicenceInfo->domains)) throw new Exception("Domains not found");
  520. if (empty($appLicenceInfo->installPath)) throw new Exception("Install path not found");
  521. }
  522. public function generateApp($installPath, $domains, $projects = []) {
  523. $cmds = array();
  524. $cmds[] = "if [ -d {$installPath} ] ; then rm -rf '{$installPath}'; fi";
  525. $cmds[] = "mkdir {$installPath}";
  526. $cmds[] = "cd {$installPath} && git clone --depth 1 ssh://git@biuro.biall-net.pl:2222/plabudda/se.git .";
  527. $cmds[] = "cd {$installPath} && echo `git show-ref --head|head -1|head -c 8` > SE/VERSION ";
  528. foreach ($cmds as $cmd) {
  529. V::exec($cmd, $out, $ret);
  530. DBG::nicePrint([ 'cmd' => $cmd, 'output' => $out ], "return: {$ret}");
  531. }
  532. foreach ($projects as $projectName) {
  533. $cmd = "ls -l SE/projects/{$projectName} | wc -l";
  534. V::exec("cd {$installPath} && {$cmd}", $out, $ret);
  535. DBG::nicePrint([ 'cmd' => $cmd, 'output' => $out ], "return: {$ret}");
  536. if (!empty($out) && '0' !== trim($out[0])) {
  537. // $cmd = "git submodule update SE/projects/{$projectName}";
  538. $cmd = "cd SE/projects/{$projectName} && git reset --hard"; // revert encode source - checkout to last commit (need update)
  539. V::exec("cd {$installPath} && {$cmd}", $out, $ret);
  540. DBG::nicePrint([ 'cmd' => $cmd, 'output' => $out ], "return: {$ret}");
  541. }
  542. $cmd = "git submodule update --init SE/projects/{$projectName}"; // checkout to current commit
  543. V::exec("cd {$installPath} && {$cmd}", $out, $ret);
  544. DBG::nicePrint([ 'cmd' => $cmd, 'output' => $out ], "return: {$ret}");
  545. }
  546. $this->_encodeSource($installPath, $domains);
  547. // 1763: $exec='cd '.$installer_dir.' && /Applications/SourceGuardian.app/Contents/MacOS/sgencoder -b-
  548. // '.INSTALL_SES_PROCESY_A::get_same_domains_for_install($h->SERVER_ADDRESS_SHORT).'
  549. // -r *.php
  550. // -x superedit-DB_PROCEDURES_CREATE.php
  551. // -x INI.php
  552. // -x .config_base_structure.php
  553. // ';
  554. //
  555. // INSTALL_SES_PROCESY_A::get_same_domains_for_install($h->SERVER_ADDRESS_SHORT):
  556. // $res2=DB::query("select SERVER_ADDRESS_SHORT from SES_PROCESY5_A where SERVER_ADDRESS_IP='".$h->SERVER_ADDRESS_IP."'");
  557. // while($h2=DB::fetch($res2)) {
  558. // $domain[]=' --domain '.$h2->SERVER_ADDRESS_SHORT;
  559. // ssh server@biuro.galeriaprzymorze.eu: PHP 5.5.20
  560. // ssh server@biuro.biall-net.pl
  561. // cd /Users/plabudda/procesy5-install-galeriaprzymorze.eu/
  562. // sudo chown -R server:admin SE/
  563. // /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
  564. }
  565. public function fetchActiveLicences() {
  566. $activeLic = array();
  567. $sql = "
  568. select l.`ID`
  569. , l.`SERVER_ADDRESS`
  570. , l.`SERVER_ADDRESS_SHORT` as domain -- domain for sgencoder
  571. , l.`SERVER_ADDRESS_IP`
  572. from `SES_PROCESY5_A` l
  573. where 1=1
  574. -- TODO: and l.`A_STATUS` in('NORMAL','WAITING')
  575. order by l.`ID` DESC
  576. ";
  577. $rows = DB::getPDO()->fetchAll($sql);
  578. foreach ($rows as $row) {
  579. $r = (object)$row;
  580. $activeLic[$r->ID] = $r;
  581. }
  582. return $activeLic;
  583. }
  584. public function fetchDomainsByLicenceId($licenceId) {
  585. $domains = array();
  586. $sql = "
  587. select g.`SERVER_ADDRESS_SHORT`, g.`SERVER_ADDRESS`
  588. from `SES_PROCESY5_A` g
  589. where g.`SERVER_ADDRESS_IP`=(select l.`SERVER_ADDRESS_IP`
  590. from `SES_PROCESY5_A` l
  591. where l.`ID`='{$licenceId}'
  592. -- TODO: and l.`A_STATUS` in('NORMAL','WAITING')
  593. )
  594. -- TODO: and g.`A_STATUS` in('NORMAL','WAITING')
  595. ";
  596. $rows = DB::getPDO()->fetchAll($sql);
  597. foreach ($rows as $row) {
  598. $r = (object)$row;
  599. $domains[] = $r->SERVER_ADDRESS_SHORT;
  600. if ($r->SERVER_ADDRESS != $r->SERVER_ADDRESS_SHORT) {
  601. $domains[] = $r->SERVER_ADDRESS;
  602. }
  603. }
  604. return $domains;
  605. }
  606. public function fetchMainServerByLicenceId($licenceId) {
  607. return DB::getPDO()->fetchValue("
  608. select g.`SERVER_ADDRESS`
  609. from `SES_PROCESY5_A` g
  610. where g.`ID`='{$licenceId}'
  611. -- TODO: and g.`A_STATUS` in('NORMAL','WAITING')
  612. ");
  613. }
  614. public function fetchAppLicenceInfo($licenceId) {
  615. $licenceInfo = null;
  616. $sql = "
  617. select g.ID
  618. , g.SERVER_ADDRESS as mainServer
  619. , g.ADMIN_USERNAME as rootLogin
  620. , g.ADMIN_USERNAME_PASSWD as rootPassword
  621. , g.SSH_PORT as sshPort
  622. , g.VERSION_GIT as project
  623. , g.ADMIN_USERNAME_DIRECTORY as ldapUser
  624. , g.ADMIN_USERNAME_PASSWD as ldapPass
  625. , g.SERVER_ADDRESS_LDAP_DC as ldapBaseDN
  626. from SES_PROCESY5_A g
  627. where g.`ID`=:id_licence
  628. -- TODO: and g.A_STATUS in('NORMAL','WAITING')
  629. ";
  630. $all = DB::getPDO()->fetchAll($sql, [ ':id_licence' => $licenceId ]);
  631. if (empty($all)) throw new Exception("Brak licencji o nr '{$licenceId}'");
  632. $licenceInfo = reset($all);
  633. if (!$licenceInfo['sshPort']) $licenceInfo['sshPort'] = 22;
  634. return $licenceInfo;
  635. }
  636. public function _endWithException($e) {
  637. echo UI::h('div', ['class'=>"container"], [
  638. UI::h('div', ['class' => "alert alert-danger"], "#" . $e->getLine() . ": " . $e->getMessage()),
  639. UI::h('p', [], [
  640. "Wróć do ",
  641. UI::h('a', ['href'=>"index.php?_route=Install"], "menu")
  642. ])
  643. ]);
  644. UI::dol();
  645. exit;
  646. }
  647. public function sendToRemoteTestDirAction() {
  648. session_write_close();
  649. $args = array();
  650. $args['licence_id'] = V::get('licence_id', 0, $_REQUEST, 'int');
  651. UI::gora();
  652. //UI::menu();
  653. //$this->menu($args['licence_id']);// TODO: GO BACK BTN
  654. try {
  655. $appLicenceInfo = $this->getAppLicenceInfo($args['licence_id']);
  656. $this->validateAppLicenceInfo($appLicenceInfo);
  657. // TODO: if (59 ) => baratosz.sledz - na lokalnym kompie
  658. // bn:~/$ scp -r SE server@192.168.61.153:~/se.encrypted.upgrade
  659. // remote SE.git = '/Users/bartoszsledz/Desktop/production-se'
  660. // remote:~/$ mv SE ~/SE.bup.2017-07-03
  661. // remote:~/$ mv ~/se.encrypted.upgrade/SE SE
  662. // remote:~/$ cp -r ~/SE.bup.2017-07-03/config SE/
  663. // remote:~/$ sudo chown -R bartoszsledz:staff SE/
  664. $this->_sendToRemoteTestDir($appLicenceInfo);
  665. echo "Test online: ";
  666. echo UI::h('a', ['target'=>"_blank", 'href'=>"https://{$appLicenceInfo->mainServer}/se.encrypted.upgrade/"], "https://{$appLicenceInfo->mainServer}/se.encrypted.upgrade/");
  667. } catch (Exception $e) {
  668. $this->_endWithException($e);
  669. }
  670. UI::dol();
  671. }
  672. public function _fetchRemoteHomeDir($appLicenceInfo) {
  673. $this->_assertRsaKeyExists($appLicenceInfo);
  674. $sshHostUsr = "{$appLicenceInfo->rootLogin}@{$appLicenceInfo->mainServer}";
  675. $sshArgs = (22 != $appLicenceInfo->sshPort)? "-p {$appLicenceInfo->sshPort}" : '';
  676. $scpArgs = (22 != $appLicenceInfo->sshPort)? "-P {$appLicenceInfo->sshPort}" : '';
  677. $rsyncSshPort = (22 != $appLicenceInfo->sshPort)? "-e 'ssh -p {$appLicenceInfo->sshPort}'" : '';
  678. if (V::get('DBG_REMOTE', '', $_GET)) {// DBG
  679. $cmd = "echo ~";
  680. V::exec("ssh {$sshArgs} {$sshHostUsr} '{$cmd}'", $out, $ret);
  681. DBG::log([ 'cmd-remote' => $cmd, 'output' => $out ], 'array', "return: {$ret}");
  682. V::execRemote($appLicenceInfo->mainServer, $appLicenceInfo->rootLogin, $appLicenceInfo->rootPassword, $cmd, $out, $ret, $appLicenceInfo->sshPort);
  683. DBG::log([ 'cmd-remote' => $cmd, 'output' => $out ], 'array', "return: {$ret}");
  684. V::execRootRemote($appLicenceInfo->mainServer, $appLicenceInfo->rootLogin, $appLicenceInfo->rootPassword, $cmd, $out, $ret, $appLicenceInfo->sshPort);
  685. DBG::log([ 'cmd-remote' => $cmd, 'output' => $out ], 'array', "return: {$ret}");
  686. }
  687. $cmd = "echo ~";
  688. V::exec("ssh {$sshArgs} {$this->sshArgsSkipHostKey} {$sshHostUsr} '{$cmd}'", $out, $ret);
  689. DBG::log([ 'cmd-remote' => $cmd, 'output' => $out ], 'array', "return: {$ret}");
  690. if (empty($out) || empty($out[0])) throw new Exception("Cannot fetch remote home dir");
  691. return $out[0];
  692. }
  693. public function _sendToRemoteTestDir($appLicenceInfo) {
  694. $cmd = ''; $out = ''; $ret = '';
  695. $dryRunOnly = (V::get('dry-run', '', $_REQUEST)) ? "--dry-run" : "";
  696. $this->_assertRsaKeyExists($appLicenceInfo);
  697. $sshHostUsr = "{$appLicenceInfo->rootLogin}@{$appLicenceInfo->mainServer}";
  698. $sshArgs = (22 != $appLicenceInfo->sshPort)? "-p {$appLicenceInfo->sshPort}" : '';
  699. $rsyncSshPort = (22 != $appLicenceInfo->sshPort)? "-e 'ssh -p {$appLicenceInfo->sshPort}'" : '';
  700. $scpArgs = (22 != $appLicenceInfo->sshPort)? "-P {$appLicenceInfo->sshPort}" : '';
  701. // $appLicenceInfo->sshPort
  702. /* rsync options:
  703. -a, --archive archive mode; same as -rlptgoD (no -H)
  704. -u, --update skip files that are newer on the receiver
  705. -t, --times preserve times
  706. --delete delete extraneous files from dest dirs
  707. */
  708. $remoteDir = $this->_fetchRemoteHomeDir($appLicenceInfo);
  709. DBG::log($remoteDir, 'array', "remote home dir:");
  710. $cmd = "
  711. ssh {$sshArgs} {$this->sshArgsSkipHostKey} {$sshHostUsr} '[ ! -d ~/se.encrypted.upgrade ] && mkdir ~/se.encrypted.upgrade || echo 1';
  712. ssh {$sshArgs} {$this->sshArgsSkipHostKey} {$sshHostUsr} 'rm -rf ~/se.encrypted.upgrade/SE';
  713. ssh {$sshArgs} {$this->sshArgsSkipHostKey} {$sshHostUsr} 'cp -r /Library/Server/Web/Data/Sites/Default/SE ~/se.encrypted.upgrade/SE';
  714. ssh {$sshArgs} {$this->sshArgsSkipHostKey} {$sshHostUsr} 'rm -rf ~/se.encrypted.upgrade/SE/config';
  715. rsync --archive --times --delete --compress --one-file-system --omit-dir-times --no-g --no-perms {$dryRunOnly} \
  716. --verbose {$rsyncSshPort} \
  717. --exclude='schema/default_db.instance.xml' \
  718. --exclude='schema/default_db.instance.xml/**' \
  719. '{$appLicenceInfo->installPath}/SE/' {$sshHostUsr}:~/se.encrypted.upgrade/SE/;
  720. ssh {$sshArgs} {$this->sshArgsSkipHostKey} {$sshHostUsr} 'cp -r /Library/Server/Web/Data/Sites/Default/SE/config ~/se.encrypted.upgrade/SE/';
  721. ssh {$sshArgs} {$this->sshArgsSkipHostKey} {$sshHostUsr} 'rm /Library/Server/Web/Data/Sites/Default/se.encrypted.upgrade'
  722. ssh {$sshArgs} {$this->sshArgsSkipHostKey} {$sshHostUsr} 'ln -s ~/se.encrypted.upgrade/SE /Library/Server/Web/Data/Sites/Default/se.encrypted.upgrade'
  723. scp {$this->sshArgsSkipHostKey} {$scpArgs} /Library/Server/Web/Data/Sites/SE-production-git/SE/config/.config_base_structure.php {$sshHostUsr}:
  724. ssh {$sshArgs} {$this->sshArgsSkipHostKey} {$sshHostUsr} 'mv ~/.config_base_structure.php /Library/Server/Web/Data/Sites/Default/se.encrypted.upgrade/config'
  725. "; //todo rsync ... -e \"{$this->sshArgsSkipHostKey}\" - maybe not working
  726. // --exclude='schema/default_db_xml_cache.public' \
  727. // --exclude='stuff' \
  728. // --exclude='stuff/**' \
  729. //--exclude='schema/default_db_xml_cache.public/**' \
  730. V::exec("$cmd 2>&1", $out, $ret);
  731. DBG::log([ 'cmd-remote' => $cmd, 'output' => $out ], 'array', "return: {$ret}");
  732. if (0 !== $ret) throw new Exception("Cannot run remote command using rsa key! #{$ret}. cmd: {$cmd} . out: {$out}");
  733. }
  734. public function upgradeRemoteFromTestDirAction() {
  735. session_write_close();
  736. $args = array();
  737. $args['licence_id'] = V::get('licence_id', 0, $_REQUEST, 'int');
  738. UI::gora();
  739. //UI::menu();
  740. //$this->menu($args['licence_id']);// TODO: GO BACK BTN
  741. try {
  742. $appLicenceInfo = $this->getAppLicenceInfo($args['licence_id']);
  743. $this->validateAppLicenceInfo($appLicenceInfo);
  744. $this->_upgradeRemoteFromTestDir($appLicenceInfo);
  745. echo "Test online: ";
  746. echo UI::h('a', ['target'=>"_blank", 'href'=>"https://{$appLicenceInfo->mainServer}/SE/"], "https://{$appLicenceInfo->mainServer}/SE/");
  747. } catch (Exception $e) {
  748. $this->_endWithException($e);
  749. }
  750. UI::dol();
  751. }
  752. public function _upgradeRemoteFromTestDir($appLicenceInfo) {
  753. $cmd = ''; $out = ''; $ret = '';
  754. $this->_assertRsaKeyExists($appLicenceInfo);
  755. $dateStr = date("Y-m-d_H-i-s");
  756. // $remoteHomeDir = "/Users/{$appLicenceInfo->rootLogin}";// BUG: alias like in ams - login = prezes is alias for arkadiuszbinder
  757. $remoteHomeDir = $this->_fetchRemoteHomeDir($appLicenceInfo);
  758. $cmd = "
  759. rm -rf /Library/Server/Web/Data/Sites/Default/SE.test 2>&1
  760. cp -r {$remoteHomeDir}/se.encrypted.upgrade/SE /Library/Server/Web/Data/Sites/Default/SE.test 2>&1
  761. [ ! -d {$remoteHomeDir}/bup.se.upgrade ] && mkdir {$remoteHomeDir}/bup.se.upgrade || echo 1
  762. [ ! -d {$remoteHomeDir}/bup.se.upgrade ] && exit 1
  763. [ ! -d {$remoteHomeDir}/bup.se.upgrade-testttttt ] && exit 1
  764. [ ! -f /Library/Server/Web/Data/Sites/Default/SE.test/VERSION ] && echo \"Error: plik VERSION nie istnieje\" || echo \"check VERSION OK\"
  765. [ ! -f /Library/Server/Web/Data/Sites/Default/SE.test/VERSION ] && exit 1
  766. [ ! -f /Library/Server/Web/Data/Sites/Default/SE.test/index.php ] && echo \"Error: plik index.php nie istnieje\" || echo \"check index.php OK\"
  767. [ ! -f /Library/Server/Web/Data/Sites/Default/SE.test/index.php ] && exit 1
  768. [ ! -d /Library/Server/Web/Data/Sites/Default/SE.test/se-lib ] && echo \"Error: plik se-lib nie istnieje\" || echo \"check se-lib OK\"
  769. [ ! -d /Library/Server/Web/Data/Sites/Default/SE.test/se-lib ] && exit 1
  770. exit 0
  771. ";
  772. V::execRootRemote($appLicenceInfo->mainServer, $appLicenceInfo->rootLogin, $appLicenceInfo->rootPassword, $cmd, $out, $ret, $appLicenceInfo->sshPort);
  773. $cmd = "
  774. mv /Library/Server/Web/Data/Sites/Default/SE {$remoteHomeDir}/bup.se.upgrade/bup.{$dateStr} 2>&1
  775. mv /Library/Server/Web/Data/Sites/Default/SE.test /Library/Server/Web/Data/Sites/Default/SE 2>&1
  776. exit 0
  777. ";
  778. V::execRootRemote($appLicenceInfo->mainServer, $appLicenceInfo->rootLogin, $appLicenceInfo->rootPassword, $cmd, $out, $ret, $appLicenceInfo->sshPort);
  779. DBG::_(true, true, "cmd: {$cmd} (return: {$ret})", $out, __CLASS__, __FUNCTION__, __LINE__);
  780. if (0 !== $ret) throw new Exception("Cannot run remote command as root! #{$ret}");
  781. // TODO: SE/bash_install_check.php requires $domain!
  782. // $cmd = "/usr/bin/php /Library/Server/Web/Data/Sites/Default/SE/bash_install_check.php {$domain}";
  783. // V::execRootRemote($appLicenceInfo->mainServer, $appLicenceInfo->rootLogin, $appLicenceInfo->rootPassword, $cmd, $out, $ret, $appLicenceInfo->sshPort);
  784. // DBG::_(true, true, "cmd: {$cmd} (return: {$ret})", $out, __CLASS__, __FUNCTION__, __LINE__);
  785. // if (0 !== $ret) throw new Exception("Cannot run remote command as root! #{$ret}");
  786. }
  787. public function _assertRsaKeyExists($appLicenceInfo) {
  788. $cmd = ''; $out = ''; $ret = '';
  789. $cmd = "echo ~ && pwd";// /Library/WebServer
  790. $cmd = "ls -1 ~/.ssh/";
  791. //$cmd = "rm /tmp/id_rsa";
  792. //$cmd = "rm /tmp/id_rsa.pub";
  793. //$cmd = "ssh-keygen -t rsa -N '' -C '_www@biuro.biall-net.pl' -f /tmp/id_rsa";
  794. //$cmd = "ssh-keygen -t rsa -N '' -C '_www@biuro.biall-net.pl' -f /tmp/id_rsa";
  795. V::exec($cmd, $out, $ret);
  796. DBG::_(true, true, "cmd: {$cmd} (return: {$ret})", $out, __CLASS__, __FUNCTION__, __LINE__);
  797. if (0 !== $ret) {// no ~/.ssh directory
  798. $rsaKeyPath = "~/.ssh";
  799. $cmds = array();
  800. $cmds[] = "mkdir {$rsaKeyPath}";
  801. $cmds[] = "ssh-keygen -t rsa -N '' -C '_www@biuro.biall-net.pl' -f {$rsaKeyPath}/id_rsa 2>&1";
  802. $cmds[] = "ls -1 $rsaKeyPath";
  803. foreach ($cmds as $cmd) {
  804. V::exec($cmd, $out, $ret);
  805. DBG::_(true, true, "cmd: {$cmd} (return: {$ret})", $out, __CLASS__, __FUNCTION__, __LINE__);
  806. if (0 !== $ret) throw new Exception("Error '{$ret}' cmd({$cmd}): " . implode("\n", $out));
  807. }
  808. }
  809. $cmd = "cat ~/.ssh/id_rsa.pub";
  810. V::exec($cmd, $out, $ret);
  811. DBG::_(true, true, "cmd: {$cmd} (return: {$ret})", $out, __CLASS__, __FUNCTION__, __LINE__);
  812. if (0 !== $ret || empty($out) || empty($out[0])) throw new Exception("Cannot read rsa public key");
  813. $rsaPubKey = $out[0];
  814. $cmd = 'ls -1a';
  815. $cmd = "
  816. [ ! -d ~/.ssh ] && mkdir ~/.ssh;
  817. [ ! -d ~/.ssh ] && echo 'ERROR ~/.ssh not exists and cannot be created';
  818. [ ! -f ~/.ssh/authorized_keys ] && echo '{$rsaPubKey}' > ~/.ssh/authorized_keys;
  819. [ ! -f ~/.ssh/authorized_keys ] && echo 'ERROR ~/.ssh/authorized_keys not exists and cannot be created';
  820. cat ~/.ssh/authorized_keys| grep '{$rsaPubKey}' && echo 'OK' || echo '{$rsaPubKey}' >> ~/.ssh/authorized_keys;
  821. chmod 600 ~/.ssh/authorized_keys;
  822. ";
  823. V::execRemote($appLicenceInfo->mainServer, $appLicenceInfo->rootLogin, $appLicenceInfo->rootPassword, $cmd, $out, $ret, $appLicenceInfo->sshPort);
  824. DBG::_(true, true, "remote cmd: {$cmd} (return: {$ret})", $out, __CLASS__, __FUNCTION__, __LINE__);
  825. //$cmd = "ssh server@{$appLicenceInfo->mainServer} 'ls -1 .ssh/'";
  826. //$cmd = "ssh -i ~/.ssh/id_rsa server@{$appLicenceInfo->mainServer} 'ls -1'";
  827. $sshPort = (22 != $appLicenceInfo->sshPort)? "-p {$appLicenceInfo->sshPort}" : '';
  828. $cmd = "ssh {$sshPort} {$this->sshArgsSkipHostKey} {$appLicenceInfo->rootLogin}@{$appLicenceInfo->mainServer} 'ls -1'";
  829. V::exec("$cmd 2>&1", $out, $ret); // http://php.net/manual/pl/function.exec.php says I saw the exec, system, shell_exec and passthru functions,
  830. //and deduced that the solution was to
  831. //redirect the standard error (stderr) to the standard output (stdout). It's not very clean, since it mixes stderr with stdout, and I only wanted to log the stderr.
  832. //But it seems to be the only solution (suggestions are welcome).
  833. DBG::_(true, true, "cmd: {$cmd} (return: {$ret})", $out, __CLASS__, __FUNCTION__, __LINE__);
  834. if (0 !== $ret) throw new Exception("Cannot run remote command using rsa key! #{$ret}; Out: ".implode($out)."; Cmd: {$cmd};");
  835. }
  836. public function newGenerateApp($appLicenceInfo) {
  837. if (empty($appLicenceInfo->ID)) throw new Exception("Nie wybrano serwera/licencji.");
  838. if (empty($appLicenceInfo->domains)) throw new Exception("Domains not found");
  839. $installPath = $appLicenceInfo->installPath;
  840. if (empty($installPath)) throw new Exception("Install path not found");
  841. $installPath .= '-p5';
  842. $cmds = array();
  843. $cmds[] = "if [ -d {$installPath} ] ; then rm -rf '{$installPath}'; fi";
  844. $cmds[] = "mkdir {$installPath}";
  845. $cmds[] = "cd {$installPath} && git clone --depth 1 ssh://git@biuro.biall-net.pl:2222/p5/p5.git .";
  846. $cmds[] = "cd {$installPath} && echo `git show-ref --head|head -1|head -c 8` > SE/VERSION ";
  847. // TODO: fetch from DB
  848. {
  849. foreach ($appLicenceInfo->projects as $projectName) {
  850. $cmds[] = "cd {$installPath} && git submodule update --init SE/projects/{$projectName}";
  851. }
  852. }
  853. foreach ($cmds as $cmd) {
  854. $out = ''; $ret = '';
  855. V::exec($cmd, $out, $ret);
  856. DBG::nicePrint([ 'cmd' => $cmd, 'output' => $out ], "return: {$ret}");
  857. }
  858. // $this->_encodeSource($appLicenceInfo->installPath, $appLicenceInfo->domains);
  859. }
  860. }