Install.php 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841
  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. } catch (Exception $e) {
  128. echo '</div></div>';// .container/ scroll
  129. $this->_endWithException($e);
  130. }
  131. echo '</div>';// .container
  132. UI::alert('success', "<strong>Gotowe</strong> Aplikacja znajduje się w katalogu {$appLicenceInfo->installFolderName}");
  133. $appLicenceInfo = $this->getAppLicenceInfo($args['licence_id']);
  134. }
  135. if ('newGenerateApp' === V::get('_postTask', '', $_POST)) {
  136. $this->newGenerateApp($appLicenceInfo);
  137. }
  138. if ('updateAndSendToRemoteTestDir' === V::get('_postTask', '', $_POST)) {
  139. echo '<details><summary style="cursor:pointer">aktualizuj werjsę, szyfruj i wyślij do testowego katalogu na serwerze</summary>';
  140. try {
  141. $idLicence = V::get('licence_id', 0, $_POST, 'int');
  142. $appLicenceInfo = $this->getAppLicenceInfo($idLicence);
  143. $this->validateAppLicenceInfo($appLicenceInfo);
  144. $this->gitResetHard($appLicenceInfo->installPath, $appLicenceInfo->projects);
  145. flush();
  146. $this->_encodeSource($appLicenceInfo->installPath, $appLicenceInfo->domains);
  147. flush();
  148. $this->_sendToRemoteTestDir($appLicenceInfo);
  149. } catch (Exception $e) {
  150. DBG::log($e);
  151. UI::alert('danger', $e->getMessage());
  152. }
  153. echo '</details>';
  154. $testDirUrl = "https://{$appLicenceInfo->mainServer}/se.encrypted.upgrade/";
  155. UI::alert('info', UI::h('p', [], [
  156. "testowy katalog zaktualizowany - ",
  157. UI::h('a', [ 'href' => $testDirUrl, 'target' => "_blank" ], $testDirUrl),
  158. ]));
  159. flush();
  160. }
  161. // echo UI::hButtonPost("TODO: Generuj z p5.git", [
  162. // 'class' => "btn btn-md btn-primary",
  163. // 'data' => [
  164. // '_postTask' => "newGenerateApp",
  165. // 'licence_id' => $appLicenceInfo->ID,
  166. // ],
  167. // ]);
  168. echo UI::h('div', [ 'class' => "jumbotron" ], [
  169. UI::h('div', [ 'class' => "container" ], [
  170. UI::h('h3', [], "Generowanie aplikacji dla licencji {$appLicenceInfo->ID}"),
  171. UI::h('p', [], "Licencja dla domen: " . implode(', ', $appLicenceInfo->domains)),
  172. UI::h('p', [], "Katalog z zakodowanymi plikami: {$appLicenceInfo->installFolderName}"),
  173. UI::hButtonPost("Generuj", [
  174. 'class' => "btn btn-primary",
  175. 'data' => [
  176. '_postTask' => '_generateEncryptedSource',
  177. 'licence_id' => $appLicenceInfo->ID,
  178. ]
  179. ]),
  180. (!$appLicenceInfo->installFolderGitExists)
  181. ? UI::h('div', [ 'class' => "alert alert-info" ], "Katalog nie istnieje - wygeneruj aplikację")
  182. : UI::h('div', [ 'class' => "alert alert-info", 'style' => "margin-top:10px" ], [
  183. UI::h('p', [], "Katalog istnieje i zawiera już repozytorium git: "),
  184. UI::h('p', [], [
  185. UI::hButtonPost("aktualizuj werjsę, szyfruj i wyślij do testowego katalogu na serwerze", [
  186. 'class' => "btn btn-xs btn-primary",
  187. 'data' => [
  188. '_postTask' => "updateAndSendToRemoteTestDir",
  189. 'licence_id' => $appLicenceInfo->ID,
  190. ],
  191. ]),
  192. ]),
  193. UI::h('p', [ 'style' => "margin-left:20px" ], [
  194. UI::h('a', [
  195. 'href' => "index.php?_route=Install&_task=gitResetHard&licence_id={$appLicenceInfo->ID}",
  196. 'target' => "_blank",
  197. 'class' => "btn btn-xs btn-default"
  198. ], "aktualizuj werjsę</a> (git reset --hard, git pull, set SE/VERSION - tak samo co 'rm -rf; git clone', ale szybciej)"),
  199. ]),
  200. UI::h('p', [ 'style' => "margin-left:20px" ], [
  201. UI::h('a', [
  202. 'href' => "index.php?_route=Install&_task=encodeSource&licence_id={$appLicenceInfo->ID}",
  203. 'target' => "_blank",
  204. 'class' => "btn btn-xs btn-default"
  205. ], "encode files"),
  206. ]),
  207. UI::h('p', [ 'style' => "margin-left:20px" ], [
  208. UI::h('a', [
  209. 'href' => "index.php?_route=Install&_task=sendToRemoteTestDir&licence_id={$appLicenceInfo->ID}",
  210. 'target' => "_blank",
  211. 'class' => "btn btn-xs btn-default"
  212. ], "send encoded files to remote server test folder (generates ssh key if not set)"),
  213. ]),
  214. UI::h('p', [ 'style' => "margin-top:30px" ], [
  215. "Test online: ",
  216. UI::h('a', [
  217. 'target' => "_blank",
  218. 'href' => "https://{$appLicenceInfo->mainServer}/se.encrypted.upgrade/"
  219. ], "https://{$appLicenceInfo->mainServer}/se.encrypted.upgrade/"),
  220. ]),
  221. "<br> - ",
  222. UI::h('a', [
  223. 'href' => "index.php?_route=Install&_task=upgradeRemoteFromTestDir&licence_id={$appLicenceInfo->ID}",
  224. 'onclick' => "return confirm('Uruchomić aktualizację SE na https://{$appLicenceInfo->mainServer}/SE/?')",
  225. 'target' => "_blank",
  226. 'class' => "btn btn-xs btn-warning"
  227. ], "UPGRADE Production folder from uploaded dir: ~/se.encrypted.upgrade/"),
  228. ]),
  229. ]),
  230. ]);
  231. ?>
  232. <script type="text/javascript">
  233. jQuery(document).ready(function () {
  234. jQuery('#fldSbmtBtn').on('click', function () {
  235. jQuery(this).text(jQuery(this).text() + '...').attr('disabled', 'disabled');
  236. jQuery(this).parent().submit();
  237. })
  238. });
  239. </script>
  240. <?php
  241. UI::dol();
  242. }
  243. public function gitResetHardAction() {
  244. session_write_close();
  245. $args = array();
  246. $args['licence_id'] = V::get('licence_id', 0, $_REQUEST, 'int');
  247. UI::gora();
  248. UI::menu();
  249. //$this->menu($args['licence_id']);// TODO: GO BACK BTN
  250. try {
  251. $appLicenceInfo = $this->getAppLicenceInfo($args['licence_id']);
  252. $this->validateAppLicenceInfo($appLicenceInfo);
  253. UI::startContainer();
  254. $this->gitResetHard($appLicenceInfo->installPath, $appLicenceInfo->projects);
  255. UI::endContainer();
  256. } catch (Exception $e) {
  257. $this->_endWithException($e);
  258. }
  259. UI::dol();
  260. }
  261. public function gitResetHard($installPath, $projects = []) {
  262. if (empty($installPath)) throw new Exception("Install path not found");
  263. $cmds = array();
  264. $cmds[] = "git reset --hard";
  265. $cmds[] = "git pull";
  266. $cmds[] = "echo `git show-ref --head|head -1|head -c 8` > SE/VERSION ";
  267. $hasError = false;
  268. foreach ($cmds as $cmd) {
  269. V::exec("cd {$installPath} && {$cmd}", $out, $ret);
  270. if (0 !== $ret) $hasError = true;
  271. DBG::nicePrint($out, "cmd: `{$cmd}` (return:{$ret})");
  272. }
  273. foreach ($projects as $projectName) {
  274. $cmd = "ls -l SE/projects/{$projectName} | wc -l";
  275. V::exec("cd {$installPath} && {$cmd}", $out, $ret);
  276. DBG::nicePrint([ 'cmd' => $cmd, 'output' => $out ], "return: {$ret}");
  277. if (!empty($out) && '0' !== trim($out[0])) {
  278. // $cmd = "git submodule update SE/projects/{$projectName}";
  279. $cmd = "cd SE/projects/{$projectName} && git reset --hard"; // revert encode source - checkout to last commit (need update)
  280. V::exec("cd {$installPath} && {$cmd}", $out, $ret);
  281. DBG::nicePrint([ 'cmd' => $cmd, 'output' => $out ], "return: {$ret}");
  282. }
  283. $cmd = "git submodule update --init SE/projects/{$projectName}"; // checkout to current commit
  284. V::exec("cd {$installPath} && {$cmd}", $out, $ret);
  285. DBG::nicePrint([ 'cmd' => $cmd, 'output' => $out ], "return: {$ret}");
  286. }
  287. if (!$hasError) {
  288. UI::alert('success', "OK");
  289. } else {
  290. UI::alert('danger', "errors");
  291. }
  292. }
  293. public function encodeSourceAction() {
  294. session_write_close();
  295. $args = array();
  296. $args['licence_id'] = V::get('licence_id', 0, $_REQUEST, 'int');
  297. UI::gora();
  298. UI::menu();
  299. //$this->menu($args['licence_id']);// TODO: GO BACK BTN
  300. try {
  301. $appLicenceInfo = $this->getAppLicenceInfo($args['licence_id']);
  302. $this->validateAppLicenceInfo($appLicenceInfo);
  303. $this->_encodeSource($appLicenceInfo->installPath, $appLicenceInfo->domains);
  304. } catch (Exception $e) {
  305. $this->_endWithException($e);
  306. }
  307. UI::dol();
  308. }
  309. public function _encodeSource($installPath, $domains) {
  310. UI::startContainer();
  311. $this->encodeSourceFiles($installPath, $domains, $dbg = true);
  312. // try {
  313. // $this->encodeSourceFiles($appLicenceInfo->installPath, $appLicenceInfo->domains, $dbg = false);
  314. // UI::alert('success', "OK");
  315. // } catch (Exception $e) {
  316. // UI::alert('danger', $e->getMessage());
  317. // }
  318. UI::endContainer();
  319. }
  320. // @usage: Router::getRoute('Install')->encodeSourceFiles($installPath = '/path_to_git_repo', $domains = [ 'domain.com', 'localhost' ], $dbg = false);
  321. public function encodeSourceFiles($installPath, $domains, $dbg = false) {
  322. if (empty($installPath)) throw new Exception("Install path not found");
  323. if (empty($domains)) throw new Exception("Domains not found");
  324. $phpVersionsForSgencoder = '--phpversion 5.5 --phpversion 5.6';// encode for PHP 5.x (currently supported PHP 5.0-5.6)
  325. if ('1' == V::get('DBG_ENCODER_HELP', '', $_REQUEST)) {// encoder help
  326. $cmd = "cd {$installPath}/SE && /Applications/SourceGuardian.app/Contents/MacOS/sgencoder --help ";
  327. $out = ''; $ret = '';
  328. exec($cmd, $out, $ret);
  329. DBG::nicePrint($out, "cmd: `{$cmd}` (return:{$ret})");
  330. exit;
  331. }
  332. $domainEncodePhpFiles = [
  333. 'ant.php',
  334. 'api.php',
  335. 'budynki.php',
  336. 'index-ajax.php',
  337. 'index.php',
  338. 'procesy5.php',
  339. 'session-expire.php',
  340. 'test-sync.php',
  341. 'wfs-data.php',
  342. 'wfs-qgis.php',
  343. 'wfs.php',
  344. ];
  345. $cmd = "find . -name '*.php' ";
  346. $out = ''; $ret = '';
  347. exec("cd {$installPath}/SE && {$cmd}", $out, $ret);
  348. if ($dbg) DBG::nicePrint($out, "cmd: `{$cmd}` (return:{$ret})");
  349. else DBG::log($out, 'array', "cmd: `{$cmd}` (return:{$ret})");
  350. if (0 !== $ret) throw new Exception("Error at find php files");
  351. if (empty($out)) throw new Exception("No php files found");
  352. $allPhpFiles = array_map(function ($phpFilePath) {
  353. return ('./' == substr($phpFilePath, 0, 2))? substr($phpFilePath, 2) : $phpFilePath;
  354. }, $out);
  355. $freeEncodePhpFiles = array_filter($allPhpFiles, function ($phpFilePath) use ($domainEncodePhpFiles) {
  356. if ('se-lib/Vendor/' === substr($phpFilePath, 0, strlen('se-lib/Vendor/'))) return false; // SKIP se-lib/Vendor/*
  357. if ('.ini.php' === substr($phpFilePath, -1 * strlen('.ini.php'))) return false; // SKIP *.ini.php
  358. return (!in_array($phpFilePath, $domainEncodePhpFiles));
  359. });
  360. DBG::log($freeEncodePhpFiles, 'array', "\$freeEncodePhpFiles");
  361. if (empty($freeEncodePhpFiles)) throw new Exception("No php files to encode");
  362. $cmdTempl = "cd {$installPath}/SE && /Applications/SourceGuardian.app/Contents/MacOS/sgencoder {$phpVersionsForSgencoder} -b- ";
  363. $cmdDomainEncodeDomainsTempl = " --domain " . implode(" --domain ", array_merge($domains, ['localhost']));
  364. $cmdDomainEncodeFilesTempl = " " . implode(" ", $domainEncodePhpFiles);
  365. $cmdFreeEncodeFilesTempl = " " . implode(" ", $freeEncodePhpFiles);
  366. $cmds = [
  367. $cmdTempl . $cmdDomainEncodeDomainsTempl . $cmdDomainEncodeFilesTempl,
  368. $cmdTempl . $cmdFreeEncodeFilesTempl,
  369. ];
  370. $returnValues = [];
  371. foreach ($cmds as $cmd) {
  372. $out = ''; $ret = '';
  373. exec($cmd, $out, $ret);
  374. $encoderSummaryLine = end($out);
  375. $returnValues[] = $encoderSummaryLine;
  376. if ($dbg) {
  377. DBG::nicePrint([$cmd], "cmd");
  378. DBG::nicePrint($out, "return: '{$ret}'");
  379. // DBG::nicePrint([$encoderSummaryLine], "cmd last line");
  380. }
  381. else DBG::log([$cmd, $out], 'array', "cmd return:'{$ret}'");
  382. // if (0 !== $ret) throw new Exception("Error at encode files");
  383. if (empty($out)) throw new Exception("No output for encode files command");
  384. }
  385. $statusInfo = array_reduce($returnValues, function ($ret, $encoderSummaryLine) {
  386. DBG::log([$ret, $encoderSummaryLine], 'array', "DBG reduce [\$ret, \$encoderSummaryLine]");
  387. $matches = [];
  388. preg_match_all('/(\d+) files, (\d+) processed, (\d+) errors/', $encoderSummaryLine, $matches, PREG_SET_ORDER, 0);
  389. return [
  390. 'files' => $ret['files'] + (int)$matches[0][1],
  391. 'processed' => $ret['processed'] + (int)$matches[0][2],
  392. 'errors' => $ret['errors'] + (int)$matches[0][3],
  393. ];
  394. }, [
  395. 'files' => 0,
  396. 'processed' => 0,
  397. 'errors' => 0,
  398. ]);
  399. if ($statusInfo['errors'] === 0 && $statusInfo['files'] > 0) {
  400. if ($dbg) UI::alert('success', "{$statusInfo['files']} files, {$statusInfo['processed']} processed, {$statusInfo['errors']} errors");
  401. } else {
  402. if ($dbg) UI::alert('danger', "{$statusInfo['files']} files, {$statusInfo['processed']} processed, {$statusInfo['errors']} errors");
  403. else throw new Exception("{$statusInfo['files']} files, {$statusInfo['processed']} processed, {$statusInfo['errors']} errors");
  404. }
  405. }
  406. public function getAppLicenceInfo($idLicence) {
  407. $idLicence = intval($idLicence);
  408. if (empty($idLicence)) throw new Exception("Nie wybrano serwera/licencji.");
  409. //DBG::_(true, true, 'idLicence', $idLicence, __CLASS__, __FUNCTION__, __LINE__);
  410. $appLicenceInfo = (object)$this->fetchAppLicenceInfo($idLicence);
  411. $appLicenceInfo->domains = $this->fetchDomainsByLicenceId($idLicence);
  412. $installRootPath = '/Library/Server/Web/Data/Sites/Default/PLIKI/SES_PROCESY5_A';
  413. $appLicenceInfo->installFolderName = "{$idLicence}_upgrade_SE_source_encrypted";
  414. $appLicenceInfo->installPath = "{$installRootPath}/{$appLicenceInfo->installFolderName}";
  415. //DBG::_(true, true, 'appLicenceInfo', $appLicenceInfo, __CLASS__, __FUNCTION__, __LINE__);
  416. if (empty($appLicenceInfo->domains)) throw new Exception("Domains not found."); // TODO: mv to validate
  417. $appLicenceInfo->installFolderExists = file_exists("{$appLicenceInfo->installPath}/SE");
  418. $appLicenceInfo->installFolderGitExists = file_exists("{$appLicenceInfo->installPath}/.git");
  419. $appLicenceInfo->projects = []; // TODO: get from db
  420. if (!empty($appLicenceInfo->projects)) {
  421. $appLicenceInfo->projects = [ $appLicenceInfo->project ];
  422. }
  423. else if (79 == $idLicence) { // bravecom.procesy5.pl
  424. $appLicenceInfo->projects = [ 'bravecare' ];
  425. } else if (80 == $idLicence) { // bravecom.yellowgroup.pl
  426. $appLicenceInfo->projects = [ 'bocian' ];
  427. } else if (81 == $idLicence) { // bocian.procesy5.pl
  428. $appLicenceInfo->projects = [ 'bocian' ];
  429. } else if (67 == $idLicence) { // bocian.procesy5.pl
  430. $appLicenceInfo->projects = [ 'bocian' ];
  431. } else if (82 == $idLicence) { // bocian-energa.procesy5.pl
  432. $appLicenceInfo->projects = [ 'bocian' ];
  433. } else if (4 == $idLicence) { // bzyk.procesy5.pl
  434. $appLicenceInfo->projects = [ 'bocian' ];
  435. }
  436. return $appLicenceInfo;
  437. }
  438. public function validateAppLicenceInfo($appLicenceInfo) {
  439. if (empty($appLicenceInfo->ID)) throw new Exception("Nie wybrano serwera/licencji.");
  440. if (empty($appLicenceInfo->domains)) throw new Exception("Domains not found");
  441. if (empty($appLicenceInfo->installPath)) throw new Exception("Install path not found");
  442. }
  443. public function generateApp($installPath, $domains, $projects = []) {
  444. $cmds = array();
  445. $cmds[] = "if [ -d {$installPath} ] ; then rm -rf '{$installPath}'; fi";
  446. $cmds[] = "mkdir {$installPath}";
  447. $cmds[] = "cd {$installPath} && git clone --depth 1 ssh://git@biuro.biall-net.pl:2222/plabudda/se.git .";
  448. $cmds[] = "cd {$installPath} && echo `git show-ref --head|head -1|head -c 8` > SE/VERSION ";
  449. foreach ($cmds as $cmd) {
  450. V::exec($cmd, $out, $ret);
  451. DBG::nicePrint([ 'cmd' => $cmd, 'output' => $out ], "return: {$ret}");
  452. }
  453. foreach ($projects as $projectName) {
  454. $cmd = "ls -l SE/projects/{$projectName} | wc -l";
  455. V::exec("cd {$installPath} && {$cmd}", $out, $ret);
  456. DBG::nicePrint([ 'cmd' => $cmd, 'output' => $out ], "return: {$ret}");
  457. if (!empty($out) && '0' !== trim($out[0])) {
  458. // $cmd = "git submodule update SE/projects/{$projectName}";
  459. $cmd = "cd SE/projects/{$projectName} && git reset --hard"; // revert encode source - checkout to last commit (need update)
  460. V::exec("cd {$installPath} && {$cmd}", $out, $ret);
  461. DBG::nicePrint([ 'cmd' => $cmd, 'output' => $out ], "return: {$ret}");
  462. }
  463. $cmd = "git submodule update --init SE/projects/{$projectName}"; // checkout to current commit
  464. V::exec("cd {$installPath} && {$cmd}", $out, $ret);
  465. DBG::nicePrint([ 'cmd' => $cmd, 'output' => $out ], "return: {$ret}");
  466. }
  467. $this->_encodeSource($installPath, $domains);
  468. // 1763: $exec='cd '.$installer_dir.' && /Applications/SourceGuardian.app/Contents/MacOS/sgencoder -b-
  469. // '.INSTALL_SES_PROCESY_A::get_same_domains_for_install($h->SERVER_ADDRESS_SHORT).'
  470. // -r *.php
  471. // -x superedit-DB_PROCEDURES_CREATE.php
  472. // -x INI.php
  473. // -x .config_base_structure.php
  474. // ';
  475. //
  476. // INSTALL_SES_PROCESY_A::get_same_domains_for_install($h->SERVER_ADDRESS_SHORT):
  477. // $res2=DB::query("select SERVER_ADDRESS_SHORT from SES_PROCESY5_A where SERVER_ADDRESS_IP='".$h->SERVER_ADDRESS_IP."'");
  478. // while($h2=DB::fetch($res2)) {
  479. // $domain[]=' --domain '.$h2->SERVER_ADDRESS_SHORT;
  480. // ssh server@biuro.galeriaprzymorze.eu: PHP 5.5.20
  481. // ssh server@biuro.biall-net.pl
  482. // cd /Users/plabudda/procesy5-install-galeriaprzymorze.eu/
  483. // sudo chown -R server:admin SE/
  484. // /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
  485. }
  486. public function fetchActiveLicences() {
  487. $activeLic = array();
  488. $sql = "
  489. select l.`ID`
  490. , l.`SERVER_ADDRESS`
  491. , l.`SERVER_ADDRESS_SHORT` as domain -- domain for sgencoder
  492. , l.`SERVER_ADDRESS_IP`
  493. from `SES_PROCESY5_A` l
  494. where 1=1
  495. -- TODO: and l.`A_STATUS` in('NORMAL','WAITING')
  496. order by l.`ID` DESC
  497. ";
  498. $rows = DB::getPDO()->fetchAll($sql);
  499. foreach ($rows as $row) {
  500. $r = (object)$row;
  501. $activeLic[$r->ID] = $r;
  502. }
  503. return $activeLic;
  504. }
  505. public function fetchDomainsByLicenceId($licenceId) {
  506. $domains = array();
  507. $sql = "
  508. select g.`SERVER_ADDRESS_SHORT`, g.`SERVER_ADDRESS`
  509. from `SES_PROCESY5_A` g
  510. where g.`SERVER_ADDRESS_IP`=(select l.`SERVER_ADDRESS_IP`
  511. from `SES_PROCESY5_A` l
  512. where l.`ID`='{$licenceId}'
  513. -- TODO: and l.`A_STATUS` in('NORMAL','WAITING')
  514. )
  515. -- TODO: and g.`A_STATUS` in('NORMAL','WAITING')
  516. ";
  517. $rows = DB::getPDO()->fetchAll($sql);
  518. foreach ($rows as $row) {
  519. $r = (object)$row;
  520. $domains[] = $r->SERVER_ADDRESS_SHORT;
  521. if ($r->SERVER_ADDRESS != $r->SERVER_ADDRESS_SHORT) {
  522. $domains[] = $r->SERVER_ADDRESS;
  523. }
  524. }
  525. return $domains;
  526. }
  527. public function fetchMainServerByLicenceId($licenceId) {
  528. return DB::getPDO()->fetchValue("
  529. select g.`SERVER_ADDRESS`
  530. from `SES_PROCESY5_A` g
  531. where g.`ID`='{$licenceId}'
  532. -- TODO: and g.`A_STATUS` in('NORMAL','WAITING')
  533. ");
  534. }
  535. public function fetchAppLicenceInfo($licenceId) {
  536. $licenceInfo = null;
  537. $sql = "
  538. select g.ID
  539. , g.SERVER_ADDRESS as mainServer
  540. , g.ADMIN_USERNAME as rootLogin
  541. , g.ADMIN_USERNAME_PASSWD as rootPassword
  542. , g.SSH_PORT as sshPort
  543. , g.VERSION_GIT as project
  544. from SES_PROCESY5_A g
  545. where g.`ID`=:id_licence
  546. -- TODO: and g.A_STATUS in('NORMAL','WAITING')
  547. ";
  548. $all = DB::getPDO()->fetchAll($sql, [ ':id_licence' => $licenceId ]);
  549. if (empty($all)) throw new Exception("Brak licencji o nr '{$licenceId}'");
  550. $licenceInfo = reset($all);
  551. if (!$licenceInfo['sshPort']) $licenceInfo['sshPort'] = 22;
  552. return $licenceInfo;
  553. }
  554. public function _endWithException($e) {
  555. echo UI::h('div', ['class'=>"container"], [
  556. UI::h('div', ['class' => "alert alert-danger"], "#" . $e->getLine() . ": " . $e->getMessage()),
  557. UI::h('p', [], [
  558. "Wróć do ",
  559. UI::h('a', ['href'=>"index.php?_route=Install"], "menu")
  560. ])
  561. ]);
  562. UI::dol();
  563. exit;
  564. }
  565. public function sendToRemoteTestDirAction() {
  566. session_write_close();
  567. $args = array();
  568. $args['licence_id'] = V::get('licence_id', 0, $_REQUEST, 'int');
  569. UI::gora();
  570. //UI::menu();
  571. //$this->menu($args['licence_id']);// TODO: GO BACK BTN
  572. try {
  573. $appLicenceInfo = $this->getAppLicenceInfo($args['licence_id']);
  574. $this->validateAppLicenceInfo($appLicenceInfo);
  575. // TODO: if (59 ) => baratosz.sledz - na lokalnym kompie
  576. // bn:~/$ scp -r SE server@192.168.61.153:~/se.encrypted.upgrade
  577. // remote SE.git = '/Users/bartoszsledz/Desktop/production-se'
  578. // remote:~/$ mv SE ~/SE.bup.2017-07-03
  579. // remote:~/$ mv ~/se.encrypted.upgrade/SE SE
  580. // remote:~/$ cp -r ~/SE.bup.2017-07-03/config SE/
  581. // remote:~/$ sudo chown -R bartoszsledz:staff SE/
  582. $this->_sendToRemoteTestDir($appLicenceInfo);
  583. echo "Test online: ";
  584. echo UI::h('a', ['target'=>"_blank", 'href'=>"https://{$appLicenceInfo->mainServer}/se.encrypted.upgrade/"], "https://{$appLicenceInfo->mainServer}/se.encrypted.upgrade/");
  585. } catch (Exception $e) {
  586. $this->_endWithException($e);
  587. }
  588. UI::dol();
  589. }
  590. public function _fetchRemoteHomeDir($appLicenceInfo) {
  591. $this->_assertRsaKeyExists($appLicenceInfo);
  592. $sshHostUsr = "{$appLicenceInfo->rootLogin}@{$appLicenceInfo->mainServer}";
  593. $sshArgs = (22 != $appLicenceInfo->sshPort)? "-p {$appLicenceInfo->sshPort}" : '';
  594. $rsyncSshPort = (22 != $appLicenceInfo->sshPort)? "-e 'ssh -p {$appLicenceInfo->sshPort}'" : '';
  595. if (V::get('DBG_REMOTE', '', $_GET)) {// DBG
  596. $cmd = "echo ~";
  597. V::exec("ssh {$sshArgs} {$sshHostUsr} '{$cmd}'", $out, $ret);
  598. DBG::log([ 'cmd-remote' => $cmd, 'output' => $out ], 'array', "return: {$ret}");
  599. V::execRemote($appLicenceInfo->mainServer, $appLicenceInfo->rootLogin, $appLicenceInfo->rootPassword, $cmd, $out, $ret, $appLicenceInfo->sshPort);
  600. DBG::log([ 'cmd-remote' => $cmd, 'output' => $out ], 'array', "return: {$ret}");
  601. V::execRootRemote($appLicenceInfo->mainServer, $appLicenceInfo->rootLogin, $appLicenceInfo->rootPassword, $cmd, $out, $ret, $appLicenceInfo->sshPort);
  602. DBG::log([ 'cmd-remote' => $cmd, 'output' => $out ], 'array', "return: {$ret}");
  603. }
  604. $cmd = "echo ~";
  605. V::exec("ssh {$sshArgs} {$this->sshArgsSkipHostKey} {$sshHostUsr} '{$cmd}'", $out, $ret);
  606. DBG::log([ 'cmd-remote' => $cmd, 'output' => $out ], 'array', "return: {$ret}");
  607. if (empty($out) || empty($out[0])) throw new Exception("Cannot fetch remote home dir");
  608. return $out[0];
  609. }
  610. public function _sendToRemoteTestDir($appLicenceInfo) {
  611. $cmd = ''; $out = ''; $ret = '';
  612. $dryRunOnly = (V::get('dry-run', '', $_REQUEST)) ? "--dry-run" : "";
  613. $this->_assertRsaKeyExists($appLicenceInfo);
  614. $sshHostUsr = "{$appLicenceInfo->rootLogin}@{$appLicenceInfo->mainServer}";
  615. $sshArgs = (22 != $appLicenceInfo->sshPort)? "-p {$appLicenceInfo->sshPort}" : '';
  616. $rsyncSshPort = (22 != $appLicenceInfo->sshPort)? "-e 'ssh -p {$appLicenceInfo->sshPort}'" : '';
  617. // $appLicenceInfo->sshPort
  618. /* rsync options:
  619. -a, --archive archive mode; same as -rlptgoD (no -H)
  620. -u, --update skip files that are newer on the receiver
  621. -t, --times preserve times
  622. --delete delete extraneous files from dest dirs
  623. */
  624. $remoteDir = $this->_fetchRemoteHomeDir($appLicenceInfo);
  625. DBG::log($remoteDir, 'array', "remote home dir:");
  626. $cmd = "
  627. ssh {$sshArgs} {$this->sshArgsSkipHostKey} {$sshHostUsr} '[ ! -d ~/se.encrypted.upgrade ] && mkdir ~/se.encrypted.upgrade || echo 1';
  628. ssh {$sshArgs} {$this->sshArgsSkipHostKey} {$sshHostUsr} 'rm -rf ~/se.encrypted.upgrade/SE';
  629. ssh {$sshArgs} {$this->sshArgsSkipHostKey} {$sshHostUsr} 'cp -r /Library/Server/Web/Data/Sites/Default/SE ~/se.encrypted.upgrade/SE';
  630. ssh {$sshArgs} {$this->sshArgsSkipHostKey} {$sshHostUsr} 'rm -rf ~/se.encrypted.upgrade/SE/config';
  631. rsync -e \"{$this->sshArgsSkipHostKey}\" --archive --times --delete --compress --one-file-system --omit-dir-times --no-g --no-perms {$dryRunOnly} \
  632. --verbose {$rsyncSshPort} \
  633. --exclude='stuff' \
  634. --exclude='stuff/**' \
  635. --exclude='schema/default_db.instance.xml' \
  636. --exclude='schema/default_db_xml_cache.public' \
  637. --exclude='schema/default_db.instance.xml/**' \
  638. --exclude='schema/default_db_xml_cache.public/**' \
  639. '{$appLicenceInfo->installPath}/SE/' {$sshHostUsr}:~/se.encrypted.upgrade/SE/;
  640. ssh {$sshArgs} {$this->sshArgsSkipHostKey} {$sshHostUsr} 'cp -r /Library/Server/Web/Data/Sites/Default/SE/config ~/se.encrypted.upgrade/SE/';
  641. ssh {$sshArgs} {$this->sshArgsSkipHostKey} {$sshHostUsr} 'rm /Library/Server/Web/Data/Sites/Default/se.encrypted.upgrade'
  642. ssh {$sshArgs} {$this->sshArgsSkipHostKey} {$sshHostUsr} 'ln -s ~/se.encrypted.upgrade/SE /Library/Server/Web/Data/Sites/Default/se.encrypted.upgrade'
  643. ";
  644. V::exec("$cmd 2>&1", $out, $ret);
  645. DBG::log([ 'cmd-remote' => $cmd, 'output' => $out ], 'array', "return: {$ret}");
  646. if (0 !== $ret) throw new Exception("Cannot run remote command using rsa key! #{$ret}. cmd: {$cmd} . out: {$out}");
  647. }
  648. public function upgradeRemoteFromTestDirAction() {
  649. session_write_close();
  650. $args = array();
  651. $args['licence_id'] = V::get('licence_id', 0, $_REQUEST, 'int');
  652. UI::gora();
  653. //UI::menu();
  654. //$this->menu($args['licence_id']);// TODO: GO BACK BTN
  655. try {
  656. $appLicenceInfo = $this->getAppLicenceInfo($args['licence_id']);
  657. $this->validateAppLicenceInfo($appLicenceInfo);
  658. $this->_upgradeRemoteFromTestDir($appLicenceInfo);
  659. echo "Test online: ";
  660. echo UI::h('a', ['target'=>"_blank", 'href'=>"https://{$appLicenceInfo->mainServer}/SE/"], "https://{$appLicenceInfo->mainServer}/SE/");
  661. } catch (Exception $e) {
  662. $this->_endWithException($e);
  663. }
  664. UI::dol();
  665. }
  666. public function _upgradeRemoteFromTestDir($appLicenceInfo) {
  667. $cmd = ''; $out = ''; $ret = '';
  668. $this->_assertRsaKeyExists($appLicenceInfo);
  669. $dateStr = date("Y-m-d_H-i-s");
  670. // $remoteHomeDir = "/Users/{$appLicenceInfo->rootLogin}";// BUG: alias like in ams - login = prezes is alias for arkadiuszbinder
  671. $remoteHomeDir = $this->_fetchRemoteHomeDir($appLicenceInfo);
  672. $cmd = "
  673. rm -rf /Library/Server/Web/Data/Sites/Default/SE.test 2>&1
  674. cp -r {$remoteHomeDir}/se.encrypted.upgrade/SE /Library/Server/Web/Data/Sites/Default/SE.test 2>&1
  675. [ ! -d {$remoteHomeDir}/bup.se.upgrade ] && mkdir {$remoteHomeDir}/bup.se.upgrade || echo 1
  676. [ ! -d {$remoteHomeDir}/bup.se.upgrade ] && exit 1
  677. [ ! -d {$remoteHomeDir}/bup.se.upgrade-testttttt ] && exit 1
  678. [ ! -f /Library/Server/Web/Data/Sites/Default/SE.test/VERSION ] && echo \"Error: plik VERSION nie istnieje\" || echo \"check VERSION OK\"
  679. [ ! -f /Library/Server/Web/Data/Sites/Default/SE.test/VERSION ] && exit 1
  680. [ ! -f /Library/Server/Web/Data/Sites/Default/SE.test/index.php ] && echo \"Error: plik index.php nie istnieje\" || echo \"check index.php OK\"
  681. [ ! -f /Library/Server/Web/Data/Sites/Default/SE.test/index.php ] && exit 1
  682. [ ! -d /Library/Server/Web/Data/Sites/Default/SE.test/se-lib ] && echo \"Error: plik se-lib nie istnieje\" || echo \"check se-lib OK\"
  683. [ ! -d /Library/Server/Web/Data/Sites/Default/SE.test/se-lib ] && exit 1
  684. exit 0
  685. ";
  686. V::execRootRemote($appLicenceInfo->mainServer, $appLicenceInfo->rootLogin, $appLicenceInfo->rootPassword, $cmd, $out, $ret, $appLicenceInfo->sshPort);
  687. $cmd = "
  688. mv /Library/Server/Web/Data/Sites/Default/SE {$remoteHomeDir}/bup.se.upgrade/bup.{$dateStr} 2>&1
  689. mv /Library/Server/Web/Data/Sites/Default/SE.test /Library/Server/Web/Data/Sites/Default/SE 2>&1
  690. exit 0
  691. ";
  692. V::execRootRemote($appLicenceInfo->mainServer, $appLicenceInfo->rootLogin, $appLicenceInfo->rootPassword, $cmd, $out, $ret, $appLicenceInfo->sshPort);
  693. DBG::_(true, true, "cmd: {$cmd} (return: {$ret})", $out, __CLASS__, __FUNCTION__, __LINE__);
  694. if (0 !== $ret) throw new Exception("Cannot run remote command as root! #{$ret}");
  695. // TODO: SE/bash_install_check.php requires $domain!
  696. // $cmd = "/usr/bin/php /Library/Server/Web/Data/Sites/Default/SE/bash_install_check.php {$domain}";
  697. // V::execRootRemote($appLicenceInfo->mainServer, $appLicenceInfo->rootLogin, $appLicenceInfo->rootPassword, $cmd, $out, $ret, $appLicenceInfo->sshPort);
  698. // DBG::_(true, true, "cmd: {$cmd} (return: {$ret})", $out, __CLASS__, __FUNCTION__, __LINE__);
  699. // if (0 !== $ret) throw new Exception("Cannot run remote command as root! #{$ret}");
  700. }
  701. public function _assertRsaKeyExists($appLicenceInfo) {
  702. $cmd = ''; $out = ''; $ret = '';
  703. $cmd = "echo ~ && pwd";// /Library/WebServer
  704. $cmd = "ls -1 ~/.ssh/";
  705. //$cmd = "rm /tmp/id_rsa";
  706. //$cmd = "rm /tmp/id_rsa.pub";
  707. //$cmd = "ssh-keygen -t rsa -N '' -C '_www@biuro.biall-net.pl' -f /tmp/id_rsa";
  708. //$cmd = "ssh-keygen -t rsa -N '' -C '_www@biuro.biall-net.pl' -f /tmp/id_rsa";
  709. V::exec($cmd, $out, $ret);
  710. DBG::_(true, true, "cmd: {$cmd} (return: {$ret})", $out, __CLASS__, __FUNCTION__, __LINE__);
  711. if (0 !== $ret) {// no ~/.ssh directory
  712. $rsaKeyPath = "~/.ssh";
  713. $cmds = array();
  714. $cmds[] = "mkdir {$rsaKeyPath}";
  715. $cmds[] = "ssh-keygen -t rsa -N '' -C '_www@biuro.biall-net.pl' -f {$rsaKeyPath}/id_rsa 2>&1";
  716. $cmds[] = "ls -1 $rsaKeyPath";
  717. foreach ($cmds as $cmd) {
  718. V::exec($cmd, $out, $ret);
  719. DBG::_(true, true, "cmd: {$cmd} (return: {$ret})", $out, __CLASS__, __FUNCTION__, __LINE__);
  720. if (0 !== $ret) throw new Exception("Error '{$ret}' cmd({$cmd}): " . implode("\n", $out));
  721. }
  722. }
  723. $cmd = "cat ~/.ssh/id_rsa.pub";
  724. V::exec($cmd, $out, $ret);
  725. DBG::_(true, true, "cmd: {$cmd} (return: {$ret})", $out, __CLASS__, __FUNCTION__, __LINE__);
  726. if (0 !== $ret || empty($out) || empty($out[0])) throw new Exception("Cannot read rsa public key");
  727. $rsaPubKey = $out[0];
  728. $cmd = 'ls -1a';
  729. $cmd = "
  730. [ ! -d ~/.ssh ] && mkdir ~/.ssh;
  731. [ ! -d ~/.ssh ] && echo 'ERROR ~/.ssh not exists and cannot be created';
  732. [ ! -f ~/.ssh/authorized_keys ] && echo '{$rsaPubKey}' > ~/.ssh/authorized_keys;
  733. [ ! -f ~/.ssh/authorized_keys ] && echo 'ERROR ~/.ssh/authorized_keys not exists and cannot be created';
  734. cat ~/.ssh/authorized_keys| grep '{$rsaPubKey}' && echo 'OK' || echo '{$rsaPubKey}' >> ~/.ssh/authorized_keys;
  735. chmod 600 ~/.ssh/authorized_keys;
  736. ";
  737. V::execRemote($appLicenceInfo->mainServer, $appLicenceInfo->rootLogin, $appLicenceInfo->rootPassword, $cmd, $out, $ret, $appLicenceInfo->sshPort);
  738. DBG::_(true, true, "remote cmd: {$cmd} (return: {$ret})", $out, __CLASS__, __FUNCTION__, __LINE__);
  739. //$cmd = "ssh server@{$appLicenceInfo->mainServer} 'ls -1 .ssh/'";
  740. //$cmd = "ssh -i ~/.ssh/id_rsa server@{$appLicenceInfo->mainServer} 'ls -1'";
  741. $sshPort = (22 != $appLicenceInfo->sshPort)? "-p {$appLicenceInfo->sshPort}" : '';
  742. $cmd = "ssh {$sshPort} {$this->sshArgsSkipHostKey} {$appLicenceInfo->rootLogin}@{$appLicenceInfo->mainServer} 'ls -1'";
  743. 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,
  744. //and deduced that the solution was to
  745. //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.
  746. //But it seems to be the only solution (suggestions are welcome).
  747. DBG::_(true, true, "cmd: {$cmd} (return: {$ret})", $out, __CLASS__, __FUNCTION__, __LINE__);
  748. if (0 !== $ret) throw new Exception("Cannot run remote command using rsa key! #{$ret}; Out: ".implode($out)."; Cmd: {$cmd};");
  749. }
  750. public function newGenerateApp($appLicenceInfo) {
  751. if (empty($appLicenceInfo->ID)) throw new Exception("Nie wybrano serwera/licencji.");
  752. if (empty($appLicenceInfo->domains)) throw new Exception("Domains not found");
  753. $installPath = $appLicenceInfo->installPath;
  754. if (empty($installPath)) throw new Exception("Install path not found");
  755. $installPath .= '-p5';
  756. $cmds = array();
  757. $cmds[] = "if [ -d {$installPath} ] ; then rm -rf '{$installPath}'; fi";
  758. $cmds[] = "mkdir {$installPath}";
  759. $cmds[] = "cd {$installPath} && git clone --depth 1 ssh://git@biuro.biall-net.pl:2222/p5/p5.git .";
  760. $cmds[] = "cd {$installPath} && echo `git show-ref --head|head -1|head -c 8` > SE/VERSION ";
  761. // TODO: fetch from DB
  762. {
  763. foreach ($appLicenceInfo->projects as $projectName) {
  764. $cmds[] = "cd {$installPath} && git submodule update --init SE/projects/{$projectName}";
  765. }
  766. }
  767. foreach ($cmds as $cmd) {
  768. $out = ''; $ret = '';
  769. exec($cmd, $out, $ret);
  770. DBG::nicePrint([ 'cmd' => $cmd, 'output' => $out ], "return: {$ret}");
  771. }
  772. // $this->_encodeSource($appLicenceInfo->installPath, $appLicenceInfo->domains);
  773. }
  774. }