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