xref: /dokuwiki/inc/infoutils.php (revision bff2c9d24314e25b31ceb53d51de76d678a0a4dc)
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    global $conf;
29    global $INFO;
30    global $updateVersion;
31    if(!$conf['updatecheck']) return;
32    if($conf['useacl'] && !$INFO['ismanager']) return;
33
34    $cf = getCacheName($updateVersion, '.updmsg');
35    $lm = @filemtime($cf);
36    $is_http = substr(DOKU_MESSAGEURL, 0, 5) != 'https';
37
38    // check if new messages needs to be fetched
39    if($lm < time()-(60*60*24) || $lm < @filemtime(DOKU_INC.DOKU_SCRIPT)){
40        @touch($cf);
41        Logger::debug("checkUpdateMessages(): downloading messages to ".$cf.($is_http?' (without SSL)':' (with SSL)'));
42        $http = new DokuHTTPClient();
43        $http->timeout = 12;
44        $resp = $http->get(DOKU_MESSAGEURL.$updateVersion);
45        if(is_string($resp) && ($resp == "" || substr(trim($resp), -1) == '%')) {
46            // basic sanity check that this is either an empty string response (ie "no messages")
47            // or it looks like one of our messages, not WiFi login or other interposed response
48            io_saveFile($cf,$resp);
49        } else {
50            Logger::debug("checkUpdateMessages(): unexpected HTTP response received", $http->error);
51        }
52    }else{
53        Logger::debug("checkUpdateMessages(): messages up to date");
54    }
55
56    $data = io_readFile($cf);
57    // show messages through the usual message mechanism
58    $msgs = explode("\n%\n",$data);
59    foreach($msgs as $msg){
60        if($msg) msg($msg,2);
61    }
62}
63
64
65/**
66 * Return DokuWiki's version (split up in date and type)
67 *
68 * @author Andreas Gohr <andi@splitbrain.org>
69 */
70function getVersionData(){
71    $version = [];
72    //import version string
73    if(file_exists(DOKU_INC.'VERSION')){
74        //official release
75        $version['date'] = trim(io_readFile(DOKU_INC.'VERSION'));
76        $version['type'] = 'Release';
77    }elseif(is_dir(DOKU_INC.'.git')){
78        $version['type'] = 'Git';
79        $version['date'] = 'unknown';
80
81        // First try to get date and commit hash by calling Git
82        if (function_exists('shell_exec')) {
83            $commitInfo = shell_exec("git log -1 --pretty=format:'%h %cd' --date=short");
84            if ($commitInfo) {
85                [$version['sha'], $date] = explode(' ', $commitInfo);
86                $version['date'] = hsc($date);
87                return $version;
88            }
89        }
90
91        // we cannot use git on the shell -- let's do it manually!
92        if (file_exists(DOKU_INC . '.git/HEAD')) {
93            $headCommit = trim(file_get_contents(DOKU_INC . '.git/HEAD'));
94            if (strpos($headCommit, 'ref: ') === 0) {
95                // it is something like `ref: refs/heads/master`
96                $headCommit = substr($headCommit, 5);
97                $pathToHead = DOKU_INC . '.git/' . $headCommit;
98                if (file_exists($pathToHead)) {
99                    $headCommit = trim(file_get_contents($pathToHead));
100                } else {
101                    $packedRefs = file_get_contents(DOKU_INC . '.git/packed-refs');
102                    if (!preg_match("~([[:xdigit:]]+) $headCommit~", $packedRefs, $matches)) {
103                        # ref not found in pack file
104                        return $version;
105                    }
106                    $headCommit = $matches[1];
107                }
108            }
109            // At this point $headCommit is a SHA
110            $version['sha'] = $headCommit;
111
112            // Get commit date from Git object
113            $subDir = substr($headCommit, 0, 2);
114            $fileName = substr($headCommit, 2);
115            $gitCommitObject = DOKU_INC . ".git/objects/$subDir/$fileName";
116            if (file_exists($gitCommitObject) && function_exists('zlib_decode')) {
117                $commit = zlib_decode(file_get_contents($gitCommitObject));
118                $committerLine = explode("\n", $commit)[3];
119                $committerData = explode(' ', $committerLine);
120                end($committerData);
121                $ts = prev($committerData);
122                if ($ts && $date = date('Y-m-d', $ts)) {
123                    $version['date'] = $date;
124                }
125            }
126        }
127    }else{
128        global $updateVersion;
129        $version['date'] = 'update version '.$updateVersion;
130        $version['type'] = 'snapshot?';
131    }
132    return $version;
133}
134
135/**
136 * Return DokuWiki's version (as a string)
137 *
138 * @author Anika Henke <anika@selfthinker.org>
139 */
140function getVersion(){
141    $version = getVersionData();
142    $sha = empty($version['sha']) ? '' : ' (' . $version['sha'] . ')';
143    return $version['type'] . ' ' . $version['date'] . $sha;
144}
145
146/**
147 * Run a few sanity checks
148 *
149 * @author Andreas Gohr <andi@splitbrain.org>
150 */
151function check(){
152    global $conf;
153    global $INFO;
154    /* @var Input $INPUT */
155    global $INPUT;
156
157    if ($INFO['isadmin'] || $INFO['ismanager']) {
158        msg('DokuWiki version: '.getVersion(),1);
159        if(version_compare(phpversion(),'7.4.0','<')){
160            msg('Your PHP version is too old ('.phpversion().' vs. 7.4+ needed)',-1);
161        }else{
162            msg('PHP version '.phpversion(),1);
163        }
164    } elseif (version_compare(phpversion(),'7.4.0','<')) {
165        msg('Your PHP version is too old',-1);
166    }
167
168    $mem = php_to_byte(ini_get('memory_limit'));
169    if($mem){
170        if ($mem === -1) {
171            msg('PHP memory is unlimited', 1);
172        } elseif ($mem < 16_777_216) {
173            msg('PHP is limited to less than 16MB RAM (' . filesize_h($mem) . ').
174            Increase memory_limit in php.ini', -1);
175        } elseif ($mem < 20_971_520) {
176            msg('PHP is limited to less than 20MB RAM (' . filesize_h($mem) . '),
177                you might encounter problems with bigger pages. Increase memory_limit in php.ini', -1);
178        } elseif ($mem < 33_554_432) {
179            msg('PHP is limited to less than 32MB RAM (' . filesize_h($mem) . '),
180                but that should be enough in most cases. If not, increase memory_limit in php.ini', 0);
181        } else {
182            msg('More than 32MB RAM (' . filesize_h($mem) . ') available.', 1);
183        }
184    }
185
186    if (is_writable($conf['changelog'])) {
187        msg('Changelog is writable',1);
188    } elseif (file_exists($conf['changelog'])) {
189        msg('Changelog is not writable',-1);
190    }
191
192    if (isset($conf['changelog_old']) && file_exists($conf['changelog_old'])) {
193        msg('Old changelog exists', 0);
194    }
195
196    if (file_exists($conf['changelog'].'_failed')) {
197        msg('Importing old changelog failed', -1);
198    } elseif (file_exists($conf['changelog'].'_importing')) {
199        msg('Importing old changelog now.', 0);
200    } elseif (file_exists($conf['changelog'].'_import_ok')) {
201        msg('Old changelog imported', 1);
202        if (!plugin_isdisabled('importoldchangelog')) {
203            msg('Importoldchangelog plugin not disabled after import', -1);
204        }
205    }
206
207    if(is_writable(DOKU_CONF)){
208        msg('conf directory is writable',1);
209    }else{
210        msg('conf directory is not writable',-1);
211    }
212
213    if($conf['authtype'] == 'plain'){
214        global $config_cascade;
215        if(is_writable($config_cascade['plainauth.users']['default'])){
216            msg('conf/users.auth.php is writable',1);
217        }else{
218            msg('conf/users.auth.php is not writable',0);
219        }
220    }
221
222    if(function_exists('mb_strpos')){
223        if(defined('UTF8_NOMBSTRING')){
224            msg('mb_string extension is available but will not be used',0);
225        }else{
226            msg('mb_string extension is available and will be used',1);
227            if(ini_get('mbstring.func_overload') != 0){
228                msg('mb_string function overloading is enabled, this will cause problems and should be disabled',-1);
229            }
230        }
231    }else{
232        msg('mb_string extension not available - PHP only replacements will be used',0);
233    }
234
235    if (!UTF8_PREGSUPPORT) {
236        msg('PHP is missing UTF-8 support in Perl-Compatible Regular Expressions (PCRE)', -1);
237    }
238    if (!UTF8_PROPERTYSUPPORT) {
239        msg('PHP is missing Unicode properties support in Perl-Compatible Regular Expressions (PCRE)', -1);
240    }
241
242    $loc = setlocale(LC_ALL, 0);
243    if(!$loc){
244        msg('No valid locale is set for your PHP setup. You should fix this',-1);
245    }elseif(stripos($loc,'utf') === false){
246        msg('Your locale <code>'.hsc($loc).'</code> seems not to be a UTF-8 locale,
247             you should fix this if you encounter problems.',0);
248    }else{
249        msg('Valid locale '.hsc($loc).' found.', 1);
250    }
251
252    if($conf['allowdebug']){
253        msg('Debugging support is enabled. If you don\'t need it you should set $conf[\'allowdebug\'] = 0',-1);
254    }else{
255        msg('Debugging support is disabled',1);
256    }
257
258    if(!empty($INFO['userinfo']['name'])){
259        msg('You are currently logged in as '.$INPUT->server->str('REMOTE_USER').' ('.$INFO['userinfo']['name'].')',0);
260        msg('You are part of the groups '.implode(', ', $INFO['userinfo']['grps']),0);
261    }else{
262        msg('You are currently not logged in',0);
263    }
264
265    msg('Your current permission for this page is '.$INFO['perm'],0);
266
267    if (file_exists($INFO['filepath']) && is_writable($INFO['filepath'])) {
268        msg('The current page is writable by the webserver', 1);
269    } elseif (!file_exists($INFO['filepath']) && is_writable(dirname($INFO['filepath']))) {
270        msg('The current page can be created by the webserver', 1);
271    } else {
272        msg('The current page is not writable by the webserver', -1);
273    }
274
275    if ($INFO['writable']) {
276        msg('The current page is writable by you', 1);
277    } else {
278        msg('The current page is not writable by you', -1);
279    }
280
281    // Check for corrupted search index
282    $lengths = idx_listIndexLengths();
283    $index_corrupted = false;
284    foreach ($lengths as $length) {
285        if (count(idx_getIndex('w', $length)) !== count(idx_getIndex('i', $length))) {
286            $index_corrupted = true;
287            break;
288        }
289    }
290
291    foreach (idx_getIndex('metadata', '') as $index) {
292        if (count(idx_getIndex($index.'_w', '')) !== count(idx_getIndex($index.'_i', ''))) {
293            $index_corrupted = true;
294            break;
295        }
296    }
297
298    if($index_corrupted) {
299        msg(
300            'The search index is corrupted. It might produce wrong results and most
301                probably needs to be rebuilt. See
302                <a href="http://www.dokuwiki.org/faq:searchindex">faq:searchindex</a>
303                for ways to rebuild the search index.', -1
304        );
305    } elseif(!empty($lengths)) {
306        msg('The search index seems to be working', 1);
307    } else {
308        msg(
309            'The search index is empty. See
310                <a href="http://www.dokuwiki.org/faq:searchindex">faq:searchindex</a>
311                for help on how to fix the search index. If the default indexer
312                isn\'t used or the wiki is actually empty this is normal.'
313        );
314    }
315
316    // rough time check
317    $http = new DokuHTTPClient();
318    $http->max_redirect = 0;
319    $http->timeout = 3;
320    $http->sendRequest('http://www.dokuwiki.org', '', 'HEAD');
321    $now = time();
322    if(isset($http->resp_headers['date'])) {
323        $time = strtotime($http->resp_headers['date']);
324        $diff = $time - $now;
325
326        if(abs($diff) < 4) {
327            msg("Server time seems to be okay. Diff: {$diff}s", 1);
328        } else {
329            msg("Your server's clock seems to be out of sync!
330                 Consider configuring a sync with a NTP server.  Diff: {$diff}s");
331        }
332    }
333
334}
335
336/**
337 * Display a message to the user
338 *
339 * If HTTP headers were not sent yet the message is added
340 * to the global message array else it's printed directly
341 * using html_msgarea()
342 *
343 * Triggers INFOUTIL_MSG_SHOW
344 *
345 * @see    html_msgarea()
346 * @param string $message
347 * @param int    $lvl   -1 = error, 0 = info, 1 = success, 2 = notify
348 * @param string $line  line number
349 * @param string $file  file number
350 * @param int    $allow who's allowed to see the message, see MSG_* constants
351 */
352function msg($message,$lvl=0,$line='',$file='',$allow=MSG_PUBLIC){
353    global $MSG, $MSG_shown;
354    static $errors = [
355        -1 => 'error',
356        0 => 'info',
357        1 => 'success',
358        2 => 'notify',
359    ];
360
361    $msgdata = [
362        'msg' => $message,
363        'lvl' => $errors[$lvl],
364        'allow' => $allow,
365        'line' => $line,
366        'file' => $file,
367    ];
368
369    $evt = new Event('INFOUTIL_MSG_SHOW', $msgdata);
370    if ($evt->advise_before()) {
371        /* Show msg normally - event could suppress message show */
372        if($msgdata['line'] || $msgdata['file']) {
373            $basename = PhpString::basename($msgdata['file']);
374            $msgdata['msg'] .=' ['.$basename.':'.$msgdata['line'].']';
375        }
376
377        if(!isset($MSG)) $MSG = [];
378        $MSG[] = $msgdata;
379        if(isset($MSG_shown) || headers_sent()){
380            if(function_exists('html_msgarea')){
381                html_msgarea();
382            }else{
383                print "ERROR(".$msgdata['lvl'].") ".$msgdata['msg']."\n";
384            }
385            unset($GLOBALS['MSG']);
386        }
387    }
388    $evt->advise_after();
389    unset($evt);
390}
391/**
392 * Determine whether the current user is allowed to view the message
393 * in the $msg data structure
394 *
395 * @param  $msg   array    dokuwiki msg structure
396 *                         msg   => string, the message
397 *                         lvl   => int, level of the message (see msg() function)
398 *                         allow => int, flag used to determine who is allowed to see the message
399 *                                       see MSG_* constants
400 * @return bool
401 */
402function info_msg_allowed($msg){
403    global $INFO, $auth;
404
405    // is the message public? - everyone and anyone can see it
406    if (empty($msg['allow']) || ($msg['allow'] == MSG_PUBLIC)) return true;
407
408    // restricted msg, but no authentication
409    if (empty($auth)) return false;
410
411    switch ($msg['allow']){
412        case MSG_USERS_ONLY:
413            return !empty($INFO['userinfo']);
414
415        case MSG_MANAGERS_ONLY:
416            return $INFO['ismanager'];
417
418        case MSG_ADMINS_ONLY:
419            return $INFO['isadmin'];
420
421        default:
422            trigger_error('invalid msg allow restriction.  msg="'.$msg['msg'].'" allow='.$msg['allow'].'"',
423                          E_USER_WARNING);
424            return $INFO['isadmin'];
425    }
426}
427
428/**
429 * print debug messages
430 *
431 * little function to print the content of a var
432 *
433 * @author Andreas Gohr <andi@splitbrain.org>
434 *
435 * @param string $msg
436 * @param bool $hidden
437 */
438function dbg($msg,$hidden=false){
439    if($hidden){
440        echo "<!--\n";
441        print_r($msg);
442        echo "\n-->";
443    }else{
444        echo '<pre class="dbg">';
445        echo hsc(print_r($msg,true));
446        echo '</pre>';
447    }
448}
449
450/**
451 * Print info to debug log file
452 *
453 * @author Andreas Gohr <andi@splitbrain.org>
454 * @deprecated 2020-08-13
455 * @param string $msg
456 * @param string $header
457 */
458function dbglog($msg,$header=''){
459    dbg_deprecated('\\dokuwiki\\Logger');
460
461    // was the msg as single line string? use it as header
462    if($header === '' && is_string($msg) && strpos($msg, "\n") === false) {
463        $header = $msg;
464        $msg = '';
465    }
466
467    Logger::getInstance(Logger::LOG_DEBUG)->log(
468        $header, $msg
469    );
470}
471
472/**
473 * Log accesses to deprecated fucntions to the debug log
474 *
475 * @param string $alternative The function or method that should be used instead
476 * @triggers INFO_DEPRECATION_LOG
477 */
478function dbg_deprecated($alternative = '') {
479    DebugHelper::dbgDeprecatedFunction($alternative, 2);
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 = [];
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 = [];
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[] = '"'.$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