Install.php 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087
  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->configGenerate(...);
  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-left:20px" ], [
  224. UI::h('a', [
  225. 'href' => "index.php?_route=Install&_task=generateUpgradeScript&licence_id={$appLicenceInfo->ID}",
  226. 'target' => "_blank",
  227. 'class' => "btn btn-xs btn-warning"
  228. ], "generuj skrypt aktualizacji"),
  229. ]),
  230. UI::h('p', [ 'style' => "margin-top:30px" ], [
  231. "Test online: ",
  232. UI::h('a', [
  233. 'target' => "_blank",
  234. 'href' => "https://{$appLicenceInfo->mainServer}/se.encrypted.upgrade/"
  235. ], "https://{$appLicenceInfo->mainServer}/se.encrypted.upgrade/"),
  236. ]),
  237. "<br> - ",
  238. UI::h('a', [
  239. 'href' => "index.php?_route=Install&_task=upgradeRemoteFromTestDir&licence_id={$appLicenceInfo->ID}",
  240. 'onclick' => "return confirm('Uruchomić aktualizację SE na https://{$appLicenceInfo->mainServer}/SE/?')",
  241. 'target' => "_blank",
  242. 'class' => "btn btn-xs btn-warning"
  243. ], "UPGRADE Production folder from uploaded dir: ~/se.encrypted.upgrade/"),
  244. ]),
  245. ]),
  246. ]);
  247. ?>
  248. <script type="text/javascript">
  249. jQuery(document).ready(function () {
  250. jQuery('#fldSbmtBtn').on('click', function () {
  251. jQuery(this).text(jQuery(this).text() + '...').attr('disabled', 'disabled');
  252. jQuery(this).parent().submit();
  253. })
  254. });
  255. </script>
  256. <?php
  257. UI::dol();
  258. }
  259. public function generateUpgradeScriptAction() {
  260. session_write_close();
  261. $args = array();
  262. $args['licence_id'] = V::get('licence_id', 0, $_REQUEST, 'int');
  263. UI::gora();
  264. UI::menu();
  265. //$this->menu($args['licence_id']);// TODO: GO BACK BTN
  266. try {
  267. $appLicenceInfo = $this->getAppLicenceInfo($args['licence_id']);
  268. $this->validateAppLicenceInfo($appLicenceInfo);
  269. UI::startContainer();
  270. $this->generateUpgradeScript($appLicenceInfo);
  271. UI::endContainer();
  272. } catch (Exception $e) {
  273. $this->_endWithException($e);
  274. }
  275. UI::dol();
  276. }
  277. public function generateUpgradeScript($appLicenceInfo) {
  278. $cmds = [];
  279. //
  280. $cmds[] = "# TODO: commands from remote upgrade";
  281. $cmds[] = "# cp -r {UPDATE_ZIP_PATH_SE} {public_html}/se.encrypted.upgrade";
  282. $cmds[] = "# rm -rf {public_html}/se.encrypted.upgrade";
  283. // '[ ! -d ~/se.encrypted.upgrade ] && mkdir ~/se.encrypted.upgrade || echo 1';
  284. // 'rm -rf ~/se.encrypted.upgrade/SE';
  285. // 'cp -r /Library/Server/Web/Data/Sites/Default/SE ~/se.encrypted.upgrade/SE';
  286. // 'rm -rf ~/se.encrypted.upgrade/SE/config';
  287. // rsync --archive --times --delete --compress --one-file-system --omit-dir-times --no-g --no-perms {$dryRunOnly} \
  288. // --verbose {$rsyncSshPort} \
  289. // --exclude='schema/default_db.instance.xml' \
  290. // --exclude='schema/default_db.instance.xml/**' \
  291. // '{$appLicenceInfo->installPath}/SE/' {$sshHostUsr}:~/se.encrypted.upgrade/SE/;
  292. // 'cp -r /Library/Server/Web/Data/Sites/Default/SE/config ~/se.encrypted.upgrade/SE/';
  293. // 'rm /Library/Server/Web/Data/Sites/Default/se.encrypted.upgrade'
  294. // 'ln -s ~/se.encrypted.upgrade/SE /Library/Server/Web/Data/Sites/Default/se.encrypted.upgrade'
  295. // scp {$this->sshArgsSkipHostKey} {$scpArgs} /Library/Server/Web/Data/Sites/SE-production-git/SE/config/.config_base_structure.php {$sshHostUsr}:
  296. // 'mv ~/.config_base_structure.php /Library/Server/Web/Data/Sites/Default/se.encrypted.upgrade/config'
  297. // config
  298. // $cmds[] = "TODO cp -r from {SE}/config";
  299. $cmds[] = "rm ~/se.encrypted.upgrade/.*.inc.php";
  300. $cmds[] = "cp -r {UPDATE_ZIP_PATH_SE}/.*.inc.php ~/se.encrypted.upgrade/";
  301. // $domainList = INSTALL_SES_PROCESY_A::fetch_same_domains_for_install($SERVER_ADDRESS_SHORT, $SERVER_ADDRESS);// [ $SERVER_ADDRESS, localhost, 127.0.0.1, ... ]
  302. DBG::nicePrint($appLicenceInfo, '$appLicenceInfo');
  303. $mainDomain = $appLicenceInfo->mainServer;
  304. $additionalDomains = array_filter($appLicenceInfo->domains, function ($domain) use ($mainDomain) {
  305. return ($mainDomain != $domain);
  306. });
  307. foreach ($additionalDomains as $domain) {
  308. if ('localhost' == $domain) continue;// skip localhost (127.0.0.1)
  309. $cmds[] = ' test -f /Library/Server/Web/Data/Sites/Default/SE/config/.cnf--default_db-'.$domain.'.ini.php || ln -s /Library/Server/Web/Data/Sites/Default/SE/config/.cnf--default_db-'.$mainDomain.'.inc.php /Library/Server/Web/Data/Sites/Default/SE/config/.cnf--default_db-'.$domain.'.inc.php';
  310. $cmds[] = ' test -f /Library/Server/Web/Data/Sites/Default/SE/config/.cnf--zasob_2-'.$domain.'.inc.php || ln -s /Library/Server/Web/Data/Sites/Default/SE/config/.cnf--zasob_2-'.$mainDomain.'.inc.php /Library/Server/Web/Data/Sites/Default/SE/config/.cnf--zasob_2-'.$domain.'.inc.php';
  311. // $cmds[] = ' test -f /Library/Server/Web/Data/Sites/Default/SE/config/.cnf--import_db-'.$domain.'.inc.php || ln -s /Library/Server/Web/Data/Sites/Default/SE/config/.cnf--import_db-'.$mainDomain.'.inc.php /Library/Server/Web/Data/Sites/Default/SE/config/.cnf--import_db-'.$domain.'.inc.php';
  312. $cmds[] = ' test -f /Library/Server/Web/Data/Sites/Default/SE/config/.cnf--folders-'.$domain.'.inc.php || ln -s /Library/Server/Web/Data/Sites/Default/SE/config/.cnf--folders-'.$mainDomain.'.inc.php /Library/Server/Web/Data/Sites/Default/SE/config/.cnf--folders-'.$domain.'.inc.php';
  313. $cmds[] = ' test -f /Library/Server/Web/Data/Sites/Default/SE/config/.cnf--default_ldap-'.$domain.'.inc.php || ln -s /Library/Server/Web/Data/Sites/Default/SE/config/.cnf--default_ldap-'.$mainDomain.'.inc.php /Library/Server/Web/Data/Sites/Default/SE/config/.cnf--default_ldap-'.$domain.'.inc.php';
  314. }
  315. DBG::nicePrint($cmds, "\$cmds");
  316. }
  317. public function configGenerateAction() {
  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->configGenerate($appLicenceInfo->configPath, $appLicenceInfo->mainServer, $appLicenceInfo->domains, $appLicenceInfo->rootPassword
  329. , $appLicenceInfo->ldapUser, $appLicenceInfo->ldapPass, $appLicenceInfo->ldapBaseDN
  330. );
  331. UI::endContainer();
  332. } catch (Exception $e) {
  333. $this->_endWithException($e);
  334. }
  335. UI::dol();
  336. }
  337. public function configGenerate($configPath, $mainServer, $domains, $rootPassword, $ldapUser, $ldapPass, $ldapBaseDN) {
  338. if (empty($configPath)) throw new Exception("Install path not found");
  339. $cmds = array();
  340. $cmds[] = "if [ -d {$configPath} ] ; then rm -rf '{$configPath}'; fi";
  341. $cmds[] = "mkdir {$configPath}";
  342. $REMOTE_FOLDER_ROOT = str_replace([ ".", "-" ], '_', $mainServer);
  343. $cmds[] = ' echo "' . V::quoteBashEcho(
  344. Config::generateDefaultDbConfigFile(
  345. [
  346. 'database' => $REMOTE_FOLDER_ROOT,
  347. 'password' => $rootPassword,
  348. ],
  349. $outputFormat = 'inc'
  350. )
  351. ) . '" > ' . $configPath . '/.cnf--default_db-' . $mainServer . '.inc.php';
  352. $cmds[] = ' echo "' . V::quoteBashEcho(
  353. Config::generateDefaultDbConfigFile(
  354. [
  355. 'database' => $REMOTE_FOLDER_ROOT,
  356. 'password' => $rootPassword,
  357. ],
  358. $outputFormat = 'inc'
  359. )
  360. ) . '" > ' . $configPath . '/.cnf--zasob_2-' . $mainServer . '.inc.php';
  361. $cmds[] = ' echo "' . V::quoteBashEcho(
  362. Config::generateDefaultLdapConfigFile(
  363. [
  364. 'user' => $ldapUser,
  365. 'pass' => $ldapPass,
  366. 'base_dn' => $ldapBaseDN,
  367. ],
  368. $outputFormat = 'inc'
  369. )
  370. ) . '" > ' . $configPath . '/.cnf--default_ldap-' . $mainServer . '.inc.php';
  371. // TODO: create .cnf--default_ldap-{$mainServer}.inc.php
  372. $additionalDomains = array_filter($domains, function ($domain) use ($mainServer) {
  373. return ($mainServer != $domain);
  374. });
  375. foreach ($additionalDomains as $domain) {
  376. if ('localhost' == $domain) continue;// skip localhost (127.0.0.1)
  377. $cmds[] = "cd {$configPath} && ln -s .cnf--default_db-{$mainServer}.inc.php .cnf--default_db-{$domain}.inc.php";
  378. $cmds[] = "cd {$configPath} && ln -s .cnf--zasob_2-{$mainServer}.inc.php .cnf--zasob_2-{$domain}.inc.php";
  379. // $cmds[] = "cd {$configPath} && ln -s .cnf--import_db-{$mainServer}.inc.php .cnf--import_db-{$domain}.inc.php";
  380. // TODO: $cmds[] = "cd {$configPath} && ln -s .cnf--folders-{$mainServer}.inc.php .cnf--folders-{$domain}.inc.php";
  381. $cmds[] = "cd {$configPath} && ln -s .cnf--default_ldap-{$mainServer}.inc.php .cnf--default_ldap-{$domain}.inc.php";
  382. }
  383. $hasError = false;
  384. foreach ($cmds as $cmd) {
  385. V::exec($cmd, $out, $ret);
  386. if (0 !== $ret) $hasError = true;
  387. DBG::nicePrint($out, "cmd: `{$cmd}` (return:{$ret})");
  388. }
  389. if (!$hasError) {
  390. UI::alert('success', "OK");
  391. } else {
  392. UI::alert('danger', "errors");
  393. }
  394. }
  395. public function gitResetHardAction() {
  396. session_write_close();
  397. $args = array();
  398. $args['licence_id'] = V::get('licence_id', 0, $_REQUEST, 'int');
  399. UI::gora();
  400. UI::menu();
  401. //$this->menu($args['licence_id']);// TODO: GO BACK BTN
  402. try {
  403. $appLicenceInfo = $this->getAppLicenceInfo($args['licence_id']);
  404. $this->validateAppLicenceInfo($appLicenceInfo);
  405. UI::startContainer();
  406. $this->gitResetHard($appLicenceInfo->installPath, $appLicenceInfo->projects);
  407. UI::endContainer();
  408. } catch (Exception $e) {
  409. $this->_endWithException($e);
  410. }
  411. UI::dol();
  412. }
  413. public function gitResetHard($installPath, $projects = []) {
  414. if (empty($installPath)) throw new Exception("Install path not found");
  415. $cmds = array();
  416. $cmds[] = "git reset --hard";
  417. $cmds[] = "git pull";
  418. $cmds[] = "echo `git show-ref --head|head -1|head -c 8` > SE/VERSION ";
  419. $hasError = false;
  420. foreach ($cmds as $cmd) {
  421. V::exec("cd {$installPath} && {$cmd}", $out, $ret);
  422. if (0 !== $ret) $hasError = true;
  423. DBG::nicePrint($out, "cmd: `{$cmd}` (return:{$ret})");
  424. }
  425. foreach ($projects as $projectName) {
  426. $cmd = "ls -l SE/projects/{$projectName} | wc -l";
  427. V::exec("cd {$installPath} && {$cmd}", $out, $ret);
  428. DBG::nicePrint([ 'cmd' => $cmd, 'output' => $out ], "return: {$ret}");
  429. if (!empty($out) && '0' !== trim($out[0])) {
  430. // $cmd = "git submodule update SE/projects/{$projectName}";
  431. $cmd = "cd SE/projects/{$projectName} && git reset --hard"; // revert encode source - checkout to last commit (need update)
  432. V::exec("cd {$installPath} && {$cmd}", $out, $ret);
  433. DBG::nicePrint([ 'cmd' => $cmd, 'output' => $out ], "return: {$ret}");
  434. }
  435. $cmd = "git submodule update --init SE/projects/{$projectName}"; // checkout to current commit
  436. V::exec("cd {$installPath} && {$cmd}", $out, $ret);
  437. DBG::nicePrint([ 'cmd' => $cmd, 'output' => $out ], "return: {$ret}");
  438. }
  439. if (!$hasError) {
  440. UI::alert('success', "OK");
  441. } else {
  442. UI::alert('danger', "errors");
  443. }
  444. }
  445. public function encodeSourceAction() {
  446. session_write_close();
  447. $args = array();
  448. $args['licence_id'] = V::get('licence_id', 0, $_REQUEST, 'int');
  449. UI::gora();
  450. UI::menu();
  451. //$this->menu($args['licence_id']);// TODO: GO BACK BTN
  452. try {
  453. $appLicenceInfo = $this->getAppLicenceInfo($args['licence_id']);
  454. $this->validateAppLicenceInfo($appLicenceInfo);
  455. $this->_encodeSource($appLicenceInfo->installPath, $appLicenceInfo->domains);
  456. $this->_encodeConfigs($appLicenceInfo->configPath);
  457. } catch (Exception $e) {
  458. $this->_endWithException($e);
  459. }
  460. UI::dol();
  461. }
  462. public function _encodeSource($installPath, $domains) {
  463. UI::startContainer();
  464. $this->encodeSourceFiles($installPath, $domains, $dbg = true);
  465. // try {
  466. // $this->encodeSourceFiles($appLicenceInfo->installPath, $appLicenceInfo->domains, $dbg = false);
  467. // UI::alert('success', "OK");
  468. // } catch (Exception $e) {
  469. // UI::alert('danger', $e->getMessage());
  470. // }
  471. UI::endContainer();
  472. }
  473. // @usage: Router::getRoute('Install')->encodeSourceFiles($installPath = '/path_to_git_repo', $domains = [ 'domain.com', 'localhost' ], $dbg = false);
  474. public function encodeSourceFiles($installPath, $domains, $dbg = false) {
  475. if (empty($installPath)) throw new Exception("Install path not found");
  476. if (empty($domains)) throw new Exception("Domains not found");
  477. $phpVersionsForSgencoder = '--phpversion 5.5 --phpversion 5.6';// encode for PHP 5.x (currently supported PHP 5.0-5.6)
  478. if ('1' == V::get('DBG_ENCODER_HELP', '', $_REQUEST)) {// encoder help
  479. $cmd = "cd {$installPath}/SE && /Applications/SourceGuardian.app/Contents/MacOS/sgencoder --help ";
  480. $out = ''; $ret = '';
  481. V::exec($cmd, $out, $ret);
  482. DBG::nicePrint($out, "cmd: `{$cmd}` (return:{$ret})");
  483. exit;
  484. }
  485. $domainEncodePhpFiles = [
  486. 'ant.php',
  487. 'api.php',
  488. 'budynki.php',
  489. 'index-ajax.php',
  490. 'index.php',
  491. 'procesy5.php',
  492. 'session-expire.php',
  493. 'test-sync.php',
  494. 'wfs-data.php',
  495. 'wfs-qgis.php',
  496. 'wfs.php',
  497. ];
  498. $cmd = "find . -name '*.php' ";
  499. $out = ''; $ret = '';
  500. V::exec("cd {$installPath}/SE && {$cmd}", $out, $ret);
  501. if ($dbg) DBG::nicePrint($out, "cmd: `{$cmd}` (return:{$ret})");
  502. else DBG::log($out, 'array', "cmd: `{$cmd}` (return:{$ret})");
  503. if (0 !== $ret) throw new Exception("Error at find php files");
  504. if (empty($out)) throw new Exception("No php files found");
  505. $allPhpFiles = array_map(function ($phpFilePath) {
  506. return ('./' == substr($phpFilePath, 0, 2))? substr($phpFilePath, 2) : $phpFilePath;
  507. }, $out);
  508. $freeEncodePhpFiles = array_filter($allPhpFiles, function ($phpFilePath) use ($domainEncodePhpFiles) {
  509. if ('se-lib/Vendor/' === substr($phpFilePath, 0, strlen('se-lib/Vendor/'))) return false; // SKIP se-lib/Vendor/*
  510. if ('.ini.php' === substr($phpFilePath, -1 * strlen('.ini.php'))) return false; // SKIP *.ini.php
  511. return (!in_array($phpFilePath, $domainEncodePhpFiles));
  512. });
  513. DBG::log($freeEncodePhpFiles, 'array', "\$freeEncodePhpFiles");
  514. if (empty($freeEncodePhpFiles)) throw new Exception("No php files to encode");
  515. $cmdTempl = "cd {$installPath}/SE && /Applications/SourceGuardian.app/Contents/MacOS/sgencoder {$phpVersionsForSgencoder} -b- ";
  516. $cmdDomainEncodeDomainsTempl = " --domain " . implode(" --domain ", $domains);
  517. $cmdDomainEncodeFilesTempl = " " . implode(" ", $domainEncodePhpFiles);
  518. $cmdFreeEncodeFilesTempl = " " . implode(" ", $freeEncodePhpFiles);
  519. $cmds = [
  520. $cmdTempl . $cmdDomainEncodeDomainsTempl . $cmdDomainEncodeFilesTempl,
  521. $cmdTempl . $cmdFreeEncodeFilesTempl,
  522. ];
  523. $returnValues = [];
  524. foreach ($cmds as $cmd) {
  525. $out = ''; $ret = '';
  526. V::exec($cmd, $out, $ret);
  527. $encoderSummaryLine = end($out);
  528. $returnValues[] = $encoderSummaryLine;
  529. if ($dbg) {
  530. DBG::nicePrint([$cmd], "cmd");
  531. DBG::nicePrint($out, "return: '{$ret}'");
  532. // DBG::nicePrint([$encoderSummaryLine], "cmd last line");
  533. }
  534. else DBG::log([$cmd, $out], 'array', "cmd return:'{$ret}'");
  535. // if (0 !== $ret) throw new Exception("Error at encode files");
  536. if (empty($out)) throw new Exception("No output for encode files command");
  537. }
  538. $statusInfo = array_reduce($returnValues, function ($ret, $encoderSummaryLine) {
  539. DBG::log([$ret, $encoderSummaryLine], 'array', "DBG reduce [\$ret, \$encoderSummaryLine]");
  540. $matches = [];
  541. preg_match_all('/(\d+) files, (\d+) processed, (\d+) errors/', $encoderSummaryLine, $matches, PREG_SET_ORDER, 0);
  542. return [
  543. 'files' => $ret['files'] + (int)$matches[0][1],
  544. 'processed' => $ret['processed'] + (int)$matches[0][2],
  545. 'errors' => $ret['errors'] + (int)$matches[0][3],
  546. ];
  547. }, [
  548. 'files' => 0,
  549. 'processed' => 0,
  550. 'errors' => 0,
  551. ]);
  552. if ($statusInfo['errors'] === 0 && $statusInfo['files'] > 0) {
  553. if ($dbg) UI::alert('success', "{$statusInfo['files']} files, {$statusInfo['processed']} processed, {$statusInfo['errors']} errors");
  554. } else {
  555. if ($dbg) UI::alert('danger', "{$statusInfo['files']} files, {$statusInfo['processed']} processed, {$statusInfo['errors']} errors");
  556. else throw new Exception("{$statusInfo['files']} files, {$statusInfo['processed']} processed, {$statusInfo['errors']} errors");
  557. }
  558. }
  559. public function _encodeConfigs($configPath) {
  560. $cmd = "find . -name '*.inc.php' ";
  561. $out = ''; $ret = '';
  562. V::exec("cd {$configPath} && {$cmd}", $out, $ret);
  563. DBG::nicePrint($out, "cmd: `{$cmd}` (return:{$ret})");
  564. $freeEncodePhpFiles = $out;
  565. $phpVersionsForSgencoder = '--phpversion 5.5 --phpversion 5.6';// encode for PHP 5.x (currently supported PHP 5.0-5.6)
  566. $cmdTempl = "cd {$configPath} && /Applications/SourceGuardian.app/Contents/MacOS/sgencoder {$phpVersionsForSgencoder} -b- ";
  567. $cmdDomainEncodeDomainsTempl = " --domain " . implode(" --domain ", array_merge($domains, ['localhost']));
  568. // $cmdDomainEncodeFilesTempl = " " . implode(" ", $domainEncodePhpFiles);
  569. $cmdFreeEncodeFilesTempl = " " . implode(" ", $freeEncodePhpFiles);
  570. $cmds = [
  571. // $cmdTempl . $cmdDomainEncodeDomainsTempl . $cmdDomainEncodeFilesTempl,
  572. $cmdTempl . $cmdFreeEncodeFilesTempl,
  573. ];
  574. $dbg = true;
  575. $returnValues = [];
  576. foreach ($cmds as $cmd) {
  577. $out = ''; $ret = '';
  578. V::exec($cmd, $out, $ret);
  579. $encoderSummaryLine = end($out);
  580. $returnValues[] = $encoderSummaryLine;
  581. if ($dbg) {
  582. DBG::nicePrint([$cmd], "cmd");
  583. DBG::nicePrint($out, "return: '{$ret}'");
  584. // DBG::nicePrint([$encoderSummaryLine], "cmd last line");
  585. }
  586. else DBG::log([$cmd, $out], 'array', "cmd return:'{$ret}'");
  587. // if (0 !== $ret) throw new Exception("Error at encode files");
  588. if (empty($out)) throw new Exception("No output for encode files command");
  589. }
  590. $statusInfo = array_reduce($returnValues, function ($ret, $encoderSummaryLine) {
  591. DBG::log([$ret, $encoderSummaryLine], 'array', "DBG reduce [\$ret, \$encoderSummaryLine]");
  592. $matches = [];
  593. preg_match_all('/(\d+) files, (\d+) processed, (\d+) errors/', $encoderSummaryLine, $matches, PREG_SET_ORDER, 0);
  594. return [
  595. 'files' => $ret['files'] + (int)$matches[0][1],
  596. 'processed' => $ret['processed'] + (int)$matches[0][2],
  597. 'errors' => $ret['errors'] + (int)$matches[0][3],
  598. ];
  599. }, [
  600. 'files' => 0,
  601. 'processed' => 0,
  602. 'errors' => 0,
  603. ]);
  604. if ($statusInfo['errors'] === 0 && $statusInfo['files'] > 0) {
  605. if ($dbg) UI::alert('success', "{$statusInfo['files']} files, {$statusInfo['processed']} processed, {$statusInfo['errors']} errors");
  606. } else {
  607. if ($dbg) UI::alert('danger', "{$statusInfo['files']} files, {$statusInfo['processed']} processed, {$statusInfo['errors']} errors");
  608. else throw new Exception("{$statusInfo['files']} files, {$statusInfo['processed']} processed, {$statusInfo['errors']} errors");
  609. }
  610. }
  611. public function getAppLicenceInfo($idLicence) {
  612. $idLicence = intval($idLicence);
  613. if (empty($idLicence)) throw new Exception("Nie wybrano serwera/licencji.");
  614. //DBG::_(true, true, 'idLicence', $idLicence, __CLASS__, __FUNCTION__, __LINE__);
  615. $appLicenceInfo = (object)$this->fetchAppLicenceInfo($idLicence);
  616. $appLicenceInfo->domains = $this->fetchDomainsByLicenceId($idLicence);
  617. $installRootPath = '/Library/Server/Web/Data/Sites/Default/PLIKI/SES_PROCESY5_A';
  618. $appLicenceInfo->installFolderName = "{$idLicence}_upgrade_SE_source_encrypted";
  619. $appLicenceInfo->configFolderName = "{$idLicence}_upgrade_SE_config_encrypted";
  620. $appLicenceInfo->installPath = "{$installRootPath}/{$appLicenceInfo->installFolderName}";
  621. $appLicenceInfo->configPath = "{$installRootPath}/{$appLicenceInfo->configFolderName}";
  622. //DBG::_(true, true, 'appLicenceInfo', $appLicenceInfo, __CLASS__, __FUNCTION__, __LINE__);
  623. if (empty($appLicenceInfo->domains)) throw new Exception("Domains not found."); // TODO: mv to validate
  624. $appLicenceInfo->installFolderExists = file_exists("{$appLicenceInfo->installPath}/SE");
  625. $appLicenceInfo->installFolderGitExists = file_exists("{$appLicenceInfo->installPath}/.git");
  626. $appLicenceInfo->projects = []; // TODO: get from db
  627. if (!empty($appLicenceInfo->projects)) {
  628. $appLicenceInfo->projects = [ $appLicenceInfo->project ];
  629. }
  630. else if (79 == $idLicence) { // bravecom.procesy5.pl
  631. $appLicenceInfo->projects = [ 'bravecare' ];
  632. } else if (80 == $idLicence) { // bravecom.yellowgroup.pl
  633. $appLicenceInfo->projects = [ 'bocian' ];
  634. } else if (81 == $idLicence) { // bocian.procesy5.pl
  635. $appLicenceInfo->projects = [ 'bocian' ];
  636. } else if (67 == $idLicence) { // bocian.procesy5.pl
  637. $appLicenceInfo->projects = [ 'bocian' ];
  638. } else if (82 == $idLicence) { // bocian-energa.procesy5.pl
  639. $appLicenceInfo->projects = [ 'bocian' ];
  640. } else if (4 == $idLicence) { // bzyk.procesy5.pl
  641. $appLicenceInfo->projects = [ 'bocian' ];
  642. }
  643. return $appLicenceInfo;
  644. }
  645. public function validateAppLicenceInfo($appLicenceInfo) {
  646. if (empty($appLicenceInfo->ID)) throw new Exception("Nie wybrano serwera/licencji.");
  647. if (empty($appLicenceInfo->domains)) throw new Exception("Domains not found");
  648. if (empty($appLicenceInfo->installPath)) throw new Exception("Install path not found");
  649. }
  650. public function generateApp($installPath, $domains, $projects = []) {
  651. $cmds = array();
  652. $cmds[] = "if [ -d {$installPath} ] ; then rm -rf '{$installPath}'; fi";
  653. $cmds[] = "mkdir {$installPath}";
  654. $cmds[] = "cd {$installPath} && git clone --depth 1 ssh://git@biuro.biall-net.pl:2222/plabudda/se.git .";
  655. $cmds[] = "cd {$installPath} && echo `git show-ref --head|head -1|head -c 8` > SE/VERSION ";
  656. foreach ($cmds as $cmd) {
  657. V::exec($cmd, $out, $ret);
  658. DBG::nicePrint([ 'cmd' => $cmd, 'output' => $out ], "return: {$ret}");
  659. }
  660. foreach ($projects as $projectName) {
  661. $cmd = "ls -l SE/projects/{$projectName} | wc -l";
  662. V::exec("cd {$installPath} && {$cmd}", $out, $ret);
  663. DBG::nicePrint([ 'cmd' => $cmd, 'output' => $out ], "return: {$ret}");
  664. if (!empty($out) && '0' !== trim($out[0])) {
  665. // $cmd = "git submodule update SE/projects/{$projectName}";
  666. $cmd = "cd SE/projects/{$projectName} && git reset --hard"; // revert encode source - checkout to last commit (need update)
  667. V::exec("cd {$installPath} && {$cmd}", $out, $ret);
  668. DBG::nicePrint([ 'cmd' => $cmd, 'output' => $out ], "return: {$ret}");
  669. }
  670. $cmd = "git submodule update --init SE/projects/{$projectName}"; // checkout to current commit
  671. V::exec("cd {$installPath} && {$cmd}", $out, $ret);
  672. DBG::nicePrint([ 'cmd' => $cmd, 'output' => $out ], "return: {$ret}");
  673. }
  674. $this->_encodeSource($installPath, $domains);
  675. $this->configGenerate($appLicenceInfo->configPath, $appLicenceInfo->mainServer, $appLicenceInfo->domains, $appLicenceInfo->rootPassword
  676. , $appLicenceInfo->ldapUser, $appLicenceInfo->ldapPass, $appLicenceInfo->ldapBaseDN
  677. );
  678. $this->_encodeConfigs($appLicenceInfo->configPath);
  679. // 1763: $exec='cd '.$installer_dir.' && /Applications/SourceGuardian.app/Contents/MacOS/sgencoder -b-
  680. // '.INSTALL_SES_PROCESY_A::get_same_domains_for_install($h->SERVER_ADDRESS_SHORT).'
  681. // -r *.php
  682. // -x superedit-DB_PROCEDURES_CREATE.php
  683. // -x INI.php
  684. // -x .config_base_structure.php
  685. // ';
  686. //
  687. // INSTALL_SES_PROCESY_A::get_same_domains_for_install($h->SERVER_ADDRESS_SHORT):
  688. // $res2=DB::query("select SERVER_ADDRESS_SHORT from SES_PROCESY5_A where SERVER_ADDRESS_IP='".$h->SERVER_ADDRESS_IP."'");
  689. // while($h2=DB::fetch($res2)) {
  690. // $domain[]=' --domain '.$h2->SERVER_ADDRESS_SHORT;
  691. // ssh server@biuro.galeriaprzymorze.eu: PHP 5.5.20
  692. // ssh server@biuro.biall-net.pl
  693. // cd /Users/plabudda/procesy5-install-galeriaprzymorze.eu/
  694. // sudo chown -R server:admin SE/
  695. // /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
  696. }
  697. public function fetchActiveLicences() {
  698. $activeLic = array();
  699. $sql = "
  700. select l.`ID`
  701. , l.`SERVER_ADDRESS`
  702. , l.`SERVER_ADDRESS_SHORT` as domain -- domain for sgencoder
  703. , l.`SERVER_ADDRESS_IP`
  704. from `SES_PROCESY5_A` l
  705. where 1=1
  706. -- TODO: and l.`A_STATUS` in('NORMAL','WAITING')
  707. order by l.`ID` DESC
  708. ";
  709. $rows = DB::getPDO()->fetchAll($sql);
  710. foreach ($rows as $row) {
  711. $r = (object)$row;
  712. $activeLic[$r->ID] = $r;
  713. }
  714. return $activeLic;
  715. }
  716. public function fetchDomainsByLicenceId($licenceId) {
  717. $domains = array();
  718. $sql = "
  719. select g.ID, g.`SERVER_ADDRESS_SHORT`, g.`SERVER_ADDRESS`
  720. from `SES_PROCESY5_A` g
  721. where g.`SERVER_ADDRESS_IP`=(select l.`SERVER_ADDRESS_IP`
  722. from `SES_PROCESY5_A` l
  723. where l.`ID`='{$licenceId}'
  724. -- TODO: and l.`A_STATUS` in('NORMAL','WAITING')
  725. )
  726. -- TODO: and g.`A_STATUS` in('NORMAL','WAITING')
  727. ";
  728. $rows = DB::getPDO()->fetchAll($sql);
  729. $mainDomain = null;
  730. foreach ($rows as $row) {
  731. if ($licenceId == $row['ID']) $mainDomain = $row['SERVER_ADDRESS'];
  732. }
  733. foreach ($rows as $row) {
  734. $r = (object)$row;
  735. $domains[] = $r->SERVER_ADDRESS_SHORT;
  736. if ($r->SERVER_ADDRESS != $r->SERVER_ADDRESS_SHORT) {
  737. $domains[] = $r->SERVER_ADDRESS;
  738. }
  739. }
  740. if ($mainDomain && (!preg_match('/^(.*)\.procesy5\.pl$/', $mainDomain))) {
  741. $subDomainP5 = '' . $mainDomain . '.procesy5.pl';
  742. if (!in_array($subDomainP5, $domainList)) $domains[] = $subDomainP5;
  743. }
  744. $domains[] = '127.0.0.1';
  745. $domains[] = 'localhost';
  746. return $domains;
  747. }
  748. public function fetchMainServerByLicenceId($licenceId) {
  749. return DB::getPDO()->fetchValue("
  750. select g.`SERVER_ADDRESS`
  751. from `SES_PROCESY5_A` g
  752. where g.`ID`='{$licenceId}'
  753. -- TODO: and g.`A_STATUS` in('NORMAL','WAITING')
  754. ");
  755. }
  756. public function fetchAppLicenceInfo($licenceId) {
  757. $licenceInfo = null;
  758. $sql = "
  759. select g.ID
  760. , g.SERVER_ADDRESS as mainServer
  761. , g.ADMIN_USERNAME as rootLogin
  762. , g.ADMIN_USERNAME_PASSWD as rootPassword
  763. , g.SSH_PORT as sshPort
  764. , g.VERSION_GIT as project
  765. , g.ADMIN_USERNAME_DIRECTORY as ldapUser
  766. , g.ADMIN_USERNAME_PASSWD as ldapPass
  767. , g.SERVER_ADDRESS_LDAP_DC as ldapBaseDN
  768. from SES_PROCESY5_A g
  769. where g.`ID`=:id_licence
  770. -- TODO: and g.A_STATUS in('NORMAL','WAITING')
  771. ";
  772. $all = DB::getPDO()->fetchAll($sql, [ ':id_licence' => $licenceId ]);
  773. if (empty($all)) throw new Exception("Brak licencji o nr '{$licenceId}'");
  774. $licenceInfo = reset($all);
  775. if (!$licenceInfo['sshPort']) $licenceInfo['sshPort'] = 22;
  776. return $licenceInfo;
  777. }
  778. public function _endWithException($e) {
  779. echo UI::h('div', ['class'=>"container"], [
  780. UI::h('div', ['class' => "alert alert-danger"], "#" . $e->getLine() . ": " . $e->getMessage()),
  781. UI::h('p', [], [
  782. "Wróć do ",
  783. UI::h('a', ['href'=>"index.php?_route=Install"], "menu")
  784. ])
  785. ]);
  786. UI::dol();
  787. exit;
  788. }
  789. public function sendToRemoteTestDirAction() {
  790. session_write_close();
  791. $args = array();
  792. $args['licence_id'] = V::get('licence_id', 0, $_REQUEST, 'int');
  793. UI::gora();
  794. //UI::menu();
  795. //$this->menu($args['licence_id']);// TODO: GO BACK BTN
  796. try {
  797. $appLicenceInfo = $this->getAppLicenceInfo($args['licence_id']);
  798. $this->validateAppLicenceInfo($appLicenceInfo);
  799. // TODO: if (59 ) => baratosz.sledz - na lokalnym kompie
  800. // bn:~/$ scp -r SE server@192.168.61.153:~/se.encrypted.upgrade
  801. // remote SE.git = '/Users/bartoszsledz/Desktop/production-se'
  802. // remote:~/$ mv SE ~/SE.bup.2017-07-03
  803. // remote:~/$ mv ~/se.encrypted.upgrade/SE SE
  804. // remote:~/$ cp -r ~/SE.bup.2017-07-03/config SE/
  805. // remote:~/$ sudo chown -R bartoszsledz:staff SE/
  806. $this->_sendToRemoteTestDir($appLicenceInfo);
  807. echo "Test online: ";
  808. echo UI::h('a', ['target'=>"_blank", 'href'=>"https://{$appLicenceInfo->mainServer}/se.encrypted.upgrade/"], "https://{$appLicenceInfo->mainServer}/se.encrypted.upgrade/");
  809. } catch (Exception $e) {
  810. $this->_endWithException($e);
  811. }
  812. UI::dol();
  813. }
  814. public function _fetchRemoteHomeDir($appLicenceInfo) {
  815. $this->_assertRsaKeyExists($appLicenceInfo);
  816. $sshHostUsr = "{$appLicenceInfo->rootLogin}@{$appLicenceInfo->mainServer}";
  817. $sshArgs = (22 != $appLicenceInfo->sshPort)? "-p {$appLicenceInfo->sshPort}" : '';
  818. $scpArgs = (22 != $appLicenceInfo->sshPort)? "-P {$appLicenceInfo->sshPort}" : '';
  819. $rsyncSshPort = (22 != $appLicenceInfo->sshPort)? "-e 'ssh -p {$appLicenceInfo->sshPort}'" : '';
  820. if (V::get('DBG_REMOTE', '', $_GET)) {// DBG
  821. $cmd = "echo ~";
  822. V::exec("ssh {$sshArgs} {$sshHostUsr} '{$cmd}'", $out, $ret);
  823. DBG::log([ 'cmd-remote' => $cmd, 'output' => $out ], 'array', "return: {$ret}");
  824. V::execRemote($appLicenceInfo->mainServer, $appLicenceInfo->rootLogin, $appLicenceInfo->rootPassword, $cmd, $out, $ret, $appLicenceInfo->sshPort);
  825. DBG::log([ 'cmd-remote' => $cmd, 'output' => $out ], 'array', "return: {$ret}");
  826. V::execRootRemote($appLicenceInfo->mainServer, $appLicenceInfo->rootLogin, $appLicenceInfo->rootPassword, $cmd, $out, $ret, $appLicenceInfo->sshPort);
  827. DBG::log([ 'cmd-remote' => $cmd, 'output' => $out ], 'array', "return: {$ret}");
  828. }
  829. $cmd = "echo ~";
  830. V::exec("ssh {$sshArgs} {$this->sshArgsSkipHostKey} {$sshHostUsr} '{$cmd}'", $out, $ret);
  831. DBG::log([ 'cmd-remote' => $cmd, 'output' => $out ], 'array', "return: {$ret}");
  832. if (empty($out) || empty($out[0])) throw new Exception("Cannot fetch remote home dir");
  833. return $out[0];
  834. }
  835. public function _sendToRemoteTestDir($appLicenceInfo) {
  836. $cmd = ''; $out = ''; $ret = '';
  837. $dryRunOnly = (V::get('dry-run', '', $_REQUEST)) ? "--dry-run" : "";
  838. $this->_assertRsaKeyExists($appLicenceInfo);
  839. $sshHostUsr = "{$appLicenceInfo->rootLogin}@{$appLicenceInfo->mainServer}";
  840. $sshArgs = (22 != $appLicenceInfo->sshPort)? "-p {$appLicenceInfo->sshPort}" : '';
  841. $rsyncSshPort = (22 != $appLicenceInfo->sshPort)? "-e 'ssh -p {$appLicenceInfo->sshPort}'" : '';
  842. $scpArgs = (22 != $appLicenceInfo->sshPort)? "-P {$appLicenceInfo->sshPort}" : '';
  843. // $appLicenceInfo->sshPort
  844. /* rsync options:
  845. -a, --archive archive mode; same as -rlptgoD (no -H)
  846. -u, --update skip files that are newer on the receiver
  847. -t, --times preserve times
  848. --delete delete extraneous files from dest dirs
  849. */
  850. $remoteDir = $this->_fetchRemoteHomeDir($appLicenceInfo);
  851. DBG::log($remoteDir, 'array', "remote home dir:");
  852. $cmd = "
  853. ssh {$sshArgs} {$this->sshArgsSkipHostKey} {$sshHostUsr} '[ ! -d ~/se.encrypted.upgrade ] && mkdir ~/se.encrypted.upgrade || echo 1';
  854. ssh {$sshArgs} {$this->sshArgsSkipHostKey} {$sshHostUsr} 'rm -rf ~/se.encrypted.upgrade/SE';
  855. ssh {$sshArgs} {$this->sshArgsSkipHostKey} {$sshHostUsr} 'cp -r /Library/Server/Web/Data/Sites/Default/SE ~/se.encrypted.upgrade/SE';
  856. ssh {$sshArgs} {$this->sshArgsSkipHostKey} {$sshHostUsr} 'rm -rf ~/se.encrypted.upgrade/SE/config';
  857. rsync --archive --times --delete --compress --one-file-system --omit-dir-times --no-g --no-perms {$dryRunOnly} \
  858. --verbose {$rsyncSshPort} \
  859. --exclude='schema/default_db.instance.xml' \
  860. --exclude='schema/default_db.instance.xml/**' \
  861. '{$appLicenceInfo->installPath}/SE/' {$sshHostUsr}:~/se.encrypted.upgrade/SE/;
  862. ssh {$sshArgs} {$this->sshArgsSkipHostKey} {$sshHostUsr} 'cp -r /Library/Server/Web/Data/Sites/Default/SE/config ~/se.encrypted.upgrade/SE/';
  863. ssh {$sshArgs} {$this->sshArgsSkipHostKey} {$sshHostUsr} 'rm /Library/Server/Web/Data/Sites/Default/se.encrypted.upgrade'
  864. ssh {$sshArgs} {$this->sshArgsSkipHostKey} {$sshHostUsr} 'ln -s ~/se.encrypted.upgrade/SE /Library/Server/Web/Data/Sites/Default/se.encrypted.upgrade'
  865. scp {$this->sshArgsSkipHostKey} {$scpArgs} /Library/Server/Web/Data/Sites/SE-production-git/SE/config/.config_base_structure.php {$sshHostUsr}:
  866. ssh {$sshArgs} {$this->sshArgsSkipHostKey} {$sshHostUsr} 'mv ~/.config_base_structure.php /Library/Server/Web/Data/Sites/Default/se.encrypted.upgrade/config'
  867. "; //todo rsync ... -e \"{$this->sshArgsSkipHostKey}\" - maybe not working
  868. // --exclude='schema/default_db_xml_cache.public' \
  869. // --exclude='stuff' \
  870. // --exclude='stuff/**' \
  871. //--exclude='schema/default_db_xml_cache.public/**' \
  872. V::exec("$cmd 2>&1", $out, $ret);
  873. DBG::log([ 'cmd-remote' => $cmd, 'output' => $out ], 'array', "return: {$ret}");
  874. if (0 !== $ret) throw new Exception("Cannot run remote command using rsa key! #{$ret}. cmd: {$cmd} . out: {$out}");
  875. }
  876. public function upgradeRemoteFromTestDirAction() {
  877. session_write_close();
  878. $args = array();
  879. $args['licence_id'] = V::get('licence_id', 0, $_REQUEST, 'int');
  880. UI::gora();
  881. //UI::menu();
  882. //$this->menu($args['licence_id']);// TODO: GO BACK BTN
  883. try {
  884. $appLicenceInfo = $this->getAppLicenceInfo($args['licence_id']);
  885. $this->validateAppLicenceInfo($appLicenceInfo);
  886. $this->_upgradeRemoteFromTestDir($appLicenceInfo);
  887. echo "Test online: ";
  888. echo UI::h('a', ['target'=>"_blank", 'href'=>"https://{$appLicenceInfo->mainServer}/SE/"], "https://{$appLicenceInfo->mainServer}/SE/");
  889. } catch (Exception $e) {
  890. $this->_endWithException($e);
  891. }
  892. UI::dol();
  893. }
  894. public function _upgradeRemoteFromTestDir($appLicenceInfo) {
  895. $cmd = ''; $out = ''; $ret = '';
  896. $this->_assertRsaKeyExists($appLicenceInfo);
  897. $dateStr = date("Y-m-d_H-i-s");
  898. // $remoteHomeDir = "/Users/{$appLicenceInfo->rootLogin}";// BUG: alias like in ams - login = prezes is alias for arkadiuszbinder
  899. $remoteHomeDir = $this->_fetchRemoteHomeDir($appLicenceInfo);
  900. $cmd = "
  901. rm -rf /Library/Server/Web/Data/Sites/Default/SE.test 2>&1
  902. cp -r {$remoteHomeDir}/se.encrypted.upgrade/SE /Library/Server/Web/Data/Sites/Default/SE.test 2>&1
  903. [ ! -d {$remoteHomeDir}/bup.se.upgrade ] && mkdir {$remoteHomeDir}/bup.se.upgrade || echo 1
  904. [ ! -d {$remoteHomeDir}/bup.se.upgrade ] && exit 1
  905. [ ! -d {$remoteHomeDir}/bup.se.upgrade-testttttt ] && exit 1
  906. [ ! -f /Library/Server/Web/Data/Sites/Default/SE.test/VERSION ] && echo \"Error: plik VERSION nie istnieje\" || echo \"check VERSION OK\"
  907. [ ! -f /Library/Server/Web/Data/Sites/Default/SE.test/VERSION ] && exit 1
  908. [ ! -f /Library/Server/Web/Data/Sites/Default/SE.test/index.php ] && echo \"Error: plik index.php nie istnieje\" || echo \"check index.php OK\"
  909. [ ! -f /Library/Server/Web/Data/Sites/Default/SE.test/index.php ] && exit 1
  910. [ ! -d /Library/Server/Web/Data/Sites/Default/SE.test/se-lib ] && echo \"Error: plik se-lib nie istnieje\" || echo \"check se-lib OK\"
  911. [ ! -d /Library/Server/Web/Data/Sites/Default/SE.test/se-lib ] && exit 1
  912. exit 0
  913. ";
  914. V::execRootRemote($appLicenceInfo->mainServer, $appLicenceInfo->rootLogin, $appLicenceInfo->rootPassword, $cmd, $out, $ret, $appLicenceInfo->sshPort);
  915. $cmd = "
  916. mv /Library/Server/Web/Data/Sites/Default/SE {$remoteHomeDir}/bup.se.upgrade/bup.{$dateStr} 2>&1
  917. mv /Library/Server/Web/Data/Sites/Default/SE.test /Library/Server/Web/Data/Sites/Default/SE 2>&1
  918. exit 0
  919. ";
  920. V::execRootRemote($appLicenceInfo->mainServer, $appLicenceInfo->rootLogin, $appLicenceInfo->rootPassword, $cmd, $out, $ret, $appLicenceInfo->sshPort);
  921. DBG::_(true, true, "cmd: {$cmd} (return: {$ret})", $out, __CLASS__, __FUNCTION__, __LINE__);
  922. if (0 !== $ret) throw new Exception("Cannot run remote command as root! #{$ret}");
  923. // TODO: SE/bash_install_check.php requires $domain!
  924. // $cmd = "/usr/bin/php /Library/Server/Web/Data/Sites/Default/SE/bash_install_check.php {$domain}";
  925. // V::execRootRemote($appLicenceInfo->mainServer, $appLicenceInfo->rootLogin, $appLicenceInfo->rootPassword, $cmd, $out, $ret, $appLicenceInfo->sshPort);
  926. // DBG::_(true, true, "cmd: {$cmd} (return: {$ret})", $out, __CLASS__, __FUNCTION__, __LINE__);
  927. // if (0 !== $ret) throw new Exception("Cannot run remote command as root! #{$ret}");
  928. }
  929. public function _assertRsaKeyExists($appLicenceInfo) {
  930. $cmd = ''; $out = ''; $ret = '';
  931. $cmd = "echo ~ && pwd";// /Library/WebServer
  932. $cmd = "ls -1 ~/.ssh/";
  933. //$cmd = "rm /tmp/id_rsa";
  934. //$cmd = "rm /tmp/id_rsa.pub";
  935. //$cmd = "ssh-keygen -t rsa -N '' -C '_www@biuro.biall-net.pl' -f /tmp/id_rsa";
  936. //$cmd = "ssh-keygen -t rsa -N '' -C '_www@biuro.biall-net.pl' -f /tmp/id_rsa";
  937. V::exec($cmd, $out, $ret);
  938. DBG::_(true, true, "cmd: {$cmd} (return: {$ret})", $out, __CLASS__, __FUNCTION__, __LINE__);
  939. if (0 !== $ret) {// no ~/.ssh directory
  940. $rsaKeyPath = "~/.ssh";
  941. $cmds = array();
  942. $cmds[] = "mkdir {$rsaKeyPath}";
  943. $cmds[] = "ssh-keygen -t rsa -N '' -C '_www@biuro.biall-net.pl' -f {$rsaKeyPath}/id_rsa 2>&1";
  944. $cmds[] = "ls -1 $rsaKeyPath";
  945. foreach ($cmds as $cmd) {
  946. V::exec($cmd, $out, $ret);
  947. DBG::_(true, true, "cmd: {$cmd} (return: {$ret})", $out, __CLASS__, __FUNCTION__, __LINE__);
  948. if (0 !== $ret) throw new Exception("Error '{$ret}' cmd({$cmd}): " . implode("\n", $out));
  949. }
  950. }
  951. $cmd = "cat ~/.ssh/id_rsa.pub";
  952. V::exec($cmd, $out, $ret);
  953. DBG::_(true, true, "cmd: {$cmd} (return: {$ret})", $out, __CLASS__, __FUNCTION__, __LINE__);
  954. if (0 !== $ret || empty($out) || empty($out[0])) throw new Exception("Cannot read rsa public key");
  955. $rsaPubKey = $out[0];
  956. $cmd = 'ls -1a';
  957. $cmd = "
  958. [ ! -d ~/.ssh ] && mkdir ~/.ssh;
  959. [ ! -d ~/.ssh ] && echo 'ERROR ~/.ssh not exists and cannot be created';
  960. [ ! -f ~/.ssh/authorized_keys ] && echo '{$rsaPubKey}' > ~/.ssh/authorized_keys;
  961. [ ! -f ~/.ssh/authorized_keys ] && echo 'ERROR ~/.ssh/authorized_keys not exists and cannot be created';
  962. cat ~/.ssh/authorized_keys| grep '{$rsaPubKey}' && echo 'OK' || echo '{$rsaPubKey}' >> ~/.ssh/authorized_keys;
  963. chmod 600 ~/.ssh/authorized_keys;
  964. ";
  965. V::execRemote($appLicenceInfo->mainServer, $appLicenceInfo->rootLogin, $appLicenceInfo->rootPassword, $cmd, $out, $ret, $appLicenceInfo->sshPort);
  966. DBG::_(true, true, "remote cmd: {$cmd} (return: {$ret})", $out, __CLASS__, __FUNCTION__, __LINE__);
  967. //$cmd = "ssh server@{$appLicenceInfo->mainServer} 'ls -1 .ssh/'";
  968. //$cmd = "ssh -i ~/.ssh/id_rsa server@{$appLicenceInfo->mainServer} 'ls -1'";
  969. $sshPort = (22 != $appLicenceInfo->sshPort)? "-p {$appLicenceInfo->sshPort}" : '';
  970. $cmd = "ssh {$sshPort} {$this->sshArgsSkipHostKey} {$appLicenceInfo->rootLogin}@{$appLicenceInfo->mainServer} 'ls -1'";
  971. 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,
  972. //and deduced that the solution was to
  973. //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.
  974. //But it seems to be the only solution (suggestions are welcome).
  975. DBG::_(true, true, "cmd: {$cmd} (return: {$ret})", $out, __CLASS__, __FUNCTION__, __LINE__);
  976. if (0 !== $ret) throw new Exception("Cannot run remote command using rsa key! #{$ret}; Out: ".implode($out)."; Cmd: {$cmd};");
  977. }
  978. public function newGenerateApp($appLicenceInfo) {
  979. if (empty($appLicenceInfo->ID)) throw new Exception("Nie wybrano serwera/licencji.");
  980. if (empty($appLicenceInfo->domains)) throw new Exception("Domains not found");
  981. $installPath = $appLicenceInfo->installPath;
  982. if (empty($installPath)) throw new Exception("Install path not found");
  983. $installPath .= '-p5';
  984. $cmds = array();
  985. $cmds[] = "if [ -d {$installPath} ] ; then rm -rf '{$installPath}'; fi";
  986. $cmds[] = "mkdir {$installPath}";
  987. $cmds[] = "cd {$installPath} && git clone --depth 1 ssh://git@biuro.biall-net.pl:2222/p5/p5.git .";
  988. $cmds[] = "cd {$installPath} && echo `git show-ref --head|head -1|head -c 8` > SE/VERSION ";
  989. // TODO: fetch from DB
  990. {
  991. foreach ($appLicenceInfo->projects as $projectName) {
  992. $cmds[] = "cd {$installPath} && git submodule update --init SE/projects/{$projectName}";
  993. }
  994. }
  995. foreach ($cmds as $cmd) {
  996. $out = ''; $ret = '';
  997. V::exec($cmd, $out, $ret);
  998. DBG::nicePrint([ 'cmd' => $cmd, 'output' => $out ], "return: {$ret}");
  999. }
  1000. // $this->_encodeSource($appLicenceInfo->installPath, $appLicenceInfo->domains);
  1001. }
  1002. }