4 * Information and debugging functions
6 * @license GPL 2 (http://www.gnu.org/licenses/gpl.html)
7 * @author Andreas Gohr <andi@splitbrain.org>
10 use dokuwiki\Extension\AuthPlugin
;
11 use dokuwiki\Extension\Event
;
12 use dokuwiki\Utf8\PhpString
;
13 use dokuwiki\Debug\DebugHelper
;
14 use dokuwiki\HTTP\DokuHTTPClient
;
17 if (!defined('DOKU_MESSAGEURL')) {
18 if (in_array('ssl', stream_get_transports())) {
19 define('DOKU_MESSAGEURL', 'https://update.dokuwiki.org/check/');
21 define('DOKU_MESSAGEURL', 'http://update.dokuwiki.org/check/');
26 * Check for new messages from upstream
28 * @author Andreas Gohr <andi@splitbrain.org>
30 function checkUpdateMessages()
34 global $updateVersion;
35 if (!$conf['updatecheck']) return;
36 if ($conf['useacl'] && !$INFO['ismanager']) return;
38 $cf = getCacheName($updateVersion, '.updmsg');
39 $lm = @filemtime
($cf);
40 $is_http = !str_starts_with(DOKU_MESSAGEURL
, 'https');
42 // check if new messages needs to be fetched
43 if ($lm < time() - (60 * 60 * 24) ||
$lm < @filemtime
(DOKU_INC
. DOKU_SCRIPT
)) {
47 'checkUpdateMessages(): downloading messages to %s%s',
49 $is_http ?
' (without SSL)' : ' (with SSL)'
52 $http = new DokuHTTPClient();
54 $resp = $http->get(DOKU_MESSAGEURL
. $updateVersion);
55 if (is_string($resp) && ($resp == '' ||
str_ends_with(trim($resp), '%'))) {
56 // basic sanity check that this is either an empty string response (ie "no messages")
57 // or it looks like one of our messages, not WiFi login or other interposed response
58 io_saveFile($cf, $resp);
60 Logger
::debug("checkUpdateMessages(): unexpected HTTP response received", $http->error
);
63 Logger
::debug("checkUpdateMessages(): messages up to date");
66 $data = io_readFile($cf);
67 // show messages through the usual message mechanism
68 $msgs = explode("\n%\n", $data);
69 foreach ($msgs as $msg) {
70 if ($msg) msg($msg, 2);
76 * Return DokuWiki's version (split up in date and type)
78 * @author Andreas Gohr <andi@splitbrain.org>
80 function getVersionData()
83 //import version string
84 if (file_exists(DOKU_INC
. 'VERSION')) {
86 $version['date'] = trim(io_readFile(DOKU_INC
. 'VERSION'));
87 $version['type'] = 'Release';
88 } elseif (is_dir(DOKU_INC
. '.git')) {
89 $version['type'] = 'Git';
90 $version['date'] = 'unknown';
92 // First try to get date and commit hash by calling Git
93 if (function_exists('shell_exec')) {
94 $commitInfo = shell_exec("git log -1 --pretty=format:'%h %cd' --date=short");
96 [$version['sha'], $date] = explode(' ', $commitInfo);
97 $version['date'] = hsc($date);
102 // we cannot use git on the shell -- let's do it manually!
103 if (file_exists(DOKU_INC
. '.git/HEAD')) {
104 $headCommit = trim(file_get_contents(DOKU_INC
. '.git/HEAD'));
105 if (strpos($headCommit, 'ref: ') === 0) {
106 // it is something like `ref: refs/heads/master`
107 $headCommit = substr($headCommit, 5);
108 $pathToHead = DOKU_INC
. '.git/' . $headCommit;
109 if (file_exists($pathToHead)) {
110 $headCommit = trim(file_get_contents($pathToHead));
112 $packedRefs = file_get_contents(DOKU_INC
. '.git/packed-refs');
113 if (!preg_match("~([[:xdigit:]]+) $headCommit~", $packedRefs, $matches)) {
114 # ref not found in pack file
117 $headCommit = $matches[1];
120 // At this point $headCommit is a SHA
121 $version['sha'] = $headCommit;
123 // Get commit date from Git object
124 $subDir = substr($headCommit, 0, 2);
125 $fileName = substr($headCommit, 2);
126 $gitCommitObject = DOKU_INC
. ".git/objects/$subDir/$fileName";
127 if (file_exists($gitCommitObject) && function_exists('zlib_decode')) {
128 $commit = zlib_decode(file_get_contents($gitCommitObject));
129 $committerLine = explode("\n", $commit)[3];
130 $committerData = explode(' ', $committerLine);
132 $ts = prev($committerData);
133 if ($ts && $date = date('Y-m-d', $ts)) {
134 $version['date'] = $date;
139 global $updateVersion;
140 $version['date'] = 'update version ' . $updateVersion;
141 $version['type'] = 'snapshot?';
147 * Return DokuWiki's version
149 * This returns the version in the form "Type Date (SHA)". Where type is either
150 * "Release" or "Git" and date is the date of the release or the date of the
151 * last commit. SHA is the short SHA of the last commit - this is only added on
154 * If no version can be determined "snapshot? update version XX" is returned.
155 * Where XX represents the update version number set in doku.php.
157 * @author Anika Henke <anika@selfthinker.org>
158 * @return string The version string e.g. "Release 2023-04-04a"
160 function getVersion()
162 $version = getVersionData();
163 $sha = empty($version['sha']) ?
'' : ' (' . $version['sha'] . ')';
164 return $version['type'] . ' ' . $version['date'] . $sha;
168 * Run a few sanity checks
170 * @author Andreas Gohr <andi@splitbrain.org>
176 /* @var Input $INPUT */
179 if ($INFO['isadmin'] ||
$INFO['ismanager']) {
180 msg('DokuWiki version: ' . getVersion(), 1);
181 if (version_compare(phpversion(), '7.4.0', '<')) {
182 msg('Your PHP version is too old (' . phpversion() . ' vs. 7.4+ needed)', -1);
184 msg('PHP version ' . phpversion(), 1);
186 } elseif (version_compare(phpversion(), '7.4.0', '<')) {
187 msg('Your PHP version is too old', -1);
190 $mem = php_to_byte(ini_get('memory_limit'));
193 msg('PHP memory is unlimited', 1);
194 } elseif ($mem < 16_777_216
) {
195 msg('PHP is limited to less than 16MB RAM (' . filesize_h($mem) . ').
196 Increase memory_limit in php.ini', -1);
197 } elseif ($mem < 20_971_520
) {
198 msg('PHP is limited to less than 20MB RAM (' . filesize_h($mem) . '),
199 you might encounter problems with bigger pages. Increase memory_limit in php.ini', -1);
200 } elseif ($mem < 33_554_432
) {
201 msg('PHP is limited to less than 32MB RAM (' . filesize_h($mem) . '),
202 but that should be enough in most cases. If not, increase memory_limit in php.ini', 0);
204 msg('More than 32MB RAM (' . filesize_h($mem) . ') available.', 1);
208 if (is_writable($conf['changelog'])) {
209 msg('Changelog is writable', 1);
210 } elseif (file_exists($conf['changelog'])) {
211 msg('Changelog is not writable', -1);
214 if (isset($conf['changelog_old']) && file_exists($conf['changelog_old'])) {
215 msg('Old changelog exists', 0);
218 if (file_exists($conf['changelog'] . '_failed')) {
219 msg('Importing old changelog failed', -1);
220 } elseif (file_exists($conf['changelog'] . '_importing')) {
221 msg('Importing old changelog now.', 0);
222 } elseif (file_exists($conf['changelog'] . '_import_ok')) {
223 msg('Old changelog imported', 1);
224 if (!plugin_isdisabled('importoldchangelog')) {
225 msg('Importoldchangelog plugin not disabled after import', -1);
229 if (is_writable(DOKU_CONF
)) {
230 msg('conf directory is writable', 1);
232 msg('conf directory is not writable', -1);
235 if ($conf['authtype'] == 'plain') {
236 global $config_cascade;
237 if (is_writable($config_cascade['plainauth.users']['default'])) {
238 msg('conf/users.auth.php is writable', 1);
240 msg('conf/users.auth.php is not writable', 0);
244 if (function_exists('mb_strpos')) {
245 if (defined('UTF8_NOMBSTRING')) {
246 msg('mb_string extension is available but will not be used', 0);
248 msg('mb_string extension is available and will be used', 1);
249 if (ini_get('mbstring.func_overload') != 0) {
250 msg('mb_string function overloading is enabled, this will cause problems and should be disabled', -1);
254 msg('mb_string extension not available - PHP only replacements will be used', 0);
257 if (!UTF8_PREGSUPPORT
) {
258 msg('PHP is missing UTF-8 support in Perl-Compatible Regular Expressions (PCRE)', -1);
260 if (!UTF8_PROPERTYSUPPORT
) {
261 msg('PHP is missing Unicode properties support in Perl-Compatible Regular Expressions (PCRE)', -1);
264 $loc = setlocale(LC_ALL
, 0);
266 msg('No valid locale is set for your PHP setup. You should fix this', -1);
267 } elseif (stripos($loc, 'utf') === false) {
268 msg('Your locale <code>' . hsc($loc) . '</code> seems not to be a UTF-8 locale,
269 you should fix this if you encounter problems.', 0);
271 msg('Valid locale ' . hsc($loc) . ' found.', 1);
274 if ($conf['allowdebug']) {
275 msg('Debugging support is enabled. If you don\'t need it you should set $conf[\'allowdebug\'] = 0', -1);
277 msg('Debugging support is disabled', 1);
280 if (!empty($INFO['userinfo']['name'])) {
282 "You are currently logged in as %s (%s)",
283 $INPUT->server
->str('REMOTE_USER'),
284 $INFO['userinfo']['name']
286 msg('You are part of the groups ' . implode(', ', $INFO['userinfo']['grps']), 0);
288 msg('You are currently not logged in', 0);
291 msg('Your current permission for this page is ' . $INFO['perm'], 0);
293 if (file_exists($INFO['filepath']) && is_writable($INFO['filepath'])) {
294 msg('The current page is writable by the webserver', 1);
295 } elseif (!file_exists($INFO['filepath']) && is_writable(dirname($INFO['filepath']))) {
296 msg('The current page can be created by the webserver', 1);
298 msg('The current page is not writable by the webserver', -1);
301 if ($INFO['writable']) {
302 msg('The current page is writable by you', 1);
304 msg('The current page is not writable by you', -1);
307 // Check for corrupted search index
308 $lengths = idx_listIndexLengths();
309 $index_corrupted = false;
310 foreach ($lengths as $length) {
311 if (count(idx_getIndex('w', $length)) !== count(idx_getIndex('i', $length))) {
312 $index_corrupted = true;
317 foreach (idx_getIndex('metadata', '') as $index) {
318 if (count(idx_getIndex($index . '_w', '')) !== count(idx_getIndex($index . '_i', ''))) {
319 $index_corrupted = true;
324 if ($index_corrupted) {
326 'The search index is corrupted. It might produce wrong results and most
327 probably needs to be rebuilt. See
328 <a href="https://www.dokuwiki.org/faq:searchindex">faq:searchindex</a>
329 for ways to rebuild the search index.',
332 } elseif (!empty($lengths)) {
333 msg('The search index seems to be working', 1);
336 'The search index is empty. See
337 <a href="https://www.dokuwiki.org/faq:searchindex">faq:searchindex</a>
338 for help on how to fix the search index. If the default indexer
339 isn\'t used or the wiki is actually empty this is normal.'
344 $http = new DokuHTTPClient();
345 $http->max_redirect
= 0;
347 $http->sendRequest('https://www.dokuwiki.org', '', 'HEAD');
349 if (isset($http->resp_headers
['date'])) {
350 $time = strtotime($http->resp_headers
['date']);
351 $diff = $time - $now;
353 if (abs($diff) < 4) {
354 msg("Server time seems to be okay. Diff: {$diff}s", 1);
356 msg("Your server's clock seems to be out of sync!
357 Consider configuring a sync with a NTP server. Diff: {$diff}s");
363 * Display a message to the user
365 * If HTTP headers were not sent yet the message is added
366 * to the global message array else it's printed directly
367 * using html_msgarea()
369 * Triggers INFOUTIL_MSG_SHOW
371 * @param string $message
372 * @param int $lvl -1 = error, 0 = info, 1 = success, 2 = notify
373 * @param string $line line number
374 * @param string $file file number
375 * @param int $allow who's allowed to see the message, see MSG_* constants
376 * @see html_msgarea()
378 function msg($message, $lvl = 0, $line = '', $file = '', $allow = MSG_PUBLIC
)
380 global $MSG, $MSG_shown;
390 'lvl' => $errors[$lvl],
396 $evt = new Event('INFOUTIL_MSG_SHOW', $msgdata);
397 if ($evt->advise_before()) {
398 /* Show msg normally - event could suppress message show */
399 if ($msgdata['line'] ||
$msgdata['file']) {
400 $basename = PhpString
::basename($msgdata['file']);
401 $msgdata['msg'] .= ' [' . $basename . ':' . $msgdata['line'] . ']';
404 if (!isset($MSG)) $MSG = [];
406 if (isset($MSG_shown) ||
headers_sent()) {
407 if (function_exists('html_msgarea')) {
410 echo "ERROR(" . $msgdata['lvl'] . ") " . $msgdata['msg'] . "\n";
412 unset($GLOBALS['MSG']);
415 $evt->advise_after();
420 * Determine whether the current user is allowed to view the message
421 * in the $msg data structure
423 * @param array $msg dokuwiki msg structure:
424 * msg => string, the message;
425 * lvl => int, level of the message (see msg() function);
426 * allow => int, flag used to determine who is allowed to see the message, see MSG_* constants
429 function info_msg_allowed($msg)
433 // is the message public? - everyone and anyone can see it
434 if (empty($msg['allow']) ||
($msg['allow'] == MSG_PUBLIC
)) return true;
436 // restricted msg, but no authentication
437 if (!$auth instanceof AuthPlugin
) return false;
439 switch ($msg['allow']) {
441 return !empty($INFO['userinfo']);
443 case MSG_MANAGERS_ONLY
:
444 return $INFO['ismanager'];
446 case MSG_ADMINS_ONLY
:
447 return $INFO['isadmin'];
451 'invalid msg allow restriction. msg="' . $msg['msg'] . '" allow=' . $msg['allow'] . '"',
454 return $INFO['isadmin'];
459 * print debug messages
461 * little function to print the content of a var
464 * @param bool $hidden
466 * @author Andreas Gohr <andi@splitbrain.org>
468 function dbg($msg, $hidden = false)
475 echo '<pre class="dbg">';
476 echo hsc(print_r($msg, true));
482 * Print info to debug log file
485 * @param string $header
487 * @author Andreas Gohr <andi@splitbrain.org>
488 * @deprecated 2020-08-13
490 function dbglog($msg, $header = '')
492 dbg_deprecated('\\dokuwiki\\Logger');
494 // was the msg as single line string? use it as header
495 if ($header === '' && is_string($msg) && strpos($msg, "\n") === false) {
500 Logger
::getInstance(Logger
::LOG_DEBUG
)->log(
507 * Log accesses to deprecated fucntions to the debug log
509 * @param string $alternative The function or method that should be used instead
510 * @triggers INFO_DEPRECATION_LOG
512 function dbg_deprecated($alternative = '')
514 DebugHelper
::dbgDeprecatedFunction($alternative, 2);
518 * Print a reversed, prettyprinted backtrace
520 * @author Gary Owen <gary_owen@bigfoot.com>
522 function dbg_backtrace()
525 $backtrace = debug_backtrace();
527 // Unset call to debug_print_backtrace
528 array_shift($backtrace);
532 $depth = count($backtrace) - 1;
533 foreach ($backtrace as $i => $call) {
534 if (isset($call['file'])) {
535 $location = $call['file'] . ':' . ($call['line'] ??
'0');
537 $location = '[anonymous]';
539 if (isset($call['class'])) {
540 $function = $call['class'] . $call['type'] . $call['function'];
542 $function = $call['function'];
546 if (isset($call['args'])) {
547 foreach ($call['args'] as $arg) {
548 if (is_object($arg)) {
549 $params[] = '[Object ' . get_class($arg) . ']';
550 } elseif (is_array($arg)) {
551 $params[] = '[Array]';
552 } elseif (is_null($arg)) {
553 $params[] = '[NULL]';
555 $params[] = '"' . $arg . '"';
559 $params = implode(', ', $params);
561 $calls[$depth - $i] = sprintf(
562 '%s(%s) called at %s',
564 str_replace("\n", '\n', $params),
570 return implode("\n", $calls);
574 * Remove all data from an array where the key seems to point to sensitive data
576 * This is used to remove passwords, mail addresses and similar data from the
581 * @author Andreas Gohr <andi@splitbrain.org>
583 function debug_guard(&$data)
585 foreach ($data as $key => $value) {
586 if (preg_match('/(notify|pass|auth|secret|ftp|userinfo|token|buid|mail|proxy)/i', $key)) {
590 if (is_array($value)) debug_guard($data[$key]);