xref: /dokuwiki/inc/infoutils.php (revision 9e7aeeba3a317a962406508d5e039cc5c38fb310)
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 */
8
9use dokuwiki\HTTP\DokuHTTPClient;
10use dokuwiki\Search\MetadataIndex;
11use dokuwiki\Search\FulltextIndex;
12use dokuwiki\Utf8;
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        dbglog("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            dbglog("checkUpdateMessages(): unexpected HTTP response received");
51        }
52    }else{
53        dbglog("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 = array();
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        if ($date = shell_exec("git log -1 --pretty=format:'%cd' --date=short")) {
82            $version['date'] = hsc($date);
83        } else if (file_exists(DOKU_INC . '.git/HEAD')) {
84            // we cannot use git on the shell -- let's do it manually!
85            $headCommit = trim(file_get_contents(DOKU_INC . '.git/HEAD'));
86            if (strpos($headCommit, 'ref: ') === 0) {
87                // it is something like `ref: refs/heads/master`
88                $pathToHead = substr($headCommit, 5);
89                $headCommit = trim(file_get_contents(DOKU_INC . '.git/' . $pathToHead));
90            }
91            $subDir = substr($headCommit, 0, 2);
92            $fileName = substr($headCommit, 2);
93            $gitCommitObject = DOKU_INC . ".git/objects/$subDir/$fileName";
94            if (file_exists($gitCommitObject) && method_exists(zlib_decode)) {
95                $commit = zlib_decode(file_get_contents($gitCommitObject));
96                $committerLine = explode("\n", $commit)[3];
97                $committerData = explode(' ', $committerLine);
98                end($committerData);
99                $ts = prev($committerData);
100                if ($ts && $date = date('Y-m-d', $ts)) {
101                    $version['date'] = $date;
102                }
103            }
104        }
105    }else{
106        global $updateVersion;
107        $version['date'] = 'update version '.$updateVersion;
108        $version['type'] = 'snapshot?';
109    }
110    return $version;
111}
112
113/**
114 * Return DokuWiki's version (as a string)
115 *
116 * @author Anika Henke <anika@selfthinker.org>
117 */
118function getVersion(){
119    $version = getVersionData();
120    return $version['type'].' '.$version['date'];
121}
122
123/**
124 * Run a few sanity checks
125 *
126 * @author Andreas Gohr <andi@splitbrain.org>
127 */
128function check(){
129    global $conf;
130    global $INFO;
131    /* @var Input $INPUT */
132    global $INPUT;
133
134    if ($INFO['isadmin'] || $INFO['ismanager']){
135        msg('DokuWiki version: '.getVersion(),1);
136
137        if(version_compare(phpversion(),'7.2.0','<')){
138            msg('Your PHP version is too old ('.phpversion().' vs. 7.2+ needed)',-1);
139        }else{
140            msg('PHP version '.phpversion(),1);
141        }
142    } else {
143        if(version_compare(phpversion(),'7.2.0','<')){
144            msg('Your PHP version is too old',-1);
145        }
146    }
147
148    $mem = (int) php_to_byte(ini_get('memory_limit'));
149    if($mem){
150        if ($mem === -1) {
151            msg('PHP memory is unlimited', 1);
152        } else if ($mem < 16777216) {
153            msg('PHP is limited to less than 16MB RAM (' . filesize_h($mem) . ').
154            Increase memory_limit in php.ini', -1);
155        } else if ($mem < 20971520) {
156            msg('PHP is limited to less than 20MB RAM (' . filesize_h($mem) . '),
157                you might encounter problems with bigger pages. Increase memory_limit in php.ini', -1);
158        } else if ($mem < 33554432) {
159            msg('PHP is limited to less than 32MB RAM (' . filesize_h($mem) . '),
160                but that should be enough in most cases. If not, increase memory_limit in php.ini', 0);
161        } else {
162            msg('More than 32MB RAM (' . filesize_h($mem) . ') available.', 1);
163        }
164    }
165
166    if(is_writable($conf['changelog'])){
167        msg('Changelog is writable',1);
168    }else{
169        if (file_exists($conf['changelog'])) {
170            msg('Changelog is not writable',-1);
171        }
172    }
173
174    if (isset($conf['changelog_old']) && file_exists($conf['changelog_old'])) {
175        msg('Old changelog exists', 0);
176    }
177
178    if (file_exists($conf['changelog'].'_failed')) {
179        msg('Importing old changelog failed', -1);
180    } else if (file_exists($conf['changelog'].'_importing')) {
181        msg('Importing old changelog now.', 0);
182    } else if (file_exists($conf['changelog'].'_import_ok')) {
183        msg('Old changelog imported', 1);
184        if (!plugin_isdisabled('importoldchangelog')) {
185            msg('Importoldchangelog plugin not disabled after import', -1);
186        }
187    }
188
189    if(is_writable(DOKU_CONF)){
190        msg('conf directory is writable',1);
191    }else{
192        msg('conf directory is not writable',-1);
193    }
194
195    if($conf['authtype'] == 'plain'){
196        global $config_cascade;
197        if(is_writable($config_cascade['plainauth.users']['default'])){
198            msg('conf/users.auth.php is writable',1);
199        }else{
200            msg('conf/users.auth.php is not writable',0);
201        }
202    }
203
204    if(function_exists('mb_strpos')){
205        if(defined('UTF8_NOMBSTRING')){
206            msg('mb_string extension is available but will not be used',0);
207        }else{
208            msg('mb_string extension is available and will be used',1);
209            if(ini_get('mbstring.func_overload') != 0){
210                msg('mb_string function overloading is enabled, this will cause problems and should be disabled',-1);
211            }
212        }
213    }else{
214        msg('mb_string extension not available - PHP only replacements will be used',0);
215    }
216
217    if (!UTF8_PREGSUPPORT) {
218        msg('PHP is missing UTF-8 support in Perl-Compatible Regular Expressions (PCRE)', -1);
219    }
220    if (!UTF8_PROPERTYSUPPORT) {
221        msg('PHP is missing Unicode properties support in Perl-Compatible Regular Expressions (PCRE)', -1);
222    }
223
224    $loc = setlocale(LC_ALL, 0);
225    if(!$loc){
226        msg('No valid locale is set for your PHP setup. You should fix this',-1);
227    }elseif(stripos($loc,'utf') === false){
228        msg('Your locale <code>'.hsc($loc).'</code> seems not to be a UTF-8 locale,
229             you should fix this if you encounter problems.',0);
230    }else{
231        msg('Valid locale '.hsc($loc).' found.', 1);
232    }
233
234    if($conf['allowdebug']){
235        msg('Debugging support is enabled. If you don\'t need it you should set $conf[\'allowdebug\'] = 0',-1);
236    }else{
237        msg('Debugging support is disabled',1);
238    }
239
240    if($INFO['userinfo']['name']){
241        msg('You are currently logged in as '.$INPUT->server->str('REMOTE_USER').' ('.$INFO['userinfo']['name'].')',0);
242        msg('You are part of the groups '.implode(', ', $INFO['userinfo']['grps']),0);
243    }else{
244        msg('You are currently not logged in',0);
245    }
246
247    msg('Your current permission for this page is '.$INFO['perm'],0);
248
249    if (file_exists($INFO['filepath']) && is_writable($INFO['filepath'])) {
250        msg('The current page is writable by the webserver', 1);
251    } elseif (!file_exists($INFO['filepath']) && is_writable(dirname($INFO['filepath']))) {
252        msg('The current page can be created by the webserver', 1);
253    } else {
254        msg('The current page is not writable by the webserver', -1);
255    }
256
257    if ($INFO['writable']) {
258        msg('The current page is writable by you', 1);
259    } else {
260        msg('The current page is not writable by you', -1);
261    }
262
263    // Check for corrupted fulltext search index
264    $FulltextIndex = new FulltextIndex();
265    $lengths = $FulltextIndex->listIndexLengths();
266    $index_corrupted = false;
267    foreach ($lengths as $length) {
268        if (count($FulltextIndex->getIndex('w', $length)) != count($FulltextIndex->getIndex('i', $length))) {
269            $index_corrupted = true;
270            break;
271        }
272    }
273
274    // Check for corrupted metadata index
275    $MetadataIndex = new MetadataIndex();
276    foreach ($MetadataIndex->getIndex('metadata', '') as $name) {
277        if (count($MetadataIndex->getIndex($name.'_w', '')) != count($MetadataIndex->getIndex($name.'_i', ''))) {
278            $index_corrupted = true;
279            break;
280        }
281    }
282
283    if($index_corrupted) {
284        msg(
285            'The search index is corrupted. It might produce wrong results and most
286                probably needs to be rebuilt. See
287                <a href="http://www.dokuwiki.org/faq:searchindex">faq:searchindex</a>
288                for ways to rebuild the search index.', -1
289        );
290    } elseif(!empty($lengths)) {
291        msg('The search index seems to be working', 1);
292    } else {
293        msg(
294            'The search index is empty. See
295                <a href="http://www.dokuwiki.org/faq:searchindex">faq:searchindex</a>
296                for help on how to fix the search index. If the default indexer
297                isn\'t used or the wiki is actually empty this is normal.'
298        );
299    }
300
301    // rough time check
302    $http = new DokuHTTPClient();
303    $http->max_redirect = 0;
304    $http->timeout = 3;
305    $http->sendRequest('http://www.dokuwiki.org', '', 'HEAD');
306    $now = time();
307    if(isset($http->resp_headers['date'])) {
308        $time = strtotime($http->resp_headers['date']);
309        $diff = $time - $now;
310
311        if(abs($diff) < 4) {
312            msg("Server time seems to be okay. Diff: {$diff}s", 1);
313        } else {
314            msg("Your server's clock seems to be out of sync!
315                 Consider configuring a sync with a NTP server.  Diff: {$diff}s");
316        }
317    }
318
319}
320
321/**
322 * Display a message to the user
323 *
324 * If HTTP headers were not sent yet the message is added
325 * to the global message array else it's printed directly
326 * using html_msgarea()
327 *
328 * Triggers INFOUTIL_MSG_SHOW
329 *
330 * @see    html_msgarea()
331 * @param string $message
332 * @param int    $lvl   -1 = error, 0 = info, 1 = success, 2 = notify
333 * @param string $line  line number
334 * @param string $file  file number
335 * @param int    $allow who's allowed to see the message, see MSG_* constants
336 */
337function msg($message,$lvl=0,$line='',$file='',$allow=MSG_PUBLIC){
338    global $MSG, $MSG_shown;
339    static $errors = [
340        -1 => 'error',
341        0 => 'info',
342        1 => 'success',
343        2 => 'notify',
344    ];
345
346    $msgdata = [
347        'msg' => $message,
348        'lvl' => $errors[$lvl],
349        'allow' => $allow,
350        'line' => $line,
351        'file' => $file,
352    ];
353
354    $evt = new \dokuwiki\Extension\Event('INFOUTIL_MSG_SHOW', $msgdata);
355    if ($evt->advise_before()) {
356        /* Show msg normally - event could suppress message show */
357        if($msgdata['line'] || $msgdata['file']) {
358            $basename = \dokuwiki\Utf8\PhpString::basename($msgdata['file']);
359            $msgdata['msg'] .=' ['.$basename.':'.$msgdata['line'].']';
360        }
361
362        if(!isset($MSG)) $MSG = array();
363        $MSG[] = $msgdata;
364        if(isset($MSG_shown) || headers_sent()){
365            if(function_exists('html_msgarea')){
366                html_msgarea();
367            }else{
368                print "ERROR(".$msgdata['lvl'].") ".$msgdata['msg']."\n";
369            }
370            unset($GLOBALS['MSG']);
371        }
372    }
373    $evt->advise_after();
374    unset($evt);
375}
376/**
377 * Determine whether the current user is allowed to view the message
378 * in the $msg data structure
379 *
380 * @param  $msg   array    dokuwiki msg structure
381 *                         msg   => string, the message
382 *                         lvl   => int, level of the message (see msg() function)
383 *                         allow => int, flag used to determine who is allowed to see the message
384 *                                       see MSG_* constants
385 * @return bool
386 */
387function info_msg_allowed($msg){
388    global $INFO, $auth;
389
390    // is the message public? - everyone and anyone can see it
391    if (empty($msg['allow']) || ($msg['allow'] == MSG_PUBLIC)) return true;
392
393    // restricted msg, but no authentication
394    if (empty($auth)) return false;
395
396    switch ($msg['allow']){
397        case MSG_USERS_ONLY:
398            return !empty($INFO['userinfo']);
399
400        case MSG_MANAGERS_ONLY:
401            return $INFO['ismanager'];
402
403        case MSG_ADMINS_ONLY:
404            return $INFO['isadmin'];
405
406        default:
407            trigger_error('invalid msg allow restriction.  msg="'.$msg['msg'].'" allow='.$msg['allow'].'"',
408                          E_USER_WARNING);
409            return $INFO['isadmin'];
410    }
411
412    return false;
413}
414
415/**
416 * print debug messages
417 *
418 * little function to print the content of a var
419 *
420 * @author Andreas Gohr <andi@splitbrain.org>
421 *
422 * @param string $msg
423 * @param bool $hidden
424 */
425function dbg($msg,$hidden=false){
426    if($hidden){
427        echo "<!--\n";
428        print_r($msg);
429        echo "\n-->";
430    }else{
431        echo '<pre class="dbg">';
432        echo hsc(print_r($msg,true));
433        echo '</pre>';
434    }
435}
436
437/**
438 * Print info to a log file
439 *
440 * @author Andreas Gohr <andi@splitbrain.org>
441 *
442 * @param string $msg
443 * @param string $header
444 */
445function dbglog($msg,$header=''){
446    global $conf;
447    /* @var Input $INPUT */
448    global $INPUT;
449
450    // The debug log isn't automatically cleaned thus only write it when
451    // debugging has been enabled by the user.
452    if($conf['allowdebug'] !== 1) return;
453    if(is_object($msg) || is_array($msg)){
454        $msg = print_r($msg,true);
455    }
456
457    if($header) $msg = "$header\n$msg";
458
459    $file = $conf['cachedir'].'/debug.log';
460    $fh = fopen($file,'a');
461    if($fh){
462        fwrite($fh,date('H:i:s ').$INPUT->server->str('REMOTE_ADDR').': '.$msg."\n");
463        fclose($fh);
464    }
465}
466
467/**
468 * Log accesses to deprecated fucntions to the debug log
469 *
470 * @param string $alternative The function or method that should be used instead
471 * @triggers INFO_DEPRECATION_LOG
472 */
473function dbg_deprecated($alternative = '') {
474    \dokuwiki\Debug\DebugHelper::dbgDeprecatedFunction($alternative, 2);
475}
476
477/**
478 * Print a reversed, prettyprinted backtrace
479 *
480 * @author Gary Owen <gary_owen@bigfoot.com>
481 */
482function dbg_backtrace(){
483    // Get backtrace
484    $backtrace = debug_backtrace();
485
486    // Unset call to debug_print_backtrace
487    array_shift($backtrace);
488
489    // Iterate backtrace
490    $calls = array();
491    $depth = count($backtrace) - 1;
492    foreach ($backtrace as $i => $call) {
493        $location = $call['file'] . ':' . $call['line'];
494        $function = (isset($call['class'])) ?
495            $call['class'] . $call['type'] . $call['function'] : $call['function'];
496
497        $params = array();
498        if (isset($call['args'])){
499            foreach($call['args'] as $arg){
500                if(is_object($arg)){
501                    $params[] = '[Object '.get_class($arg).']';
502                }elseif(is_array($arg)){
503                    $params[] = '[Array]';
504                }elseif(is_null($arg)){
505                    $params[] = '[NULL]';
506                }else{
507                    $params[] = (string) '"'.$arg.'"';
508                }
509            }
510        }
511        $params = implode(', ',$params);
512
513        $calls[$depth - $i] = sprintf('%s(%s) called at %s',
514                $function,
515                str_replace("\n", '\n', $params),
516                $location);
517    }
518    ksort($calls);
519
520    return implode("\n", $calls);
521}
522
523/**
524 * Remove all data from an array where the key seems to point to sensitive data
525 *
526 * This is used to remove passwords, mail addresses and similar data from the
527 * debug output
528 *
529 * @author Andreas Gohr <andi@splitbrain.org>
530 *
531 * @param array $data
532 */
533function debug_guard(&$data){
534    foreach($data as $key => $value){
535        if(preg_match('/(notify|pass|auth|secret|ftp|userinfo|token|buid|mail|proxy)/i',$key)){
536            $data[$key] = '***';
537            continue;
538        }
539        if(is_array($value)) debug_guard($data[$key]);
540    }
541}
542