xref: /dokuwiki/inc/infoutils.php (revision 9664a2b801ce91ae3707306f01fb4cad528b1258)
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        dbglog("checkUpdatesMessages(): downloading messages.txt");
29        $http = new DokuHTTPClient();
30        $http->timeout = 8;
31        $data = $http->get(DOKU_MESSAGEURL.$updateVersion);
32        io_saveFile($cf,$data);
33        @touch($cf);
34    }else{
35        dbglog("checkUpdatesMessages(): 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        $version['date'] = 'unknown';
81        $version['type'] = 'snapshot?';
82    }
83    return $version;
84}
85
86/**
87 * Return DokuWiki's version (as a string)
88 *
89 * @author Anika Henke <anika@selfthinker.org>
90 */
91function getVersion(){
92    $version = getVersionData();
93    return $version['type'].' '.$version['date'];
94}
95
96/**
97 * Run a few sanity checks
98 *
99 * @author Andreas Gohr <andi@splitbrain.org>
100 */
101function check(){
102    global $conf;
103    global $INFO;
104
105    if ($INFO['isadmin'] || $INFO['ismanager']){
106        msg('DokuWiki version: '.getVersion(),1);
107    }
108
109    if(version_compare(phpversion(),'5.1.2','<')){
110        msg('Your PHP version is too old ('.phpversion().' vs. 5.1.2+ needed)',-1);
111    }else{
112        msg('PHP version '.phpversion(),1);
113    }
114
115    $mem = (int) php_to_byte(ini_get('memory_limit'));
116    if($mem){
117        if($mem < 16777216){
118            msg('PHP is limited to less than 16MB RAM ('.$mem.' bytes). Increase memory_limit in php.ini',-1);
119        }elseif($mem < 20971520){
120            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);
121        }elseif($mem < 33554432){
122            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);
123        }else{
124            msg('More than 32MB RAM ('.$mem.' bytes) available.',1);
125        }
126    }
127
128    if(is_writable($conf['changelog'])){
129        msg('Changelog is writable',1);
130    }else{
131        if (@file_exists($conf['changelog'])) {
132            msg('Changelog is not writable',-1);
133        }
134    }
135
136    if (isset($conf['changelog_old']) && @file_exists($conf['changelog_old'])) {
137        msg('Old changelog exists', 0);
138    }
139
140    if (@file_exists($conf['changelog'].'_failed')) {
141        msg('Importing old changelog failed', -1);
142    } else if (@file_exists($conf['changelog'].'_importing')) {
143        msg('Importing old changelog now.', 0);
144    } else if (@file_exists($conf['changelog'].'_import_ok')) {
145        msg('Old changelog imported', 1);
146        if (!plugin_isdisabled('importoldchangelog')) {
147            msg('Importoldchangelog plugin not disabled after import', -1);
148        }
149    }
150
151    if(is_writable($conf['datadir'])){
152        msg('Datadir is writable',1);
153    }else{
154        msg('Datadir is not writable',-1);
155    }
156
157    if(is_writable($conf['olddir'])){
158        msg('Attic is writable',1);
159    }else{
160        msg('Attic is not writable',-1);
161    }
162
163    if(is_writable($conf['mediadir'])){
164        msg('Mediadir is writable',1);
165    }else{
166        msg('Mediadir is not writable',-1);
167    }
168
169    if(is_writable($conf['cachedir'])){
170        msg('Cachedir is writable',1);
171    }else{
172        msg('Cachedir is not writable',-1);
173    }
174
175    if(is_writable($conf['lockdir'])){
176        msg('Lockdir is writable',1);
177    }else{
178        msg('Lockdir is not writable',-1);
179    }
180
181    if(is_writable(DOKU_CONF)){
182        msg('conf directory is writable',1);
183    }else{
184        msg('conf directory is not writable',-1);
185    }
186
187    if($conf['authtype'] == 'plain'){
188        global $config_cascade;
189        if(is_writable($config_cascade['plainauth.users']['default'])){
190            msg('conf/users.auth.php is writable',1);
191        }else{
192            msg('conf/users.auth.php is not writable',0);
193        }
194    }
195
196    if(function_exists('mb_strpos')){
197        if(defined('UTF8_NOMBSTRING')){
198            msg('mb_string extension is available but will not be used',0);
199        }else{
200            msg('mb_string extension is available and will be used',1);
201            if(ini_get('mbstring.func_overload') != 0){
202                msg('mb_string function overloading is enabled, this will cause problems and should be disabled',-1);
203            }
204        }
205    }else{
206        msg('mb_string extension not available - PHP only replacements will be used',0);
207    }
208
209    if($conf['allowdebug']){
210        msg('Debugging support is enabled. If you don\'t need it you should set $conf[\'allowdebug\'] = 0',-1);
211    }else{
212        msg('Debugging support is disabled',1);
213    }
214
215    if($INFO['userinfo']['name']){
216        msg('You are currently logged in as '.$_SERVER['REMOTE_USER'].' ('.$INFO['userinfo']['name'].')',0);
217        msg('You are part of the groups '.join($INFO['userinfo']['grps'],', '),0);
218    }else{
219        msg('You are currently not logged in',0);
220    }
221
222    msg('Your current permission for this page is '.$INFO['perm'],0);
223
224    if(is_writable($INFO['filepath'])){
225        msg('The current page is writable by the webserver',0);
226    }else{
227        msg('The current page is not writable by the webserver',0);
228    }
229
230    if($INFO['writable']){
231        msg('The current page is writable by you',0);
232    }else{
233        msg('The current page is not writable by you',0);
234    }
235
236    $check = wl('','',true).'data/_dummy';
237    $http = new DokuHTTPClient();
238    $http->timeout = 6;
239    $res = $http->get($check);
240    if(strpos($res,'data directory') !== false){
241        msg('It seems like the data directory is accessible from the web.
242                Make sure this directory is properly protected
243                (See <a href="http://www.dokuwiki.org/security">security</a>)',-1);
244    }elseif($http->status == 404 || $http->status == 403){
245        msg('The data directory seems to be properly protected',1);
246    }else{
247        msg('Failed to check if the data directory is accessible from the web.
248                Make sure this directory is properly protected
249                (See <a href="http://www.dokuwiki.org/security">security</a>)',-1);
250    }
251
252    // Check for corrupted search index
253    $lengths = idx_listIndexLengths();
254    $index_corrupted = false;
255    foreach ($lengths as $length) {
256        if (count(idx_getIndex('w', $length)) != count(idx_getIndex('i', $length))) {
257            $index_corrupted = true;
258            break;
259        }
260    }
261
262    foreach (idx_getIndex('metadata', '') as $index) {
263        if (count(idx_getIndex($index.'_w', '')) != count(idx_getIndex($index.'_i', ''))) {
264            $index_corrupted = true;
265            break;
266        }
267    }
268
269    if ($index_corrupted)
270        msg('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    elseif (!empty($lengths))
275        msg('The search index seems to be working', 1);
276    else
277        msg('The search index is empty. See
278                <a href="http://www.dokuwiki.org/faq:searchindex">faq:searchindex</a>
279                for help on how to fix the search index. If the default indexer
280                isn\'t used or the wiki is actually empty this is normal.');
281}
282
283/**
284 * print a message
285 *
286 * If HTTP headers were not sent yet the message is added
287 * to the global message array else it's printed directly
288 * using html_msgarea()
289 *
290 *
291 * Levels can be:
292 *
293 * -1 error
294 *  0 info
295 *  1 success
296 *
297 * @author Andreas Gohr <andi@splitbrain.org>
298 * @see    html_msgarea
299 */
300function msg($message,$lvl=0,$line='',$file=''){
301    global $MSG, $MSG_shown;
302    $errors[-1] = 'error';
303    $errors[0]  = 'info';
304    $errors[1]  = 'success';
305    $errors[2]  = 'notify';
306
307    if($line || $file) $message.=' ['.basename($file).':'.$line.']';
308
309    if(!isset($MSG)) $MSG = array();
310    $MSG[]=array('lvl' => $errors[$lvl], 'msg' => $message);
311    if(isset($MSG_shown) || headers_sent()){
312        if(function_exists('html_msgarea')){
313            html_msgarea();
314        }else{
315            print "ERROR($lvl) $message";
316        }
317        unset($GLOBALS['MSG']);
318    }
319}
320
321/**
322 * print debug messages
323 *
324 * little function to print the content of a var
325 *
326 * @author Andreas Gohr <andi@splitbrain.org>
327 */
328function dbg($msg,$hidden=false){
329    if($hidden){
330        echo "<!--\n";
331        print_r($msg);
332        echo "\n-->";
333    }else{
334        echo '<pre class="dbg">';
335        echo hsc(print_r($msg,true));
336        echo '</pre>';
337    }
338}
339
340/**
341 * Print info to a log file
342 *
343 * @author Andreas Gohr <andi@splitbrain.org>
344 */
345function dbglog($msg,$header=''){
346    global $conf;
347    // The debug log isn't automatically cleaned thus only write it when
348    // debugging has been enabled by the user.
349    if($conf['allowdebug'] !== 1) return;
350    if(is_object($msg) || is_array($msg)){
351        $msg = print_r($msg,true);
352    }
353
354    if($header) $msg = "$header\n$msg";
355
356    $file = $conf['cachedir'].'/debug.log';
357    $fh = fopen($file,'a');
358    if($fh){
359        fwrite($fh,date('H:i:s ').$_SERVER['REMOTE_ADDR'].': '.$msg."\n");
360        fclose($fh);
361    }
362}
363
364/**
365 * Print a reversed, prettyprinted backtrace
366 *
367 * @author Gary Owen <gary_owen@bigfoot.com>
368 */
369function dbg_backtrace(){
370    // Get backtrace
371    $backtrace = debug_backtrace();
372
373    // Unset call to debug_print_backtrace
374    array_shift($backtrace);
375
376    // Iterate backtrace
377    $calls = array();
378    $depth = count($backtrace) - 1;
379    foreach ($backtrace as $i => $call) {
380        $location = $call['file'] . ':' . $call['line'];
381        $function = (isset($call['class'])) ?
382            $call['class'] . $call['type'] . $call['function'] : $call['function'];
383
384        $params = array();
385        if (isset($call['args'])){
386            foreach($call['args'] as $arg){
387                if(is_object($arg)){
388                    $params[] = '[Object '.get_class($arg).']';
389                }elseif(is_array($arg)){
390                    $params[] = '[Array]';
391                }elseif(is_null($arg)){
392                    $param[] = '[NULL]';
393                }else{
394                    $params[] = (string) '"'.$arg.'"';
395                }
396            }
397        }
398        $params = implode(', ',$params);
399
400        $calls[$depth - $i] = sprintf('%s(%s) called at %s',
401                $function,
402                str_replace("\n", '\n', $params),
403                $location);
404    }
405    ksort($calls);
406
407    return implode("\n", $calls);
408}
409
410/**
411 * Remove all data from an array where the key seems to point to sensitive data
412 *
413 * This is used to remove passwords, mail addresses and similar data from the
414 * debug output
415 *
416 * @author Andreas Gohr <andi@splitbrain.org>
417 */
418function debug_guard(&$data){
419    foreach($data as $key => $value){
420        if(preg_match('/(notify|pass|auth|secret|ftp|userinfo|token|buid|mail|proxy)/i',$key)){
421            $data[$key] = '***';
422            continue;
423        }
424        if(is_array($value)) debug_guard($data[$key]);
425    }
426}
427