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