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