xref: /dokuwiki/inc/infoutils.php (revision 093fe67e98c0cdb4b73fd46938e49b64971483c2)
1<?php
2
3/**
4 * Information and debugging functions
5 *
6 * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
7 * @author     Andreas Gohr <andi@splitbrain.org>
8 */
9
10use dokuwiki\Debug\DebugHelper;
11use dokuwiki\Extension\AuthPlugin;
12use dokuwiki\Extension\Event;
13use dokuwiki\HTTP\DokuHTTPClient;
14use dokuwiki\Logger;
15use dokuwiki\Utf8\PhpString;
16
17if (!defined('DOKU_MESSAGEURL')) {
18    if (in_array('ssl', stream_get_transports())) {
19        define('DOKU_MESSAGEURL', 'https://update.dokuwiki.org/check/');
20    } else {
21        define('DOKU_MESSAGEURL', 'http://update.dokuwiki.org/check/');
22    }
23}
24
25/**
26 * Check for new messages from upstream
27 *
28 * @author Andreas Gohr <andi@splitbrain.org>
29 */
30function checkUpdateMessages()
31{
32    global $conf;
33    global $INFO;
34    global $updateVersion;
35    if (!$conf['updatecheck']) return;
36    if ($conf['useacl'] && !$INFO['ismanager']) return;
37
38    $cf = getCacheName($updateVersion, '.updmsg');
39    $lm = @filemtime($cf);
40    $is_http = !str_starts_with(DOKU_MESSAGEURL, 'https');
41
42    // check if new messages needs to be fetched
43    if ($lm < time() - (60 * 60 * 24) || $lm < @filemtime(DOKU_INC . DOKU_SCRIPT)) {
44        @touch($cf);
45        Logger::debug(
46            sprintf(
47                'checkUpdateMessages(): downloading messages to %s%s',
48                $cf,
49                $is_http ? ' (without SSL)' : ' (with SSL)'
50            )
51        );
52        $http = new DokuHTTPClient();
53        $http->timeout = 12;
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);
59        } else {
60            Logger::debug("checkUpdateMessages(): unexpected HTTP response received", $http->error);
61        }
62    } else {
63        Logger::debug("checkUpdateMessages(): messages up to date");
64    }
65
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);
71    }
72}
73
74
75/**
76 * Return DokuWiki's version (split up in date and type)
77 *
78 * @author Andreas Gohr <andi@splitbrain.org>
79 */
80function getVersionData()
81{
82    $version = [];
83    //import version string
84    if (file_exists(DOKU_INC . 'VERSION')) {
85        //official release
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';
91
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");
95            if ($commitInfo) {
96                [$version['sha'], $date] = explode(' ', $commitInfo);
97                $version['date'] = hsc($date);
98                return $version;
99            }
100        }
101
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 (str_starts_with($headCommit, 'ref: ')) {
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));
111                } else {
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
115                        return $version;
116                    }
117                    $headCommit = $matches[1];
118                }
119            }
120            // At this point $headCommit is a SHA
121            $version['sha'] = $headCommit;
122
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);
131                end($committerData);
132                $ts = prev($committerData);
133                if ($ts && $date = date('Y-m-d', $ts)) {
134                    $version['date'] = $date;
135                }
136            }
137        }
138    } else {
139        global $updateVersion;
140        $version['date'] = 'update version ' . $updateVersion;
141        $version['type'] = 'snapshot?';
142    }
143    return $version;
144}
145
146/**
147 * Return DokuWiki's version
148 *
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
152 * git checkouts.
153 *
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.
156 *
157 * @return string The version string e.g. "Release 2023-04-04a"
158 * @author Anika Henke <anika@selfthinker.org>
159 */
160function getVersion()
161{
162    $version = getVersionData();
163    $sha = empty($version['sha']) ? '' : ' (' . $version['sha'] . ')';
164    return $version['type'] . ' ' . $version['date'] . $sha;
165}
166
167/**
168 * Get some data about the environment this wiki is running in
169 *
170 * @return array
171 */
172function getRuntimeVersions()
173{
174    $data = [];
175    $data['php'] = 'PHP ' . PHP_VERSION;
176
177    $osRelease = getOsRelease();
178    if (isset($osRelease['PRETTY_NAME'])) {
179        $data['dist'] = $osRelease['PRETTY_NAME'];
180    }
181
182    $data['os'] = php_uname('s') . ' ' . php_uname('r');
183    $data['sapi'] = PHP_SAPI;
184
185    if (getenv('KUBERNETES_SERVICE_HOST')) {
186        $data['container'] = 'Kubernetes';
187    } elseif (@file_exists('/.dockerenv')) {
188        $data['container'] = 'Docker';
189    }
190
191    return $data;
192}
193
194/**
195 * Get informational data about the linux distribution this wiki is running on
196 *
197 * @see https://gist.github.com/natefoo/814c5bf936922dad97ff
198 * @return array an os-release array, might be empty
199 */
200function getOsRelease()
201{
202    $reader = fn($file) => @parse_ini_string(preg_replace('/#.*$/m', '', file_get_contents($file)));
203
204    $osRelease = [];
205    if (@file_exists('/etc/os-release')) {
206        // pretty much any common Linux distribution has this
207        $osRelease = $reader('/etc/os-release');
208    } elseif (@file_exists('/etc/synoinfo.conf') && @file_exists('/etc/VERSION')) {
209        // Synology DSM has its own way
210        $synoInfo = $reader('/etc/synoinfo.conf');
211        $synoVersion = $reader('/etc/VERSION');
212        $osRelease['NAME'] = 'Synology DSM';
213        $osRelease['ID'] = 'synology';
214        $osRelease['ID_LIKE'] = 'linux';
215        $osRelease['VERSION_ID'] = $synoVersion['productversion'];
216        $osRelease['VERSION'] = $synoVersion['productversion'];
217        $osRelease['SYNO_MODEL'] = $synoInfo['upnpmodelname'];
218        $osRelease['PRETTY_NAME'] = implode(' ', [$osRelease['NAME'], $osRelease['VERSION'], $osRelease['SYNO_MODEL']]);
219    }
220    return $osRelease;
221}
222
223
224/**
225 * Run a few sanity checks
226 *
227 * @author Andreas Gohr <andi@splitbrain.org>
228 */
229function check()
230{
231    global $conf;
232    global $INFO;
233    /* @var Input $INPUT */
234    global $INPUT;
235
236    if ($INFO['isadmin'] || $INFO['ismanager']) {
237        msg('DokuWiki version: ' . getVersion(), 1);
238        if (version_compare(phpversion(), '8.2.0', '<')) {
239            msg('Your PHP version is too old (' . phpversion() . ' vs. 8.2+ needed)', -1);
240        } else {
241            msg('PHP version ' . phpversion(), 1);
242        }
243    } elseif (version_compare(phpversion(), '8.2.0', '<')) {
244        msg('Your PHP version is too old', -1);
245    }
246
247    $mem = php_to_byte(ini_get('memory_limit'));
248    if ($mem) {
249        if ($mem === -1) {
250            msg('PHP memory is unlimited', 1);
251        } elseif ($mem < 16_777_216) {
252            msg('PHP is limited to less than 16MB RAM (' . filesize_h($mem) . ').
253            Increase memory_limit in php.ini', -1);
254        } elseif ($mem < 20_971_520) {
255            msg('PHP is limited to less than 20MB RAM (' . filesize_h($mem) . '),
256                you might encounter problems with bigger pages. Increase memory_limit in php.ini', -1);
257        } elseif ($mem < 33_554_432) {
258            msg('PHP is limited to less than 32MB RAM (' . filesize_h($mem) . '),
259                but that should be enough in most cases. If not, increase memory_limit in php.ini', 0);
260        } else {
261            msg('More than 32MB RAM (' . filesize_h($mem) . ') available.', 1);
262        }
263    }
264
265    if (is_writable($conf['changelog'])) {
266        msg('Changelog is writable', 1);
267    } elseif (file_exists($conf['changelog'])) {
268        msg('Changelog is not writable', -1);
269    }
270
271    if (isset($conf['changelog_old']) && file_exists($conf['changelog_old'])) {
272        msg('Old changelog exists', 0);
273    }
274
275    if (file_exists($conf['changelog'] . '_failed')) {
276        msg('Importing old changelog failed', -1);
277    } elseif (file_exists($conf['changelog'] . '_importing')) {
278        msg('Importing old changelog now.', 0);
279    } elseif (file_exists($conf['changelog'] . '_import_ok')) {
280        msg('Old changelog imported', 1);
281        if (!plugin_isdisabled('importoldchangelog')) {
282            msg('Importoldchangelog plugin not disabled after import', -1);
283        }
284    }
285
286    if (is_writable(DOKU_CONF)) {
287        msg('conf directory is writable', 1);
288    } else {
289        msg('conf directory is not writable', -1);
290    }
291
292    if ($conf['authtype'] == 'plain') {
293        global $config_cascade;
294        if (is_writable($config_cascade['plainauth.users']['default'])) {
295            msg('conf/users.auth.php is writable', 1);
296        } else {
297            msg('conf/users.auth.php is not writable', 0);
298        }
299    }
300
301    if (function_exists('mb_strpos')) {
302        if (defined('UTF8_NOMBSTRING')) {
303            msg('mb_string extension is available but will not be used', 0);
304        } else {
305            msg('mb_string extension is available and will be used', 1);
306        }
307    } else {
308        msg('mb_string extension not available - PHP only replacements will be used', 0);
309    }
310
311    if (!UTF8_PREGSUPPORT) {
312        msg('PHP is missing UTF-8 support in Perl-Compatible Regular Expressions (PCRE)', -1);
313    }
314    if (!UTF8_PROPERTYSUPPORT) {
315        msg('PHP is missing Unicode properties support in Perl-Compatible Regular Expressions (PCRE)', -1);
316    }
317
318    $loc = setlocale(LC_ALL, 0);
319    if (!$loc) {
320        msg('No valid locale is set for your PHP setup. You should fix this', -1);
321    } elseif (stripos($loc, 'utf') === false) {
322        msg('Your locale <code>' . hsc($loc) . '</code> seems not to be a UTF-8 locale,
323             you should fix this if you encounter problems.', 0);
324    } else {
325        msg('Valid locale ' . hsc($loc) . ' found.', 1);
326    }
327
328    if ($conf['allowdebug']) {
329        msg('Debugging support is enabled. If you don\'t need it you should set $conf[\'allowdebug\'] = 0', -1);
330    } else {
331        msg('Debugging support is disabled', 1);
332    }
333
334    if (!empty($INFO['userinfo']['name'])) {
335        msg(sprintf(
336            "You are currently logged in as %s (%s)",
337            $INPUT->server->str('REMOTE_USER'),
338            $INFO['userinfo']['name']
339        ), 0);
340        msg('You are part of the groups ' . implode(', ', $INFO['userinfo']['grps']), 0);
341    } else {
342        msg('You are currently not logged in', 0);
343    }
344
345    msg('Your current permission for this page is ' . $INFO['perm'], 0);
346
347    if (file_exists($INFO['filepath']) && is_writable($INFO['filepath'])) {
348        msg('The current page is writable by the webserver', 1);
349    } elseif (!file_exists($INFO['filepath']) && is_writable(dirname($INFO['filepath']))) {
350        msg('The current page can be created by the webserver', 1);
351    } else {
352        msg('The current page is not writable by the webserver', -1);
353    }
354
355    if ($INFO['writable']) {
356        msg('The current page is writable by you', 1);
357    } else {
358        msg('The current page is not writable by you', -1);
359    }
360
361    // Check for corrupted search index
362    $lengths = idx_listIndexLengths();
363    $index_corrupted = false;
364    foreach ($lengths as $length) {
365        if (count(idx_getIndex('w', $length)) !== count(idx_getIndex('i', $length))) {
366            $index_corrupted = true;
367            break;
368        }
369    }
370
371    foreach (idx_getIndex('metadata', '') as $index) {
372        if (count(idx_getIndex($index . '_w', '')) !== count(idx_getIndex($index . '_i', ''))) {
373            $index_corrupted = true;
374            break;
375        }
376    }
377
378    if ($index_corrupted) {
379        msg(
380            'The search index is corrupted. It might produce wrong results and most
381                probably needs to be rebuilt. See
382                <a href="https://www.dokuwiki.org/faq:searchindex">faq:searchindex</a>
383                for ways to rebuild the search index.',
384            -1
385        );
386    } elseif (!empty($lengths)) {
387        msg('The search index seems to be working', 1);
388    } else {
389        msg(
390            'The search index is empty. See
391                <a href="https://www.dokuwiki.org/faq:searchindex">faq:searchindex</a>
392                for help on how to fix the search index. If the default indexer
393                isn\'t used or the wiki is actually empty this is normal.'
394        );
395    }
396
397    // rough time check
398    $http = new DokuHTTPClient();
399    $http->max_redirect = 0;
400    $http->timeout = 3;
401    $http->sendRequest('https://www.dokuwiki.org', '', 'HEAD');
402
403    $now = time();
404    if (isset($http->resp_headers['date'])) {
405        $time = strtotime($http->resp_headers['date']);
406        $diff = $time - $now;
407
408        if (abs($diff) < 4) {
409            msg("Server time seems to be okay. Diff: {$diff}s", 1);
410        } else {
411            msg("Your server's clock seems to be out of sync!
412                 Consider configuring a sync with a NTP server.  Diff: {$diff}s");
413        }
414    }
415}
416
417/**
418 * Display a message to the user
419 *
420 * If HTTP headers were not sent yet the message is added
421 * to the global message array else it's printed directly
422 * using html_msgarea()
423 *
424 * Triggers INFOUTIL_MSG_SHOW
425 *
426 * @param string $message
427 * @param int $lvl -1 = error, 0 = info, 1 = success, 2 = notify
428 * @param string $line line number
429 * @param string $file file number
430 * @param int $allow who's allowed to see the message, see MSG_* constants
431 * @see html_msgarea()
432 */
433function msg($message, $lvl = 0, $line = '', $file = '', $allow = MSG_PUBLIC)
434{
435    global $MSG, $MSG_shown;
436    static $errors = [
437        -1 => 'error',
438        0 => 'info',
439        1 => 'success',
440        2 => 'notify',
441    ];
442
443    $msgdata = [
444        'msg' => $message,
445        'lvl' => $errors[$lvl],
446        'allow' => $allow,
447        'line' => $line,
448        'file' => $file,
449    ];
450
451    $evt = new Event('INFOUTIL_MSG_SHOW', $msgdata);
452    if ($evt->advise_before()) {
453        /* Show msg normally - event could suppress message show */
454        if ($msgdata['line'] || $msgdata['file']) {
455            $basename = PhpString::basename($msgdata['file']);
456            $msgdata['msg'] .= ' [' . $basename . ':' . $msgdata['line'] . ']';
457        }
458
459        if (!isset($MSG)) $MSG = [];
460        $MSG[] = $msgdata;
461        if (isset($MSG_shown) || headers_sent()) {
462            if (function_exists('html_msgarea')) {
463                html_msgarea();
464            } else {
465                echo "ERROR(" . $msgdata['lvl'] . ") " . $msgdata['msg'] . "\n";
466            }
467            unset($GLOBALS['MSG']);
468        }
469    }
470    $evt->advise_after();
471    unset($evt);
472}
473
474/**
475 * Determine whether the current user is allowed to view the message
476 * in the $msg data structure
477 *
478 * @param array $msg dokuwiki msg structure:
479 *              msg   => string, the message;
480 *              lvl   => int, level of the message (see msg() function);
481 *              allow => int, flag used to determine who is allowed to see the message, see MSG_* constants
482 * @return bool
483 */
484function info_msg_allowed($msg)
485{
486    global $INFO, $auth;
487
488    // is the message public? - everyone and anyone can see it
489    if (empty($msg['allow']) || ($msg['allow'] == MSG_PUBLIC)) return true;
490
491    // restricted msg, but no authentication
492    if (!$auth instanceof AuthPlugin) return false;
493
494    switch ($msg['allow']) {
495        case MSG_USERS_ONLY:
496            return !empty($INFO['userinfo']);
497
498        case MSG_MANAGERS_ONLY:
499            return $INFO['ismanager'];
500
501        case MSG_ADMINS_ONLY:
502            return $INFO['isadmin'];
503
504        default:
505            trigger_error(
506                'invalid msg allow restriction.  msg="' . $msg['msg'] . '" allow=' . $msg['allow'] . '"',
507                E_USER_WARNING
508            );
509            return $INFO['isadmin'];
510    }
511}
512
513/**
514 * print debug messages
515 *
516 * little function to print the content of a var
517 *
518 * @param string $msg
519 * @param bool $hidden
520 *
521 * @author Andreas Gohr <andi@splitbrain.org>
522 */
523function dbg($msg, $hidden = false)
524{
525    if ($hidden) {
526        echo "<!--\n";
527        print_r($msg);
528        echo "\n-->";
529    } else {
530        echo '<pre class="dbg">';
531        echo hsc(print_r($msg, true));
532        echo '</pre>';
533    }
534}
535
536/**
537 * Print info to debug log file
538 *
539 * @param string $msg
540 * @param string $header
541 *
542 * @author Andreas Gohr <andi@splitbrain.org>
543 * @deprecated 2020-08-13
544 */
545function dbglog($msg, $header = '')
546{
547    dbg_deprecated('\\dokuwiki\\Logger');
548
549    // was the msg as single line string? use it as header
550    if ($header === '' && is_string($msg) && !str_contains($msg, "\n")) {
551        $header = $msg;
552        $msg = '';
553    }
554
555    Logger::getInstance(Logger::LOG_DEBUG)->log(
556        $header,
557        $msg
558    );
559}
560
561/**
562 * Log accesses to deprecated fucntions to the debug log
563 *
564 * @param string $alternative The function or method that should be used instead
565 * @triggers INFO_DEPRECATION_LOG
566 */
567function dbg_deprecated($alternative = '')
568{
569    DebugHelper::dbgDeprecatedFunction($alternative, 2);
570}
571
572/**
573 * Print a reversed, prettyprinted backtrace
574 *
575 * @author Gary Owen <gary_owen@bigfoot.com>
576 */
577function dbg_backtrace()
578{
579    // Get backtrace
580    $backtrace = debug_backtrace();
581
582    // Unset call to debug_print_backtrace
583    array_shift($backtrace);
584
585    // Iterate backtrace
586    $calls = [];
587    $depth = count($backtrace) - 1;
588    foreach ($backtrace as $i => $call) {
589        if (isset($call['file'])) {
590            $location = $call['file'] . ':' . ($call['line'] ?? '0');
591        } else {
592            $location = '[anonymous]';
593        }
594        if (isset($call['class'])) {
595            $function = $call['class'] . $call['type'] . $call['function'];
596        } else {
597            $function = $call['function'];
598        }
599
600        $params = [];
601        if (isset($call['args'])) {
602            foreach ($call['args'] as $arg) {
603                if (is_object($arg)) {
604                    $params[] = '[Object ' . $arg::class . ']';
605                } elseif (is_array($arg)) {
606                    $params[] = '[Array]';
607                } elseif (is_null($arg)) {
608                    $params[] = '[NULL]';
609                } else {
610                    $params[] = '"' . $arg . '"';
611                }
612            }
613        }
614        $params = implode(', ', $params);
615
616        $calls[$depth - $i] = sprintf(
617            '%s(%s) called at %s',
618            $function,
619            str_replace("\n", '\n', $params),
620            $location
621        );
622    }
623    ksort($calls);
624
625    return implode("\n", $calls);
626}
627
628/**
629 * Remove all data from an array where the key seems to point to sensitive data
630 *
631 * This is used to remove passwords, mail addresses and similar data from the
632 * debug output
633 *
634 * @param array $data
635 *
636 * @author Andreas Gohr <andi@splitbrain.org>
637 */
638function debug_guard(&$data)
639{
640    foreach ($data as $key => $value) {
641        if (preg_match('/(notify|pass|auth|secret|ftp|userinfo|token|buid|mail|proxy)/i', $key)) {
642            $data[$key] = '***';
643            continue;
644        }
645        if (is_array($value)) debug_guard($data[$key]);
646    }
647}
648