4 * Copyright (C) 1999, 2000, 2001, 2002 $ThePhpWikiProgrammingTeam
5 * Copyright 2008-2009 Marc-Etienne Vargenau, Alcatel-Lucent
7 * This file is part of PhpWiki.
9 * PhpWiki is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
14 * PhpWiki is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License along
20 * with PhpWiki; if not, write to the Free Software Foundation, Inc.,
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
25 * Usage: <<SystemInfo all >>
26 * or <<SystemInfo pagestats cachestats discspace hitstats >>
27 * or <<SystemInfo version >>
28 * or <<SystemInfo current_theme >>
29 * or <<SystemInfo PHPWIKI_DIR >>
31 * Provide access to phpwiki's lower level system information.
33 * version, charset, pagestats, SERVER_NAME, database, discspace,
34 * cachestats, userstats, linkstats, accessstats, hitstats,
35 * revisionstats, interwikilinks, imageextensions, wikiwordregexp,
36 * availableplugins, downloadurl or any other predefined CONSTANT
38 * In spirit to http://www.ecyrd.com/JSPWiki/SystemInfo.jsp
40 * Done: Some calculations are heavy (~5-8 secs), so we should cache
41 * the result. In the page or with WikiPluginCached?
44 require_once 'lib/WikiPluginCached.php';
45 class WikiPlugin_SystemInfo
46 extends WikiPluginCached
48 function getPluginType()
50 return PLUGIN_CACHED_HTML;
55 return _("SystemInfo");
58 function getDescription()
60 return _("Provide access to PhpWiki's lower level system information.");
63 /* From lib/WikiPlugin.php:
64 * If the plugin can deduce a modification time, or equivalent
65 * sort of tag for it's content, then the plugin should
66 * call $request->appendValidators() with appropriate arguments,
67 * and should override this method to return true.
69 function managesValidators()
74 function getExpire($dbi, $argarray, $request)
76 return '+1800'; // 30 minutes
79 function getHtml($dbi, $argarray, $request, $basepage)
81 $loader = new WikiPluginLoader;
82 return $loader->expandPI('<<SystemInfo '
83 . WikiPluginCached::glueArgs($argarray) // all
84 . ' ?>', $request, $this, $basepage);
87 function getDefaultArguments()
89 return array( // 'seperator' => ' ', // on multiple args
95 $s = "DATABASE_TYPE: " . DATABASE_TYPE . ", ";
96 switch (DATABASE_TYPE) {
101 $s .= "DATABASE BACKEND:" . " ";
102 $s .= (DATABASE_TYPE == 'SQL') ? 'PearDB' : 'ADODB';
103 if (preg_match('/^(\w+):/', $dsn, $m)) {
107 $s .= ", DATABASE_PREFIX: \"" . DATABASE_PREFIX . "\", ";
110 $s .= "DATABASE_DBA_HANDLER: " . DATABASE_DBA_HANDLER . ", ";
111 $s .= "DATABASE_DIRECTORY: \"" . DATABASE_DIRECTORY . "\", ";
114 $s .= "DATABASE_DIRECTORY: \"" . DATABASE_DIRECTORY . "\", ";
115 // $s .= "cvs stuff: , ";
118 $s .= "DATABASE_DIRECTORY: " . DATABASE_DIRECTORY . ", ";
121 // hack: suppress error when using sql, so no timeout
122 @$s .= "DATABASE_TIMEOUT: " . DATABASE_TIMEOUT;
126 function cachestats()
128 if (!defined('USECACHE') or !USECACHE)
129 return _("no cache used");
131 $cache = $dbi->_cache;
132 $s = _("cached pagedata:") . " " . count($cache->_pagedata_cache);
133 $s .= ", " . _("cached versiondata:");
134 $s .= " " . count($cache->_versiondata_cache);
135 //$s .= ", glv size: " . count($cache->_glv_cache);
136 //$s .= ", cache hits: ?";
137 //$s .= ", cache misses: ?";
141 function ExpireParams()
143 global $ExpireParams;
144 $s = sprintf(_("Keep up to %d major edits, but keep them no longer than %d days."),
145 $ExpireParams['major']['keep'],
146 $ExpireParams['major']['max_age']);
147 $s .= sprintf(_(" Keep up to %d minor edits, but keep them no longer than %d days."),
148 $ExpireParams['minor']['keep'],
149 $ExpireParams['minor']['max_age']);
150 $s .= sprintf(_(" Keep the latest contributions of the last %d authors up to %d days."),
151 $ExpireParams['author']['keep'], $ExpireParams['author']['max_age']);
152 $s .= sprintf(_(" Additionally, try to keep the latest contributions of all authors in the last %d days (even if there are more than %d of them,) but in no case keep more than %d unique author revisions."),
153 $ExpireParams['author']['min_age'],
154 $ExpireParams['author']['keep'],
155 $ExpireParams['author']['max_keep']);
162 $dbi = $request->getDbh();
163 $s = sprintf(_("%d pages"), $dbi->numPages(true));
164 $s .= ", " . sprintf(_("%d not-empty pages"), $dbi->numPages(false));
166 // $s .= ", " . sprintf(_("earliest page from %s"), $earliestdate);
167 // $s .= ", " . sprintf(_("latest page from %s"), $latestdate);
168 // $s .= ", " . sprintf(_("latest pagerevision from %s"), $latestrevdate);
172 //What kind of link statistics?
173 // total links in, total links out, mean links per page, ...
174 // Any useful numbers similar to a VisualWiki interestmap?
181 // number of homepages: easy
182 // number of anonymous users?
183 // calc this from accesslog info?
184 // number of anonymous edits?
185 // easy. related to the view/edit rate in accessstats.
190 $page_iter = $dbi->getAllPages(true);
191 while ($page = $page_iter->next()) {
192 if ($page->isUserPage(true)) // check if the admin is there. if not add him to the authusers.
195 $s = sprintf(_("%d homepages"), $h);
196 // $s .= ", " . sprintf(_("%d anonymous users"), $au); // ??
197 // $s .= ", " . sprintf(_("%d anonymous edits"), $ae); // see recentchanges
198 // $s .= ", " . sprintf(_("%d authenticated users"), $auth); // users with password set
199 // $s .= ", " . sprintf(_("%d externally authenticated users"), $extauth); // query AuthDB?
203 //only from logging info possible. = hitstats per time.
204 // total hits per day/month/year
206 // TODO: see WhoIsOnline hit stats, and sql accesslogs
207 function accessstats()
214 function _stats($hits, $treshold = 10.0)
220 $min = 9999999999999;
222 foreach ($hits as $h) {
224 $max = max($h, $max);
225 $min = min($h, $min);
227 $median_i = (int)$n / 2;
229 $median = $hits[$median_i];
231 $median = $hits[$median_i];
232 $mintreshold = $max * $treshold / 100.0; // lower than 10% of the hits
234 $nmin = $hits[0] < $mintreshold ? 1 : 0;
235 while (next($hits) < $mintreshold)
237 $maxtreshold = $max - $mintreshold; // more than 90% of the hits
240 while (prev($hits) > $maxtreshold)
242 return array('n' => $n,
248 'stddev' => stddev($hits, $sum),
249 'treshold' => $treshold,
251 'mintreshold' => $mintreshold,
253 'maxtreshold' => $maxtreshold);
256 // only absolute numbers, not for any time interval. see accessstats
257 // some useful number derived from the curve of the hit stats.
258 // total, max, mean, median, stddev;
259 // %d pages less than 3 hits (<10%) <10% percent of the leastpopular
260 // %d pages more than 100 hits (>90%) >90% percent of the mostpopular
265 $page_iter = $dbi->getAllPages(true);
266 while ($page = $page_iter->next()) {
267 if (($current = $page->getCurrentRevision())
268 && (!$current->hasDefaultContents())
270 $hits[] = $page->get('hits');
274 $stats = $this->_stats($hits, $treshold);
276 $s = sprintf(_("total hits: %d"), $stats['sum']);
277 $s .= ", " . sprintf(_("max: %d"), $stats['max']);
278 $s .= ", " . sprintf(_("mean: %2.3f"), $stats['mean']);
279 $s .= ", " . sprintf(_("median: %d"), $stats['median']);
280 $s .= ", " . sprintf(_("stddev: %2.3f"), $stats['stddev']);
281 $s .= "; " . sprintf(_("%d pages with less than %d hits (<%d%%)."),
282 $stats['nmin'], $stats['mintreshold'], $treshold);
283 $s .= " " . sprintf(_("%d page(s) with more than %d hits (>%d%%)."),
284 $stats['nmax'], $stats['maxtreshold'], 100 - $treshold);
290 function revisionstats()
294 include_once 'lib/WikiPluginCached.php';
295 $cache = WikiPluginCached::newCache();
296 $id = $cache->generateId('SystemInfo::revisionstats_' . $LANG);
297 $cachedir = 'plugincache';
298 $content = $cache->get($id, $cachedir);
300 if (!empty($content))
305 $page_iter = $dbi->getAllPages(true);
306 $stats['empty'] = $stats['latest']['major'] = $stats['latest']['minor'] = 0;
307 while ($page = $page_iter->next()) {
308 if (!$page->exists()) {
312 $current = $page->getCurrentRevision();
313 // is the latest revision a major or minor one?
314 // latest revision: numpages 200 (100%) / major (60%) / minor (40%)
315 if ($current->get('is_minor_edit'))
316 $stats['latest']['major']++;
318 $stats['latest']['minor']++;
320 // FIXME: This needs much too long to be acceptable.
322 // number of revisions: all (100%) / major (60%) / minor (40%)
324 // per page: mean 20 / major (60%) / minor (40%)
325 $rev_iter = $page->getAllRevisions();
326 while ($rev = $rev_iter->next()) {
327 if ($rev->get('is_minor_edit'))
328 $stats['page']['major']++;
330 $stats['page']['minor']++;
333 $stats['page']['all'] = $stats['page']['major'] + $stats['page']['minor'];
334 $stats['perpage'][] = $stats['page']['all'];
335 $stats['perpage_major'][] = $stats['page']['major'];
336 $stats['sum']['all'] += $stats['page']['all'];
337 $stats['sum']['major'] += $stats['page']['major'];
338 $stats['sum']['minor'] += $stats['page']['minor'];
339 $stats['page'] = array();
343 $stats['numpages'] = $stats['latest']['major'] + $stats['latest']['minor'];
344 $stats['latest']['major_perc'] = $stats['latest']['major'] * 100.0 / $stats['numpages'];
345 $stats['latest']['minor_perc'] = $stats['latest']['minor'] * 100.0 / $stats['numpages'];
346 $empty = sprintf("empty pages: %d (%02.1f%%) / %d (100%%)\n",
347 $stats['empty'], $stats['empty'] * 100.0 / $stats['numpages'],
349 $latest = sprintf("latest revision: major %d (%02.1f%%) / minor %d (%02.1f%%) / all %d (100%%)\n",
350 $stats['latest']['major'], $stats['latest']['major_perc'],
351 $stats['latest']['minor'], $stats['latest']['minor_perc'], $stats['numpages']);
353 $stats['sum']['major_perc'] = $stats['sum']['major'] * 100.0 / $stats['sum']['all'];
354 $stats['sum']['minor_perc'] = $stats['sum']['minor'] * 100.0 / $stats['sum']['all'];
355 $sum = sprintf("number of revisions: major %d (%02.1f%%) / minor %d (%02.1f%%) / all %d (100%%)\n",
356 $stats['sum']['major'], $stats['sum']['major_perc'],
357 $stats['sum']['minor'], $stats['sum']['minor_perc'], $stats['sum']['all']);
359 $stats['perpage'] = $this->_stats($stats['perpage']);
360 $stats['perpage_major'] = $this->_stats($stats['perpage_major']);
361 $stats['perpage']['major_perc'] = $stats['perpage_major']['sum'] * 100.0 / $stats['perpage']['sum'];
362 $stats['perpage']['minor_perc'] = 100 - $stats['perpage']['major_perc'];
363 $stats['perpage_minor']['sum'] = $stats['perpage']['sum'] - $stats['perpage_major']['sum'];
364 $stats['perpage_minor']['mean'] = $stats['perpage_minor']['sum'] / ($stats['perpage']['n'] - $stats['perpage_major']['n']);
365 $perpage = sprintf("revisions per page: all %d, mean %02.1f / major %d (%02.1f%%) / minor %d (%02.1f%%)\n",
366 $stats['perpage']['sum'], $stats['perpage']['mean'],
367 $stats['perpage_major']['mean'], $stats['perpage']['major_perc'],
368 $stats['perpage_minor']['mean'], $stats['perpage']['minor_perc']);
369 $perpage .= sprintf(" %d page(s) with less than %d revisions (<%d%%)\n",
370 $stats['perpage']['nmin'], $stats['perpage']['maintreshold'], $treshold);
371 $perpage .= sprintf(" %d page(s) with more than %d revisions (>%d%%)\n",
372 $stats['perpage']['nmax'], $stats['perpage']['maxtreshold'], 100 - $treshold);
373 $content = $empty . $latest . $sum . $perpage;
375 $content = $empty . $latest;
377 // regenerate cache every 30 minutes
378 $cache->save($id, $content, '+1800', $cachedir);
382 // Size of databases/files/cvs are possible plus the known size of the app.
383 // Cache this costly operation.
384 // Even if the whole plugin call is stored internally, we cache this
385 // seperately with a seperate key.
390 include_once 'lib/WikiPluginCached.php';
391 $cache = WikiPluginCached::newCache();
392 $id = $cache->generateId('SystemInfo::discspace');
393 $cachedir = 'plugincache';
394 $content = $cache->get($id, $cachedir);
396 if (empty($content)) {
397 $dir = defined('PHPWIKI_DIR') ? PHPWIKI_DIR : '.';
398 //TODO: windows only (no cygwin)
399 $appsize = `du -s $dir | cut -f1`;
401 if (in_array($DBParams['dbtype'], array('SQL', 'ADODB'))) {
402 //TODO: where is the data is actually stored? see phpMyAdmin
404 } elseif ($DBParams['dbtype'] == 'dba') {
406 $dbdir = $DBParams['directory'];
407 if ($DBParams['dba_handler'] == 'db3')
408 $pagesize = filesize($DBParams['directory']
409 . "/wiki_pagedb.db3") / 1024;
410 // if issubdirof($dbdir, $dir) $appsize -= $pagesize;
411 } else { // flatfile, cvs
412 $dbdir = $DBParams['directory'];
413 $pagesize = `du -s $dbdir`;
414 // if issubdirof($dbdir, $dir) $appsize -= $pagesize;
416 $content = array('appsize' => $appsize,
417 'pagesize' => $pagesize);
418 // regenerate cache every 30 minutes
419 $cache->save($id, $content, '+1800', $cachedir);
421 $appsize = $content['appsize'];
422 $pagesize = $content['pagesize'];
425 $s = sprintf(_("Application size: %d KiB"), $appsize);
427 $s .= ", " . sprintf(_("Pagedata size: %d KiB", $pagesize));
431 function inlineimages()
433 return implode(' ', explode('|', INLINE_IMAGES));
436 function wikinameregexp()
438 return $GLOBALS['WikiNameRegexp'];
441 function allowedprotocols()
443 return implode(' ', explode('|', ALLOWED_PROTOCOLS));
446 function available_plugins()
448 $fileset = new FileSet(FindFile('lib/plugin'), '*.php');
449 $list = $fileset->getFiles();
452 return sprintf(_("Total %d plugins: "), count($list))
453 . implode(', ', array_map(create_function('$f',
454 'return substr($f,0,-4);'),
458 function supported_languages()
460 $available_languages = listAvailableLanguages();
461 natcasesort($available_languages);
463 return sprintf(_("Total of %d languages: "),
464 count($available_languages))
465 . implode(', ', $available_languages) . ". "
466 . _("Current language") . _(": ") . $GLOBALS['LANG']
467 . ((DEFAULT_LANGUAGE != $GLOBALS['LANG'])
468 ? ". " . sprintf(_("Default language: “%s”"), DEFAULT_LANGUAGE)
472 function supported_themes()
475 $available_themes = listAvailableThemes();
476 natcasesort($available_themes);
477 return sprintf(_("Total of %d themes: "), count($available_themes))
478 . implode(', ', $available_themes) . ". "
479 . _("Current theme") . _(": ") . $WikiTheme->_name
480 . ((THEME != $WikiTheme->_name)
481 ? ". " . sprintf(_("Default theme: “%s”"), THEME)
485 function call($arg, &$availableargs)
487 if (!empty($availableargs[$arg]))
488 return $availableargs[$arg]();
489 elseif (method_exists($this, $arg)) // any defined SystemInfo->method()
490 return call_user_func_array(array(&$this, $arg), array()); elseif (defined($arg) && // any defined constant
491 !in_array($arg, array('ADMIN_PASSWD', 'DATABASE_DSN', 'DBAUTH_AUTH_DSN'))
493 return constant($arg); else
494 return $this->error(sprintf(_("unknown argument “%s” to SystemInfo"), $arg));
497 function run($dbi, $argstr, &$request, $basepage)
499 // don't parse argstr for name=value pairs. instead we use just 'name'
500 //$args = $this->getArgs($argstr, $request);
502 $args['seperator'] = ' ';
503 $availableargs = // name => callback + 0 args
504 array('appname' => create_function('', "return 'PhpWiki';"),
505 'version' => create_function('', "return sprintf('%s', PHPWIKI_VERSION);"),
506 'LANG' => create_function('', 'return $GLOBALS["LANG"];'),
507 'LC_ALL' => create_function('', 'return setlocale(LC_ALL, 0);'),
508 'current_language' => create_function('', 'return $GLOBALS["LANG"];'),
509 'system_language' => create_function('', 'return DEFAULT_LANGUAGE;'),
510 'current_theme' => create_function('', 'return $GLOBALS["WikiTheme"]->_name;'),
511 'system_theme' => create_function('', 'return THEME;'),
512 // more here or as method.
513 '' => create_function('', "return 'dummy';")
515 // split the argument string by any number of commas or space
516 // characters, which include " ", \r, \t, \n and \f
517 $allargs = preg_split("/[\s,]+/", $argstr, -1, PREG_SPLIT_NO_EMPTY);
518 if (in_array('all', $allargs) || in_array('table', $allargs)) {
519 $allargs = array('appname' => _("Application name"),
520 'version' => _("PhpWiki engine version"),
521 'database' => _("Database"),
522 'cachestats' => _("Cache statistics"),
523 'pagestats' => _("Page statistics"),
524 //'revisionstats' => _("Page revision statistics"),
525 //'linkstats' => _("Link statistics"),
526 'userstats' => _("User statistics"),
527 //'accessstats' => _("Access statistics"),
528 'hitstats' => _("Hit statistics"),
529 'discspace' => _("Harddisc usage"),
530 'expireparams' => _("Expiry parameters"),
531 'wikinameregexp' => _("Wikiname regexp"),
532 'allowedprotocols' => _("Allowed protocols"),
533 'inlineimages' => _("Inline images"),
534 'available_plugins' => _("Available plugins"),
535 'supported_languages' => _("Supported languages"),
536 'supported_themes' => _("Supported themes"),
540 $table = HTML::table(array('class' => 'bordered'));
541 foreach ($allargs as $arg => $desc) {
546 $table->pushContent(HTML::tr(HTML::th(array('style' => "white-space:nowrap"), $desc),
547 HTML::td(HTML($this->call($arg, $availableargs)))));
552 foreach ($allargs as $arg) {
553 $o = $this->call($arg, $availableargs);
557 $output .= ($o . $args['seperator']);
559 // if more than one arg, remove the trailing seperator
560 if ($output) $output = substr($output, 0,
561 -strlen($args['seperator']));
562 return HTML($output);
567 function median($hits)
572 $median = (int)$n / 2;
573 if (!($n % 2)) // proper rounding on even length
574 return ($hits[$median] + $hits[$median - 1]) * 0.5;
576 return $hits[$median];
579 function rsum($a, $b)
585 function mean(&$hits, $total = false)
589 $total = array_reduce($hits, 'rsum');
590 return (float)$total / ($n * 1.0);
593 function stddev(&$hits, $total = false)
596 if (!$total) $total = array_reduce($hits, 'rsum');
597 $GLOBALS['mean'] = $total / $n;
598 $r = array_map(create_function('$i', 'global $mean; return ($i-$mean)*($i-$mean);'),
600 unset($GLOBALS['mean']);
601 return (float)sqrt(mean($r, $total) * ($n / (float)($n - 1)));
608 // c-hanging-comment-ender-p: nil
609 // indent-tabs-mode: nil