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