]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/AccessLog.php
Use CSS
[SourceForge/phpwiki.git] / lib / AccessLog.php
1 <?php
2
3 /*
4  * Copyright 2005, 2007 Reini Urban
5  *
6  * This file is part of PhpWiki.
7  *
8  * PhpWiki is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * PhpWiki is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License along
19  * with PhpWiki; if not, write to the Free Software Foundation, Inc.,
20  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21  */
22
23 /**
24  * Read and write file and SQL accesslog. Write sequentially.
25  *
26  * Read from file per pagename: Hits
27  *
28  */
29
30 /**
31  * Create NCSA "combined" log entry for current request.
32  * Also needed for advanced spam prevention.
33  * global object holding global state (sql or file, entries, to dump)
34  */
35 class Request_AccessLog
36 {
37     /**
38      * @param $logfile string  Log file name.
39      */
40     function Request_AccessLog($logfile, $do_sql = false)
41     {
42         //global $request; // request not yet initialized!
43
44         $this->logfile = $logfile;
45         if ($logfile and !is_writeable($logfile)) {
46             trigger_error
47             (sprintf(_("%s is not writable."), _("The PhpWiki access log file"))
48                     . "\n"
49                     . sprintf(_("Please ensure that %s is writable, or redefine %s in config/config.ini."),
50                         sprintf(_("the file ā€œ%sā€"), ACCESS_LOG),
51                         'ACCESS_LOG')
52                 , E_USER_NOTICE);
53         }
54         //$request->_accesslog =& $this;
55         //if (empty($request->_accesslog->entries))
56         register_shutdown_function("Request_AccessLogEntry_shutdown_function");
57
58         if ($do_sql) {
59             if (!$request->_dbi->isSQL()) {
60                 trigger_error("Unsupported database backend for ACCESS_LOG_SQL.\nNeed DATABASE_TYPE=SQL or ADODB or PDO");
61             } else {
62                 global $DBParams;
63                 //$this->_dbi =& $request->_dbi;
64                 $this->logtable = (!empty($DBParams['prefix']) ? $DBParams['prefix'] : '') . "accesslog";
65             }
66         }
67         $this->entries = array();
68         $this->entries[] = new Request_AccessLogEntry($this);
69     }
70
71     function _do($cmd, &$arg)
72     {
73         if ($this->entries)
74             for ($i = 0; $i < count($this->entries); $i++)
75                 $this->entries[$i]->$cmd($arg);
76     }
77
78     function push(&$request)
79     {
80         $this->_do('push', $request);
81     }
82
83     function setSize($arg)
84     {
85         $this->_do('setSize', $arg);
86     }
87
88     function setStatus($arg)
89     {
90         $this->_do('setStatus', $arg);
91     }
92
93     function setDuration($arg)
94     {
95         $this->_do('setDuration', $arg);
96     }
97
98     /**
99      * Read sequentially all previous entries from the beginning.
100      * while ($logentry = Request_AccessLogEntry::read()) ;
101      * For internal log analyzers: RecentReferrers, WikiAccessRestrictions
102      */
103     function read()
104     {
105         return $this->logtable ? $this->read_sql() : $this->read_file();
106     }
107
108     /**
109      * Return iterator of referer items reverse sorted (latest first).
110      */
111     function get_referer($limit = 15, $external_only = false)
112     {
113         if ($external_only) { // see stdlin.php:isExternalReferrer()
114             $base = SERVER_URL;
115             $blen = strlen($base);
116         }
117         if (!empty($this->_dbi)) {
118             // check same hosts in referer and request and remove them
119             $ext_where = " AND LEFT(referer,$blen) <> " . $this->_dbi->quote($base)
120                 . " AND LEFT(referer,$blen) <> LEFT(CONCAT(" . $this->_dbi->quote(SERVER_URL) . ",request_uri),$blen)";
121             return $this->_read_sql_query("(referer <>'' AND NOT(ISNULL(referer)))"
122                 . ($external_only ? $ext_where : '')
123                 . " ORDER BY time_stamp DESC"
124                 . ($limit ? " LIMIT $limit" : ""));
125         } else {
126             $iter = new WikiDB_Array_generic_iter(0);
127             $logs =& $iter->_array;
128             while ($logentry = $this->read_file()) {
129                 if (!empty($logentry->referer)
130                     and (!$external_only or (substr($logentry->referer, 0, $blen) != $base))
131                 ) {
132                     $iter->_array[] = $logentry;
133                     if ($limit and count($logs) > $limit)
134                         array_shift($logs);
135                 }
136             }
137             $logs = array_reverse($logs);
138             $logs = array_slice($logs, 0, min($limit, count($logs)));
139             return $iter;
140         }
141     }
142
143     /**
144      * Read sequentially backwards all previous entries from log file.
145      * FIXME!
146      */
147     function read_file()
148     {
149         global $request;
150         if ($this->logfile) $this->logfile = ACCESS_LOG; // support Request_AccessLog::read
151
152         if (empty($this->reader)) // start at the beginning
153             $this->reader = fopen($this->logfile, "r");
154         if ($s = fgets($this->reader)) {
155             $entry = new Request_AccessLogEntry($this);
156             $re = '/^(\S+)\s(\S+)\s(\S+)\s\[(.+?)\] "([^"]+)" (\d+) (\d+) "([^"]*)" "([^"]*)"$/';
157             if (preg_match($re, $s, $m)) {
158                 list(, $entry->host, $entry->ident, $entry->user, $entry->time,
159                     $entry->request, $entry->status, $entry->size,
160                     $entry->referer, $entry->user_agent) = $m;
161             }
162             return $entry;
163         } else { // until the end
164             fclose($this->reader);
165             return false;
166         }
167     }
168
169     function read_sql($where = '')
170     {
171         if (empty($this->sqliter))
172             $this->sqliter = $this->_read_sql_query($where);
173         return $this->sqliter->next();
174     }
175
176     function _read_sql_query($where = '')
177     {
178         global $request;
179         $dbh =& $request->_dbi;
180         $log_tbl =& $this->logtable;
181         return $dbh->genericSqlIter("SELECT *,request_uri as request,request_time as time,remote_user as user,"
182             . "remote_host as host,agent as user_agent"
183             . " FROM $log_tbl"
184             . ($where ? " WHERE $where" : ""));
185     }
186
187     /* done in request->finish() before the db is closed */
188     function write_sql()
189     {
190         global $request;
191         $dbh =& $request->_dbi;
192         if (isset($this->entries) and $dbh and $dbh->isOpen())
193             foreach ($this->entries as $entry) {
194                 $entry->write_sql();
195             }
196     }
197
198     /* done in the shutdown callback */
199     function write_file()
200     {
201         if (isset($this->entries) and $this->logfile)
202             foreach ($this->entries as $entry) {
203                 $entry->write_file();
204             }
205         unset($this->entries);
206     }
207
208     /* in an ideal world... */
209     function write()
210     {
211         if ($this->logfile) $this->write_file();
212         if ($this->logtable) $this->write_sql();
213         unset($this->entries);
214     }
215 }
216
217 class Request_AccessLogEntry
218 {
219     /**
220      * Constructor.
221      *
222      * The log entry will be automatically appended to the log file or
223      * SQL table when the current request terminates.
224      *
225      * If you want to modify a Request_AccessLogEntry before it gets
226      * written (e.g. via the setStatus and setSize methods) you should
227      * use an '&' on the constructor, so that you're working with the
228      * original (rather than a copy) object.
229      *
230      * <pre>
231      *    $log_entry = & new Request_AccessLogEntry("/tmp/wiki_access_log");
232      *    $log_entry->setStatus(401);
233      *    $log_entry->push($request);
234      * </pre>
235      *
236      *
237      */
238     function Request_AccessLogEntry(&$accesslog)
239     {
240         $this->_accesslog = $accesslog;
241         $this->logfile = $accesslog->logfile;
242         $this->time = time();
243         $this->status = 200; // see setStatus()
244         $this->size = 0; // see setSize()
245     }
246
247     /**
248      * @param $request object  Request object for current request.
249      */
250     function push(&$request)
251     {
252         $this->host = $request->get('REMOTE_HOST');
253         $this->ident = $request->get('REMOTE_IDENT');
254         if (!$this->ident)
255             $this->ident = '-';
256         $user = $request->getUser();
257         if ($user->isAuthenticated())
258             $this->user = $user->UserName();
259         else
260             $this->user = '-';
261         $this->request = join(' ', array($request->get('REQUEST_METHOD'),
262             $request->get('REQUEST_URI'),
263             $request->get('SERVER_PROTOCOL')));
264         $this->referer = (string)$request->get('HTTP_REFERER');
265         $this->user_agent = (string)$request->get('HTTP_USER_AGENT');
266     }
267
268     /**
269      * Set result status code.
270      *
271      * @param $status integer  HTTP status code.
272      */
273     function setStatus($status)
274     {
275         $this->status = $status;
276     }
277
278     /**
279      * Set response size.
280      *
281      * @param $size integer
282      */
283     function setSize($size = 0)
284     {
285         $this->size = (int)$size;
286     }
287
288     function setDuration($seconds)
289     {
290         // Pear DB does not correctly quote , in floats using ?. e.g. in european locales.
291         // Workaround:
292         $this->duration = str_replace(",", ".", sprintf("%f", $seconds));
293     }
294
295     /**
296      * Get time zone offset.
297      *
298      * This is a static member function.
299      *
300      * @param $time integer Unix timestamp (defaults to current time).
301      * @return string Zone offset, e.g. "-0800" for PST.
302      */
303     function _zone_offset($time = false)
304     {
305         if (!$time)
306             $time = time();
307         $offset = date("Z", $time);
308         $negoffset = "";
309         if ($offset < 0) {
310             $negoffset = "-";
311             $offset = -$offset;
312         }
313         $offhours = floor($offset / 3600);
314         $offmins = $offset / 60 - $offhours * 60;
315         return sprintf("%s%02d%02d", $negoffset, $offhours, $offmins);
316     }
317
318     /**
319      * Format time in NCSA format.
320      *
321      * This is a static member function.
322      *
323      * @param $time integer Unix timestamp (defaults to current time).
324      * @return string Formatted date & time.
325      */
326     function _ncsa_time($time = false)
327     {
328         if (!$time)
329             $time = time();
330         return date("d/M/Y:H:i:s", $time) .
331             " " . $this->_zone_offset();
332     }
333
334     function write()
335     {
336         if ($this->_accesslog->logfile) $this->write_file();
337         if ($this->_accesslog->logtable) $this->write_sql();
338     }
339
340     /**
341      * Write entry to log file.
342      */
343     function write_file()
344     {
345         $entry = sprintf('%s %s %s [%s] "%s" %d %d "%s" "%s"',
346             $this->host, $this->ident, $this->user,
347             $this->_ncsa_time($this->time),
348             $this->request, $this->status, $this->size,
349             $this->referer, $this->user_agent);
350         if (!empty($this->_accesslog->reader)) {
351             fclose($this->_accesslog->reader);
352             unset($this->_accesslog->reader);
353         }
354         //Error log doesn't provide locking.
355         //error_log("$entry\n", 3, $this->logfile);
356         // Alternate method
357         if (($fp = fopen($this->logfile, "a"))) {
358             flock($fp, LOCK_EX);
359             fputs($fp, "$entry\n");
360             fclose($fp);
361         }
362     }
363
364     /* This is better been done by apache mod_log_sql */
365     /* If ACCESS_LOG_SQL & 2 we do write it by our own */
366     function write_sql()
367     {
368         global $request;
369
370         $dbh =& $request->_dbi;
371         if ($dbh and $dbh->isOpen() and $this->_accesslog->logtable) {
372             //$log_tbl =& $this->_accesslog->logtable;
373             if ($request->get('REQUEST_METHOD') == "POST") {
374                 // strangely HTTP_POST_VARS doesn't contain all posted vars.
375                 $args = $_POST; // copy not ref. clone not needed on hashes
376                 // garble passwords
377                 if (!empty($args['auth']['passwd'])) $args['auth']['passwd'] = '<not displayed>';
378                 if (!empty($args['dbadmin']['passwd'])) $args['dbadmin']['passwd'] = '<not displayed>';
379                 if (!empty($args['pref']['passwd'])) $args['pref']['passwd'] = '<not displayed>';
380                 if (!empty($args['pref']['passwd2'])) $args['pref']['passwd2'] = '<not displayed>';
381                 $this->request_args = substr(serialize($args), 0, 254); // if VARCHAR(255) is used.
382             } else {
383                 $this->request_args = $request->get('QUERY_STRING');
384             }
385             $this->request_method = $request->get('REQUEST_METHOD');
386             $this->request_uri = $request->get('REQUEST_URI');
387             // duration problem: sprintf "%f" might use comma e.g. "100,201" in european locales
388             $dbh->_backend->write_accesslog($this);
389         }
390     }
391 }
392
393 /**
394  * Shutdown callback. Ensures that the file is written.
395  *
396  * @access private
397  * @see Request_AccessLogEntry
398  */
399 function Request_AccessLogEntry_shutdown_function()
400 {
401     global $request;
402
403     if (isset($request->_accesslog->entries) and $request->_accesslog->logfile)
404         foreach ($request->_accesslog->entries as $entry) {
405             $entry->write_file();
406         }
407     unset($request->_accesslog->entries);
408 }
409
410 // TODO: SQL access methods....
411 // (c) 2005 Charles Corrigan (the mysql parts)
412 // (c) 2006 Rein Urban (the postgresql parts)
413 // from AnalyseAccessLogSql.php
414 class Request_AccessLog_SQL
415 {
416
417     /**
418      * Build the query string
419      *
420      * FIXME: some or all of these queries may be MySQL specific / non-portable
421      * FIXME: properly quote the string args
422      *
423      * The column names displayed are generated from the actual query column
424      * names, so make sure that each column in the query is given a user
425      * friendly name. Note that the column names are passed to _() and so may be
426      * translated.
427      *
428      * If there are query specific where conditions, then the construction
429      * "    if ($where_conditions<>'')
430      *          $where_conditions = 'WHERE '.$where_conditions.' ';"
431      * should be changed to
432      * "    if ($where_conditions<>'')
433      *          $where_conditions = 'AND '.$where_conditions.' ';"
434      * and in the assignment to query have something like
435      * "    $query= "SELECT "
436      *          ."referer "
437      *          ."FROM $accesslog "
438      *          ."WHERE referer IS NOT NULL "
439      *          .$where_conditions
440      */
441     function _getQueryString(&$args)
442     {
443         // extract any parametrised conditions from the arguments,
444         // in particular, how much history to select
445         $where_conditions = $this->_getWhereConditions($args);
446
447         // get the correct name for the table
448         //FIXME is there a more correct way to do this?
449         global $DBParams, $request;
450         $accesslog = (!empty($DBParams['prefix']) ? $DBParams['prefix'] : '') . "accesslog";
451
452         $query = '';
453         $backend_type = $request->_dbi->_backend->backendType();
454         switch ($backend_type) {
455             case 'mysql':
456                 $Referring_URL = "left(referer,length(referer)-instr(reverse(referer),'?'))";
457                 break;
458             case 'pgsql':
459             case 'postgres7':
460                 $Referring_URL = "substr(referer,0,position('?' in referer))";
461                 break;
462             default:
463                 $Referring_URL = "referer";
464         }
465         switch ($args['mode']) {
466             case 'referring_urls':
467                 if ($where_conditions <> '')
468                     $where_conditions = 'WHERE ' . $where_conditions . ' ';
469                 $query = "SELECT "
470                     . "$Referring_URL AS Referring_URL, "
471                     . "count(*) AS Referral_Count "
472                     . "FROM $accesslog "
473                     . $where_conditions
474                     . "GROUP BY Referring_URL";
475                 break;
476             case 'external_referers':
477                 $args['local_referrers'] = 'false';
478                 $where_conditions = $this->_getWhereConditions($args);
479                 if ($where_conditions <> '')
480                     $where_conditions = 'WHERE ' . $where_conditions . ' ';
481                 $query = "SELECT "
482                     . "$Referring_URL AS Referring_URL, "
483                     . "count(*) AS Referral_Count "
484                     . "FROM $accesslog "
485                     . $where_conditions
486                     . "GROUP BY Referring_URL";
487                 break;
488             case 'referring_domains':
489                 if ($where_conditions <> '')
490                     $where_conditions = 'WHERE ' . $where_conditions . ' ';
491                 switch ($backend_type) {
492                     case 'mysql':
493                         $Referring_Domain = "left(referer, if(locate('/', referer, 8) > 0,locate('/', referer, 8) -1, length(referer)))";
494                         break;
495                     case 'pgsql':
496                     case 'postgres7':
497                         $Referring_Domain = "substr(referer,0,8) || regexp_replace(substr(referer,8), '/.*', '')";
498                         break;
499                     default:
500                         $Referring_Domain = "referer";
501                         break;
502                 }
503                 $query = "SELECT "
504                     . "$Referring_Domain AS Referring_Domain, "
505                     . "count(*) AS Referral_Count "
506                     . "FROM $accesslog "
507                     . $where_conditions
508                     . "GROUP BY Referring_Domain";
509                 break;
510             case 'remote_hosts':
511                 if ($where_conditions <> '')
512                     $where_conditions = 'WHERE ' . $where_conditions . ' ';
513                 $query = "SELECT "
514                     . "remote_host AS Remote_Host, "
515                     . "count(*) AS Access_Count "
516                     . "FROM $accesslog "
517                     . $where_conditions
518                     . "GROUP BY Remote_Host";
519                 break;
520             case 'users':
521                 if ($where_conditions <> '')
522                     $where_conditions = 'WHERE ' . $where_conditions . ' ';
523                 $query = "SELECT "
524                     . "remote_user AS User, "
525                     . "count(*) AS Access_Count "
526                     . "FROM $accesslog "
527                     . $where_conditions
528                     . "GROUP BY remote_user";
529                 break;
530             case 'host_users':
531                 if ($where_conditions <> '')
532                     $where_conditions = 'WHERE ' . $where_conditions . ' ';
533                 $query = "SELECT "
534                     . "remote_host AS Remote_Host, "
535                     . "remote_user AS User, "
536                     . "count(*) AS Access_Count "
537                     . "FROM $accesslog "
538                     . $where_conditions
539                     . "GROUP BY remote_host, remote_user";
540                 break;
541             case "search_bots":
542                 // This queries for all entries in the SQL access log table that
543                 // have a dns name that I know to be a web search engine crawler and
544                 // categorises the results into time buckets as per the list below
545                 // 0 - 1 minute - 60
546                 // 1 - 1 hour   - 3600     = 60 * 60
547                 // 2 - 1 day    - 86400    = 60 * 60 * 24
548                 // 3 - 1 week   - 604800   = 60 * 60 * 24 * 7
549                 // 4 - 1 month  - 2629800  = 60 * 60 * 24 * 365.25 / 12
550                 // 5 - 1 year   - 31557600 = 60 * 60 * 24 * 365.25
551                 $now = time();
552                 $query = "SELECT "
553                     . "CASE WHEN $now-time_stamp<60 THEN '" . _("0 - last minute") . "' ELSE "
554                     . "CASE WHEN $now-time_stamp<3600 THEN '" . _("1 - 1 minute to 1 hour") . "' ELSE "
555                     . "CASE WHEN $now-time_stamp<86400 THEN '" . _("2 - 1 hour to 1 day") . "' ELSE "
556                     . "CASE WHEN $now-time_stamp<604800 THEN '" . _("3 - 1 day to 1 week") . "' ELSE "
557                     . "CASE WHEN $now-time_stamp<2629800 THEN '" . _("4 - 1 week to 1 month") . "' ELSE "
558                     . "CASE WHEN $now-time_stamp<31557600 THEN '" . _("5 - 1 month to 1 year") . "' ELSE "
559                     . "'" . _("6 - more than 1 year") . "' END END END END END END AS Time_Scale, "
560                     . "remote_host AS Remote_Host, "
561                     . "count(*) AS Access_Count "
562                     . "FROM $accesslog "
563                     . "WHERE (remote_host LIKE '%googlebot.com' "
564                     . "OR remote_host LIKE '%alexa.com' "
565                     . "OR remote_host LIKE '%inktomisearch.com' "
566                     . "OR remote_host LIKE '%msnbot.msn.com') "
567                     . ($where_conditions ? 'AND ' . $where_conditions : '')
568                     . "GROUP BY Time_Scale, remote_host";
569                 break;
570             case "search_bots_hits":
571                 // This queries for all entries in the SQL access log table that
572                 // have a dns name that I know to be a web search engine crawler and
573                 // displays the URI that was hit.
574                 // If PHPSESSID appears in the URI, just display the URI to the left of this
575                 $sessname = session_name();
576                 switch ($backend_type) {
577                     case 'mysql':
578                         $Request_URI = "IF(instr(request_uri, '$sessname')=0, request_uri,left(request_uri, instr(request_uri, '$sessname')-2))";
579                         break;
580                     case 'pgsql':
581                     case 'postgres7':
582                         $Request_URI = "regexp_replace(request_uri, '$sessname.*', '')";
583                         break;
584                     default:
585                         $Request_URI = 'request_uri';
586                         break;
587                 }
588                 $now = time();
589                 $query = "SELECT "
590                     . "CASE WHEN $now-time_stamp<60 THEN '" . _("0 - last minute") . "' ELSE "
591                     . "CASE WHEN $now-time_stamp<3600 THEN '" . _("1 - 1 minute to 1 hour") . "' ELSE "
592                     . "CASE WHEN $now-time_stamp<86400 THEN '" . _("2 - 1 hour to 1 day") . "' ELSE "
593                     . "CASE WHEN $now-time_stamp<604800 THEN '" . _("3 - 1 day to 1 week") . "' ELSE "
594                     . "CASE WHEN $now-time_stamp<2629800 THEN '" . _("4 - 1 week to 1 month") . "' ELSE "
595                     . "CASE WHEN $now-time_stamp<31557600 THEN '" . _("5 - 1 month to 1 year") . "' ELSE "
596                     . "'" . _("6 - more than 1 year") . "' END END END END END END AS Time_Scale, "
597                     . "remote_host AS Remote_Host, "
598                     . "$Request_URI AS Request_URI "
599                     . "FROM $accesslog "
600                     . "WHERE (remote_host LIKE '%googlebot.com' "
601                     . "OR remote_host LIKE '%alexa.com' "
602                     . "OR remote_host LIKE '%inktomisearch.com' "
603                     . "OR remote_host LIKE '%msnbot.msn.com') "
604                     . ($where_conditions ? 'AND ' . $where_conditions : '')
605                     . "ORDER BY time_stamp";
606         }
607         return $query;
608     }
609
610     /** Honeypot for xgettext. Those strings are translated dynamically.
611      */
612     function _locale_dummy()
613     {
614         $dummy = array(
615             // mode caption
616             _("referring_urls"),
617             _("external_referers"),
618             _("referring_domains"),
619             _("remote_hosts"),
620             _("users"),
621             _("host_users"),
622             _("search_bots"),
623             _("search_bots_hits"),
624             // period header
625             _("minutes"),
626             _("hours"),
627             _("days"),
628             _("weeks"),
629         );
630     }
631
632     function getDefaultArguments()
633     {
634         return array(
635             'mode' => 'referring_domains',
636             // referring_domains, referring_urls, remote_hosts, users, host_users, search_bots, search_bots_hits
637             'caption' => '',
638             // blank means use the mode as the caption/title for the output
639             'local_referrers' => 'true', // only show external referring sites
640             'period' => '', // the type of period to report:
641             // may be weeks, days, hours, minutes, or blank for all
642             'count' => '0' // the number of periods to report
643         );
644     }
645
646     function table_output()
647     {
648         $query = $this->_getQueryString($args);
649
650         if ($query == '')
651             return HTML::p(sprintf(_("Unrecognised parameter 'mode=%s'"),
652                 $args['mode']));
653
654         // get the data back.
655         // Note that this must be done before the final generation ofthe table,
656         // otherwise the headers will not be ready
657         $tbody = $this->_getQueryResults($query, $dbi);
658
659         return HTML::table(array('border' => 1),
660             HTML::caption($this->_getCaption($args)),
661             HTML::thead($this->_theadrow),
662             $tbody);
663     }
664
665     function _getQueryResults($query, &$dbi)
666     {
667         $queryResult = $dbi->genericSqlIter($query);
668         if (!$queryResult) {
669             $tbody = HTML::tbody(HTML::tr(HTML::td(_("<empty>"))));
670         } else {
671             $tbody = HTML::tbody();
672             while ($row = $queryResult->next()) {
673                 $this->_setHeaders($row);
674                 $tr = HTML::tr();
675                 foreach ($row as $value) {
676                     // output a '-' for empty values, otherwise the table looks strange
677                     $tr->pushContent(HTML::td(empty($value) ? '-' : $value));
678                 }
679                 $tbody->pushContent($tr);
680             }
681         }
682         $queryResult->free();
683         return $tbody;
684     }
685
686     function _setHeaders($row)
687     {
688         if (!$this->_headerSet) {
689             foreach ($row as $key => $value) {
690                 $this->_theadrow->pushContent(HTML::th(_($key)));
691             }
692             $this->_headerSet = true;
693         }
694     }
695
696     function _getWhereConditions(&$args)
697     {
698         $where_conditions = '';
699
700         if ($args['period'] <> '') {
701             $since = 0;
702             if ($args['period'] == 'minutes') {
703                 $since = 60;
704             } elseif ($args['period'] == 'hours') {
705                 $since = 60 * 60;
706             } elseif ($args['period'] == 'days') {
707                 $since = 60 * 60 * 24;
708             } elseif ($args['period'] == 'weeks') {
709                 $since = 60 * 60 * 24 * 7;
710             }
711             $since = $since * $args['count'];
712             if ($since > 0) {
713                 if ($where_conditions <> '')
714                     $where_conditions = $where_conditions . ' AND ';
715                 $since = time() - $since;
716                 $where_conditions = $where_conditions . "time_stamp > $since";
717             }
718         }
719
720         if ($args['local_referrers'] <> 'true') {
721             global $request;
722             if ($where_conditions <> '')
723                 $where_conditions = $where_conditions . ' AND ';
724             $localhost = SERVER_URL;
725             $len = strlen($localhost);
726             $backend_type = $request->_dbi->_backend->backendType();
727             switch ($backend_type) {
728                 case 'mysql':
729                     $ref_localhost = "left(referer,$len)<>'$localhost'";
730                     break;
731                 case 'pgsql':
732                 case 'postgres7':
733                     $ref_localhost = "substr(referer,0,$len)<>'$localhost'";
734                     break;
735                 default:
736                     $ref_localhost = "";
737             }
738             $where_conditions = $where_conditions . $ref_localhost;
739         }
740
741         // The assumed contract is that there is a space at the end of the
742         // conditions string, so that following SQL clauses (such as GROUP BY)
743         // will not cause a syntax error
744         if ($where_conditions <> '')
745             $where_conditions = $where_conditions . ' ';
746
747         return $where_conditions;
748     }
749
750     function _getCaption(&$args)
751     {
752         $caption = $args['caption'];
753         if ($caption == '')
754             $caption = gettext($args['mode']);
755         if ($args['period'] <> '' && $args['count'])
756             $caption = $caption . " - " . $args['count'] . " " . gettext($args['period']);
757         return $caption;
758     }
759
760 }
761
762 // Local Variables:
763 // mode: php
764 // tab-width: 8
765 // c-basic-offset: 4
766 // c-hanging-comment-ender-p: nil
767 // indent-tabs-mode: nil
768 // End: