Install.php 48 KB

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