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