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