xref: /dokuwiki/inc/infoutils.php (revision 8daa2c9f98ef02857c1d92f2f226288c313146a7)
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
106    if ($INFO['isadmin'] || $INFO['ismanager']){
107        msg('DokuWiki version: '.getVersion(),1);
108
109        if(version_compare(phpversion(),'5.2.0','<')){
110            msg('Your PHP version is too old ('.phpversion().' vs. 5.2.0+ needed)',-1);
111        }else{
112            msg('PHP version '.phpversion(),1);
113        }
114    } else {
115        if(version_compare(phpversion(),'5.2.0','<')){
116            msg('Your PHP version is too old',-1);
117        }
118    }
119
120    $mem = (int) php_to_byte(ini_get('memory_limit'));
121    if($mem){
122        if($mem < 16777216){
123            msg('PHP is limited to less than 16MB RAM ('.$mem.' bytes). Increase memory_limit in php.ini',-1);
124        }elseif($mem < 20971520){
125            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);
126        }elseif($mem < 33554432){
127            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);
128        }else{
129            msg('More than 32MB RAM ('.$mem.' bytes) available.',1);
130        }
131    }
132
133    if(is_writable($conf['changelog'])){
134        msg('Changelog is writable',1);
135    }else{
136        if (@file_exists($conf['changelog'])) {
137            msg('Changelog is not writable',-1);
138        }
139    }
140
141    if (isset($conf['changelog_old']) && @file_exists($conf['changelog_old'])) {
142        msg('Old changelog exists', 0);
143    }
144
145    if (@file_exists($conf['changelog'].'_failed')) {
146        msg('Importing old changelog failed', -1);
147    } else if (@file_exists($conf['changelog'].'_importing')) {
148        msg('Importing old changelog now.', 0);
149    } else if (@file_exists($conf['changelog'].'_import_ok')) {
150        msg('Old changelog imported', 1);
151        if (!plugin_isdisabled('importoldchangelog')) {
152            msg('Importoldchangelog plugin not disabled after import', -1);
153        }
154    }
155
156    if(is_writable(DOKU_CONF)){
157        msg('conf directory is writable',1);
158    }else{
159        msg('conf directory is not writable',-1);
160    }
161
162    if($conf['authtype'] == 'plain'){
163        global $config_cascade;
164        if(is_writable($config_cascade['plainauth.users']['default'])){
165            msg('conf/users.auth.php is writable',1);
166        }else{
167            msg('conf/users.auth.php is not writable',0);
168        }
169    }
170
171    if(function_exists('mb_strpos')){
172        if(defined('UTF8_NOMBSTRING')){
173            msg('mb_string extension is available but will not be used',0);
174        }else{
175            msg('mb_string extension is available and will be used',1);
176            if(ini_get('mbstring.func_overload') != 0){
177                msg('mb_string function overloading is enabled, this will cause problems and should be disabled',-1);
178            }
179        }
180    }else{
181        msg('mb_string extension not available - PHP only replacements will be used',0);
182    }
183
184    if (!UTF8_PREGSUPPORT) {
185        msg('PHP is missing UTF-8 support in Perl-Compatible Regular Expressions (PCRE)', -1);
186    }
187    if (!UTF8_PROPERTYSUPPORT) {
188        msg('PHP is missing Unicode properties support in Perl-Compatible Regular Expressions (PCRE)', -1);
189    }
190
191    $loc = setlocale(LC_ALL, 0);
192    if(!$loc){
193        msg('No valid locale is set for your PHP setup. You should fix this',-1);
194    }elseif(stripos($loc,'utf') === false){
195        msg('Your locale <code>'.hsc($loc).'</code> seems not to be a UTF-8 locale, you should fix this if you encounter problems.',0);
196    }else{
197        msg('Valid locale '.hsc($loc).' found.', 1);
198    }
199
200    if($conf['allowdebug']){
201        msg('Debugging support is enabled. If you don\'t need it you should set $conf[\'allowdebug\'] = 0',-1);
202    }else{
203        msg('Debugging support is disabled',1);
204    }
205
206    if($INFO['userinfo']['name']){
207        msg('You are currently logged in as '.$_SERVER['REMOTE_USER'].' ('.$INFO['userinfo']['name'].')',0);
208        msg('You are part of the groups '.join($INFO['userinfo']['grps'],', '),0);
209    }else{
210        msg('You are currently not logged in',0);
211    }
212
213    msg('Your current permission for this page is '.$INFO['perm'],0);
214
215    if(is_writable($INFO['filepath'])){
216        msg('The current page is writable by the webserver',0);
217    }else{
218        msg('The current page is not writable by the webserver',0);
219    }
220
221    if($INFO['writable']){
222        msg('The current page is writable by you',0);
223    }else{
224        msg('The current page is not writable by you',0);
225    }
226
227    // Check for corrupted search index
228    $lengths = idx_listIndexLengths();
229    $index_corrupted = false;
230    foreach ($lengths as $length) {
231        if (count(idx_getIndex('w', $length)) != count(idx_getIndex('i', $length))) {
232            $index_corrupted = true;
233            break;
234        }
235    }
236
237    foreach (idx_getIndex('metadata', '') as $index) {
238        if (count(idx_getIndex($index.'_w', '')) != count(idx_getIndex($index.'_i', ''))) {
239            $index_corrupted = true;
240            break;
241        }
242    }
243
244    if ($index_corrupted)
245        msg('The search index is corrupted. It might produce wrong results and most
246                probably needs to be rebuilt. See
247                <a href="http://www.dokuwiki.org/faq:searchindex">faq:searchindex</a>
248                for ways to rebuild the search index.', -1);
249    elseif (!empty($lengths))
250        msg('The search index seems to be working', 1);
251    else
252        msg('The search index is empty. See
253                <a href="http://www.dokuwiki.org/faq:searchindex">faq:searchindex</a>
254                for help on how to fix the search index. If the default indexer
255                isn\'t used or the wiki is actually empty this is normal.');
256}
257
258/**
259 * print a message
260 *
261 * If HTTP headers were not sent yet the message is added
262 * to the global message array else it's printed directly
263 * using html_msgarea()
264 *
265 *
266 * Levels can be:
267 *
268 * -1 error
269 *  0 info
270 *  1 success
271 *
272 * @author Andreas Gohr <andi@splitbrain.org>
273 * @see    html_msgarea
274 */
275
276define('MSG_PUBLIC', 0);
277define('MSG_USERS_ONLY', 1);
278define('MSG_MANAGERS_ONLY',2);
279define('MSG_ADMINS_ONLY',4);
280
281function msg($message,$lvl=0,$line='',$file='',$allow=MSG_PUBLIC){
282    global $MSG, $MSG_shown;
283    $errors[-1] = 'error';
284    $errors[0]  = 'info';
285    $errors[1]  = 'success';
286    $errors[2]  = 'notify';
287
288    if($line || $file) $message.=' ['.utf8_basename($file).':'.$line.']';
289
290    if(!isset($MSG)) $MSG = array();
291    $MSG[]=array('lvl' => $errors[$lvl], 'msg' => $message, 'allow' => $allow);
292    if(isset($MSG_shown) || headers_sent()){
293        if(function_exists('html_msgarea')){
294            html_msgarea();
295        }else{
296            print "ERROR($lvl) $message";
297        }
298        unset($GLOBALS['MSG']);
299    }
300}
301/**
302 * Determine whether the current user is allowed to view the message
303 * in the $msg data structure
304 *
305 * @param  $msg   array    dokuwiki msg structure
306 *                         msg   => string, the message
307 *                         lvl   => int, level of the message (see msg() function)
308 *                         allow => int, flag used to determine who is allowed to see the message
309 *                                       see MSG_* constants
310 */
311function info_msg_allowed($msg){
312    global $INFO, $auth;
313
314    // is the message public? - everyone and anyone can see it
315    if (empty($msg['allow']) || ($msg['allow'] == MSG_PUBLIC)) return true;
316
317    // restricted msg, but no authentication
318    if (empty($auth)) return false;
319
320    switch ($msg['allow']){
321        case MSG_USERS_ONLY:
322            return !empty($INFO['userinfo']);
323
324        case MSG_MANAGERS_ONLY:
325            return $INFO['ismanager'];
326
327        case MSG_ADMINS_ONLY:
328            return $INFO['isadmin'];
329
330        default:
331            trigger_error('invalid msg allow restriction.  msg="'.$msg['msg'].'" allow='.$msg['allow'].'"', E_USER_WARNING);
332            return $INFO['isadmin'];
333    }
334
335    return false;
336}
337
338/**
339 * print debug messages
340 *
341 * little function to print the content of a var
342 *
343 * @author Andreas Gohr <andi@splitbrain.org>
344 */
345function dbg($msg,$hidden=false){
346    if($hidden){
347        echo "<!--\n";
348        print_r($msg);
349        echo "\n-->";
350    }else{
351        echo '<pre class="dbg">';
352        echo hsc(print_r($msg,true));
353        echo '</pre>';
354    }
355}
356
357/**
358 * Print info to a log file
359 *
360 * @author Andreas Gohr <andi@splitbrain.org>
361 */
362function dbglog($msg,$header=''){
363    global $conf;
364    // The debug log isn't automatically cleaned thus only write it when
365    // debugging has been enabled by the user.
366    if($conf['allowdebug'] !== 1) return;
367    if(is_object($msg) || is_array($msg)){
368        $msg = print_r($msg,true);
369    }
370
371    if($header) $msg = "$header\n$msg";
372
373    $file = $conf['cachedir'].'/debug.log';
374    $fh = fopen($file,'a');
375    if($fh){
376        fwrite($fh,date('H:i:s ').$_SERVER['REMOTE_ADDR'].': '.$msg."\n");
377        fclose($fh);
378    }
379}
380
381/**
382 * Print a reversed, prettyprinted backtrace
383 *
384 * @author Gary Owen <gary_owen@bigfoot.com>
385 */
386function dbg_backtrace(){
387    // Get backtrace
388    $backtrace = debug_backtrace();
389
390    // Unset call to debug_print_backtrace
391    array_shift($backtrace);
392
393    // Iterate backtrace
394    $calls = array();
395    $depth = count($backtrace) - 1;
396    foreach ($backtrace as $i => $call) {
397        $location = $call['file'] . ':' . $call['line'];
398        $function = (isset($call['class'])) ?
399            $call['class'] . $call['type'] . $call['function'] : $call['function'];
400
401        $params = array();
402        if (isset($call['args'])){
403            foreach($call['args'] as $arg){
404                if(is_object($arg)){
405                    $params[] = '[Object '.get_class($arg).']';
406                }elseif(is_array($arg)){
407                    $params[] = '[Array]';
408                }elseif(is_null($arg)){
409                    $param[] = '[NULL]';
410                }else{
411                    $params[] = (string) '"'.$arg.'"';
412                }
413            }
414        }
415        $params = implode(', ',$params);
416
417        $calls[$depth - $i] = sprintf('%s(%s) called at %s',
418                $function,
419                str_replace("\n", '\n', $params),
420                $location);
421    }
422    ksort($calls);
423
424    return implode("\n", $calls);
425}
426
427/**
428 * Remove all data from an array where the key seems to point to sensitive data
429 *
430 * This is used to remove passwords, mail addresses and similar data from the
431 * debug output
432 *
433 * @author Andreas Gohr <andi@splitbrain.org>
434 */
435function debug_guard(&$data){
436    foreach($data as $key => $value){
437        if(preg_match('/(notify|pass|auth|secret|ftp|userinfo|token|buid|mail|proxy)/i',$key)){
438            $data[$key] = '***';
439            continue;
440        }
441        if(is_array($value)) debug_guard($data[$key]);
442    }
443}
444