Subversion Repositories oidplus

Rev

Rev 1426 | Rev 1434 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed

  1. <?php
  2.  
  3. /*
  4.  * OIDplus 2.0
  5.  * Copyright 2019 - 2023 Daniel Marschall, ViaThinkSoft
  6.  *
  7.  * Licensed under the Apache License, Version 2.0 (the "License");
  8.  * you may not use this file except in compliance with the License.
  9.  * You may obtain a copy of the License at
  10.  *
  11.  *     http://www.apache.org/licenses/LICENSE-2.0
  12.  *
  13.  * Unless required by applicable law or agreed to in writing, software
  14.  * distributed under the License is distributed on an "AS IS" BASIS,
  15.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16.  * See the License for the specific language governing permissions and
  17.  * limitations under the License.
  18.  */
  19.  
  20. namespace ViaThinkSoft\OIDplus;
  21.  
  22. // phpcs:disable PSR1.Files.SideEffects
  23. \defined('INSIDE_OIDPLUS') or die;
  24. // phpcs:enable PSR1.Files.SideEffects
  25.  
  26. class OIDplusPageAdminSoftwareUpdate extends OIDplusPagePluginAdmin
  27.         implements INTF_OID_1_3_6_1_4_1_37476_2_5_2_3_8 /* getNotifications */
  28. {
  29.  
  30.         /**
  31.          * @param bool $html
  32.          * @return void
  33.          */
  34.         public function init(bool $html=true) {
  35.         }
  36.  
  37.         /**
  38.          * @return string
  39.          */
  40.         private function getGitCommand(): string {
  41.                 return 'git --git-dir='.escapeshellarg(OIDplus::findGitFolder()).' --work-tree='.escapeshellarg(OIDplus::localpath()).' -C "" pull origin master -s recursive -X theirs';
  42.         }
  43.  
  44.         /**
  45.          * @return string
  46.          */
  47.         private function getSvnCommand(): string {
  48.                 return 'svn update --accept theirs-full';
  49.         }
  50.  
  51.         /**
  52.          * @param array $params
  53.          * @return array
  54.          * @throws OIDplusException
  55.          */
  56.         private function action_Update(array $params): array {
  57.                 @set_time_limit(0);
  58.  
  59.                 if (!OIDplus::authUtils()->isAdminLoggedIn()) {
  60.                         throw new OIDplusHtmlException(_L('You need to <a %1>log in</a> as administrator.',OIDplus::gui()->link('oidplus:login$admin')), null, 401);
  61.                 }
  62.  
  63.                 if (OIDplus::getInstallType() === 'git-wc') {
  64.                         $cmd = $this->getGitCommand().' 2>&1';
  65.  
  66.                         $ec = -1;
  67.                         $out = array();
  68.                         exec($cmd, $out, $ec);
  69.  
  70.                         $res = _L('Execute command:').' '.$cmd."\n\n".trim(implode("\n",$out));
  71.                         if ($ec === 0) {
  72.                                 $next_version = 'HEAD'; // do not translate
  73.                                 return array("status" => 0, "content" => $res, "rev" => $next_version);
  74.                         } else {
  75.                                 return array("status" => -1, "error" => $res, "content" => "");
  76.                         }
  77.                 }
  78.                 else if (OIDplus::getInstallType() === 'svn-wc') {
  79.                         $cmd = $this->getSvnCommand().' 2>&1';
  80.  
  81.                         $ec = -1;
  82.                         $out = array();
  83.                         exec($cmd, $out, $ec);
  84.  
  85.                         $res = _L('Execute command:').' '.$cmd."\n\n".trim(implode("\n",$out));
  86.                         if ($ec === 0) {
  87.                                 $next_version = 'HEAD'; // do not translate
  88.                                 return array("status" => 0, "content" => $res, "rev" => $next_version);
  89.                         } else {
  90.                                 return array("status" => -1, "error" => $res, "content" => "");
  91.                         }
  92.                 }
  93.                 else if (OIDplus::getInstallType() === 'manual') {
  94.  
  95.                         $update_version = $params['update_version'] ?? 1;
  96.                         if (($update_version != 1) && ($update_version != 2) && ($update_version != 3)) {
  97.                                 throw new OIDplusException(_L('Unknown update version'));
  98.                         }
  99.  
  100.                         if ($update_version >= 3) {
  101.                                 $next_version = $params['next_version'];
  102.                                 $max_version = $params['max_version'] ?? null;
  103.                         } else {
  104.                                 $next_version = $params['rev'];
  105.                                 $max_version = null;
  106.                         }
  107.  
  108.                         // Prepare update for all next versions
  109.  
  110.                         $downloaded_changescripts = [];
  111.  
  112.                         $ver = $next_version;
  113.                         do {
  114.                                 // Download and unzip
  115.  
  116.                                 $cont = false;
  117.                                 $basename = 'changescript_'.$ver.'.txt';
  118.                                 for ($retry=1; $retry<=3; $retry++) {
  119.                                         if (function_exists('gzdecode')) {
  120.                                                 $url = OIDplus::getEditionInfo()['update_packages'].$basename.'.gz';
  121.                                                 $cont = url_get_contents($url);
  122.                                                 if ($cont !== false) $cont = @gzdecode($cont);
  123.                                         } else {
  124.                                                 $url = OIDplus::getEditionInfo()['update_packages'].$basename;
  125.                                                 $cont = url_get_contents($url);
  126.                                         }
  127.                                         if ($cont !== false) {
  128.                                                 break;
  129.                                         } else {
  130.                                                 sleep(1);
  131.                                         }
  132.                                 }
  133.                                 if ($cont === false) throw new OIDplusException(_L("Update %1 could not be downloaded from the remote server (%2). Please try again later.",$ver,$url));
  134.  
  135.                                 // Check signature...
  136.  
  137.                                 if (function_exists('openssl_verify')) {
  138.                                         $m = array();
  139.                                         if (!preg_match('@<\?php /\* <ViaThinkSoftSignature>(.+)</ViaThinkSoftSignature> \*/ \?>\n@ismU', $cont, $m)) {
  140.                                                 throw new OIDplusException(_L("Update package file of revision %1 not digitally signed",$ver));
  141.                                         }
  142.                                         $signature = base64_decode($m[1]);
  143.  
  144.                                         $naked = preg_replace('@<\?php /\* <ViaThinkSoftSignature>(.+)</ViaThinkSoftSignature> \*/ \?>\n@ismU', '', $cont);
  145.                                         $hash = hash("sha256", $naked.$basename);
  146.  
  147.                                         $public_key = file_get_contents(__DIR__.'/public.pem');
  148.                                         if (!openssl_verify($hash, $signature, $public_key, OPENSSL_ALGO_SHA256)) {
  149.                                                 throw new OIDplusException(_L("Update package file of revision %1: Signature invalid",$ver));
  150.                                         }
  151.  
  152.                                 }
  153.  
  154.                                 // All OK! Now write the file
  155.  
  156.                                 $tmp_filename = 'update_'.generateRandomString(10).'.tmp.php';
  157.                                 $local_file = OIDplus::localpath().$tmp_filename;
  158.  
  159.                                 @file_put_contents($local_file, $cont);
  160.  
  161.                                 if (!file_exists($local_file) || (@file_get_contents($local_file) !== $cont)) {
  162.                                         throw new OIDplusException(_L('Update file could not written. Probably there are no write-permissions to the root folder.'));
  163.                                 }
  164.  
  165.                                 $downloaded_changescripts[] = [ $ver, $tmp_filename ];
  166.  
  167.                         } while (($update_version>=3)&&($ver!=$max_version)&&($ver=$this->getNextVersionFrom($ver,false)));
  168.  
  169.                         # ---
  170.  
  171.  
  172.                         if ($update_version == 1) {
  173.                                 // Now call the written file
  174.                                 // Note: we may not use eval($cont) because the script uses die(),
  175.                                 // and things in the script might collide with currently (un)loaded source code files, shutdown procedues, etc.
  176.                                 $web_file = OIDplus::webpath(null,OIDplus::PATH_ABSOLUTE_CANONICAL).$tmp_filename;
  177.                                 $res = url_get_contents($web_file);
  178.                                 if ($res === false) {
  179.                                         $web_file = OIDplus::webpath(null,OIDplus::PATH_ABSOLUTE).$tmp_filename;
  180.                                         $res = url_get_contents($web_file);
  181.                                         if ($res === false) {
  182.                                                 throw new OIDplusException(_L('Update-script %1 could not be executed',$web_file));
  183.                                         }
  184.                                 }
  185.                                 return array("status" => 0, "content" => $res, "rev" => $next_version);
  186.                         } else if ($update_version == 2) {
  187.                                 // In this version, the client will call the web-update file.
  188.                                 // This has the advantage that it will also work if the system is htpasswd protected
  189.                                 return array("status" => 0, "update_file" => $tmp_filename, "rev" => $next_version);
  190.                         } else if ($update_version == 3) {
  191.                                 // Version 3:
  192.                                 // - All changescripts are downloaded at once and then processed purely in JS (reduces risk of bricking if an intermediate version is broken)
  193.                                 // - We return the next version(s) in the list of changescripts
  194.                                 // - Versions are not SVN revisions anymore, but version strings
  195.                                 return array("status" => 0, "update_files" => $downloaded_changescripts);
  196.                         } else {
  197.                                 throw new OIDplusException(_L("Unexpected update version"));
  198.                         }
  199.                 }
  200.                 else {
  201.                         throw new OIDplusException(_L('Multiple version files/directories (.git and .svn) are existing! Therefore, the distribution channel is ambiguous!'));
  202.                 }
  203.         }
  204.  
  205.         /**
  206.          * @param string $actionID
  207.          * @param array $params
  208.          * @return array
  209.          * @throws OIDplusException
  210.          */
  211.         public function action(string $actionID, array $params): array {
  212.                 if ($actionID == 'update_now') {
  213.                         return $this->action_Update($params);
  214.                 } else {
  215.                         return parent::action($actionID, $params);
  216.                 }
  217.         }
  218.  
  219.         /**
  220.          * @param string $id
  221.          * @param array $out
  222.          * @param bool $handled
  223.          * @return void
  224.          * @throws OIDplusException
  225.          */
  226.         public function gui(string $id, array &$out, bool &$handled) {
  227.                 if ($id == 'oidplus:software_update') {
  228.                         @set_time_limit(0);
  229.  
  230.                         $handled = true;
  231.                         $out['title'] = _L('Software update');
  232.                         $out['icon']  = OIDplus::webpath(__DIR__,OIDplus::PATH_RELATIVE).'img/main_icon.png';
  233.  
  234.                         if (!OIDplus::authUtils()->isAdminLoggedIn()) {
  235.                                 throw new OIDplusHtmlException(_L('You need to <a %1>log in</a> as administrator.',OIDplus::gui()->link('oidplus:login$admin')), $out['title'], 401);
  236.                         }
  237.  
  238.                         $out['text'] .= '<div id="update_versioninfo">';
  239.  
  240.                         $out['text'] .= '<p><u>'._L('There are three possibilities how to keep OIDplus up-to-date').':</u></p>';
  241.  
  242.                         if (isset(OIDplus::getEditionInfo()['svnrepo']) && (OIDplus::getEditionInfo()['svnrepo'] != '')) {
  243.                                 $out['text'] .= '<p><b>'._L('Method A').'</b>: '._L('Install OIDplus using the subversion tool in your SSH/Linux shell using the command <code>svn co %1</code> and update it regularly with the command <code>svn update</code> . This will automatically download the latest version and check for conflicts.',htmlentities(OIDplus::getEditionInfo()['svnrepo']).'/trunk/');
  244.                                 if (!str_starts_with(PHP_OS, 'WIN')) {
  245.                                         $out['text'] .= ' '._L('Make sure that you invoke the <code>%1</code> command as the user who runs PHP or that you <code>%1</code> the files after invoking <code>%2</code>','chown -R ...','svn update');
  246.                                 }
  247.                                 $out['text'] .= '</p>';
  248.                         } else {
  249.                                 $out['text'] .= '<p><b>'._L('Method A').'</b>: '._L('Distribution via %1 is not possible with this edition of OIDplus','GIT').'</p>';
  250.                         }
  251.  
  252.                         if (isset(OIDplus::getEditionInfo()['gitrepo']) && (OIDplus::getEditionInfo()['gitrepo'] != '')) {
  253.                                 $out['text'] .= '<p><b>'._L('Method B').'</b>: '._L('Install OIDplus using the Git client in your SSH/Linux shell using the command <code>git clone %1</code> and update it regularly with the command <code>git pull</code> . This will automatically download the latest version and check for conflicts.',htmlentities(OIDplus::getEditionInfo()['gitrepo'].'.git'));
  254.                                 if (!str_starts_with(PHP_OS, 'WIN')) {
  255.                                         $out['text'] .= ' '._L('Make sure that you invoke the <code>%1</code> command as the user who runs PHP or that you <code>%1</code> the files after invoking <code>%2</code>','chown -R ...','git pull');
  256.                                 }
  257.                                 $out['text'] .= '</p>';
  258.                         } else {
  259.                                 $out['text'] .= '<p><b>'._L('Method B').'</b>: '._L('Distribution via %1 is not possible with this edition of OIDplus','SVN').'</p>';
  260.                         }
  261.  
  262.                         if (isset(OIDplus::getEditionInfo()['downloadpage']) && (OIDplus::getEditionInfo()['downloadpage'] != '')) {
  263.                                 $out['text'] .= '<p><b>'._L('Method C').'</b>: '._L('Install OIDplus by downloading an archive file from %1, which contains the latest development version, and extract it to your webspace. This update-tool will then update the files using change-scripts from the remote update server. It is required that the files on your webspace have create/write/delete permissions.','<a href="'.OIDplus::getEditionInfo()['downloadpage'].'">'.parse_url(OIDplus::getEditionInfo()['downloadpage'])['host'].'</a>').'</p>';
  264.                         } else {
  265.                                 $out['text'] .= '<p><b>'._L('Method C').'</b>: '._L('Distribution via %1 is not possible with this edition of OIDplus','Snapshot').'</p>';
  266.                         }
  267.  
  268.  
  269.                         $out['text'] .= '<hr>';
  270.  
  271.                         $installType = OIDplus::getInstallType();
  272.  
  273.                         if ($installType === 'ambigous') {
  274.                                 $out['text'] .= '<font color="red">'.mb_strtoupper(_L('Error')).': '._L('Multiple version files/directories (.git and .svn) are existing! Therefore, the distribution channel is ambiguous!').'</font>';
  275.                                 $out['text'] .= '</div>';
  276.                         } else if ($installType === 'unknown') {
  277.                                 $out['text'] .= '<font color="red">'.mb_strtoupper(_L('Error')).': '._L('The version cannot be determined, and the update needs to be applied manually!').'</font>';
  278.                                 $out['text'] .= '</div>';
  279.                         } else if (($installType === 'svn-wc') || ($installType === 'git-wc') || ($installType === 'manual')) {
  280.                                 if ($installType === 'svn-wc') {
  281.                                         $out['text'] .= '<p>'._L('You are using <b>method A</b> (SVN working copy).').'</p>';
  282.                                         $requireInfo = _L('shell access with svn/svnversion tool, or PDO/SQLite3 PHP extension');
  283.                                         $updateCommand = $this->getSvnCommand();
  284.                                 } else if ($installType === 'git-wc') {
  285.                                         $out['text'] .= '<p>'._L('You are using <b>method B</b> (Git working copy).').'</p>';
  286.                                         $requireInfo = _L('shell access with Git client');
  287.                                         $updateCommand = $this->getGitCommand();
  288.                                 } else if ($installType === 'manual') {
  289.                                         $out['text'] .= '<p>'._L('You are using <b>method C</b> (Snapshot file).').'</p>';
  290.                                         $requireInfo = ''; // unused
  291.                                         $updateCommand = ''; // unused
  292.                                 } else {
  293.                                         assert(false);
  294.                                 }
  295.  
  296.                                 $local_installation = OIDplus::getVersion();
  297.                                 $newest_version = $this->getLatestRevision(false);
  298.  
  299.                                 $out['text'] .= _L('Local installation: %1',($local_installation ?: _L('unknown'))).'<br>';
  300.                                 $out['text'] .= _L('Latest published version: %1',($newest_version ?: _L('unknown'))).'<br><br>';
  301.  
  302.                                 if (!$newest_version) {
  303.                                         if (!url_get_contents_available(true, $reason)) {
  304.                                                 $out['text'] .= '<p><font color="red">'._L('OIDplus could not determine the latest version.').'<br>'.$reason.'</p>';
  305.                                         } else {
  306.                                                 $out['text'] .= '<p><font color="red">'._L('OIDplus could not determine the latest version.').'<br>'._L('Probably the remote server could not be reached.').'</font></p>';
  307.                                         }
  308.                                         $out['text'] .= '</div>';
  309.                                 } else if (!$local_installation) {
  310.                                         if ($installType === 'manual') {
  311.                                                 $out['text'] .= '<p><font color="red">'._L('OIDplus could not determine its version.').'</font></p>';
  312.                                         } else {
  313.                                                 $out['text'] .= '<p><font color="red">'._L('OIDplus could not determine its version. (Required: %1). Please update your system manually via the "%2" command regularly.',$requireInfo,$updateCommand).'</font></p>';
  314.                                         }
  315.                                         $out['text'] .= '</div>';
  316.                                 } else if (version_compare($local_installation, $newest_version) >= 0) {
  317.                                         $out['text'] .= '<p><font color="green">'._L('You are already using the latest version of OIDplus.').'</font></p>';
  318.                                         $out['text'] .= '</div>';
  319.                                 } else {
  320.                                         if (($installType === 'svn-wc') || ($installType === 'git-wc')) {
  321.                                                 if ($installType === 'svn-wc') {
  322.                                                         $shell_diff_cmd = 'svn stat';
  323.                                                 } else if ($installType === 'git-wc') {
  324.                                                         $shell_diff_cmd = 'git status -s';
  325.                                                 } else {
  326.                                                         $shell_diff_cmd = '';
  327.                                                 }
  328.  
  329.                                                 $can_access_shell = true;
  330.                                                 if ($shell_diff_cmd) {
  331.                                                         $cout = [];
  332.                                                         exec("svn stat", $cout, $ec);
  333.                                                         if ($ec === 0) {
  334.                                                                 // TODO: should this also be shown when there is no update available?
  335.                                                                 if (trim(implode('',$cout)) !== '') {
  336.                                                                         $out['text'] .= '<p><font color="red">'._L('WARNING: There are changes in your working copy which WILL be reverted if you continue!').'</font></p>';
  337.                                                                         $out['text'] .= '<p><font color="red">'._L('Detected changes:').'</font></p>';
  338.                                                                         $out['text'] .= '<p><font color="red"><pre>'.htmlentities(implode("\n",$cout)).'</pre></font></p>';
  339.                                                                 } else {
  340.                                                                         $out['text'] .= '<p><font color="green">'._L('Working copy is clean.').'</font></p>';
  341.                                                                 }
  342.                                                         } else {
  343.                                                                 $can_access_shell = false;
  344.                                                         }
  345.                                                 }
  346.  
  347.                                                 $out['text'] .= '<p><font color="blue">'._L('Please enter %1 into the SSH shell to update OIDplus to the latest version.','<code>'.$updateCommand.'</code>').'</font></p>';
  348.                                                 if ($can_access_shell) {
  349.                                                         $out['text'] .= '<p>'._L('Alternatively, click this button to execute the command through the web-interface (command execution and write permissions required).').'</p>';
  350.                                                 }
  351.                                         }
  352.  
  353.                                         $next_version = $this->getNextVersionFrom($local_installation,false);
  354.                                         if ($next_version) {
  355.                                                 $out['text'] .= '<p><input type="button" onclick="OIDplusPageAdminSoftwareUpdate.doUpdateOIDplus('.js_escape($next_version).', '.js_escape($newest_version).')" value="'._L('Update NOW').'"></p>';
  356.                                         } else {
  357.                                                 $out['text'] .= '<p><font color="red">'._L('Could not determine next version. Please try again later.').'</font></p>';
  358.                                         }
  359.  
  360.                                         // TODO: Open "system_file_check" without page reload.
  361.                                         // TODO: Only show link if the plugin is installed
  362.                                         $out['text'] .= '<p><font color="red">'.mb_strtoupper(_L('Warning')).': '._L('Please make a backup of your files before updating. In case of an error, the OIDplus system (including this update-assistant) might become unavailable. Also, since the web-update does not contain collision-detection, changes you have applied (like adding, removing or modified files) might get reverted/lost! (<a href="%1">Click here to check which files have been modified</a>) In case the update fails, you can download and extract the complete <a href="%s">archive file</a> again. Since all your data should lay inside the folder "userdata" and "userdata_pub", this should be safe.','?goto='.urlencode('oidplus:system_file_check'),OIDplus::getEditionInfo()['downloadpage']).'</font></p>';
  363.  
  364.                                         $out['text'] .= '</div>';
  365.  
  366.                                         $out['text'] .= $this->showPreview($local_installation, $newest_version);
  367.                                 }
  368.                         }
  369.                 } else {
  370.                         $handled = false;
  371.                 }
  372.         }
  373.  
  374.         /**
  375.          * @param array $json
  376.          * @param string|null $ra_email
  377.          * @param bool $nonjs
  378.          * @param string $req_goto
  379.          * @return bool
  380.          * @throws OIDplusException
  381.          */
  382.         public function tree(array &$json, string $ra_email=null, bool $nonjs=false, string $req_goto=''): bool {
  383.                 if (!OIDplus::authUtils()->isAdminLoggedIn()) return false;
  384.  
  385.                 if (file_exists(__DIR__.'/img/main_icon16.png')) {
  386.                         $tree_icon = OIDplus::webpath(__DIR__,OIDplus::PATH_RELATIVE).'img/main_icon16.png';
  387.                 } else {
  388.                         $tree_icon = null; // default icon (folder)
  389.                 }
  390.  
  391.                 $json[] = array(
  392.                         'id' => 'oidplus:software_update',
  393.                         'icon' => $tree_icon,
  394.                         'text' => _L('Software update')
  395.                 );
  396.  
  397.                 return true;
  398.         }
  399.  
  400.         /**
  401.          * @param string $request
  402.          * @return array|false
  403.          */
  404.         public function tree_search(string $request) {
  405.                 return false;
  406.         }
  407.  
  408.  
  409.         /*
  410.          * @return array|false
  411.          */
  412.         private function changeLogJson() {
  413.                 static $cache = null;
  414.                 if (!is_null($cache)) return $cache;
  415.  
  416.                 $cache_file = OIDplus::localpath() . 'userdata/cache/master_changelog.json';
  417.                 if ((file_exists($cache_file)) && (time()-filemtime($cache_file) <= 10*60/*10 Minutes*/)) {
  418.                         $changelog = file_get_contents($cache_file);
  419.                 } else {
  420.                         $master_changelog = OIDplus::getEditionInfo()['master_changelog'];
  421.                         if ((stripos($master_changelog,'http://')===0) || (stripos($master_changelog,'https://')===0)) {
  422.                                 $changelog = @url_get_contents($master_changelog);
  423.                         } else {
  424.                                 $changelog = @file_get_contents($master_changelog);
  425.                         }
  426.                         if (!$changelog) return false;
  427.                         file_put_contents($cache_file, $changelog);
  428.                 }
  429.  
  430.                 $json = @json_decode($changelog, true);
  431.                 if (!$json) return false;
  432.  
  433.                 $cache = $json;
  434.                 return $json;
  435.         }
  436.  
  437.         /**
  438.          * @param string $local_ver
  439.          * @return false|string
  440.          */
  441.         private function showChangelog(string $local_ver) {
  442.                 try {
  443.                         $json = $this->changeLogJson();
  444.                         if (!$json) return false;
  445.  
  446.                         $content = '';
  447.  
  448.                         foreach ($json as $data) {
  449.                                 if (!isset($data['version'])) continue;
  450.                                 if (version_compare($data['version'], $local_ver) <= 0) continue;
  451.  
  452.                                 $data['msg'] = implode("\n", $data['changes']);
  453.                                 $comment = empty($data['msg']) ? _L('No comment') : $data['msg'];
  454.                                 $tex = _L("Version %1",$data['version'])." (".$data['date'].") ";
  455.                                 $tex = str_pad($tex, 48, ' ', STR_PAD_RIGHT);
  456.                                 $content .= trim($tex . str_replace("\n", "\n".str_repeat(' ', strlen($tex)), $comment));
  457.                                 $content .= "\n";
  458.  
  459.  
  460.                         }
  461.  
  462.                         return $content;
  463.                 } catch (\Exception $e) {
  464.                         return false;
  465.                 }
  466.         }
  467.  
  468.         /**
  469.          * @param bool $allow_dev_version
  470.          * @return false|string
  471.          */
  472.         private function getLatestRevision(bool $allow_dev_version=true) {
  473.                 try {
  474.                         $master_changelog = OIDplus::getEditionInfo()['master_changelog'];
  475.                         return OIDplus::getVersion($master_changelog, $allow_dev_version);
  476.                 } catch (\Exception $e) {
  477.                         return false;
  478.                 }
  479.         }
  480.  
  481.         /**
  482.          * @param string $prev_version
  483.          * @param bool $allow_dev_version
  484.          * @return false|string
  485.          */
  486.         private function getNextVersionFrom(string $prev_version, bool $allow_dev_version=true) {
  487.                 $json = $this->changeLogJson();
  488.                 if (!$json) return false;
  489.                 $next_version = false;
  490.                 foreach ($json as $v) {
  491.                         if (!isset($v['version'])) continue;
  492.                         if (!$allow_dev_version && str_ends_with($v['version'],'-dev')) continue;
  493.                         if ($v['version'] == $prev_version) {
  494.                                 break;
  495.                         }
  496.                         $next_version = $v['version']; // the order of $json is critical: the version in front of our current version is the next available version
  497.                 }
  498.                 return $next_version;
  499.         }
  500.  
  501.         /**
  502.          * @param string $local_installation
  503.          * @param string $newest_version
  504.          * @return string
  505.          */
  506.         private function showPreview(string $local_installation, string $newest_version): string {
  507.                 $out = '<h2 id="update_header">'._L('Preview of update %1 &rarr; %2',$local_installation,$newest_version).'</h2>';
  508.  
  509.                 ob_start();
  510.                 try {
  511.                         $cont = $this->showChangelog($local_installation);
  512.                 } catch (\Exception $e) {
  513.                         $htmlmsg = $e instanceof OIDplusException ? $e->getHtmlMessage() : htmlentities($e->getMessage());
  514.                         $cont = _L('Error: %1',$htmlmsg);
  515.                 }
  516.                 ob_end_clean();
  517.  
  518.                 $cont = preg_replace('@!!!(.+)\\n@', '<font color="red">!!!\\1</font>'."\n", "$cont\n");
  519.                 $cont = preg_replace('@\\*\\*\\*(.+)\\n@', '<strong>!!!\\1</strong>'."\n", "$cont\n");
  520.  
  521.                 $out .= '<pre id="update_infobox">'.$cont.'</pre>';
  522.  
  523.                 return $out;
  524.         }
  525.  
  526.         /**
  527.          * Implements interface INTF_OID_1_3_6_1_4_1_37476_2_5_2_3_8
  528.          * @param string|null $user
  529.          * @return array
  530.          * @throws OIDplusException
  531.          */
  532.         public function getNotifications(string $user=null): array {
  533.                 $notifications = array();
  534.                 if ((!$user || ($user == 'admin')) && OIDplus::authUtils()->isAdminLoggedIn()) {
  535.  
  536.                         // Following code is based on the VNag plugin (admin 901) code
  537.  
  538.                         $installType = OIDplus::getInstallType();
  539.  
  540.                         if ($installType === 'ambigous') {
  541.                                 $out_stat = 'WARN';
  542.                                 $out_msg  = _L('Multiple version files/directories (.git and .svn) are existing! Therefore, the distribution channel is ambiguous!');
  543.                         } else if ($installType === 'unknown') {
  544.                                 $out_stat = 'WARN';
  545.                                 $out_msg  = _L('The version cannot be determined, and the update needs to be applied manually!');
  546.                         } else if (($installType === 'svn-wc') || ($installType === 'git-wc')) {
  547.                                 if (!url_get_contents_available(true, $reason)) {
  548.                                         $out_stat = 'WARN';
  549.                                         $out_msg  = _L('OIDplus could not determine the latest version.').' '.$reason;
  550.                                 } else {
  551.                                         $local_installation = OIDplus::getVersion();
  552.                                         $newest_version = $this->getLatestRevision(false);
  553.  
  554.                                         $requireInfo = ($installType === 'svn-wc') ? _L('shell access with svn/svnversion tool, or PDO/SQLite3 PHP extension') : _L('shell access with Git client');
  555.                                         $updateCommand = ($installType === 'svn-wc') ? 'svn update' : 'git pull';
  556.  
  557.                                         if (!$newest_version) {
  558.                                                 $out_stat = 'WARN';
  559.                                                 $out_msg = _L('OIDplus could not determine the latest version.') . ' ' . _L('Probably the remote server could not be reached.');
  560.                                         } else if (!$local_installation) {
  561.                                                 $out_stat = 'WARN';
  562.                                                 $out_msg = _L('OIDplus could not determine its version (Required: %1). Please update your system manually via the "%2" command regularly.', $requireInfo, $updateCommand);
  563.                                         } else if (version_compare($local_installation, $newest_version) >= 0) {
  564.                                                 $out_stat = 'INFO';
  565.                                                 $out_msg = _L('You are using the latest version of OIDplus (%1 local / %2 remote)', $local_installation, $newest_version);
  566.                                         } else {
  567.                                                 $out_stat = 'WARN';
  568.                                                 $out_msg = _L('OIDplus is outdated. (%1 local / %2 remote)', $local_installation, $newest_version);
  569.                                         }
  570.                                 }
  571.                         } else if ($installType === 'manual') {
  572.                                 if (!url_get_contents_available(true, $reason)) {
  573.                                         $out_stat = 'WARN';
  574.                                         $out_msg  = _L('OIDplus could not determine the latest version.').' '.$reason;
  575.                                 } else {
  576.                                         $local_installation = OIDplus::getVersion();
  577.                                         $newest_version = $this->getLatestRevision(false);
  578.  
  579.                                         if (!$newest_version) {
  580.                                                 $out_stat = 'WARN';
  581.                                                 $out_msg = _L('OIDplus could not determine the latest version.') . ' ' . _L('Probably the remote server could not be reached.');
  582.                                         } else if (!$local_installation) {
  583.                                                 $out_stat = 'WARN';
  584.                                                 $out_msg = _L('OIDplus could not determine its version. Please update your system manually by downloading the latest archive file from oidplus.com.');
  585.                                         } else if (version_compare($local_installation, $newest_version) >= 0) {
  586.                                                 $out_stat = 'INFO';
  587.                                                 $out_msg = _L('You are using the latest version of OIDplus (%1 local / %2 remote)', $local_installation, $newest_version);
  588.                                         } else {
  589.                                                 $out_stat = 'WARN';
  590.                                                 $out_msg = _L('OIDplus is outdated. (%1 local / %2 remote)', $local_installation, $newest_version);
  591.                                         }
  592.                                 }
  593.                         } else {
  594.                                 assert(false);
  595.                                 return $notifications;
  596.                         }
  597.  
  598.                         if ($out_stat != 'INFO') {
  599.                                 $out_msg = '<a '.OIDplus::gui()->link('oidplus:software_update').'>'._L('Software update').'</a>: ' . $out_msg;
  600.  
  601.                                 $notifications[] = new OIDplusNotification($out_stat, $out_msg);
  602.                         }
  603.  
  604.                 }
  605.                 return $notifications;
  606.         }
  607.  
  608. }
  609.