]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/plugin/SystemInfo.php
Spelling: seperator --> separator
[SourceForge/phpwiki.git] / lib / plugin / SystemInfo.php
1 <?php
2
3 /**
4  * Copyright (C) 1999, 2000, 2001, 2002 $ThePhpWikiProgrammingTeam
5  * Copyright 2008-2009 Marc-Etienne Vargenau, Alcatel-Lucent
6  *
7  * This file is part of PhpWiki.
8  *
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.
13  *
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.
18  *
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.
22  */
23
24 /**
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 >>
30  *
31  * Provide access to phpwiki's lower level system information.
32  *
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
37  *
38  * In spirit to http://www.ecyrd.com/JSPWiki/SystemInfo.jsp
39  *
40  * Done: Some calculations are heavy (~5-8 secs), so we should cache
41  *       the result. In the page or with WikiPluginCached?
42  */
43
44 require_once 'lib/WikiPluginCached.php';
45
46 class WikiPlugin_SystemInfo
47     extends WikiPluginCached
48 {
49     public $_dbi;
50
51     function getPluginType()
52     {
53         return PLUGIN_CACHED_HTML;
54     }
55
56     function getDescription()
57     {
58         return _("Provide access to PhpWiki's lower level system information.");
59     }
60
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.
66      */
67     function managesValidators()
68     {
69         return true;
70     }
71
72     function getExpire($dbi, $argarray, $request)
73     {
74         return '+1800'; // 30 minutes
75     }
76
77     /**
78      * @param WikiDB $dbi
79      * @param array $argarray
80      * @param WikiRequest $request
81      * @param string $basepage
82      * @return mixed
83      */
84     protected function getHtml($dbi, $argarray, $request, $basepage)
85     {
86         $loader = new WikiPluginLoader();
87         return $loader->expandPI('<<SystemInfo '
88             . WikiPluginCached::glueArgs($argarray) // all
89             . ' ?>', $request, $this, $basepage);
90     }
91
92     protected function getImage($dbi, $argarray, $request)
93     {
94         trigger_error('pure virtual', E_USER_ERROR);
95     }
96
97     protected function getMap($dbi, $argarray, $request)
98     {
99         trigger_error('pure virtual', E_USER_ERROR);
100     }
101
102     function getDefaultArguments()
103     {
104         return array( // 'separator' => ' ', // on multiple args
105         );
106     }
107
108     function database()
109     {
110         $s = "DATABASE_TYPE: " . DATABASE_TYPE . ", ";
111         switch (DATABASE_TYPE) {
112             case 'SQL': // pear
113             case 'ADODB':
114             case 'PDO':
115                 $dsn = DATABASE_DSN;
116                 $s .= "DATABASE BACKEND:" . " ";
117                 $s .= (DATABASE_TYPE == 'SQL') ? 'PearDB' : 'ADODB';
118                 if (preg_match('/^(\w+):/', $dsn, $m)) {
119                     $backend = $m[1];
120                     $s .= " $backend";
121                 }
122                 $s .= ", DATABASE_PREFIX: \"" . DATABASE_PREFIX . "\", ";
123                 break;
124             case 'dba':
125                 $s .= "DATABASE_DBA_HANDLER: " . DATABASE_DBA_HANDLER . ", ";
126                 $s .= "DATABASE_DIRECTORY: \"" . DATABASE_DIRECTORY . "\", ";
127                 break;
128             case 'cvs':
129                 $s .= "DATABASE_DIRECTORY: \"" . DATABASE_DIRECTORY . "\", ";
130                 // $s .= "cvs stuff: , ";
131                 break;
132             case 'flatfile':
133                 $s .= "DATABASE_DIRECTORY: " . DATABASE_DIRECTORY . ", ";
134                 break;
135         }
136         // hack: suppress error when using sql, so no timeout
137         @$s .= "DATABASE_TIMEOUT: " . DATABASE_TIMEOUT;
138         return $s;
139     }
140
141     function cachestats()
142     {
143         if (!defined('USECACHE') or !USECACHE)
144             return _("no cache used");
145         $dbi =& $this->_dbi;
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: ?";
153         return $s;
154     }
155
156     function ExpireParams()
157     {
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']);
171         return $s;
172     }
173
174     function pagestats()
175     {
176         global $request;
177         $dbi = $request->getDbh();
178         $s = sprintf(_("%d pages"), $dbi->numPages(true));
179         $s .= ", " . sprintf(_("%d not-empty pages"), $dbi->numPages(false));
180         // more bla....
181         // $s  .= ", " . sprintf(_("earliest page from %s"), $earliestdate);
182         // $s  .= ", " . sprintf(_("latest page from %s"), $latestdate);
183         // $s  .= ", " . sprintf(_("latest pagerevision from %s"), $latestrevdate);
184         return $s;
185     }
186
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?
190     function linkstats()
191     {
192         $s = _("not yet");
193         return $s;
194     }
195
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.
201     function userstats()
202     {
203         $dbi =& $this->_dbi;
204         $h = 0;
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.
208                 $h++;
209         }
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?
215         return $s;
216     }
217
218     //only from logging info possible. = hitstats per time.
219     // total hits per day/month/year
220     // view/edit rate
221     // TODO: see WhoIsOnline hit stats, and sql accesslogs
222     function accessstats()
223     {
224         $s = _("not yet");
225         return $s;
226     }
227
228     // numeric array
229     private function get_stats($hits, $treshold = 10.0)
230     {
231         sort($hits);
232         reset($hits);
233         $n = count($hits);
234         $max = 0;
235         $min = 9999999999999;
236         $sum = 0;
237         foreach ($hits as $h) {
238             $sum += $h;
239             $max = max($h, $max);
240             $min = min($h, $min);
241         }
242         $mean = $n ? $sum / $n : 0;
243         $median = $hits[ (int)($n / 2) ];
244         $mintreshold = $max * $treshold / 100.0; // lower than 10% of the hits
245         reset($hits);
246         $nmin = $hits[0] < $mintreshold ? 1 : 0;
247         while (next($hits) < $mintreshold)
248             $nmin++;
249         $maxtreshold = $max - $mintreshold; // more than 90% of the hits
250         end($hits);
251         $nmax = 1;
252         while (prev($hits) > $maxtreshold)
253             $nmax++;
254         return array('n' => $n,
255             'sum' => $sum,
256             'min' => $min,
257             'max' => $max,
258             'mean' => $mean,
259             'median' => $median,
260             'stddev' => stddev($hits, $sum),
261             'treshold' => $treshold,
262             'nmin' => $nmin,
263             'mintreshold' => $mintreshold,
264             'nmax' => $nmax,
265             'maxtreshold' => $maxtreshold);
266     }
267
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
273     function hitstats()
274     {
275         $dbi =& $this->_dbi;
276         $hits = array();
277         $page_iter = $dbi->getAllPages(true);
278         while ($page = $page_iter->next()) {
279             if (($current = $page->getCurrentRevision())
280                 && (!$current->hasDefaultContents())
281             ) {
282                 $hits[] = $page->get('hits');
283             }
284         }
285         $treshold = 10.0;
286         $stats = $this->get_stats($hits, $treshold);
287
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);
297         return $s;
298     }
299
300     /* not yet ready
301      */
302     function revisionstats()
303     {
304         global $LANG;
305
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);
311
312         if (!empty($content))
313             return $content;
314
315         $dbi =& $this->_dbi;
316         $stats = array();
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()) {
321                 $stats['empty']++;
322                 continue;
323             }
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']++;
329             else
330                 $stats['latest']['minor']++;
331             /*
332                         // FIXME: This needs much too long to be acceptable.
333                         // overall:
334                         //   number of revisions: all (100%) / major (60%) / minor (40%)
335                         // revs per page:
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']++;
341                             else
342                                 $stats['page']['minor']++;
343                         }
344                         $rev_iter->free();
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();
352             */
353         }
354         $page_iter->free();
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'],
360             $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']);
364         /*
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']);
370
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;
386         */
387         $content = $empty . $latest;
388
389         // regenerate cache every 30 minutes
390         $cache->save($id, $content, '+1800', $cachedir);
391         return $content;
392     }
393
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.
398     function discspace()
399     {
400         global $DBParams;
401
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);
407
408         if (empty($content)) {
409             $dir = defined('PHPWIKI_DIR') ? PHPWIKI_DIR : '.';
410             //TODO: windows only (no cygwin)
411             $appsize = `du -s $dir | cut -f1`;
412
413             if (in_array($DBParams['dbtype'], array('SQL', 'ADODB'))) {
414                 //TODO: where is the data is actually stored? see phpMyAdmin
415                 $pagesize = 0;
416             } elseif ($DBParams['dbtype'] == 'dba') {
417                 $pagesize = 0;
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;
427             }
428             $content = array('appsize' => $appsize,
429                 'pagesize' => $pagesize);
430             // regenerate cache every 30 minutes
431             $cache->save($id, $content, '+1800', $cachedir);
432         } else {
433             $appsize = $content['appsize'];
434             $pagesize = $content['pagesize'];
435         }
436
437         $s = sprintf(_("Application size: %d KiB"), $appsize);
438         if ($pagesize)
439             $s .= ", " . sprintf(_("Pagedata size: %d KiB", $pagesize));
440         return $s;
441     }
442
443     function inlineimages()
444     {
445         return implode(' ', explode('|', INLINE_IMAGES));
446     }
447
448     function wikinameregexp()
449     {
450         return $GLOBALS['WikiNameRegexp'];
451     }
452
453     function allowedprotocols()
454     {
455         return implode(' ', explode('|', ALLOWED_PROTOCOLS));
456     }
457
458     function available_plugins()
459     {
460         $fileset = new FileSet(FindFile('lib/plugin'), '*.php');
461         $list = $fileset->getFiles();
462         natcasesort($list);
463         reset($list);
464         return sprintf(_("Total %d plugins: "), count($list))
465             . implode(', ', array_map(create_function('$f',
466                     'return substr($f,0,-4);'),
467                 $list));
468     }
469
470     function supported_languages()
471     {
472         $available_languages = listAvailableLanguages();
473         natcasesort($available_languages);
474
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
481                 : '');
482     }
483
484     function supported_themes()
485     {
486         global $WikiTheme;
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
494                 : '');
495     }
496
497     function call($arg, &$availableargs)
498     {
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'))
504         )
505             return constant($arg); else
506             return $this->error(sprintf(_("unknown argument ā€œ%sā€ to SystemInfo"), $arg));
507     }
508
509     /**
510      * @param WikiDB $dbi
511      * @param string $argstr
512      * @param WikiRequest $request
513      * @param string $basepage
514      * @return mixed
515      */
516     function run($dbi, $argstr, &$request, $basepage)
517     {
518         // don't parse argstr for name=value pairs. instead we use just 'name'
519         //$args = $this->getArgs($argstr, $request);
520         $this->_dbi =& $dbi;
521         $args['separator'] = ' ';
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';")
533             );
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"),
556 //                           '' => _(""),
557                 '' => ""
558             );
559             $table = HTML::table(array('class' => 'bordered'));
560             foreach ($allargs as $arg => $desc) {
561                 if (!$arg)
562                     continue;
563                 if (!$desc)
564                     $desc = _($arg);
565                 $table->pushContent(HTML::tr(HTML::th(array('style' => "white-space:nowrap"), $desc),
566                     HTML::td(HTML($this->call($arg, $availableargs)))));
567             }
568             return $table;
569         } else {
570             $output = '';
571             foreach ($allargs as $arg) {
572                 $o = $this->call($arg, $availableargs);
573                 if (is_object($o))
574                     return $o;
575                 else
576                     $output .= ($o . $args['separator']);
577             }
578             // if more than one arg, remove the trailing separator
579             if ($output) $output = substr($output, 0,
580                 -strlen($args['separator']));
581             return HTML($output);
582         }
583     }
584 }
585
586 function median($hits)
587 {
588     sort($hits);
589     reset($hits);
590     $n = count($hits);
591     $median = (int)($n / 2);
592     if (!($n % 2)) // proper rounding on even length
593         return ($hits[$median] + $hits[$median - 1]) * 0.5;
594     else
595         return $hits[$median];
596 }
597
598 function rsum($a, $b)
599 {
600     $a += $b;
601     return $a;
602 }
603
604 function mean(&$hits, $total = false)
605 {
606     $n = count($hits);
607     if (!$total)
608         $total = array_reduce($hits, 'rsum');
609     return (float)$total / ($n * 1.0);
610 }
611
612 function stddev(&$hits, $total = false)
613 {
614     $n = count($hits);
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);'),
618         $hits);
619     unset($GLOBALS['mean']);
620     return (float)sqrt(mean($r, $total) * ($n / (float)($n - 1)));
621 }
622
623 // Local Variables:
624 // mode: php
625 // tab-width: 8
626 // c-basic-offset: 4
627 // c-hanging-comment-ender-p: nil
628 // indent-tabs-mode: nil
629 // End: