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 $mean = $n ? $sum / $n : 0;
228 $median = $hits[ (int)($n / 2) ];
229 $mintreshold = $max * $treshold / 100.0; // lower than 10% of the hits
231 $nmin = $hits[0] < $mintreshold ? 1 : 0;
232 while (next($hits) < $mintreshold)
234 $maxtreshold = $max - $mintreshold; // more than 90% of the hits
237 while (prev($hits) > $maxtreshold)
239 return array('n' => $n,
245 'stddev' => stddev($hits, $sum),
246 'treshold' => $treshold,
248 'mintreshold' => $mintreshold,
250 'maxtreshold' => $maxtreshold);
253 // only absolute numbers, not for any time interval. see accessstats
254 // some useful number derived from the curve of the hit stats.
255 // total, max, mean, median, stddev;
256 // %d pages less than 3 hits (<10%) <10% percent of the leastpopular
257 // %d pages more than 100 hits (>90%) >90% percent of the mostpopular
262 $page_iter = $dbi->getAllPages(true);
263 while ($page = $page_iter->next()) {
264 if (($current = $page->getCurrentRevision())
265 && (!$current->hasDefaultContents())
267 $hits[] = $page->get('hits');
271 $stats = $this->_stats($hits, $treshold);
273 $s = sprintf(_("total hits: %d"), $stats['sum']);
274 $s .= ", " . sprintf(_("max: %d"), $stats['max']);
275 $s .= ", " . sprintf(_("mean: %2.3f"), $stats['mean']);
276 $s .= ", " . sprintf(_("median: %d"), $stats['median']);
277 $s .= ", " . sprintf(_("stddev: %2.3f"), $stats['stddev']);
278 $s .= "; " . sprintf(_("%d pages with less than %d hits (<%d%%)."),
279 $stats['nmin'], $stats['mintreshold'], $treshold);
280 $s .= " " . sprintf(_("%d page(s) with more than %d hits (>%d%%)."),
281 $stats['nmax'], $stats['maxtreshold'], 100 - $treshold);
287 function revisionstats()
291 include_once 'lib/WikiPluginCached.php';
292 $cache = WikiPluginCached::newCache();
293 $id = $cache->generateId('SystemInfo::revisionstats_' . $LANG);
294 $cachedir = 'plugincache';
295 $content = $cache->get($id, $cachedir);
297 if (!empty($content))
302 $page_iter = $dbi->getAllPages(true);
303 $stats['empty'] = $stats['latest']['major'] = $stats['latest']['minor'] = 0;
304 while ($page = $page_iter->next()) {
305 if (!$page->exists()) {
309 $current = $page->getCurrentRevision();
310 // is the latest revision a major or minor one?
311 // latest revision: numpages 200 (100%) / major (60%) / minor (40%)
312 if ($current->get('is_minor_edit'))
313 $stats['latest']['major']++;
315 $stats['latest']['minor']++;
317 // FIXME: This needs much too long to be acceptable.
319 // number of revisions: all (100%) / major (60%) / minor (40%)
321 // per page: mean 20 / major (60%) / minor (40%)
322 $rev_iter = $page->getAllRevisions();
323 while ($rev = $rev_iter->next()) {
324 if ($rev->get('is_minor_edit'))
325 $stats['page']['major']++;
327 $stats['page']['minor']++;
330 $stats['page']['all'] = $stats['page']['major'] + $stats['page']['minor'];
331 $stats['perpage'][] = $stats['page']['all'];
332 $stats['perpage_major'][] = $stats['page']['major'];
333 $stats['sum']['all'] += $stats['page']['all'];
334 $stats['sum']['major'] += $stats['page']['major'];
335 $stats['sum']['minor'] += $stats['page']['minor'];
336 $stats['page'] = array();
340 $stats['numpages'] = $stats['latest']['major'] + $stats['latest']['minor'];
341 $stats['latest']['major_perc'] = $stats['latest']['major'] * 100.0 / $stats['numpages'];
342 $stats['latest']['minor_perc'] = $stats['latest']['minor'] * 100.0 / $stats['numpages'];
343 $empty = sprintf("empty pages: %d (%02.1f%%) / %d (100%%)\n",
344 $stats['empty'], $stats['empty'] * 100.0 / $stats['numpages'],
346 $latest = sprintf("latest revision: major %d (%02.1f%%) / minor %d (%02.1f%%) / all %d (100%%)\n",
347 $stats['latest']['major'], $stats['latest']['major_perc'],
348 $stats['latest']['minor'], $stats['latest']['minor_perc'], $stats['numpages']);
350 $stats['sum']['major_perc'] = $stats['sum']['major'] * 100.0 / $stats['sum']['all'];
351 $stats['sum']['minor_perc'] = $stats['sum']['minor'] * 100.0 / $stats['sum']['all'];
352 $sum = sprintf("number of revisions: major %d (%02.1f%%) / minor %d (%02.1f%%) / all %d (100%%)\n",
353 $stats['sum']['major'], $stats['sum']['major_perc'],
354 $stats['sum']['minor'], $stats['sum']['minor_perc'], $stats['sum']['all']);
356 $stats['perpage'] = $this->_stats($stats['perpage']);
357 $stats['perpage_major'] = $this->_stats($stats['perpage_major']);
358 $stats['perpage']['major_perc'] = $stats['perpage_major']['sum'] * 100.0 / $stats['perpage']['sum'];
359 $stats['perpage']['minor_perc'] = 100 - $stats['perpage']['major_perc'];
360 $stats['perpage_minor']['sum'] = $stats['perpage']['sum'] - $stats['perpage_major']['sum'];
361 $stats['perpage_minor']['mean'] = $stats['perpage_minor']['sum'] / ($stats['perpage']['n'] - $stats['perpage_major']['n']);
362 $perpage = sprintf("revisions per page: all %d, mean %02.1f / major %d (%02.1f%%) / minor %d (%02.1f%%)\n",
363 $stats['perpage']['sum'], $stats['perpage']['mean'],
364 $stats['perpage_major']['mean'], $stats['perpage']['major_perc'],
365 $stats['perpage_minor']['mean'], $stats['perpage']['minor_perc']);
366 $perpage .= sprintf(" %d page(s) with less than %d revisions (<%d%%)\n",
367 $stats['perpage']['nmin'], $stats['perpage']['maintreshold'], $treshold);
368 $perpage .= sprintf(" %d page(s) with more than %d revisions (>%d%%)\n",
369 $stats['perpage']['nmax'], $stats['perpage']['maxtreshold'], 100 - $treshold);
370 $content = $empty . $latest . $sum . $perpage;
372 $content = $empty . $latest;
374 // regenerate cache every 30 minutes
375 $cache->save($id, $content, '+1800', $cachedir);
379 // Size of databases/files/cvs are possible plus the known size of the app.
380 // Cache this costly operation.
381 // Even if the whole plugin call is stored internally, we cache this
382 // separately with a separate key.
387 include_once 'lib/WikiPluginCached.php';
388 $cache = WikiPluginCached::newCache();
389 $id = $cache->generateId('SystemInfo::discspace');
390 $cachedir = 'plugincache';
391 $content = $cache->get($id, $cachedir);
393 if (empty($content)) {
394 $dir = defined('PHPWIKI_DIR') ? PHPWIKI_DIR : '.';
395 //TODO: windows only (no cygwin)
396 $appsize = `du -s $dir | cut -f1`;
398 if (in_array($DBParams['dbtype'], array('SQL', 'ADODB'))) {
399 //TODO: where is the data is actually stored? see phpMyAdmin
401 } elseif ($DBParams['dbtype'] == 'dba') {
403 $dbdir = $DBParams['directory'];
404 if ($DBParams['dba_handler'] == 'db3')
405 $pagesize = filesize($DBParams['directory']
406 . "/wiki_pagedb.db3") / 1024;
407 // if issubdirof($dbdir, $dir) $appsize -= $pagesize;
408 } else { // flatfile, cvs
409 $dbdir = $DBParams['directory'];
410 $pagesize = `du -s $dbdir`;
411 // if issubdirof($dbdir, $dir) $appsize -= $pagesize;
413 $content = array('appsize' => $appsize,
414 'pagesize' => $pagesize);
415 // regenerate cache every 30 minutes
416 $cache->save($id, $content, '+1800', $cachedir);
418 $appsize = $content['appsize'];
419 $pagesize = $content['pagesize'];
422 $s = sprintf(_("Application size: %d KiB"), $appsize);
424 $s .= ", " . sprintf(_("Pagedata size: %d KiB", $pagesize));
428 function inlineimages()
430 return implode(' ', explode('|', INLINE_IMAGES));
433 function wikinameregexp()
435 return $GLOBALS['WikiNameRegexp'];
438 function allowedprotocols()
440 return implode(' ', explode('|', ALLOWED_PROTOCOLS));
443 function available_plugins()
445 $fileset = new FileSet(FindFile('lib/plugin'), '*.php');
446 $list = $fileset->getFiles();
449 return sprintf(_("Total %d plugins: "), count($list))
450 . implode(', ', array_map(create_function('$f',
451 'return substr($f,0,-4);'),
455 function supported_languages()
457 $available_languages = listAvailableLanguages();
458 natcasesort($available_languages);
460 return sprintf(_("Total of %d languages: "),
461 count($available_languages))
462 . implode(', ', $available_languages) . ". "
463 . _("Current language") . _(": ") . $GLOBALS['LANG']
464 . ((DEFAULT_LANGUAGE != $GLOBALS['LANG'])
465 ? ". " . sprintf(_("Default language: “%s”"), DEFAULT_LANGUAGE)
469 function supported_themes()
472 $available_themes = listAvailableThemes();
473 natcasesort($available_themes);
474 return sprintf(_("Total of %d themes: "), count($available_themes))
475 . implode(', ', $available_themes) . ". "
476 . _("Current theme") . _(": ") . $WikiTheme->_name
477 . ((THEME != $WikiTheme->_name)
478 ? ". " . sprintf(_("Default theme: “%s”"), THEME)
482 function call($arg, &$availableargs)
484 if (!empty($availableargs[$arg]))
485 return $availableargs[$arg]();
486 elseif (method_exists($this, $arg)) // any defined SystemInfo->method()
487 return call_user_func_array(array(&$this, $arg), array()); elseif (defined($arg) && // any defined constant
488 !in_array($arg, array('ADMIN_PASSWD', 'DATABASE_DSN', 'DBAUTH_AUTH_DSN'))
490 return constant($arg); else
491 return $this->error(sprintf(_("unknown argument “%s” to SystemInfo"), $arg));
494 function run($dbi, $argstr, &$request, $basepage)
496 // don't parse argstr for name=value pairs. instead we use just 'name'
497 //$args = $this->getArgs($argstr, $request);
499 $args['seperator'] = ' ';
500 $availableargs = // name => callback + 0 args
501 array('appname' => create_function('', "return 'PhpWiki';"),
502 'version' => create_function('', "return sprintf('%s', PHPWIKI_VERSION);"),
503 'LANG' => create_function('', 'return $GLOBALS["LANG"];'),
504 'LC_ALL' => create_function('', 'return setlocale(LC_ALL, 0);'),
505 'current_language' => create_function('', 'return $GLOBALS["LANG"];'),
506 'system_language' => create_function('', 'return DEFAULT_LANGUAGE;'),
507 'current_theme' => create_function('', 'return $GLOBALS["WikiTheme"]->_name;'),
508 'system_theme' => create_function('', 'return THEME;'),
509 // more here or as method.
510 '' => create_function('', "return 'dummy';")
512 // split the argument string by any number of commas or space
513 // characters, which include " ", \r, \t, \n and \f
514 $allargs = preg_split("/[\s,]+/", $argstr, -1, PREG_SPLIT_NO_EMPTY);
515 if (in_array('all', $allargs) || in_array('table', $allargs)) {
516 $allargs = array('appname' => _("Application name"),
517 'version' => _("PhpWiki engine version"),
518 'database' => _("Database"),
519 'cachestats' => _("Cache statistics"),
520 'pagestats' => _("Page statistics"),
521 //'revisionstats' => _("Page revision statistics"),
522 //'linkstats' => _("Link statistics"),
523 'userstats' => _("User statistics"),
524 //'accessstats' => _("Access statistics"),
525 'hitstats' => _("Hit statistics"),
526 'discspace' => _("Harddisc usage"),
527 'expireparams' => _("Expiry parameters"),
528 'wikinameregexp' => _("Wikiname regexp"),
529 'allowedprotocols' => _("Allowed protocols"),
530 'inlineimages' => _("Inline images"),
531 'available_plugins' => _("Available plugins"),
532 'supported_languages' => _("Supported languages"),
533 'supported_themes' => _("Supported themes"),
537 $table = HTML::table(array('class' => 'bordered'));
538 foreach ($allargs as $arg => $desc) {
543 $table->pushContent(HTML::tr(HTML::th(array('style' => "white-space:nowrap"), $desc),
544 HTML::td(HTML($this->call($arg, $availableargs)))));
549 foreach ($allargs as $arg) {
550 $o = $this->call($arg, $availableargs);
554 $output .= ($o . $args['seperator']);
556 // if more than one arg, remove the trailing seperator
557 if ($output) $output = substr($output, 0,
558 -strlen($args['seperator']));
559 return HTML($output);
564 function median($hits)
569 $median = (int)($n / 2);
570 if (!($n % 2)) // proper rounding on even length
571 return ($hits[$median] + $hits[$median - 1]) * 0.5;
573 return $hits[$median];
576 function rsum($a, $b)
582 function mean(&$hits, $total = false)
586 $total = array_reduce($hits, 'rsum');
587 return (float)$total / ($n * 1.0);
590 function stddev(&$hits, $total = false)
593 if (!$total) $total = array_reduce($hits, 'rsum');
594 $GLOBALS['mean'] = $total / $n;
595 $r = array_map(create_function('$i', 'global $mean; return ($i-$mean)*($i-$mean);'),
597 unset($GLOBALS['mean']);
598 return (float)sqrt(mean($r, $total) * ($n / (float)($n - 1)));
605 // c-hanging-comment-ender-p: nil
606 // indent-tabs-mode: nil