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