Install.php 48 KB

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