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