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