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