[ Index ]

PHP Cross Reference of DokuWiki

title

Body

[close]

/inc/ -> infoutils.php (source)

   1  <?php
   2  /**
   3   * Information and debugging functions
   4   *
   5   * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
   6   * @author     Andreas Gohr <andi@splitbrain.org>
   7   */
   8  
   9  use dokuwiki\HTTP\DokuHTTPClient;
  10  use dokuwiki\Logger;
  11  
  12  if(!defined('DOKU_MESSAGEURL')){
  13      if(in_array('ssl', stream_get_transports())) {
  14          define('DOKU_MESSAGEURL','https://update.dokuwiki.org/check/');
  15      }else{
  16          define('DOKU_MESSAGEURL','http://update.dokuwiki.org/check/');
  17      }
  18  }
  19  
  20  /**
  21   * Check for new messages from upstream
  22   *
  23   * @author Andreas Gohr <andi@splitbrain.org>
  24   */
  25  function checkUpdateMessages(){
  26      global $conf;
  27      global $INFO;
  28      global $updateVersion;
  29      if(!$conf['updatecheck']) return;
  30      if($conf['useacl'] && !$INFO['ismanager']) return;
  31  
  32      $cf = getCacheName($updateVersion, '.updmsg');
  33      $lm = @filemtime($cf);
  34      $is_http = substr(DOKU_MESSAGEURL, 0, 5) != 'https';
  35  
  36      // check if new messages needs to be fetched
  37      if($lm < time()-(60*60*24) || $lm < @filemtime(DOKU_INC.DOKU_SCRIPT)){
  38          @touch($cf);
  39          Logger::debug("checkUpdateMessages(): downloading messages to ".$cf.($is_http?' (without SSL)':' (with SSL)'));
  40          $http = new DokuHTTPClient();
  41          $http->timeout = 12;
  42          $resp = $http->get(DOKU_MESSAGEURL.$updateVersion);
  43          if(is_string($resp) && ($resp == "" || substr(trim($resp), -1) == '%')) {
  44              // basic sanity check that this is either an empty string response (ie "no messages")
  45              // or it looks like one of our messages, not WiFi login or other interposed response
  46              io_saveFile($cf,$resp);
  47          } else {
  48              Logger::debug("checkUpdateMessages(): unexpected HTTP response received", $http->error);
  49          }
  50      }else{
  51          Logger::debug("checkUpdateMessages(): messages up to date");
  52      }
  53  
  54      $data = io_readFile($cf);
  55      // show messages through the usual message mechanism
  56      $msgs = explode("\n%\n",$data);
  57      foreach($msgs as $msg){
  58          if($msg) msg($msg,2);
  59      }
  60  }
  61  
  62  
  63  /**
  64   * Return DokuWiki's version (split up in date and type)
  65   *
  66   * @author Andreas Gohr <andi@splitbrain.org>
  67   */
  68  function getVersionData(){
  69      $version = array();
  70      //import version string
  71      if(file_exists(DOKU_INC.'VERSION')){
  72          //official release
  73          $version['date'] = trim(io_readFile(DOKU_INC.'VERSION'));
  74          $version['type'] = 'Release';
  75      }elseif(is_dir(DOKU_INC.'.git')){
  76          $version['type'] = 'Git';
  77          $version['date'] = 'unknown';
  78  
  79          // First try to get date and commit hash by calling Git
  80          if (function_exists('shell_exec')) {
  81              $commitInfo = shell_exec("git log -1 --pretty=format:'%h %cd' --date=short");
  82              if ($commitInfo) {
  83                  list($version['sha'], $date) = explode(' ', $commitInfo);
  84                  $version['date'] = hsc($date);
  85                  return $version;
  86              }
  87          }
  88  
  89          // we cannot use git on the shell -- let's do it manually!
  90          if (file_exists(DOKU_INC . '.git/HEAD')) {
  91              $headCommit = trim(file_get_contents(DOKU_INC . '.git/HEAD'));
  92              if (strpos($headCommit, 'ref: ') === 0) {
  93                  // it is something like `ref: refs/heads/master`
  94                  $headCommit = substr($headCommit, 5);
  95                  $pathToHead = DOKU_INC . '.git/' . $headCommit;
  96                  if (file_exists($pathToHead)) {
  97                      $headCommit = trim(file_get_contents($pathToHead));
  98                  } else {
  99                      $packedRefs = file_get_contents(DOKU_INC . '.git/packed-refs');
 100                      if (!preg_match("~([[:xdigit:]]+) $headCommit~", $packedRefs, $matches)) {
 101                          # ref not found in pack file
 102                          return $version;
 103                      }
 104                      $headCommit = $matches[1];
 105                  }
 106              }
 107              // At this point $headCommit is a SHA
 108              $version['sha'] = $headCommit;
 109  
 110              // Get commit date from Git object
 111              $subDir = substr($headCommit, 0, 2);
 112              $fileName = substr($headCommit, 2);
 113              $gitCommitObject = DOKU_INC . ".git/objects/$subDir/$fileName";
 114              if (file_exists($gitCommitObject) && function_exists('zlib_decode')) {
 115                  $commit = zlib_decode(file_get_contents($gitCommitObject));
 116                  $committerLine = explode("\n", $commit)[3];
 117                  $committerData = explode(' ', $committerLine);
 118                  end($committerData);
 119                  $ts = prev($committerData);
 120                  if ($ts && $date = date('Y-m-d', $ts)) {
 121                      $version['date'] = $date;
 122                  }
 123              }
 124          }
 125      }else{
 126          global $updateVersion;
 127          $version['date'] = 'update version '.$updateVersion;
 128          $version['type'] = 'snapshot?';
 129      }
 130      return $version;
 131  }
 132  
 133  /**
 134   * Return DokuWiki's version (as a string)
 135   *
 136   * @author Anika Henke <anika@selfthinker.org>
 137   */
 138  function getVersion(){
 139      $version = getVersionData();
 140      $sha = !empty($version['sha']) ? ' (' . $version['sha'] . ')' : '';
 141      return $version['type'] . ' ' . $version['date'] . $sha;
 142  }
 143  
 144  /**
 145   * Run a few sanity checks
 146   *
 147   * @author Andreas Gohr <andi@splitbrain.org>
 148   */
 149  function check(){
 150      global $conf;
 151      global $INFO;
 152      /* @var Input $INPUT */
 153      global $INPUT;
 154  
 155      if ($INFO['isadmin'] || $INFO['ismanager']){
 156          msg('DokuWiki version: '.getVersion(),1);
 157  
 158          if(version_compare(phpversion(),'7.2.0','<')){
 159              msg('Your PHP version is too old ('.phpversion().' vs. 7.2+ needed)',-1);
 160          }else{
 161              msg('PHP version '.phpversion(),1);
 162          }
 163      } else {
 164          if(version_compare(phpversion(),'7.2.0','<')){
 165              msg('Your PHP version is too old',-1);
 166          }
 167      }
 168  
 169      $mem = (int) php_to_byte(ini_get('memory_limit'));
 170      if($mem){
 171          if ($mem === -1) {
 172              msg('PHP memory is unlimited', 1);
 173          } else if ($mem < 16777216) {
 174              msg('PHP is limited to less than 16MB RAM (' . filesize_h($mem) . ').
 175              Increase memory_limit in php.ini', -1);
 176          } else if ($mem < 20971520) {
 177              msg('PHP is limited to less than 20MB RAM (' . filesize_h($mem) . '),
 178                  you might encounter problems with bigger pages. Increase memory_limit in php.ini', -1);
 179          } else if ($mem < 33554432) {
 180              msg('PHP is limited to less than 32MB RAM (' . filesize_h($mem) . '),
 181                  but that should be enough in most cases. If not, increase memory_limit in php.ini', 0);
 182          } else {
 183              msg('More than 32MB RAM (' . filesize_h($mem) . ') available.', 1);
 184          }
 185      }
 186  
 187      if(is_writable($conf['changelog'])){
 188          msg('Changelog is writable',1);
 189      }else{
 190          if (file_exists($conf['changelog'])) {
 191              msg('Changelog is not writable',-1);
 192          }
 193      }
 194  
 195      if (isset($conf['changelog_old']) && file_exists($conf['changelog_old'])) {
 196          msg('Old changelog exists', 0);
 197      }
 198  
 199      if (file_exists($conf['changelog'].'_failed')) {
 200          msg('Importing old changelog failed', -1);
 201      } else if (file_exists($conf['changelog'].'_importing')) {
 202          msg('Importing old changelog now.', 0);
 203      } else if (file_exists($conf['changelog'].'_import_ok')) {
 204          msg('Old changelog imported', 1);
 205          if (!plugin_isdisabled('importoldchangelog')) {
 206              msg('Importoldchangelog plugin not disabled after import', -1);
 207          }
 208      }
 209  
 210      if(is_writable(DOKU_CONF)){
 211          msg('conf directory is writable',1);
 212      }else{
 213          msg('conf directory is not writable',-1);
 214      }
 215  
 216      if($conf['authtype'] == 'plain'){
 217          global $config_cascade;
 218          if(is_writable($config_cascade['plainauth.users']['default'])){
 219              msg('conf/users.auth.php is writable',1);
 220          }else{
 221              msg('conf/users.auth.php is not writable',0);
 222          }
 223      }
 224  
 225      if(function_exists('mb_strpos')){
 226          if(defined('UTF8_NOMBSTRING')){
 227              msg('mb_string extension is available but will not be used',0);
 228          }else{
 229              msg('mb_string extension is available and will be used',1);
 230              if(ini_get('mbstring.func_overload') != 0){
 231                  msg('mb_string function overloading is enabled, this will cause problems and should be disabled',-1);
 232              }
 233          }
 234      }else{
 235          msg('mb_string extension not available - PHP only replacements will be used',0);
 236      }
 237  
 238      if (!UTF8_PREGSUPPORT) {
 239          msg('PHP is missing UTF-8 support in Perl-Compatible Regular Expressions (PCRE)', -1);
 240      }
 241      if (!UTF8_PROPERTYSUPPORT) {
 242          msg('PHP is missing Unicode properties support in Perl-Compatible Regular Expressions (PCRE)', -1);
 243      }
 244  
 245      $loc = setlocale(LC_ALL, 0);
 246      if(!$loc){
 247          msg('No valid locale is set for your PHP setup. You should fix this',-1);
 248      }elseif(stripos($loc,'utf') === false){
 249          msg('Your locale <code>'.hsc($loc).'</code> seems not to be a UTF-8 locale,
 250               you should fix this if you encounter problems.',0);
 251      }else{
 252          msg('Valid locale '.hsc($loc).' found.', 1);
 253      }
 254  
 255      if($conf['allowdebug']){
 256          msg('Debugging support is enabled. If you don\'t need it you should set $conf[\'allowdebug\'] = 0',-1);
 257      }else{
 258          msg('Debugging support is disabled',1);
 259      }
 260  
 261      if($INFO['userinfo']['name']){
 262          msg('You are currently logged in as '.$INPUT->server->str('REMOTE_USER').' ('.$INFO['userinfo']['name'].')',0);
 263          msg('You are part of the groups '.implode(', ', $INFO['userinfo']['grps']),0);
 264      }else{
 265          msg('You are currently not logged in',0);
 266      }
 267  
 268      msg('Your current permission for this page is '.$INFO['perm'],0);
 269  
 270      if (file_exists($INFO['filepath']) && is_writable($INFO['filepath'])) {
 271          msg('The current page is writable by the webserver', 1);
 272      } elseif (!file_exists($INFO['filepath']) && is_writable(dirname($INFO['filepath']))) {
 273          msg('The current page can be created by the webserver', 1);
 274      } else {
 275          msg('The current page is not writable by the webserver', -1);
 276      }
 277  
 278      if ($INFO['writable']) {
 279          msg('The current page is writable by you', 1);
 280      } else {
 281          msg('The current page is not writable by you', -1);
 282      }
 283  
 284      // Check for corrupted search index
 285      $lengths = idx_listIndexLengths();
 286      $index_corrupted = false;
 287      foreach ($lengths as $length) {
 288          if (count(idx_getIndex('w', $length)) != count(idx_getIndex('i', $length))) {
 289              $index_corrupted = true;
 290              break;
 291          }
 292      }
 293  
 294      foreach (idx_getIndex('metadata', '') as $index) {
 295          if (count(idx_getIndex($index.'_w', '')) != count(idx_getIndex($index.'_i', ''))) {
 296              $index_corrupted = true;
 297              break;
 298          }
 299      }
 300  
 301      if($index_corrupted) {
 302          msg(
 303              'The search index is corrupted. It might produce wrong results and most
 304                  probably needs to be rebuilt. See
 305                  <a href="http://www.dokuwiki.org/faq:searchindex">faq:searchindex</a>
 306                  for ways to rebuild the search index.', -1
 307          );
 308      } elseif(!empty($lengths)) {
 309          msg('The search index seems to be working', 1);
 310      } else {
 311          msg(
 312              'The search index is empty. See
 313                  <a href="http://www.dokuwiki.org/faq:searchindex">faq:searchindex</a>
 314                  for help on how to fix the search index. If the default indexer
 315                  isn\'t used or the wiki is actually empty this is normal.'
 316          );
 317      }
 318  
 319      // rough time check
 320      $http = new DokuHTTPClient();
 321      $http->max_redirect = 0;
 322      $http->timeout = 3;
 323      $http->sendRequest('http://www.dokuwiki.org', '', 'HEAD');
 324      $now = time();
 325      if(isset($http->resp_headers['date'])) {
 326          $time = strtotime($http->resp_headers['date']);
 327          $diff = $time - $now;
 328  
 329          if(abs($diff) < 4) {
 330              msg("Server time seems to be okay. Diff: {$diff}s", 1);
 331          } else {
 332              msg("Your server's clock seems to be out of sync!
 333                   Consider configuring a sync with a NTP server.  Diff: {$diff}s");
 334          }
 335      }
 336  
 337  }
 338  
 339  /**
 340   * Display a message to the user
 341   *
 342   * If HTTP headers were not sent yet the message is added
 343   * to the global message array else it's printed directly
 344   * using html_msgarea()
 345   *
 346   * Triggers INFOUTIL_MSG_SHOW
 347   *
 348   * @see    html_msgarea()
 349   * @param string $message
 350   * @param int    $lvl   -1 = error, 0 = info, 1 = success, 2 = notify
 351   * @param string $line  line number
 352   * @param string $file  file number
 353   * @param int    $allow who's allowed to see the message, see MSG_* constants
 354   */
 355  function msg($message,$lvl=0,$line='',$file='',$allow=MSG_PUBLIC){
 356      global $MSG, $MSG_shown;
 357      static $errors = [
 358          -1 => 'error',
 359          0 => 'info',
 360          1 => 'success',
 361          2 => 'notify',
 362      ];
 363  
 364      $msgdata = [
 365          'msg' => $message,
 366          'lvl' => $errors[$lvl],
 367          'allow' => $allow,
 368          'line' => $line,
 369          'file' => $file,
 370      ];
 371  
 372      $evt = new \dokuwiki\Extension\Event('INFOUTIL_MSG_SHOW', $msgdata);
 373      if ($evt->advise_before()) {
 374          /* Show msg normally - event could suppress message show */
 375          if($msgdata['line'] || $msgdata['file']) {
 376              $basename = \dokuwiki\Utf8\PhpString::basename($msgdata['file']);
 377              $msgdata['msg'] .=' ['.$basename.':'.$msgdata['line'].']';
 378          }
 379  
 380          if(!isset($MSG)) $MSG = array();
 381          $MSG[] = $msgdata;
 382          if(isset($MSG_shown) || headers_sent()){
 383              if(function_exists('html_msgarea')){
 384                  html_msgarea();
 385              }else{
 386                  print "ERROR(".$msgdata['lvl'].") ".$msgdata['msg']."\n";
 387              }
 388              unset($GLOBALS['MSG']);
 389          }
 390      }
 391      $evt->advise_after();
 392      unset($evt);
 393  }
 394  /**
 395   * Determine whether the current user is allowed to view the message
 396   * in the $msg data structure
 397   *
 398   * @param  $msg   array    dokuwiki msg structure
 399   *                         msg   => string, the message
 400   *                         lvl   => int, level of the message (see msg() function)
 401   *                         allow => int, flag used to determine who is allowed to see the message
 402   *                                       see MSG_* constants
 403   * @return bool
 404   */
 405  function info_msg_allowed($msg){
 406      global $INFO, $auth;
 407  
 408      // is the message public? - everyone and anyone can see it
 409      if (empty($msg['allow']) || ($msg['allow'] == MSG_PUBLIC)) return true;
 410  
 411      // restricted msg, but no authentication
 412      if (empty($auth)) return false;
 413  
 414      switch ($msg['allow']){
 415          case MSG_USERS_ONLY:
 416              return !empty($INFO['userinfo']);
 417  
 418          case MSG_MANAGERS_ONLY:
 419              return $INFO['ismanager'];
 420  
 421          case MSG_ADMINS_ONLY:
 422              return $INFO['isadmin'];
 423  
 424          default:
 425              trigger_error('invalid msg allow restriction.  msg="'.$msg['msg'].'" allow='.$msg['allow'].'"',
 426                            E_USER_WARNING);
 427              return $INFO['isadmin'];
 428      }
 429  
 430      return false;
 431  }
 432  
 433  /**
 434   * print debug messages
 435   *
 436   * little function to print the content of a var
 437   *
 438   * @author Andreas Gohr <andi@splitbrain.org>
 439   *
 440   * @param string $msg
 441   * @param bool $hidden
 442   */
 443  function dbg($msg,$hidden=false){
 444      if($hidden){
 445          echo "<!--\n";
 446          print_r($msg);
 447          echo "\n-->";
 448      }else{
 449          echo '<pre class="dbg">';
 450          echo hsc(print_r($msg,true));
 451          echo '</pre>';
 452      }
 453  }
 454  
 455  /**
 456   * Print info to debug log file
 457   *
 458   * @author Andreas Gohr <andi@splitbrain.org>
 459   * @deprecated 2020-08-13
 460   * @param string $msg
 461   * @param string $header
 462   */
 463  function dbglog($msg,$header=''){
 464      dbg_deprecated('\\dokuwiki\\Logger');
 465  
 466      // was the msg as single line string? use it as header
 467      if($header === '' && is_string($msg) && strpos($msg, "\n") === false) {
 468          $header = $msg;
 469          $msg = '';
 470      }
 471  
 472      Logger::getInstance(Logger::LOG_DEBUG)->log(
 473          $header, $msg
 474      );
 475  }
 476  
 477  /**
 478   * Log accesses to deprecated fucntions to the debug log
 479   *
 480   * @param string $alternative The function or method that should be used instead
 481   * @triggers INFO_DEPRECATION_LOG
 482   */
 483  function dbg_deprecated($alternative = '') {
 484      \dokuwiki\Debug\DebugHelper::dbgDeprecatedFunction($alternative, 2);
 485  }
 486  
 487  /**
 488   * Print a reversed, prettyprinted backtrace
 489   *
 490   * @author Gary Owen <gary_owen@bigfoot.com>
 491   */
 492  function dbg_backtrace(){
 493      // Get backtrace
 494      $backtrace = debug_backtrace();
 495  
 496      // Unset call to debug_print_backtrace
 497      array_shift($backtrace);
 498  
 499      // Iterate backtrace
 500      $calls = array();
 501      $depth = count($backtrace) - 1;
 502      foreach ($backtrace as $i => $call) {
 503          $location = $call['file'] . ':' . $call['line'];
 504          $function = (isset($call['class'])) ?
 505              $call['class'] . $call['type'] . $call['function'] : $call['function'];
 506  
 507          $params = array();
 508          if (isset($call['args'])){
 509              foreach($call['args'] as $arg){
 510                  if(is_object($arg)){
 511                      $params[] = '[Object '.get_class($arg).']';
 512                  }elseif(is_array($arg)){
 513                      $params[] = '[Array]';
 514                  }elseif(is_null($arg)){
 515                      $params[] = '[NULL]';
 516                  }else{
 517                      $params[] = (string) '"'.$arg.'"';
 518                  }
 519              }
 520          }
 521          $params = implode(', ',$params);
 522  
 523          $calls[$depth - $i] = sprintf('%s(%s) called at %s',
 524                  $function,
 525                  str_replace("\n", '\n', $params),
 526                  $location);
 527      }
 528      ksort($calls);
 529  
 530      return implode("\n", $calls);
 531  }
 532  
 533  /**
 534   * Remove all data from an array where the key seems to point to sensitive data
 535   *
 536   * This is used to remove passwords, mail addresses and similar data from the
 537   * debug output
 538   *
 539   * @author Andreas Gohr <andi@splitbrain.org>
 540   *
 541   * @param array $data
 542   */
 543  function debug_guard(&$data){
 544      foreach($data as $key => $value){
 545          if(preg_match('/(notify|pass|auth|secret|ftp|userinfo|token|buid|mail|proxy)/i',$key)){
 546              $data[$key] = '***';
 547              continue;
 548          }
 549          if(is_array($value)) debug_guard($data[$key]);
 550      }
 551  }