4 * Copyright (C) 2002,2004,2005,2006,2009 $ThePhpWikiProgrammingTeam
6 * This file is part of PhpWiki.
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.
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.
18 * You should have received a copy of the GNU General Public License
19 * along with PhpWiki; if not, write to the Free Software
20 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
26 $this->_fix_magic_quotes_gpc();
27 $this->_fix_multipart_form_data();
29 switch($this->get('REQUEST_METHOD')) {
32 $this->args = &$GLOBALS['HTTP_GET_VARS'];
35 $this->args = &$GLOBALS['HTTP_POST_VARS'];
38 $this->args = array();
42 $this->session = new Request_SessionVars;
43 $this->cookies = new Request_CookieVars;
45 if (ACCESS_LOG or ACCESS_LOG_SQL) {
46 $this->_accesslog = new Request_AccessLog(ACCESS_LOG, ACCESS_LOG_SQL);
49 $GLOBALS['request'] = $this;
53 if (!empty($GLOBALS['HTTP_SERVER_VARS']))
54 $vars = &$GLOBALS['HTTP_SERVER_VARS'];
55 elseif (!empty($GLOBALS['HTTP_ENV_VARS']))
56 $vars = &$GLOBALS['HTTP_ENV_VARS']; // cgi or other servers than Apache
58 trigger_error("Serious php configuration error!"
59 ." No HTTP_SERVER_VARS and HTTP_ENV_VARS vars available."
60 ." These should get defined in lib/prepend.php",
63 if (isset($vars[$key]))
68 $addr = $vars['REMOTE_ADDR'];
69 if (defined('ENABLE_REVERSE_DNS') && ENABLE_REVERSE_DNS)
70 return $vars[$key] = gethostbyaddr($addr);
78 function getArg($key) {
79 if (isset($this->args[$key]))
80 return $this->args[$key];
88 function setArg($key, $val) {
90 unset($this->args[$key]);
92 $this->args[$key] = $val;
95 // Well oh well. Do we really want to pass POST params back as GET?
96 function getURLtoSelf($args = false, $exclude = array()) {
97 $get_args = $this->args;
99 $get_args = array_merge($get_args, $args);
101 // leave out empty arg values
102 foreach ($get_args as $g => $v) {
103 if ($v === false or $v === '') unset($get_args[$g]);
106 // Err... good point...
108 if ($this->isPost()) {
109 $exclude = array_merge($exclude, array('action','auth'));
110 //$get_args = $args; // or only the provided
112 trigger_error("Request::getURLtoSelf() should probably not be from POST",
117 foreach ($exclude as $ex) {
118 if (!empty($get_args[$ex])) unset($get_args[$ex]);
121 $pagename = $get_args['pagename'];
122 unset ($get_args['pagename']);
123 if (!empty($get_args['action']) and $get_args['action'] == 'browse')
124 unset($get_args['action']);
126 return WikiURL($pagename, $get_args);
130 return $this->get("REQUEST_METHOD") == "POST";
133 function isGetOrHead () {
134 return in_array($this->get('REQUEST_METHOD'),
135 array('GET', 'HEAD'));
138 function httpVersion() {
139 if (!preg_match('@HTTP\s*/\s*(\d+.\d+)@', $this->get('SERVER_PROTOCOL'), $m))
141 return (float) $m[1];
144 /* Redirects after edit may fail if no theme signature image is defined.
145 * Set DISABLE_HTTP_REDIRECT = true then.
147 function redirect($url, $noreturn = true) {
148 $bogus = defined('DISABLE_HTTP_REDIRECT') && DISABLE_HTTP_REDIRECT;
151 header("Location: $url");
153 * "302 Found" is not really meant to be sent in response
154 * to a POST. Worse still, according to (both HTTP 1.0
155 * and 1.1) spec, the user, if it is sent, the user agent
156 * is supposed to use the same method to fetch the
157 * redirected URI as the original.
159 * That means if we redirect from a POST, the user-agent
160 * supposed to generate another POST. Not what we want.
161 * (We do this after a page save after all.)
163 * Fortunately, most/all browsers don't do that.
165 * "303 See Other" is what we really want. But it only
168 * FIXME: this is still not spec compliant for HTTP
171 $status = $this->httpVersion() >= 1.1 ? 303 : 302;
172 $this->setStatus($status);
176 $this->discardOutput(); // This might print the gzip headers. Not good.
177 $this->buffer_output(false);
179 include_once('lib/Template.php');
180 $tmpl = new Template('redirect', $this, array('REDIRECT_URL' => $url));
185 // Safari needs window.location.href = targeturl
187 function redirect(url) {
188 if (typeof location.replace == 'function')
189 location.replace(url);
190 else if (typeof location.assign == 'function')
191 location.assign(url);
192 else if (self.location.href)
193 self.location.href = url;
195 window.location = url;
197 redirect('" . addslashes($url) . "')");
201 /** Set validators for this response.
203 * This sets a (possibly incomplete) set of validators
206 * The validator set can be extended using appendValidators().
208 * When you're all done setting and appending validators, you
209 * must call checkValidators() to check them and set the
210 * appropriate headers in the HTTP response.
214 * $request->setValidators(array('pagename' => $pagename,
215 * '%mtime' => $rev->get('mtime')));
217 * // Wups... response content depends on $otherpage, too...
218 * $request->appendValidators(array('otherpage' => $otherpagerev->getPageName(),
219 * '%mtime' => $otherpagerev->get('mtime')));
221 * // After all validators have been set:
222 * $request->checkValidators();
224 function setValidators($validator_set) {
225 if (is_array($validator_set))
226 $validator_set = new HTTP_ValidatorSet($validator_set);
227 $this->_validators = $validator_set;
230 /** Append more validators for this response.
231 * i.e dependencies on other pages mtimes
232 * now it may be called in init also to simplify client code.
234 function appendValidators($validator_set) {
235 if (!isset($this->_validators)) {
236 $this->setValidators($validator_set);
239 $this->_validators->append($validator_set);
242 /** Check validators and set headers in HTTP response
244 * This sets the appropriate "Last-Modified" and "ETag"
245 * headers in the HTTP response.
247 * Additionally, if the validators match any(all) conditional
248 * headers in the HTTP request, this method will not return, but
249 * instead will send "304 Not Modified" or "412 Precondition
250 * Failed" (as appropriate) back to the client.
252 function checkValidators() {
253 $validators = &$this->_validators;
255 // Set validator headers
256 if (!empty($this->_is_buffering_output) or !headers_sent()) {
257 if (($etag = $validators->getETag()) !== false)
258 header("ETag: " . $etag->asString());
259 if (($mtime = $validators->getModificationTime()) !== false)
260 header("Last-Modified: " . Rfc1123DateTime($mtime));
262 // Set cache control headers
263 $this->cacheControl();
266 if (CACHE_CONTROL == 'NO_CACHE')
267 return; // don't check conditionals...
269 // Check conditional headers in request
270 $status = $validators->checkConditionalRequest($this);
272 // Return short response due to failed conditionals
273 $this->setStatus($status);
275 $this->discardOutput();
281 /** Set the cache control headers in the HTTP response.
283 function cacheControl($strategy=CACHE_CONTROL, $max_age=CACHE_CONTROL_MAX_AGE) {
284 if ($strategy == 'NO_CACHE') {
285 $cache_control = "no-cache"; // better set private. See Pear HTTP_Header
288 elseif ($strategy == 'ALLOW_STALE' && $max_age > 0) {
289 $cache_control = sprintf("max-age=%d", $max_age);
292 $cache_control = "must-revalidate";
295 header("Cache-Control: $cache_control");
296 header("Expires: " . Rfc1123DateTime(time() + $max_age));
297 header("Vary: Cookie"); // FIXME: add more here?
300 function setStatus($status) {
301 if (preg_match('|^HTTP/.*?\s(\d+)|i', $status, $m)) {
306 $status = (integer) $status;
307 $reason = array('200' => 'OK',
309 '303' => 'See Other',
310 '304' => 'Not Modified',
311 '400' => 'Bad Request',
312 '401' => 'Unauthorized',
313 '403' => 'Forbidden',
314 '404' => 'Not Found',
315 '412' => 'Precondition Failed');
316 // FIXME: is it always okay to send HTTP/1.1 here, even for older clients?
317 header(sprintf("HTTP/1.1 %d %s", $status, $reason[$status]));
320 if (isset($this->_log_entry))
321 $this->_log_entry->setStatus($status);
324 function buffer_output($compress = true) {
325 // FIXME: disables sessions (some byte before all headers_sent())
326 /*if (defined('USECACHE') and !USECACHE) {
327 $this->_is_buffering_output = false;
330 if (defined('COMPRESS_OUTPUT')) {
331 if (!COMPRESS_OUTPUT)
334 elseif (!check_php_version(4,2,3))
336 elseif (isCGI()) // necessary?
339 if ($this->getArg('start_debug')) $compress = false;
340 if ($this->getArg('nocache'))
343 // Should we compress even when apache_note is not available?
344 // sf.net bug #933183 and http://bugs.php.net/17557
345 // This effectively eliminates CGI, but all other servers also. hmm.
347 and (!function_exists('ob_gzhandler')
348 or !function_exists('apache_note')))
351 // "output handler 'ob_gzhandler' cannot be used twice"
352 // http://www.php.net/ob_gzhandler
353 if ($compress and ini_get("zlib.output_compression"))
356 // New: we check for the client Accept-Encoding: "gzip" presence also
357 // This should eliminate a lot or reported problems.
359 and (!$this->get("HTTP_ACCEPT_ENCODING")
360 or !strstr($this->get("HTTP_ACCEPT_ENCODING"), "gzip")))
363 // Most RSS clients are NOT(!) application/xml gzip compatible yet.
364 // Even if they are sending the accept-encoding gzip header!
365 // wget is, Mozilla, and MSIE no.
366 // Of the RSS readers only MagpieRSS 0.5.2 is. http://www.rssgov.com/rssparsers.html
367 // See also http://phpwiki.sourceforge.net/phpwiki/KnownBugs
369 and $this->getArg('format')
370 and strstr($this->getArg('format'), 'rss'))
374 ob_start('phpwiki_gzhandler');
376 // TODO: dont send a length or get the gzip'ed data length.
377 $this->_is_compressing_output = true;
378 header("Content-Encoding: gzip");
380 * Attempt to prevent Apache from doing the dreaded double-gzip.
382 * It would be better if we could detect when apache was going
383 * to zip for us, and then let it ... but I have yet to figure
384 * out how to do that.
386 if (function_exists('apache_note'))
387 @apache_note('no-gzip', 1);
390 // Now we alway buffer output.
391 // This is so we can set HTTP headers (e.g. for redirect)
393 // FIXME: change the name of this method.
395 $this->_is_compressing_output = false;
397 $this->_is_buffering_output = true;
398 $this->_ob_get_length = 0;
401 function discardOutput() {
402 if (!empty($this->_is_buffering_output)) {
403 if (ob_get_length()) ob_clean();
404 $this->_is_buffering_output = false;
406 trigger_error("Not buffering output", E_USER_NOTICE);
411 * Longer texts need too much memory on tiny or memory-limit=8MB systems.
412 * We might want to flush our buffer and restart again.
413 * (This would be fine if php would release its memory)
414 * Note that this must not be called inside Template expansion or other
415 * sections with ob_buffering.
417 function chunkOutput() {
418 if (!empty($this->_is_buffering_output)
420 (function_exists('ob_get_level') and @ob_get_level()))
422 $this->_do_chunked_output = true;
423 if (empty($this->_ob_get_length)) $this->_ob_get_length = 0;
424 $this->_ob_get_length += ob_get_length();
425 while (@ob_end_flush());
432 $this->_finishing = true;
433 if (!empty($this->_accesslog)) {
434 $this->_accesslog->push($this);
435 if (empty($this->_do_chunked_output) and empty($this->_ob_get_length))
436 $this->_ob_get_length = ob_get_length();
437 $this->_accesslog->setSize($this->_ob_get_length);
439 if ($RUNTIMER) $this->_accesslog->setDuration($RUNTIMER->getTime());
440 // sql logging must be done before the db is closed.
441 if (isset($this->_accesslog->logtable))
442 $this->_accesslog->write_sql();
445 if (!empty($this->_is_buffering_output)) {
446 /* This cannot work because it might destroy xml markup */
448 if (0 and $GLOBALS['SearchHighLightQuery'] and check_php_version(4,2)) {
449 $html = str_replace($GLOBALS['SearchHighLightQuery'],
450 '<span class="search-term">'.$GLOBALS['SearchHighLightQuery'].'</span>',
453 header(sprintf("Content-Length: %d", strlen($html)));
457 // if _is_compressing_output then ob_get_length() returns
458 // the uncompressed length, not the gzip'ed as required.
459 if (!headers_sent() and !$this->_is_compressing_output) {
460 // php url-rewriting miscalculates the ob length. fixes bug #1376007
461 if (ini_get('use_trans_sid') == 'off') {
462 if (empty($this->_do_chunked_output)) {
463 $this->_ob_get_length = ob_get_length();
465 header(sprintf("Content-Length: %d", $this->_ob_get_length));
468 $this->_is_buffering_output = false;
470 } elseif (function_exists('ob_get_level') and @ob_get_level()) {
473 session_write_close();
474 if (!empty($this->_dbi)) {
475 $this->_dbi->close();
482 function getSessionVar($key) {
483 return $this->session->get($key);
485 function setSessionVar($key, $val) {
486 if ($key == 'wiki_user') {
487 if (empty($val->page))
488 $val->page = $this->getArg('pagename');
489 if (empty($val->action))
490 $val->action = $this->getArg('action');
491 // avoid recursive objects and session resource handles
492 // avoid overlarge session data (max 4000 byte!)
493 if (isset($val->_group)) {
494 unset($val->_group->_request);
495 unset($val->_group->user);
497 if (ENABLE_USER_NEW) {
498 unset($val->_HomePagehandle);
499 unset($val->_auth_dbi);
502 unset($val->_authdbi);
503 unset($val->_homepage);
504 unset($val->_request);
507 return $this->session->set($key, $val);
509 function deleteSessionVar($key) {
510 return $this->session->delete($key);
513 function getCookieVar($key) {
514 return $this->cookies->get($key);
516 function setCookieVar($key, $val, $lifetime_in_days = false, $path = false) {
517 return $this->cookies->set($key, $val, $lifetime_in_days, $path);
519 function deleteCookieVar($key) {
520 return $this->cookies->delete($key);
523 function getUploadedFile($key) {
524 return Request_UploadedFile::getUploadedFile($key);
528 function _fix_magic_quotes_gpc() {
529 $needs_fix = array('HTTP_POST_VARS',
536 if (get_magic_quotes_gpc()) {
537 foreach ($needs_fix as $vars)
538 $this->_stripslashes($GLOBALS[$vars]);
542 function _stripslashes(&$var) {
543 if (is_array($var)) {
544 foreach ($var as $key => $val)
545 $this->_stripslashes($var[$key]);
547 elseif (is_string($var))
548 $var = stripslashes($var);
551 function _fix_multipart_form_data () {
552 if (preg_match('|^multipart/form-data|', $this->get('CONTENT_TYPE')))
553 $this->_strip_leading_nl($GLOBALS['HTTP_POST_VARS']);
556 function _strip_leading_nl(&$var) {
557 if (is_array($var)) {
558 foreach ($var as $key => $val)
559 $this->_strip_leading_nl($var[$key]);
561 elseif (is_string($var))
562 $var = preg_replace('|^\r?\n?|', '', $var);
566 class Request_SessionVars {
567 function Request_SessionVars() {
568 // Prevent cacheing problems with IE 5
569 session_cache_limiter('none');
571 // Avoid to get a notice if session is already started,
572 // for example if session.auto_start is activated
578 $vars = &$GLOBALS['HTTP_SESSION_VARS'];
579 if (isset($vars[$key]))
581 if (isset($_SESSION) and isset($_SESSION[$key])) // php-5.2
582 return $_SESSION[$key];
586 function set($key, $val) {
587 $vars = &$GLOBALS['HTTP_SESSION_VARS'];
588 if (!function_usable('get_cfg_var') or get_cfg_var('register_globals')) {
589 // This is funky but necessary, at least in some PHP's
590 $GLOBALS[$key] = $val;
593 if (isset($_SESSION)) // php-5.2
594 $_SESSION[$key] = $val;
595 session_register($key);
598 function delete($key) {
599 $vars = &$GLOBALS['HTTP_SESSION_VARS'];
600 if (!function_usable('ini_get') or ini_get('register_globals'))
601 unset($GLOBALS[$key]);
602 if (DEBUG) trigger_error("delete session $key", E_USER_WARNING);
604 session_unregister($key);
608 class Request_CookieVars {
611 $vars = &$GLOBALS['HTTP_COOKIE_VARS'];
612 if (isset($vars[$key])) {
613 @$decode = base64_decode($vars[$key]);
614 if (strlen($decode) > 3 and substr($decode,1,1) == ':') {
615 @$val = unserialize($decode);
619 @$val = urldecode($vars[$key]);
626 function get_old($key) {
627 $vars = &$GLOBALS['HTTP_COOKIE_VARS'];
628 if (isset($vars[$key])) {
629 @$decode = base64_decode($vars[$key]);
630 if (strlen($decode) > 3 and substr($decode,1,1) == ':') {
631 @$val = unserialize($decode);
635 @$val = unserialize($vars[$key]);
645 function set($key, $val, $persist_days = false, $path = false) {
646 // if already defined, ignore
647 if (defined('MAIN_setUser') and $key = getCookieName()) return;
648 if (defined('WIKI_XMLRPC') and WIKI_XMLRPC) return;
650 $vars = &$GLOBALS['HTTP_COOKIE_VARS'];
651 if (is_numeric($persist_days)) {
652 $expires = time() + (24 * 3600) * $persist_days;
657 if (is_array($val) or is_object($val))
658 $packedval = base64_encode(serialize($val));
660 $packedval = urlencode($val);
661 $vars[$key] = $packedval;
662 @$_COOKIE[$key] = $packedval;
664 @setcookie($key, $packedval, $expires, $path);
666 @setcookie($key, $packedval, $expires);
669 function delete($key) {
670 static $deleted = array();
671 if (isset($deleted[$key])) return;
672 if (defined('WIKI_XMLRPC') and WIKI_XMLRPC) return;
674 $vars = &$GLOBALS['HTTP_COOKIE_VARS'];
675 if (!defined('COOKIE_DOMAIN'))
676 @setcookie($key, '', 0);
678 @setcookie($key, '', 0, COOKIE_DOMAIN);
679 unset($GLOBALS['HTTP_COOKIE_VARS'][$key]);
680 unset($_COOKIE[$key]);
687 You must set "upload_tmp_dir" = "/tmp/" or "C:/tmp/"
688 Best on the same drive as apache, with forward slashes
689 and with ending slash!
690 Otherwise "\\" => "" and the uploaded file will not be found.
692 class Request_UploadedFile {
693 function getUploadedFile($postname) {
694 global $HTTP_POST_FILES;
696 // Against php5 with !ini_get('register-long-arrays'). See Bug #1180115
697 if (empty($HTTP_POST_FILES) and !empty($_FILES))
698 $HTTP_POST_FILES =& $_FILES;
699 if (!isset($HTTP_POST_FILES[$postname]))
702 $fileinfo =& $HTTP_POST_FILES[$postname];
703 if ($fileinfo['error']) {
704 // See https://sourceforge.net/forum/message.php?msg_id=3093651
705 $err = (int) $fileinfo['error'];
706 // errmsgs by Shilad Sen
709 trigger_error(_("Upload error: file too big"), E_USER_WARNING);
712 trigger_error(_("Upload error: file too big"), E_USER_WARNING);
715 trigger_error(_("Upload error: file only partially received"), E_USER_WARNING);
718 trigger_error(_("Upload error: no file selected"), E_USER_WARNING);
721 trigger_error(_("Upload error: unknown error #") . $err, E_USER_WARNING);
726 // With windows/php 4.2.1 is_uploaded_file() always returns false.
727 // Be sure that upload_tmp_dir ends with a slash!
728 if (!is_uploaded_file($fileinfo['tmp_name'])) {
730 if (!$tmp_file = get_cfg_var('upload_tmp_dir')) {
731 $tmp_file = dirname(tempnam('', ''));
733 $tmp_file .= '/' . basename($fileinfo['tmp_name']);
734 /* ending slash in php.ini upload_tmp_dir is required. */
735 if (realpath(ereg_replace('/+', '/', $tmp_file)) != realpath($fileinfo['tmp_name'])) {
736 trigger_error(sprintf("Uploaded tmpfile illegal: %s != %s.",$tmp_file, $fileinfo['tmp_name']).
738 "Probably illegal TEMP environment or upload_tmp_dir setting. ".
739 "Esp. on WINDOWS be sure to set upload_tmp_dir in php.ini to use forward slashes and ".
740 "end with a slash. upload_tmp_dir = \"C:/WINDOWS/TEMP/\" is good suggestion.",
745 trigger_error(sprintf("Workaround for PHP/Windows is_uploaded_file() problem for %s.",
746 $fileinfo['tmp_name'])."\n".
747 "Probably illegal TEMP environment or upload_tmp_dir setting.",
753 trigger_error(sprintf("Uploaded tmpfile %s not found.", $fileinfo['tmp_name'])."\n".
754 " Probably illegal TEMP environment or upload_tmp_dir setting.",
758 return new Request_UploadedFile($fileinfo);
761 function Request_UploadedFile($fileinfo) {
762 $this->_info = $fileinfo;
766 return $this->_info['size'];
770 return $this->_info['name'];
774 return $this->_info['type'];
777 function getTmpName() {
778 return $this->_info['tmp_name'];
782 if ( ($fd = fopen($this->_info['tmp_name'], "rb")) ) {
783 if ($this->getSize() < filesize($this->_info['tmp_name'])) {
784 // FIXME: Some PHP's (or is it some browsers?) put
785 // HTTP/MIME headers in the file body, some don't.
787 // At least, I think that's the case. I know I used
788 // to need this code, now I don't.
790 // This code is more-or-less untested currently.
792 // Dump HTTP headers.
793 while ( ($header = fgets($fd, 4096)) ) {
794 if (trim($header) == '') {
797 else if (!preg_match('/^content-(length|type):/i', $header)) {
807 function getContents() {
809 $data = fread($fd, $this->getSize());
816 * Create NCSA "combined" log entry for current request.
817 * Also needed for advanced spam prevention.
818 * global object holding global state (sql or file, entries, to dump)
820 class Request_AccessLog {
822 * @param $logfile string Log file name.
824 function Request_AccessLog ($logfile, $do_sql = false) {
825 //global $request; // request not yet initialized!
827 $this->logfile = $logfile;
828 if ($logfile and !is_writeable($logfile)) {
830 (sprintf(_("%s is not writable."), _("The PhpWiki access log file"))
832 . sprintf(_("Please ensure that %s is writable, or redefine %s in config/config.ini."),
833 sprintf(_("the file '%s'"), ACCESS_LOG),
837 //$request->_accesslog =& $this;
838 //if (empty($request->_accesslog->entries))
839 register_shutdown_function("Request_AccessLogEntry_shutdown_function");
843 if (!in_array($DBParams['dbtype'], array('SQL','ADODB'))) {
844 trigger_error("Unsupported database backend for ACCESS_LOG_SQL.\nNeed DATABASE_TYPE=SQL or ADODB");
846 //$this->_dbi =& $request->_dbi;
847 $this->logtable = (!empty($DBParams['prefix']) ? $DBParams['prefix'] : '')."accesslog";
850 $this->entries = array();
851 $this->entries[] = new Request_AccessLogEntry($this);
854 function _do($cmd, &$arg) {
856 for ($i=0; $i < count($this->entries);$i++)
857 $this->entries[$i]->$cmd($arg);
859 function push(&$request) { $this->_do('push',$request); }
860 function setSize($arg) { $this->_do('setSize',$arg); }
861 function setStatus($arg) { $this->_do('setStatus',$arg); }
862 function setDuration($arg) { $this->_do('setDuration',$arg); }
865 * Read sequentially all previous entries from the beginning.
866 * while ($logentry = Request_AccessLogEntry::read()) ;
867 * For internal log analyzers: RecentReferrers, WikiAccessRestrictions
870 return $this->logtable ? $this->read_sql() : $this->read_file();
874 * Return iterator of referer items reverse sorted (latest first).
876 function get_referer($limit=15, $external_only=false) {
877 if ($external_only) { // see stdlin.php:isExternalReferrer()
879 $blen = strlen($base);
881 if (!empty($this->_dbi)) {
882 // check same hosts in referer and request and remove them
883 $ext_where = " AND LEFT(referer,$blen) <> ".$this->_dbi->quote($base)
884 ." AND LEFT(referer,$blen) <> LEFT(CONCAT(".$this->_dbi->quote(SERVER_URL).",request_uri),$blen)";
885 return $this->_read_sql_query("(referer <>'' AND NOT(ISNULL(referer)))"
886 .($external_only ? $ext_where : '')
887 ." ORDER BY time_stamp DESC"
888 .($limit ? " LIMIT $limit" : ""));
890 $iter = new WikiDB_Array_generic_iter(0);
891 $logs =& $iter->_array;
892 while ($logentry = $this->read_file()) {
893 if (!empty($logentry->referer)
894 and (!$external_only or (substr($logentry->referer,0,$blen) != $base)))
896 $iter->_array[] = $logentry;
897 if ($limit and count($logs) > $limit)
901 $logs = array_reverse($logs);
902 $logs = array_slice($logs,0,min($limit,count($logs)));
908 * Return iterator of matching host items reverse sorted (latest first).
910 function get_host($host, $since_minutes=20) {
911 if ($this->logtable) {
912 // mysql specific only:
913 return $this->read_sql("request_host=".$this->_dbi->quote($host)." AND time_stamp > ". (time()-$since_minutes*60)
914 ." ORDER BY time_stamp DESC");
916 $iter = new WikiDB_Array_generic_iter();
917 $logs =& $iter->_array;
918 $logentry = new Request_AccessLogEntry($this);
919 while ($logentry->read_file()) {
920 if (!empty($logentry->referer)) {
921 $iter->_array[] = $logentry;
922 if ($limit and count($logs) > $limit)
924 $logentry = new Request_AccessLogEntry($this);
927 $logs = array_reverse($logs);
928 $logs = array_slice($logs,0,min($limit,count($logs)));
934 * Read sequentially all previous entries from log file.
936 function read_file() {
938 if ($this->logfile) $this->logfile = ACCESS_LOG; // support Request_AccessLog::read
940 if (empty($this->reader)) // start at the beginning
941 $this->reader = fopen($this->logfile, "r");
942 if ($s = fgets($this->reader)) {
943 $entry = new Request_AccessLogEntry($this);
944 if (preg_match('/^(\S+)\s(\S+)\s(\S+)\s\[(.+?)\] "([^"]+)" (\d+) (\d+) "([^"]*)" "([^"]*)"$/',$s,$m)) {
945 list(,$entry->host, $entry->ident, $entry->user, $entry->time,
946 $entry->request, $entry->status, $entry->size,
947 $entry->referer, $entry->user_agent) = $m;
950 } else { // until the end
951 fclose($this->reader);
955 function _read_sql_query($where='') {
956 $dbh =& $GLOBALS['request']->_dbi;
957 $log_tbl =& $this->logtable;
958 return $dbh->genericSqlIter("SELECT *,request_uri as request,request_time as time,remote_user as user,"
959 ."remote_host as host,agent as user_agent"
961 . ($where ? " WHERE $where" : ""));
963 function read_sql($where='') {
964 if (empty($this->sqliter))
965 $this->sqliter = $this->_read_sql_query($where);
966 return $this->sqliter->next();
969 /* done in request->finish() before the db is closed */
970 function write_sql() {
971 $dbh =& $GLOBALS['request']->_dbi;
972 if (isset($this->entries) and $dbh and $dbh->isOpen())
973 foreach ($this->entries as $entry) {
977 /* done in the shutdown callback */
978 function write_file() {
979 if (isset($this->entries) and $this->logfile)
980 foreach ($this->entries as $entry) {
981 $entry->write_file();
983 unset($this->entries);
985 /* in an ideal world... */
987 if ($this->logfile) $this->write_file();
988 if ($this->logtable) $this->write_sql();
989 unset($this->entries);
993 class Request_AccessLogEntry
998 * The log entry will be automatically appended to the log file or
999 * SQL table when the current request terminates.
1001 * If you want to modify a Request_AccessLogEntry before it gets
1002 * written (e.g. via the setStatus and setSize methods) you should
1003 * use an '&' on the constructor, so that you're working with the
1004 * original (rather than a copy) object.
1007 * $log_entry = & new Request_AccessLogEntry("/tmp/wiki_access_log");
1008 * $log_entry->setStatus(401);
1009 * $log_entry->push($request);
1014 function Request_AccessLogEntry (&$accesslog) {
1015 $this->_accesslog = $accesslog;
1016 $this->logfile = $accesslog->logfile;
1017 $this->time = time();
1018 $this->status = 200; // see setStatus()
1019 $this->size = 0; // see setSize()
1023 * @param $request object Request object for current request.
1025 function push(&$request) {
1026 $this->host = $request->get('REMOTE_HOST');
1027 $this->ident = $request->get('REMOTE_IDENT');
1030 $user = $request->getUser();
1031 if ($user->isAuthenticated())
1032 $this->user = $user->UserName();
1035 $this->request = join(' ', array($request->get('REQUEST_METHOD'),
1036 $request->get('REQUEST_URI'),
1037 $request->get('SERVER_PROTOCOL')));
1038 $this->referer = (string) $request->get('HTTP_REFERER');
1039 $this->user_agent = (string) $request->get('HTTP_USER_AGENT');
1043 * Set result status code.
1045 * @param $status integer HTTP status code.
1047 function setStatus ($status) {
1048 $this->status = $status;
1052 * Set response size.
1054 * @param $size integer
1056 function setSize ($size=0) {
1057 $this->size = (int)$size;
1059 function setDuration ($seconds) {
1060 // Pear DB does not correctly quote , in floats using ?. e.g. in european locales.
1062 $this->duration = strtr(sprintf("%f", $seconds),",",".");
1066 * Get time zone offset.
1068 * This is a static member function.
1070 * @param $time integer Unix timestamp (defaults to current time).
1071 * @return string Zone offset, e.g. "-0800" for PST.
1073 function _zone_offset ($time = false) {
1076 $offset = date("Z", $time);
1082 $offhours = floor($offset / 3600);
1083 $offmins = $offset / 60 - $offhours * 60;
1084 return sprintf("%s%02d%02d", $negoffset, $offhours, $offmins);
1088 * Format time in NCSA format.
1090 * This is a static member function.
1092 * @param $time integer Unix timestamp (defaults to current time).
1093 * @return string Formatted date & time.
1095 function _ncsa_time($time = false) {
1098 return date("d/M/Y:H:i:s", $time) .
1099 " " . $this->_zone_offset();
1103 if ($this->_accesslog->logfile) $this->write_file();
1104 if ($this->_accesslog->logtable) $this->write_sql();
1108 * Write entry to log file.
1110 function write_file() {
1111 $entry = sprintf('%s %s %s [%s] "%s" %d %d "%s" "%s"',
1112 $this->host, $this->ident, $this->user,
1113 $this->_ncsa_time($this->time),
1114 $this->request, $this->status, $this->size,
1115 $this->referer, $this->user_agent);
1116 if (!empty($this->_accesslog->reader)) {
1117 fclose($this->_accesslog->reader);
1118 unset($this->_accesslog->reader);
1120 //Error log doesn't provide locking.
1121 //error_log("$entry\n", 3, $this->logfile);
1123 if (($fp = fopen($this->logfile, "a"))) {
1124 flock($fp, LOCK_EX);
1125 fputs($fp, "$entry\n");
1130 /* This is better been done by apache mod_log_sql */
1131 /* If ACCESS_LOG_SQL & 2 we do write it by our own */
1132 function write_sql() {
1135 $dbh =& $request->_dbi;
1136 if ($dbh and $dbh->isOpen() and $this->_accesslog->logtable) {
1137 //$log_tbl =& $this->_accesslog->logtable;
1138 if ($request->get('REQUEST_METHOD') == "POST") {
1139 // strangely HTTP_POST_VARS doesn't contain all posted vars.
1140 if (check_php_version(4,2))
1141 $args = $_POST; // copy not ref. clone not needed on hashes
1143 $args = $GLOBALS['HTTP_POST_VARS'];
1145 if (!empty($args['auth']['passwd'])) $args['auth']['passwd'] = '<not displayed>';
1146 if (!empty($args['dbadmin']['passwd'])) $args['dbadmin']['passwd'] = '<not displayed>';
1147 if (!empty($args['pref']['passwd'])) $args['pref']['passwd'] = '<not displayed>';
1148 if (!empty($args['pref']['passwd2'])) $args['pref']['passwd2'] = '<not displayed>';
1149 $this->request_args = substr(serialize($args),0,254); // if VARCHAR(255) is used.
1151 $this->request_args = $request->get('QUERY_STRING');
1153 $this->request_method = $request->get('REQUEST_METHOD');
1154 $this->request_uri = $request->get('REQUEST_URI');
1155 // duration problem: sprintf "%f" might use comma e.g. "100,201" in european locales
1156 $dbh->_backend->write_accesslog($this);
1162 * Shutdown callback.
1165 * @see Request_AccessLogEntry
1167 function Request_AccessLogEntry_shutdown_function () {
1170 if (isset($request->_accesslog->entries) and $request->_accesslog->logfile)
1171 foreach ($request->_accesslog->entries as $entry) {
1172 $entry->write_file();
1174 unset($request->_accesslog->entries);
1179 function HTTP_ETag($val, $is_weak=false) {
1180 $this->_val = wikihash($val);
1181 $this->_weak = $is_weak;
1186 * Strong comparison: If either (or both) tag is weak, they
1189 function equals($that, $strong_match=false) {
1190 if ($this->_val != $that->_val)
1192 if ($strong_match and ($this->_weak or $that->_weak))
1198 function asString() {
1199 $quoted = '"' . addslashes($this->_val) . '"';
1200 return $this->_weak ? "W/$quoted" : $quoted;
1203 /** Parse tag from header.
1205 * This is a static member function.
1207 function parse($strval) {
1208 if (!preg_match(':^(W/)?"(.+)"$:i', trim($strval), $m))
1209 return false; // parse failed
1210 list(,$weak,$str) = $m;
1211 return new HTTP_ETag(stripslashes($str), $weak);
1214 function matches($taglist, $strong_match=false) {
1215 $taglist = trim($taglist);
1217 if ($taglist == '*') {
1219 return ! $this->_weak;
1224 while (preg_match('@^(W/)?"((?:\\\\.|[^"])*)"\s*,?\s*@i',
1226 list($match, $weak, $str) = $m;
1227 $taglist = substr($taglist, strlen($match));
1228 $tag = new HTTP_ETag(stripslashes($str), $weak);
1229 if ($this->equals($tag, $strong_match)) {
1237 // Possible results from the HTTP_ValidatorSet::_check*() methods.
1238 // (Higher numerical values take precedence.)
1239 define ('_HTTP_VAL_PASS', 0); // Test is irrelevant
1240 define ('_HTTP_VAL_NOT_MODIFIED', 1); // Test passed, content not changed
1241 define ('_HTTP_VAL_MODIFIED', 2); // Test failed, content changed
1242 define ('_HTTP_VAL_FAILED', 3); // Precondition failed.
1244 class HTTP_ValidatorSet {
1245 function HTTP_ValidatorSet($validators) {
1246 $this->_mtime = $this->_weak = false;
1247 $this->_tag = array();
1249 foreach ($validators as $key => $val) {
1250 if ($key == '%mtime') {
1251 $this->_mtime = $val;
1253 elseif ($key == '%weak') {
1255 $this->_weak = true;
1258 $this->_tag[$key] = $val;
1263 function append($that) {
1264 if (is_array($that))
1265 $that = new HTTP_ValidatorSet($that);
1267 // Pick the most recent mtime
1268 if (isset($that->_mtime))
1269 if (!isset($this->_mtime) || $that->_mtime > $this->_mtime)
1270 $this->_mtime = $that->_mtime;
1272 // If either is weak, we're weak
1273 if (!empty($that->_weak))
1274 $this->_weak = true;
1275 if (is_array($this->_tag))
1276 $this->_tag = array_merge($this->_tag, $that->_tag);
1278 $this->_tag = $that->_tag;
1281 function getETag() {
1284 return new HTTP_ETag($this->_tag, $this->_weak);
1287 function getModificationTime() {
1288 return $this->_mtime;
1291 function checkConditionalRequest (&$request) {
1292 $result = max($this->_checkIfUnmodifiedSince($request),
1293 $this->_checkIfModifiedSince($request),
1294 $this->_checkIfMatch($request),
1295 $this->_checkIfNoneMatch($request));
1297 if ($result == _HTTP_VAL_PASS || $result == _HTTP_VAL_MODIFIED)
1298 return false; // "please proceed with normal processing"
1299 elseif ($result == _HTTP_VAL_FAILED)
1300 return 412; // "412 Precondition Failed"
1301 elseif ($result == _HTTP_VAL_NOT_MODIFIED)
1302 return 304; // "304 Not Modified"
1304 trigger_error("Ack, shouldn't get here", E_USER_ERROR);
1308 function _checkIfUnmodifiedSince(&$request) {
1309 if ($this->_mtime !== false) {
1310 $since = ParseRfc1123DateTime($request->get("HTTP_IF_UNMODIFIED_SINCE"));
1311 if ($since !== false && $this->_mtime > $since)
1312 return _HTTP_VAL_FAILED;
1314 return _HTTP_VAL_PASS;
1317 function _checkIfModifiedSince(&$request) {
1318 if ($this->_mtime !== false and $request->isGetOrHead()) {
1319 $since = ParseRfc1123DateTime($request->get("HTTP_IF_MODIFIED_SINCE"));
1320 if ($since !== false) {
1321 if ($this->_mtime <= $since)
1322 return _HTTP_VAL_NOT_MODIFIED;
1323 return _HTTP_VAL_MODIFIED;
1326 return _HTTP_VAL_PASS;
1329 function _checkIfMatch(&$request) {
1330 if ($this->_tag && ($taglist = $request->get("HTTP_IF_MATCH"))) {
1331 $tag = $this->getETag();
1332 if (!$tag->matches($taglist, 'strong'))
1333 return _HTTP_VAL_FAILED;
1335 return _HTTP_VAL_PASS;
1338 function _checkIfNoneMatch(&$request) {
1339 if ($this->_tag && ($taglist = $request->get("HTTP_IF_NONE_MATCH"))) {
1340 $tag = $this->getETag();
1341 $strong_compare = ! $request->isGetOrHead();
1343 if ($tag->matches($taglist, $strong_compare)) {
1344 if ($request->isGetOrHead())
1345 return _HTTP_VAL_NOT_MODIFIED;
1347 return _HTTP_VAL_FAILED;
1349 return _HTTP_VAL_MODIFIED;
1352 return _HTTP_VAL_PASS;
1359 // c-basic-offset: 4
1360 // c-hanging-comment-ender-p: nil
1361 // indent-tabs-mode: nil