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, 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';
46 class WikiPlugin_SystemInfo
47 extends WikiPluginCached
51 function getPluginType()
53 return PLUGIN_CACHED_HTML;
56 function getDescription()
58 return _("Provide access to PhpWiki's lower level system information.");
61 /* From lib/WikiPlugin.php:
62 * If the plugin can deduce a modification time, or equivalent
63 * sort of tag for it's content, then the plugin should
64 * call $request->appendValidators() with appropriate arguments,
65 * and should override this method to return true.
67 function managesValidators()
72 function getExpire($dbi, $argarray, $request)
74 return '+1800'; // 30 minutes
79 * @param array $argarray
80 * @param WikiRequest $request
81 * @param string $basepage
84 protected function getHtml($dbi, $argarray, $request, $basepage)
86 $loader = new WikiPluginLoader();
87 return $loader->expandPI('<<SystemInfo '
88 . WikiPluginCached::glueArgs($argarray) // all
89 . ' ?>', $request, $this, $basepage);
92 protected function getImage($dbi, $argarray, $request)
94 trigger_error('pure virtual', E_USER_ERROR);
97 protected function getMap($dbi, $argarray, $request)
99 trigger_error('pure virtual', E_USER_ERROR);
102 function getDefaultArguments()
104 return array( // 'seperator' => ' ', // on multiple args
110 $s = "DATABASE_TYPE: " . DATABASE_TYPE . ", ";
111 switch (DATABASE_TYPE) {
116 $s .= "DATABASE BACKEND:" . " ";
117 $s .= (DATABASE_TYPE == 'SQL') ? 'PearDB' : 'ADODB';
118 if (preg_match('/^(\w+):/', $dsn, $m)) {
122 $s .= ", DATABASE_PREFIX: \"" . DATABASE_PREFIX . "\", ";
125 $s .= "DATABASE_DBA_HANDLER: " . DATABASE_DBA_HANDLER . ", ";
126 $s .= "DATABASE_DIRECTORY: \"" . DATABASE_DIRECTORY . "\", ";
129 $s .= "DATABASE_DIRECTORY: \"" . DATABASE_DIRECTORY . "\", ";
130 // $s .= "cvs stuff: , ";
133 $s .= "DATABASE_DIRECTORY: " . DATABASE_DIRECTORY . ", ";
136 // hack: suppress error when using sql, so no timeout
137 @$s .= "DATABASE_TIMEOUT: " . DATABASE_TIMEOUT;
141 function cachestats()
143 if (!defined('USECACHE') or !USECACHE)
144 return _("no cache used");
146 $cache = $dbi->_cache;
147 $s = _("cached pagedata:") . " " . count($cache->_pagedata_cache);
148 $s .= ", " . _("cached versiondata:");
149 $s .= " " . count($cache->_versiondata_cache);
150 //$s .= ", glv size: " . count($cache->_glv_cache);
151 //$s .= ", cache hits: ?";
152 //$s .= ", cache misses: ?";
156 function ExpireParams()
158 global $ExpireParams;
159 $s = sprintf(_("Keep up to %d major edits, but keep them no longer than %d days."),
160 $ExpireParams['major']['keep'],
161 $ExpireParams['major']['max_age']);
162 $s .= sprintf(_(" Keep up to %d minor edits, but keep them no longer than %d days."),
163 $ExpireParams['minor']['keep'],
164 $ExpireParams['minor']['max_age']);
165 $s .= sprintf(_(" Keep the latest contributions of the last %d authors up to %d days."),
166 $ExpireParams['author']['keep'], $ExpireParams['author']['max_age']);
167 $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."),
168 $ExpireParams['author']['min_age'],
169 $ExpireParams['author']['keep'],
170 $ExpireParams['author']['max_keep']);
177 $dbi = $request->getDbh();
178 $s = sprintf(_("%d pages"), $dbi->numPages(true));
179 $s .= ", " . sprintf(_("%d not-empty pages"), $dbi->numPages(false));
181 // $s .= ", " . sprintf(_("earliest page from %s"), $earliestdate);
182 // $s .= ", " . sprintf(_("latest page from %s"), $latestdate);
183 // $s .= ", " . sprintf(_("latest pagerevision from %s"), $latestrevdate);
187 //What kind of link statistics?
188 // total links in, total links out, mean links per page, ...
189 // Any useful numbers similar to a VisualWiki interestmap?
196 // number of homepages: easy
197 // number of anonymous users?
198 // calc this from accesslog info?
199 // number of anonymous edits?
200 // easy. related to the view/edit rate in accessstats.
205 $page_iter = $dbi->getAllPages(true);
206 while ($page = $page_iter->next()) {
207 if ($page->isUserPage(true)) // check if the admin is there. if not add him to the authusers.
210 $s = sprintf(_("%d homepages"), $h);
211 // $s .= ", " . sprintf(_("%d anonymous users"), $au); // ??
212 // $s .= ", " . sprintf(_("%d anonymous edits"), $ae); // see recentchanges
213 // $s .= ", " . sprintf(_("%d authenticated users"), $auth); // users with password set
214 // $s .= ", " . sprintf(_("%d externally authenticated users"), $extauth); // query AuthDB?
218 //only from logging info possible. = hitstats per time.
219 // total hits per day/month/year
221 // TODO: see WhoIsOnline hit stats, and sql accesslogs
222 function accessstats()
229 private function get_stats($hits, $treshold = 10.0)
235 $min = 9999999999999;
237 foreach ($hits as $h) {
239 $max = max($h, $max);
240 $min = min($h, $min);
242 $mean = $n ? $sum / $n : 0;
243 $median = $hits[ (int)($n / 2) ];
244 $mintreshold = $max * $treshold / 100.0; // lower than 10% of the hits
246 $nmin = $hits[0] < $mintreshold ? 1 : 0;
247 while (next($hits) < $mintreshold)
249 $maxtreshold = $max - $mintreshold; // more than 90% of the hits
252 while (prev($hits) > $maxtreshold)
254 return array('n' => $n,
260 'stddev' => stddev($hits, $sum),
261 'treshold' => $treshold,
263 'mintreshold' => $mintreshold,
265 'maxtreshold' => $maxtreshold);
268 // only absolute numbers, not for any time interval. see accessstats
269 // some useful number derived from the curve of the hit stats.
270 // total, max, mean, median, stddev;
271 // %d pages less than 3 hits (<10%) <10% percent of the leastpopular
272 // %d pages more than 100 hits (>90%) >90% percent of the mostpopular
277 $page_iter = $dbi->getAllPages(true);
278 while ($page = $page_iter->next()) {
279 if (($current = $page->getCurrentRevision())
280 && (!$current->hasDefaultContents())
282 $hits[] = $page->get('hits');
286 $stats = $this->get_stats($hits, $treshold);
288 $s = sprintf(_("total hits: %d"), $stats['sum']);
289 $s .= ", " . sprintf(_("max: %d"), $stats['max']);
290 $s .= ", " . sprintf(_("mean: %2.3f"), $stats['mean']);
291 $s .= ", " . sprintf(_("median: %d"), $stats['median']);
292 $s .= ", " . sprintf(_("stddev: %2.3f"), $stats['stddev']);
293 $s .= "; " . sprintf(_("%d pages with less than %d hits (<%d%%)."),
294 $stats['nmin'], $stats['mintreshold'], $treshold);
295 $s .= " " . sprintf(_("%d page(s) with more than %d hits (>%d%%)."),
296 $stats['nmax'], $stats['maxtreshold'], 100 - $treshold);
302 function revisionstats()
306 include_once 'lib/WikiPluginCached.php';
307 $cache = WikiPluginCached::newCache();
308 $id = $cache->generateId('SystemInfo::revisionstats_' . $LANG);
309 $cachedir = 'plugincache';
310 $content = $cache->get($id, $cachedir);
312 if (!empty($content))
317 $page_iter = $dbi->getAllPages(true);
318 $stats['empty'] = $stats['latest']['major'] = $stats['latest']['minor'] = 0;
319 while ($page = $page_iter->next()) {
320 if (!$page->exists()) {
324 $current = $page->getCurrentRevision();
325 // is the latest revision a major or minor one?
326 // latest revision: numpages 200 (100%) / major (60%) / minor (40%)
327 if ($current->get('is_minor_edit'))
328 $stats['latest']['major']++;
330 $stats['latest']['minor']++;
332 // FIXME: This needs much too long to be acceptable.
334 // number of revisions: all (100%) / major (60%) / minor (40%)
336 // per page: mean 20 / major (60%) / minor (40%)
337 $rev_iter = $page->getAllRevisions();
338 while ($rev = $rev_iter->next()) {
339 if ($rev->get('is_minor_edit'))
340 $stats['page']['major']++;
342 $stats['page']['minor']++;
345 $stats['page']['all'] = $stats['page']['major'] + $stats['page']['minor'];
346 $stats['perpage'][] = $stats['page']['all'];
347 $stats['perpage_major'][] = $stats['page']['major'];
348 $stats['sum']['all'] += $stats['page']['all'];
349 $stats['sum']['major'] += $stats['page']['major'];
350 $stats['sum']['minor'] += $stats['page']['minor'];
351 $stats['page'] = array();
355 $stats['numpages'] = $stats['latest']['major'] + $stats['latest']['minor'];
356 $stats['latest']['major_perc'] = $stats['latest']['major'] * 100.0 / $stats['numpages'];
357 $stats['latest']['minor_perc'] = $stats['latest']['minor'] * 100.0 / $stats['numpages'];
358 $empty = sprintf("empty pages: %d (%02.1f%%) / %d (100%%)\n",
359 $stats['empty'], $stats['empty'] * 100.0 / $stats['numpages'],
361 $latest = sprintf("latest revision: major %d (%02.1f%%) / minor %d (%02.1f%%) / all %d (100%%)\n",
362 $stats['latest']['major'], $stats['latest']['major_perc'],
363 $stats['latest']['minor'], $stats['latest']['minor_perc'], $stats['numpages']);
365 $stats['sum']['major_perc'] = $stats['sum']['major'] * 100.0 / $stats['sum']['all'];
366 $stats['sum']['minor_perc'] = $stats['sum']['minor'] * 100.0 / $stats['sum']['all'];
367 $sum = sprintf("number of revisions: major %d (%02.1f%%) / minor %d (%02.1f%%) / all %d (100%%)\n",
368 $stats['sum']['major'], $stats['sum']['major_perc'],
369 $stats['sum']['minor'], $stats['sum']['minor_perc'], $stats['sum']['all']);
371 $stats['perpage'] = $this->get_stats($stats['perpage']);
372 $stats['perpage_major'] = $this->get_stats($stats['perpage_major']);
373 $stats['perpage']['major_perc'] = $stats['perpage_major']['sum'] * 100.0 / $stats['perpage']['sum'];
374 $stats['perpage']['minor_perc'] = 100 - $stats['perpage']['major_perc'];
375 $stats['perpage_minor']['sum'] = $stats['perpage']['sum'] - $stats['perpage_major']['sum'];
376 $stats['perpage_minor']['mean'] = $stats['perpage_minor']['sum'] / ($stats['perpage']['n'] - $stats['perpage_major']['n']);
377 $perpage = sprintf("revisions per page: all %d, mean %02.1f / major %d (%02.1f%%) / minor %d (%02.1f%%)\n",
378 $stats['perpage']['sum'], $stats['perpage']['mean'],
379 $stats['perpage_major']['mean'], $stats['perpage']['major_perc'],
380 $stats['perpage_minor']['mean'], $stats['perpage']['minor_perc']);
381 $perpage .= sprintf(" %d page(s) with less than %d revisions (<%d%%)\n",
382 $stats['perpage']['nmin'], $stats['perpage']['maintreshold'], $treshold);
383 $perpage .= sprintf(" %d page(s) with more than %d revisions (>%d%%)\n",
384 $stats['perpage']['nmax'], $stats['perpage']['maxtreshold'], 100 - $treshold);
385 $content = $empty . $latest . $sum . $perpage;
387 $content = $empty . $latest;
389 // regenerate cache every 30 minutes
390 $cache->save($id, $content, '+1800', $cachedir);
394 // Size of databases/files/cvs are possible plus the known size of the app.
395 // Cache this costly operation.
396 // Even if the whole plugin call is stored internally, we cache this
397 // separately with a separate key.
402 include_once 'lib/WikiPluginCached.php';
403 $cache = WikiPluginCached::newCache();
404 $id = $cache->generateId('SystemInfo::discspace');
405 $cachedir = 'plugincache';
406 $content = $cache->get($id, $cachedir);
408 if (empty($content)) {
409 $dir = defined('PHPWIKI_DIR') ? PHPWIKI_DIR : '.';
410 //TODO: windows only (no cygwin)
411 $appsize = `du -s $dir | cut -f1`;
413 if (in_array($DBParams['dbtype'], array('SQL', 'ADODB'))) {
414 //TODO: where is the data is actually stored? see phpMyAdmin
416 } elseif ($DBParams['dbtype'] == 'dba') {
418 $dbdir = $DBParams['directory'];
419 if ($DBParams['dba_handler'] == 'db3')
420 $pagesize = filesize($DBParams['directory']
421 . "/wiki_pagedb.db3") / 1024;
422 // if issubdirof($dbdir, $dir) $appsize -= $pagesize;
423 } else { // flatfile, cvs
424 $dbdir = $DBParams['directory'];
425 $pagesize = `du -s $dbdir`;
426 // if issubdirof($dbdir, $dir) $appsize -= $pagesize;
428 $content = array('appsize' => $appsize,
429 'pagesize' => $pagesize);
430 // regenerate cache every 30 minutes
431 $cache->save($id, $content, '+1800', $cachedir);
433 $appsize = $content['appsize'];
434 $pagesize = $content['pagesize'];
437 $s = sprintf(_("Application size: %d KiB"), $appsize);
439 $s .= ", " . sprintf(_("Pagedata size: %d KiB", $pagesize));
443 function inlineimages()
445 return implode(' ', explode('|', INLINE_IMAGES));
448 function wikinameregexp()
450 return $GLOBALS['WikiNameRegexp'];
453 function allowedprotocols()
455 return implode(' ', explode('|', ALLOWED_PROTOCOLS));
458 function available_plugins()
460 $fileset = new FileSet(FindFile('lib/plugin'), '*.php');
461 $list = $fileset->getFiles();
464 return sprintf(_("Total %d plugins: "), count($list))
465 . implode(', ', array_map(create_function('$f',
466 'return substr($f,0,-4);'),
470 function supported_languages()
472 $available_languages = listAvailableLanguages();
473 natcasesort($available_languages);
475 return sprintf(_("Total of %d languages: "),
476 count($available_languages))
477 . implode(', ', $available_languages) . ". "
478 . _("Current language") . _(": ") . $GLOBALS['LANG']
479 . ((DEFAULT_LANGUAGE != $GLOBALS['LANG'])
480 ? ". " . _("Default language") . _(": ") . DEFAULT_LANGUAGE
484 function supported_themes()
487 $available_themes = listAvailableThemes();
488 natcasesort($available_themes);
489 return sprintf(_("Total of %d themes: "), count($available_themes))
490 . implode(', ', $available_themes) . ". "
491 . _("Current theme") . _(": ") . $WikiTheme->_name
492 . ((THEME != $WikiTheme->_name)
493 ? ". " . _("Default theme") . _(": ") . THEME
497 function call($arg, &$availableargs)
499 if (!empty($availableargs[$arg]))
500 return $availableargs[$arg]();
501 elseif (method_exists($this, $arg)) // any defined SystemInfo->method()
502 return call_user_func_array(array(&$this, $arg), array()); elseif (defined($arg) && // any defined constant
503 !in_array($arg, array('ADMIN_PASSWD', 'DATABASE_DSN', 'DBAUTH_AUTH_DSN'))
505 return constant($arg); else
506 return $this->error(sprintf(_("unknown argument ā%sā to SystemInfo"), $arg));
511 * @param string $argstr
512 * @param WikiRequest $request
513 * @param string $basepage
516 function run($dbi, $argstr, &$request, $basepage)
518 // don't parse argstr for name=value pairs. instead we use just 'name'
519 //$args = $this->getArgs($argstr, $request);
521 $args['seperator'] = ' ';
522 $availableargs = // name => callback + 0 args
523 array('appname' => create_function('', "return 'PhpWiki';"),
524 'version' => create_function('', "return sprintf('%s', PHPWIKI_VERSION);"),
525 'LANG' => create_function('', 'return $GLOBALS["LANG"];'),
526 'LC_ALL' => create_function('', 'return setlocale(LC_ALL, 0);'),
527 'current_language' => create_function('', 'return $GLOBALS["LANG"];'),
528 'system_language' => create_function('', 'return DEFAULT_LANGUAGE;'),
529 'current_theme' => create_function('', 'return $GLOBALS["WikiTheme"]->_name;'),
530 'system_theme' => create_function('', 'return THEME;'),
531 // more here or as method.
532 '' => create_function('', "return 'dummy';")
534 // split the argument string by any number of commas or space
535 // characters, which include " ", \r, \t, \n and \f
536 $allargs = preg_split("/[\s,]+/", $argstr, -1, PREG_SPLIT_NO_EMPTY);
537 if (in_array('all', $allargs) || in_array('table', $allargs)) {
538 $allargs = array('appname' => _("Application name"),
539 'version' => _("PhpWiki engine version"),
540 'database' => _("Database"),
541 'cachestats' => _("Cache statistics"),
542 'pagestats' => _("Page statistics"),
543 //'revisionstats' => _("Page revision statistics"),
544 //'linkstats' => _("Link statistics"),
545 'userstats' => _("User statistics"),
546 //'accessstats' => _("Access statistics"),
547 'hitstats' => _("Hit statistics"),
548 'discspace' => _("Harddisc usage"),
549 'expireparams' => _("Expiry parameters"),
550 'wikinameregexp' => _("Wikiname regexp"),
551 'allowedprotocols' => _("Allowed protocols"),
552 'inlineimages' => _("Inline images"),
553 'available_plugins' => _("Available plugins"),
554 'supported_languages' => _("Supported languages"),
555 'supported_themes' => _("Supported themes"),
559 $table = HTML::table(array('class' => 'bordered'));
560 foreach ($allargs as $arg => $desc) {
565 $table->pushContent(HTML::tr(HTML::th(array('style' => "white-space:nowrap"), $desc),
566 HTML::td(HTML($this->call($arg, $availableargs)))));
571 foreach ($allargs as $arg) {
572 $o = $this->call($arg, $availableargs);
576 $output .= ($o . $args['seperator']);
578 // if more than one arg, remove the trailing seperator
579 if ($output) $output = substr($output, 0,
580 -strlen($args['seperator']));
581 return HTML($output);
586 function median($hits)
591 $median = (int)($n / 2);
592 if (!($n % 2)) // proper rounding on even length
593 return ($hits[$median] + $hits[$median - 1]) * 0.5;
595 return $hits[$median];
598 function rsum($a, $b)
604 function mean(&$hits, $total = false)
608 $total = array_reduce($hits, 'rsum');
609 return (float)$total / ($n * 1.0);
612 function stddev(&$hits, $total = false)
615 if (!$total) $total = array_reduce($hits, 'rsum');
616 $GLOBALS['mean'] = $total / $n;
617 $r = array_map(create_function('$i', 'global $mean; return ($i-$mean)*($i-$mean);'),
619 unset($GLOBALS['mean']);
620 return (float)sqrt(mean($r, $total) * ($n / (float)($n - 1)));
627 // c-hanging-comment-ender-p: nil
628 // indent-tabs-mode: nil