xref: /dokuwiki/inc/infoutils.php (revision 26dfc2323f8f70cb69aac4c8c51bf7997809f2ca)
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.',
308            -1
309        );
310    } elseif (!empty($lengths)) {
311        msg('The search index seems to be working', 1);
312    } else {
313        msg(
314            'The search index is empty. See
315                <a href="http://www.dokuwiki.org/faq:searchindex">faq:searchindex</a>
316                for help on how to fix the search index. If the default indexer
317                isn\'t used or the wiki is actually empty this is normal.'
318        );
319    }
320
321    // rough time check
322    $http = new DokuHTTPClient();
323    $http->max_redirect = 0;
324    $http->timeout = 3;
325    $http->sendRequest('http://www.dokuwiki.org', '', 'HEAD');
326    $now = time();
327    if (isset($http->resp_headers['date'])) {
328        $time = strtotime($http->resp_headers['date']);
329        $diff = $time - $now;
330
331        if (abs($diff) < 4) {
332            msg("Server time seems to be okay. Diff: {$diff}s", 1);
333        } else {
334            msg("Your server's clock seems to be out of sync!
335                 Consider configuring a sync with a NTP server.  Diff: {$diff}s");
336        }
337    }
338
339}
340
341/**
342 * Display a message to the user
343 *
344 * If HTTP headers were not sent yet the message is added
345 * to the global message array else it's printed directly
346 * using html_msgarea()
347 *
348 * Triggers INFOUTIL_MSG_SHOW
349 *
350 * @see    html_msgarea()
351 * @param string $message
352 * @param int    $lvl   -1 = error, 0 = info, 1 = success, 2 = notify
353 * @param string $line  line number
354 * @param string $file  file number
355 * @param int    $allow who's allowed to see the message, see MSG_* constants
356 */
357function msg($message, $lvl = 0, $line = '', $file = '', $allow = MSG_PUBLIC)
358{
359    global $MSG, $MSG_shown;
360    static $errors = [
361        -1 => 'error',
362        0 => 'info',
363        1 => 'success',
364        2 => 'notify',
365    ];
366
367    $msgdata = [
368        'msg' => $message,
369        'lvl' => $errors[$lvl],
370        'allow' => $allow,
371        'line' => $line,
372        'file' => $file,
373    ];
374
375    $evt = new Event('INFOUTIL_MSG_SHOW', $msgdata);
376    if ($evt->advise_before()) {
377        /* Show msg normally - event could suppress message show */
378        if ($msgdata['line'] || $msgdata['file']) {
379            $basename = PhpString::basename($msgdata['file']);
380            $msgdata['msg'] .=' ['.$basename.':'.$msgdata['line'].']';
381        }
382
383        if (!isset($MSG)) $MSG = [];
384        $MSG[] = $msgdata;
385        if (isset($MSG_shown) || headers_sent()) {
386            if (function_exists('html_msgarea')) {
387                html_msgarea();
388            } else {
389                echo "ERROR(".$msgdata['lvl'].") ".$msgdata['msg']."\n";
390            }
391            unset($GLOBALS['MSG']);
392        }
393    }
394    $evt->advise_after();
395    unset($evt);
396}
397/**
398 * Determine whether the current user is allowed to view the message
399 * in the $msg data structure
400 *
401 * @param  $msg   array    dokuwiki msg structure
402 *                         msg   => string, the message
403 *                         lvl   => int, level of the message (see msg() function)
404 *                         allow => int, flag used to determine who is allowed to see the message
405 *                                       see MSG_* constants
406 * @return bool
407 */
408function info_msg_allowed($msg)
409{
410    global $INFO, $auth;
411
412    // is the message public? - everyone and anyone can see it
413    if (empty($msg['allow']) || ($msg['allow'] == MSG_PUBLIC)) return true;
414
415    // restricted msg, but no authentication
416    if (empty($auth)) return false;
417
418    switch ($msg['allow']) {
419        case MSG_USERS_ONLY:
420            return !empty($INFO['userinfo']);
421
422        case MSG_MANAGERS_ONLY:
423            return $INFO['ismanager'];
424
425        case MSG_ADMINS_ONLY:
426            return $INFO['isadmin'];
427
428        default:
429            trigger_error(
430                'invalid msg allow restriction.  msg="'.$msg['msg'].'" allow='.$msg['allow'].'"',
431                E_USER_WARNING
432            );
433            return $INFO['isadmin'];
434    }
435}
436
437/**
438 * print debug messages
439 *
440 * little function to print the content of a var
441 *
442 * @author Andreas Gohr <andi@splitbrain.org>
443 *
444 * @param string $msg
445 * @param bool $hidden
446 */
447function dbg($msg, $hidden = false)
448{
449    if ($hidden) {
450        echo "<!--\n";
451        print_r($msg);
452        echo "\n-->";
453    } else {
454        echo '<pre class="dbg">';
455        echo hsc(print_r($msg, true));
456        echo '</pre>';
457    }
458}
459
460/**
461 * Print info to debug log file
462 *
463 * @author Andreas Gohr <andi@splitbrain.org>
464 * @deprecated 2020-08-13
465 * @param string $msg
466 * @param string $header
467 */
468function dbglog($msg, $header = '')
469{
470    dbg_deprecated('\\dokuwiki\\Logger');
471
472    // was the msg as single line string? use it as header
473    if ($header === '' && is_string($msg) && strpos($msg, "\n") === false) {
474        $header = $msg;
475        $msg = '';
476    }
477
478    Logger::getInstance(Logger::LOG_DEBUG)->log(
479        $header,
480        $msg
481    );
482}
483
484/**
485 * Log accesses to deprecated fucntions to the debug log
486 *
487 * @param string $alternative The function or method that should be used instead
488 * @triggers INFO_DEPRECATION_LOG
489 */
490function dbg_deprecated($alternative = '')
491{
492    DebugHelper::dbgDeprecatedFunction($alternative, 2);
493}
494
495/**
496 * Print a reversed, prettyprinted backtrace
497 *
498 * @author Gary Owen <gary_owen@bigfoot.com>
499 */
500function dbg_backtrace()
501{
502    // Get backtrace
503    $backtrace = debug_backtrace();
504
505    // Unset call to debug_print_backtrace
506    array_shift($backtrace);
507
508    // Iterate backtrace
509    $calls = [];
510    $depth = count($backtrace) - 1;
511    foreach ($backtrace as $i => $call) {
512        $location = $call['file'] . ':' . $call['line'];
513        $function = (isset($call['class'])) ?
514            $call['class'] . $call['type'] . $call['function'] : $call['function'];
515
516        $params = [];
517        if (isset($call['args'])) {
518            foreach ($call['args'] as $arg) {
519                if (is_object($arg)) {
520                    $params[] = '[Object '.get_class($arg).']';
521                } elseif (is_array($arg)) {
522                    $params[] = '[Array]';
523                } elseif (is_null($arg)) {
524                    $params[] = '[NULL]';
525                } else {
526                    $params[] = '"'.$arg.'"';
527                }
528            }
529        }
530        $params = implode(', ', $params);
531
532        $calls[$depth - $i] = sprintf(
533            '%s(%s) called at %s',
534            $function,
535            str_replace("\n", '\n', $params),
536            $location
537        );
538    }
539    ksort($calls);
540
541    return implode("\n", $calls);
542}
543
544/**
545 * Remove all data from an array where the key seems to point to sensitive data
546 *
547 * This is used to remove passwords, mail addresses and similar data from the
548 * debug output
549 *
550 * @author Andreas Gohr <andi@splitbrain.org>
551 *
552 * @param array $data
553 */
554function debug_guard(&$data)
555{
556    foreach ($data as $key => $value) {
557        if (preg_match('/(notify|pass|auth|secret|ftp|userinfo|token|buid|mail|proxy)/i', $key)) {
558            $data[$key] = '***';
559            continue;
560        }
561        if (is_array($value)) debug_guard($data[$key]);
562    }
563}
564