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('/^\s*#.*$/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'] = trim(implode(' ', [ 223 $osRelease['NAME'], 224 $osRelease['VERSION'], 225 $osRelease['SYNO_MODEL'] 226 ])); 227 } 228 return $osRelease; 229} 230 231 232/** 233 * Run a few sanity checks 234 * 235 * @author Andreas Gohr <andi@splitbrain.org> 236 */ 237function check() 238{ 239 global $conf; 240 global $INFO; 241 /* @var Input $INPUT */ 242 global $INPUT; 243 244 if ($INFO['isadmin'] || $INFO['ismanager']) { 245 msg('DokuWiki version: ' . getVersion(), 1); 246 if (version_compare(phpversion(), '8.2.0', '<')) { 247 msg('Your PHP version is too old (' . phpversion() . ' vs. 8.2+ needed)', -1); 248 } else { 249 msg('PHP version ' . phpversion(), 1); 250 } 251 } elseif (version_compare(phpversion(), '8.2.0', '<')) { 252 msg('Your PHP version is too old', -1); 253 } 254 255 $mem = php_to_byte(ini_get('memory_limit')); 256 if ($mem) { 257 if ($mem === -1) { 258 msg('PHP memory is unlimited', 1); 259 } elseif ($mem < 16_777_216) { 260 msg('PHP is limited to less than 16MB RAM (' . filesize_h($mem) . '). 261 Increase memory_limit in php.ini', -1); 262 } elseif ($mem < 20_971_520) { 263 msg('PHP is limited to less than 20MB RAM (' . filesize_h($mem) . '), 264 you might encounter problems with bigger pages. Increase memory_limit in php.ini', -1); 265 } elseif ($mem < 33_554_432) { 266 msg('PHP is limited to less than 32MB RAM (' . filesize_h($mem) . '), 267 but that should be enough in most cases. If not, increase memory_limit in php.ini', 0); 268 } else { 269 msg('More than 32MB RAM (' . filesize_h($mem) . ') available.', 1); 270 } 271 } 272 273 if (is_writable($conf['changelog'])) { 274 msg('Changelog is writable', 1); 275 } elseif (file_exists($conf['changelog'])) { 276 msg('Changelog is not writable', -1); 277 } 278 279 if (isset($conf['changelog_old']) && file_exists($conf['changelog_old'])) { 280 msg('Old changelog exists', 0); 281 } 282 283 if (file_exists($conf['changelog'] . '_failed')) { 284 msg('Importing old changelog failed', -1); 285 } elseif (file_exists($conf['changelog'] . '_importing')) { 286 msg('Importing old changelog now.', 0); 287 } elseif (file_exists($conf['changelog'] . '_import_ok')) { 288 msg('Old changelog imported', 1); 289 if (!plugin_isdisabled('importoldchangelog')) { 290 msg('Importoldchangelog plugin not disabled after import', -1); 291 } 292 } 293 294 if (is_writable(DOKU_CONF)) { 295 msg('conf directory is writable', 1); 296 } else { 297 msg('conf directory is not writable', -1); 298 } 299 300 if ($conf['authtype'] == 'plain') { 301 global $config_cascade; 302 if (is_writable($config_cascade['plainauth.users']['default'])) { 303 msg('conf/users.auth.php is writable', 1); 304 } else { 305 msg('conf/users.auth.php is not writable', 0); 306 } 307 } 308 309 if (function_exists('mb_strpos')) { 310 if (defined('UTF8_NOMBSTRING')) { 311 msg('mb_string extension is available but will not be used', 0); 312 } else { 313 msg('mb_string extension is available and will be used', 1); 314 } 315 } else { 316 msg('mb_string extension not available - PHP only replacements will be used', 0); 317 } 318 319 if (!UTF8_PREGSUPPORT) { 320 msg('PHP is missing UTF-8 support in Perl-Compatible Regular Expressions (PCRE)', -1); 321 } 322 if (!UTF8_PROPERTYSUPPORT) { 323 msg('PHP is missing Unicode properties support in Perl-Compatible Regular Expressions (PCRE)', -1); 324 } 325 326 $loc = setlocale(LC_ALL, 0); 327 if (!$loc) { 328 msg('No valid locale is set for your PHP setup. You should fix this', -1); 329 } elseif (stripos($loc, 'utf') === false) { 330 msg('Your locale <code>' . hsc($loc) . '</code> seems not to be a UTF-8 locale, 331 you should fix this if you encounter problems.', 0); 332 } else { 333 msg('Valid locale ' . hsc($loc) . ' found.', 1); 334 } 335 336 if ($conf['allowdebug']) { 337 msg('Debugging support is enabled. If you don\'t need it you should set $conf[\'allowdebug\'] = 0', -1); 338 } else { 339 msg('Debugging support is disabled', 1); 340 } 341 342 if (!empty($INFO['userinfo']['name'])) { 343 msg(sprintf( 344 "You are currently logged in as %s (%s)", 345 $INPUT->server->str('REMOTE_USER'), 346 $INFO['userinfo']['name'] 347 ), 0); 348 msg('You are part of the groups ' . implode(', ', $INFO['userinfo']['grps']), 0); 349 } else { 350 msg('You are currently not logged in', 0); 351 } 352 353 msg('Your current permission for this page is ' . $INFO['perm'], 0); 354 355 if (file_exists($INFO['filepath']) && is_writable($INFO['filepath'])) { 356 msg('The current page is writable by the webserver', 1); 357 } elseif (!file_exists($INFO['filepath']) && is_writable(dirname($INFO['filepath']))) { 358 msg('The current page can be created by the webserver', 1); 359 } else { 360 msg('The current page is not writable by the webserver', -1); 361 } 362 363 if ($INFO['writable']) { 364 msg('The current page is writable by you', 1); 365 } else { 366 msg('The current page is not writable by you', -1); 367 } 368 369 // Check for corrupted search index 370 $indexer = new Indexer(); 371 try { 372 $indexer->checkIntegrity(); 373 if (!$indexer->isIndexEmpty()) { 374 msg('The search index seems to be working', 1); 375 } else { 376 msg( 377 'The search index is empty. See 378 <a href="https://www.dokuwiki.org/faq:searchindex">faq:searchindex</a> 379 for help on how to fix the search index. If the default indexer 380 isn\'t used or the wiki is actually empty this is normal.' 381 ); 382 } 383 } catch (IndexIntegrityException) { 384 msg( 385 'The search index is corrupted. It might produce wrong results and most 386 probably needs to be rebuilt. See 387 <a href="https://www.dokuwiki.org/faq:searchindex">faq:searchindex</a> 388 for ways to rebuild the search index.', 389 -1 390 ); 391 } 392 393 // rough time check 394 $http = new DokuHTTPClient(); 395 $http->max_redirect = 0; 396 $http->timeout = 3; 397 $http->sendRequest('https://www.dokuwiki.org', '', 'HEAD'); 398 399 $now = time(); 400 if (isset($http->resp_headers['date'])) { 401 $time = strtotime($http->resp_headers['date']); 402 $diff = $time - $now; 403 404 if (abs($diff) < 4) { 405 msg("Server time seems to be okay. Diff: {$diff}s", 1); 406 } else { 407 msg("Your server's clock seems to be out of sync! 408 Consider configuring a sync with a NTP server. Diff: {$diff}s"); 409 } 410 } 411} 412 413/** 414 * Display a message to the user 415 * 416 * If HTTP headers were not sent yet the message is added 417 * to the global message array else it's printed directly 418 * using html_msgarea() 419 * 420 * Triggers INFOUTIL_MSG_SHOW 421 * 422 * @param string $message 423 * @param int $lvl -1 = error, 0 = info, 1 = success, 2 = notify 424 * @param string $line line number 425 * @param string $file file number 426 * @param int $allow who's allowed to see the message, see MSG_* constants 427 * @see html_msgarea() 428 */ 429function msg($message, $lvl = 0, $line = '', $file = '', $allow = MSG_PUBLIC) 430{ 431 global $MSG, $MSG_shown; 432 static $errors = [ 433 -1 => 'error', 434 0 => 'info', 435 1 => 'success', 436 2 => 'notify', 437 ]; 438 439 $msgdata = [ 440 'msg' => $message, 441 'lvl' => $errors[$lvl], 442 'allow' => $allow, 443 'line' => $line, 444 'file' => $file, 445 ]; 446 447 $evt = new Event('INFOUTIL_MSG_SHOW', $msgdata); 448 if ($evt->advise_before()) { 449 /* Show msg normally - event could suppress message show */ 450 if ($msgdata['line'] || $msgdata['file']) { 451 $basename = PhpString::basename($msgdata['file']); 452 $msgdata['msg'] .= ' [' . $basename . ':' . $msgdata['line'] . ']'; 453 } 454 455 if (!isset($MSG)) $MSG = []; 456 $MSG[] = $msgdata; 457 if (isset($MSG_shown) || headers_sent()) { 458 if (function_exists('html_msgarea')) { 459 html_msgarea(); 460 } else { 461 echo "ERROR(" . $msgdata['lvl'] . ") " . $msgdata['msg'] . "\n"; 462 } 463 unset($GLOBALS['MSG']); 464 } 465 } 466 $evt->advise_after(); 467 unset($evt); 468} 469 470/** 471 * Determine whether the current user is allowed to view the message 472 * in the $msg data structure 473 * 474 * @param array $msg dokuwiki msg structure: 475 * msg => string, the message; 476 * lvl => int, level of the message (see msg() function); 477 * allow => int, flag used to determine who is allowed to see the message, see MSG_* constants 478 * @return bool 479 */ 480function info_msg_allowed($msg) 481{ 482 global $INFO, $auth; 483 484 // is the message public? - everyone and anyone can see it 485 if (empty($msg['allow']) || ($msg['allow'] == MSG_PUBLIC)) return true; 486 487 // restricted msg, but no authentication 488 if (!$auth instanceof AuthPlugin) return false; 489 490 switch ($msg['allow']) { 491 case MSG_USERS_ONLY: 492 return !empty($INFO['userinfo']); 493 494 case MSG_MANAGERS_ONLY: 495 return $INFO['ismanager']; 496 497 case MSG_ADMINS_ONLY: 498 return $INFO['isadmin']; 499 500 default: 501 trigger_error( 502 'invalid msg allow restriction. msg="' . $msg['msg'] . '" allow=' . $msg['allow'] . '"', 503 E_USER_WARNING 504 ); 505 return $INFO['isadmin']; 506 } 507} 508 509/** 510 * print debug messages 511 * 512 * little function to print the content of a var 513 * 514 * @param string $msg 515 * @param bool $hidden 516 * 517 * @author Andreas Gohr <andi@splitbrain.org> 518 */ 519function dbg($msg, $hidden = false) 520{ 521 if ($hidden) { 522 echo "<!--\n"; 523 print_r($msg); 524 echo "\n-->"; 525 } else { 526 echo '<pre class="dbg">'; 527 echo hsc(print_r($msg, true)); 528 echo '</pre>'; 529 } 530} 531 532/** 533 * Print info to debug log file 534 * 535 * @param string $msg 536 * @param string $header 537 * 538 * @author Andreas Gohr <andi@splitbrain.org> 539 * @deprecated 2020-08-13 540 */ 541function dbglog($msg, $header = '') 542{ 543 dbg_deprecated('\\dokuwiki\\Logger'); 544 545 // was the msg as single line string? use it as header 546 if ($header === '' && is_string($msg) && !str_contains($msg, "\n")) { 547 $header = $msg; 548 $msg = ''; 549 } 550 551 Logger::getInstance(Logger::LOG_DEBUG)->log( 552 $header, 553 $msg 554 ); 555} 556 557/** 558 * Log accesses to deprecated fucntions to the debug log 559 * 560 * @param string $alternative The function or method that should be used instead 561 * @triggers INFO_DEPRECATION_LOG 562 */ 563function dbg_deprecated($alternative = '') 564{ 565 DebugHelper::dbgDeprecatedFunction($alternative, 2); 566} 567 568/** 569 * Print a reversed, prettyprinted backtrace 570 * 571 * @author Gary Owen <gary_owen@bigfoot.com> 572 */ 573function dbg_backtrace() 574{ 575 // Get backtrace 576 $backtrace = debug_backtrace(); 577 578 // Unset call to debug_print_backtrace 579 array_shift($backtrace); 580 581 // Iterate backtrace 582 $calls = []; 583 $depth = count($backtrace) - 1; 584 foreach ($backtrace as $i => $call) { 585 if (isset($call['file'])) { 586 $location = $call['file'] . ':' . ($call['line'] ?? '0'); 587 } else { 588 $location = '[anonymous]'; 589 } 590 if (isset($call['class'])) { 591 $function = $call['class'] . $call['type'] . $call['function']; 592 } else { 593 $function = $call['function']; 594 } 595 596 $params = []; 597 if (isset($call['args'])) { 598 foreach ($call['args'] as $arg) { 599 if (is_object($arg)) { 600 $params[] = '[Object ' . $arg::class . ']'; 601 } elseif (is_array($arg)) { 602 $params[] = '[Array]'; 603 } elseif (is_null($arg)) { 604 $params[] = '[NULL]'; 605 } else { 606 $params[] = '"' . $arg . '"'; 607 } 608 } 609 } 610 $params = implode(', ', $params); 611 612 $calls[$depth - $i] = sprintf( 613 '%s(%s) called at %s', 614 $function, 615 str_replace("\n", '\n', $params), 616 $location 617 ); 618 } 619 ksort($calls); 620 621 return implode("\n", $calls); 622} 623 624/** 625 * Remove all data from an array where the key seems to point to sensitive data 626 * 627 * This is used to remove passwords, mail addresses and similar data from the 628 * debug output 629 * 630 * @param array $data 631 * 632 * @author Andreas Gohr <andi@splitbrain.org> 633 */ 634function debug_guard(&$data) 635{ 636 foreach ($data as $key => $value) { 637 if (preg_match('/(notify|pass|auth|secret|ftp|userinfo|token|buid|mail|proxy)/i', $key)) { 638 $data[$key] = '***'; 639 continue; 640 } 641 if (is_array($value)) debug_guard($data[$key]); 642 } 643} 644