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