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 along
19 * with PhpWiki; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
28 $this->_fix_magic_quotes_gpc();
29 $this->_fix_multipart_form_data();
31 switch ($this->get('REQUEST_METHOD')) {
34 $this->args = &$GLOBALS['HTTP_GET_VARS'];
37 $this->args = &$GLOBALS['HTTP_POST_VARS'];
40 $this->args = array();
44 $this->session = new Request_SessionVars;
45 $this->cookies = new Request_CookieVars;
47 if (ACCESS_LOG or ACCESS_LOG_SQL) {
48 $this->_accesslog = new Request_AccessLog(ACCESS_LOG, ACCESS_LOG_SQL);
51 $GLOBALS['request'] = $this;
56 if (!empty($GLOBALS['HTTP_SERVER_VARS']))
57 $vars = &$GLOBALS['HTTP_SERVER_VARS'];
58 elseif (!empty($GLOBALS['HTTP_ENV_VARS']))
59 $vars = &$GLOBALS['HTTP_ENV_VARS']; // cgi or other servers than Apache
61 trigger_error("Serious php configuration error!"
62 . " No HTTP_SERVER_VARS and HTTP_ENV_VARS vars available."
63 . " These should get defined in lib/prepend.php",
66 if (isset($vars[$key]))
71 $addr = $vars['REMOTE_ADDR'];
72 if (defined('ENABLE_REVERSE_DNS') && ENABLE_REVERSE_DNS)
73 return $vars[$key] = gethostbyaddr($addr);
83 if (isset($this->args[$key]))
84 return $this->args[$key];
93 function setArg($key, $val)
96 unset($this->args[$key]);
98 $this->args[$key] = $val;
101 // Well oh well. Do we really want to pass POST params back as GET?
102 function getURLtoSelf($args = false, $exclude = array())
104 $get_args = $this->args;
106 $get_args = array_merge($get_args, $args);
108 // leave out empty arg values
109 foreach ($get_args as $g => $v) {
110 if ($v === false or $v === '') unset($get_args[$g]);
113 // Err... good point...
115 if ($this->isPost()) {
116 $exclude = array_merge($exclude, array('action', 'auth'));
117 //$get_args = $args; // or only the provided
119 trigger_error("Request::getURLtoSelf() should probably not be from POST",
124 foreach ($exclude as $ex) {
125 if (!empty($get_args[$ex])) unset($get_args[$ex]);
128 $pagename = $get_args['pagename'];
129 unset ($get_args['pagename']);
130 if (!empty($get_args['action']) and $get_args['action'] == 'browse')
131 unset($get_args['action']);
133 return WikiURL($pagename, $get_args);
138 return $this->get("REQUEST_METHOD") == "POST";
141 function isGetOrHead()
143 return in_array($this->get('REQUEST_METHOD'),
144 array('GET', 'HEAD'));
147 function httpVersion()
149 if (!preg_match('@HTTP\s*/\s*(\d+.\d+)@', $this->get('SERVER_PROTOCOL'), $m))
154 /* Redirects after edit may fail if no theme signature image is defined.
155 * Set DISABLE_HTTP_REDIRECT = true then.
157 function redirect($url, $noreturn = true)
159 $bogus = defined('DISABLE_HTTP_REDIRECT') && DISABLE_HTTP_REDIRECT;
162 header("Location: $url");
164 * "302 Found" is not really meant to be sent in response
165 * to a POST. Worse still, according to (both HTTP 1.0
166 * and 1.1) spec, the user, if it is sent, the user agent
167 * is supposed to use the same method to fetch the
168 * redirected URI as the original.
170 * That means if we redirect from a POST, the user-agent
171 * supposed to generate another POST. Not what we want.
172 * (We do this after a page save after all.)
174 * Fortunately, most/all browsers don't do that.
176 * "303 See Other" is what we really want. But it only
179 * FIXME: this is still not spec compliant for HTTP
182 $status = $this->httpVersion() >= 1.1 ? 303 : 302;
183 $this->setStatus($status);
187 $this->discardOutput(); // This might print the gzip headers. Not good.
188 $this->buffer_output(false);
190 include_once 'lib/Template.php';
191 $tmpl = new Template('redirect', $this, array('REDIRECT_URL' => $url));
195 // Safari needs window.location.href = targeturl
197 function redirect(url) {
198 if (typeof location.replace == 'function')
199 location.replace(url);
200 else if (typeof location.assign == 'function')
201 location.assign(url);
202 else if (self.location.href)
203 self.location.href = url;
205 window.location = url;
207 redirect('" . addslashes($url) . "')");
211 /** Set validators for this response.
213 * This sets a (possibly incomplete) set of validators
216 * The validator set can be extended using appendValidators().
218 * When you're all done setting and appending validators, you
219 * must call checkValidators() to check them and set the
220 * appropriate headers in the HTTP response.
224 * $request->setValidators(array('pagename' => $pagename,
225 * '%mtime' => $rev->get('mtime')));
227 * // Wups... response content depends on $otherpage, too...
228 * $request->appendValidators(array('otherpage' => $otherpagerev->getPageName(),
229 * '%mtime' => $otherpagerev->get('mtime')));
231 * // After all validators have been set:
232 * $request->checkValidators();
234 function setValidators($validator_set)
236 if (is_array($validator_set))
237 $validator_set = new HTTP_ValidatorSet($validator_set);
238 $this->_validators = $validator_set;
241 /** Append more validators for this response.
242 * i.e dependencies on other pages mtimes
243 * now it may be called in init also to simplify client code.
245 function appendValidators($validator_set)
247 if (!isset($this->_validators)) {
248 $this->setValidators($validator_set);
251 $this->_validators->append($validator_set);
254 /** Check validators and set headers in HTTP response
256 * This sets the appropriate "Last-Modified" and "ETag"
257 * headers in the HTTP response.
259 * Additionally, if the validators match any(all) conditional
260 * headers in the HTTP request, this method will not return, but
261 * instead will send "304 Not Modified" or "412 Precondition
262 * Failed" (as appropriate) back to the client.
264 function checkValidators()
266 $validators = &$this->_validators;
268 // Set validator headers
269 if (!empty($this->_is_buffering_output) or !headers_sent()) {
270 if (($etag = $validators->getETag()) !== false)
271 header("ETag: " . $etag->asString());
272 if (($mtime = $validators->getModificationTime()) !== false)
273 header("Last-Modified: " . Rfc1123DateTime($mtime));
275 // Set cache control headers
276 $this->cacheControl();
279 if (CACHE_CONTROL == 'NO_CACHE')
280 return; // don't check conditionals...
282 // Check conditional headers in request
283 $status = $validators->checkConditionalRequest($this);
285 // Return short response due to failed conditionals
286 $this->setStatus($status);
288 $this->discardOutput();
294 /** Set the cache control headers in the HTTP response.
296 function cacheControl($strategy = CACHE_CONTROL, $max_age = CACHE_CONTROL_MAX_AGE)
298 if ($strategy == 'NO_CACHE') {
299 $cache_control = "no-cache"; // better set private. See Pear HTTP_Header
301 } elseif ($strategy == 'ALLOW_STALE' && $max_age > 0) {
302 $cache_control = sprintf("max-age=%d", $max_age);
304 $cache_control = "must-revalidate";
307 header("Cache-Control: $cache_control");
308 header("Expires: " . Rfc1123DateTime(time() + $max_age));
309 header("Vary: Cookie"); // FIXME: add more here?
312 function setStatus($status)
314 if (preg_match('|^HTTP/.*?\s(\d+)|i', $status, $m)) {
318 $status = (integer)$status;
319 $reason = array('200' => 'OK',
321 '303' => 'See Other',
322 '304' => 'Not Modified',
323 '400' => 'Bad Request',
324 '401' => 'Unauthorized',
325 '403' => 'Forbidden',
326 '404' => 'Not Found',
327 '412' => 'Precondition Failed');
328 // FIXME: is it always okay to send HTTP/1.1 here, even for older clients?
329 header(sprintf("HTTP/1.1 %d %s", $status, $reason[$status]));
332 if (isset($this->_log_entry))
333 $this->_log_entry->setStatus($status);
336 function buffer_output($compress = true)
338 // FIXME: disables sessions (some byte before all headers_sent())
339 /*if (defined('USECACHE') and !USECACHE) {
340 $this->_is_buffering_output = false;
343 if (defined('COMPRESS_OUTPUT')) {
344 if (!COMPRESS_OUTPUT)
346 } elseif (isCGI()) // necessary?
349 if ($this->getArg('start_debug')) $compress = false;
350 if ($this->getArg('nocache'))
353 // Should we compress even when apache_note is not available?
354 // sf.net bug #933183 and http://bugs.php.net/17557
355 // This effectively eliminates CGI, but all other servers also. hmm.
357 and (!function_exists('ob_gzhandler')
358 or !function_exists('apache_note'))
362 // "output handler 'ob_gzhandler' cannot be used twice"
363 // http://www.php.net/ob_gzhandler
364 if ($compress and ini_get("zlib.output_compression"))
367 // New: we check for the client Accept-Encoding: "gzip" presence also
368 // This should eliminate a lot or reported problems.
370 and (!$this->get("HTTP_ACCEPT_ENCODING")
371 or !strstr($this->get("HTTP_ACCEPT_ENCODING"), "gzip"))
375 // Most RSS clients are NOT(!) application/xml gzip compatible yet.
376 // Even if they are sending the accept-encoding gzip header!
377 // wget is, Mozilla, and MSIE no.
378 // Of the RSS readers only MagpieRSS 0.5.2 is. http://www.rssgov.com/rssparsers.html
379 // See also http://phpwiki.sourceforge.net/phpwiki/KnownBugs
381 and $this->getArg('format')
382 and strstr($this->getArg('format'), 'rss')
387 ob_start('phpwiki_gzhandler');
389 // TODO: dont send a length or get the gzip'ed data length.
390 $this->_is_compressing_output = true;
391 header("Content-Encoding: gzip");
393 * Attempt to prevent Apache from doing the dreaded double-gzip.
395 * It would be better if we could detect when apache was going
396 * to zip for us, and then let it ... but I have yet to figure
397 * out how to do that.
399 if (function_exists('apache_note'))
400 @apache_note('no-gzip', 1);
402 // Now we alway buffer output.
403 // This is so we can set HTTP headers (e.g. for redirect)
405 // FIXME: change the name of this method.
407 $this->_is_compressing_output = false;
409 $this->_is_buffering_output = true;
410 $this->_ob_get_length = 0;
413 function discardOutput()
415 if (!empty($this->_is_buffering_output)) {
416 if (ob_get_length()) ob_clean();
417 $this->_is_buffering_output = false;
419 trigger_error("Not buffering output", E_USER_NOTICE);
424 * Longer texts need too much memory on tiny or memory-limit=8MB systems.
425 * We might want to flush our buffer and restart again.
426 * (This would be fine if php would release its memory)
427 * Note that this must not be called inside Template expansion or other
428 * sections with ob_buffering.
430 function chunkOutput()
432 if (!empty($this->_is_buffering_output)
434 (function_exists('ob_get_level') and @ob_get_level())
436 $this->_do_chunked_output = true;
437 if (empty($this->_ob_get_length)) $this->_ob_get_length = 0;
438 $this->_ob_get_length += ob_get_length();
439 while (ob_get_level() > 0) {
442 if (ob_get_level() > 0) {
451 $this->_finishing = true;
452 if (!empty($this->_accesslog)) {
453 $this->_accesslog->push($this);
454 if (empty($this->_do_chunked_output) and empty($this->_ob_get_length))
455 $this->_ob_get_length = ob_get_length();
456 $this->_accesslog->setSize($this->_ob_get_length);
458 if ($RUNTIMER) $this->_accesslog->setDuration($RUNTIMER->getTime());
459 // sql logging must be done before the db is closed.
460 if (isset($this->_accesslog->logtable))
461 $this->_accesslog->write_sql();
464 if (!empty($this->_is_buffering_output)) {
465 // if _is_compressing_output then ob_get_length() returns
466 // the uncompressed length, not the gzip'ed as required.
467 if (!headers_sent() and !$this->_is_compressing_output) {
468 // php url-rewriting miscalculates the ob length. fixes bug #1376007
469 if (ini_get('use_trans_sid') == 'off') {
470 if (empty($this->_do_chunked_output)) {
471 $this->_ob_get_length = ob_get_length();
473 header(sprintf("Content-Length: %d", $this->_ob_get_length));
476 $this->_is_buffering_output = false;
478 } elseif (function_exists('ob_get_level') and @ob_get_level()) {
481 session_write_close();
482 if (!empty($this->_dbi)) {
483 $this->_dbi->close();
490 function getSessionVar($key)
492 return $this->session->get($key);
495 function setSessionVar($key, $val)
497 if ($key == 'wiki_user') {
498 if (empty($val->page))
499 $val->page = $this->getArg('pagename');
500 if (empty($val->action))
501 $val->action = $this->getArg('action');
502 // avoid recursive objects and session resource handles
503 // avoid overlarge session data (max 4000 byte!)
504 if (isset($val->_group)) {
505 unset($val->_group->_request);
506 unset($val->_group->user);
508 if (ENABLE_USER_NEW) {
509 unset($val->_HomePagehandle);
510 unset($val->_auth_dbi);
513 unset($val->_authdbi);
514 unset($val->_homepage);
515 unset($val->_request);
518 return $this->session->set($key, $val);
521 function deleteSessionVar($key)
523 return $this->session->delete($key);
526 function getCookieVar($key)
528 return $this->cookies->get($key);
531 function setCookieVar($key, $val, $lifetime_in_days = false, $path = false)
533 return $this->cookies->set($key, $val, $lifetime_in_days, $path);
536 function deleteCookieVar($key)
538 return $this->cookies->delete($key);
541 function getUploadedFile($key)
543 return Request_UploadedFile::getUploadedFile($key);
546 function _fix_magic_quotes_gpc()
548 $needs_fix = array('HTTP_POST_VARS',
555 if (get_magic_quotes_gpc()) {
556 foreach ($needs_fix as $vars)
557 $this->_stripslashes($GLOBALS[$vars]);
561 function _stripslashes(&$var)
563 if (is_array($var)) {
564 foreach ($var as $key => $val)
565 $this->_stripslashes($var[$key]);
566 } elseif (is_string($var))
567 $var = stripslashes($var);
570 function _fix_multipart_form_data()
572 if (preg_match('|^multipart/form-data|', $this->get('CONTENT_TYPE')))
573 $this->_strip_leading_nl($GLOBALS['HTTP_POST_VARS']);
576 function _strip_leading_nl(&$var)
578 if (is_array($var)) {
579 foreach ($var as $key => $val)
580 $this->_strip_leading_nl($var[$key]);
581 } elseif (is_string($var))
582 $var = preg_replace('|^\r?\n?|', '', $var);
586 class Request_SessionVars
588 function Request_SessionVars()
590 // Prevent cacheing problems with IE 5
591 session_cache_limiter('none');
593 // Avoid to get a notice if session is already started,
594 // for example if session.auto_start is activated
601 $vars = &$GLOBALS['HTTP_SESSION_VARS'];
602 if (isset($vars[$key]))
604 if (isset($_SESSION) and isset($_SESSION[$key])) // php-5.2
605 return $_SESSION[$key];
609 function set($key, $val)
611 $vars = &$GLOBALS['HTTP_SESSION_VARS'];
612 if (!function_usable('get_cfg_var') or get_cfg_var('register_globals')) {
613 // This is funky but necessary, at least in some PHP's
614 $GLOBALS[$key] = $val;
617 if (isset($_SESSION)) // php-5.2
618 $_SESSION[$key] = $val;
619 if (!check_php_version(5, 3))
620 session_register($key);
623 function delete($key)
625 $vars = &$GLOBALS['HTTP_SESSION_VARS'];
626 if (!function_usable('ini_get') or ini_get('register_globals'))
627 unset($GLOBALS[$key]);
628 if (DEBUG) trigger_error("delete session $key", E_USER_WARNING);
630 if (isset($_SESSION)) // php-5.2
631 unset($_SESSION[$key]);
632 if (!check_php_version(5, 3))
633 session_unregister($key);
637 class Request_CookieVars
642 $vars = &$GLOBALS['HTTP_COOKIE_VARS'];
643 if (isset($vars[$key])) {
644 @$decode = base64_decode($vars[$key]);
645 if (strlen($decode) > 3 and substr($decode, 1, 1) == ':') {
646 @$val = unserialize($decode);
650 @$val = urldecode($vars[$key]);
657 function get_old($key)
659 if (defined('FUSIONFORGE') and FUSIONFORGE) {
662 $vars = &$GLOBALS['HTTP_COOKIE_VARS'];
663 if (isset($vars[$key])) {
664 @$decode = base64_decode($vars[$key]);
665 if (strlen($decode) > 3 and substr($decode, 1, 1) == ':') {
666 @$val = unserialize($decode);
670 @$val = unserialize($vars[$key]);
680 function set($key, $val, $persist_days = false, $path = false)
682 // if already defined, ignore
683 if (defined('MAIN_setUser') and $key = getCookieName()) return;
684 if (defined('WIKI_XMLRPC') and WIKI_XMLRPC) return;
686 $vars = &$GLOBALS['HTTP_COOKIE_VARS'];
687 if (is_numeric($persist_days)) {
688 $expires = time() + (24 * 3600) * $persist_days;
692 if (is_array($val) or is_object($val))
693 $packedval = base64_encode(serialize($val));
695 $packedval = urlencode($val);
696 $vars[$key] = $packedval;
697 @$_COOKIE[$key] = $packedval;
699 @setcookie($key, $packedval, $expires, $path);
701 @setcookie($key, $packedval, $expires);
704 function delete($key)
706 static $deleted = array();
707 if (isset($deleted[$key])) return;
708 if (defined('WIKI_XMLRPC') and WIKI_XMLRPC) return;
710 $vars = &$GLOBALS['HTTP_COOKIE_VARS'];
711 if (!defined('COOKIE_DOMAIN'))
712 @setcookie($key, '', 0);
714 @setcookie($key, '', 0, COOKIE_DOMAIN);
715 unset($GLOBALS['HTTP_COOKIE_VARS'][$key]);
716 unset($_COOKIE[$key]);
723 You must set "upload_tmp_dir" = "/tmp/" or "C:/tmp/"
724 Best on the same drive as apache, with forward slashes
725 and with ending slash!
726 Otherwise "\\" => "" and the uploaded file will not be found.
728 class Request_UploadedFile
730 function getUploadedFile($postname)
732 global $HTTP_POST_FILES;
734 // Against php5 with !ini_get('register-long-arrays'). See Bug #1180115
735 if (empty($HTTP_POST_FILES) and !empty($_FILES))
736 $HTTP_POST_FILES =& $_FILES;
737 if (!isset($HTTP_POST_FILES[$postname]))
740 $fileinfo =& $HTTP_POST_FILES[$postname];
741 if ($fileinfo['error']) {
742 // See https://sourceforge.net/forum/message.php?msg_id=3093651
743 $err = (int)$fileinfo['error'];
744 // errmsgs by Shilad Sen
747 trigger_error(_("Upload error: file too big"), E_USER_WARNING);
750 trigger_error(_("Upload error: file too big"), E_USER_WARNING);
753 trigger_error(_("Upload error: file only partially received"), E_USER_WARNING);
756 trigger_error(_("Upload error: no file selected"), E_USER_WARNING);
759 trigger_error(_("Upload error: unknown error #") . $err, E_USER_WARNING);
764 // With windows/php 4.2.1 is_uploaded_file() always returns false.
765 // Be sure that upload_tmp_dir ends with a slash!
766 if (!is_uploaded_file($fileinfo['tmp_name'])) {
768 if (!$tmp_file = get_cfg_var('upload_tmp_dir')) {
769 $tmp_file = dirname(tempnam('', ''));
771 $tmp_file .= '/' . basename($fileinfo['tmp_name']);
772 /* ending slash in php.ini upload_tmp_dir is required. */
773 if (realpath(ereg_replace('/+', '/', $tmp_file)) != realpath($fileinfo['tmp_name'])) {
774 trigger_error(sprintf("Uploaded tmpfile illegal: %s != %s.", $tmp_file, $fileinfo['tmp_name']) .
776 "Probably illegal TEMP environment or upload_tmp_dir setting. " .
777 "Esp. on WINDOWS be sure to set upload_tmp_dir in php.ini to use forward slashes and " .
778 "end with a slash. upload_tmp_dir = \"C:/WINDOWS/TEMP/\" is good suggestion.",
783 trigger_error(sprintf("Workaround for PHP/Windows is_uploaded_file() problem for %s.",
784 $fileinfo['tmp_name'])."\n".
785 "Probably illegal TEMP environment or upload_tmp_dir setting.",
791 trigger_error(sprintf("Uploaded tmpfile %s not found.", $fileinfo['tmp_name']) . "\n" .
792 " Probably illegal TEMP environment or upload_tmp_dir setting.",
796 return new Request_UploadedFile($fileinfo);
799 function Request_UploadedFile($fileinfo)
801 $this->_info = $fileinfo;
806 return $this->_info['size'];
811 return $this->_info['name'];
816 return $this->_info['type'];
819 function getTmpName()
821 return $this->_info['tmp_name'];
826 if (($fd = fopen($this->_info['tmp_name'], "rb"))) {
827 if ($this->getSize() < filesize($this->_info['tmp_name'])) {
828 // FIXME: Some PHP's (or is it some browsers?) put
829 // HTTP/MIME headers in the file body, some don't.
831 // At least, I think that's the case. I know I used
832 // to need this code, now I don't.
834 // This code is more-or-less untested currently.
836 // Dump HTTP headers.
837 while (($header = fgets($fd, 4096))) {
838 if (trim($header) == '') {
840 } elseif (!preg_match('/^content-(length|type):/i', $header)) {
850 function getContents()
853 $data = fread($fd, $this->getSize());
860 * Create NCSA "combined" log entry for current request.
861 * Also needed for advanced spam prevention.
862 * global object holding global state (sql or file, entries, to dump)
864 class Request_AccessLog
867 * @param $logfile string Log file name.
869 function Request_AccessLog($logfile, $do_sql = false)
871 //global $request; // request not yet initialized!
873 $this->logfile = $logfile;
874 if ($logfile and !is_writeable($logfile)) {
876 (sprintf(_("%s is not writable."), _("The PhpWiki access log file"))
878 . sprintf(_("Please ensure that %s is writable, or redefine %s in config/config.ini."),
879 sprintf(_("the file '%s'"), ACCESS_LOG),
883 //$request->_accesslog =& $this;
884 //if (empty($request->_accesslog->entries))
885 register_shutdown_function("Request_AccessLogEntry_shutdown_function");
889 if (!in_array($DBParams['dbtype'], array('SQL', 'ADODB'))) {
890 trigger_error("Unsupported database backend for ACCESS_LOG_SQL.\nNeed DATABASE_TYPE=SQL or ADODB");
892 //$this->_dbi =& $request->_dbi;
893 $this->logtable = (!empty($DBParams['prefix']) ? $DBParams['prefix'] : '') . "accesslog";
896 $this->entries = array();
897 $this->entries[] = new Request_AccessLogEntry($this);
900 function _do($cmd, &$arg)
903 for ($i = 0; $i < count($this->entries); $i++)
904 $this->entries[$i]->$cmd($arg);
907 function push(&$request)
909 $this->_do('push', $request);
912 function setSize($arg)
914 $this->_do('setSize', $arg);
917 function setStatus($arg)
919 $this->_do('setStatus', $arg);
922 function setDuration($arg)
924 $this->_do('setDuration', $arg);
928 * Read sequentially all previous entries from the beginning.
929 * while ($logentry = Request_AccessLogEntry::read()) ;
930 * For internal log analyzers: RecentReferrers, WikiAccessRestrictions
934 return $this->logtable ? $this->read_sql() : $this->read_file();
938 * Return iterator of referer items reverse sorted (latest first).
940 function get_referer($limit = 15, $external_only = false)
942 if ($external_only) { // see stdlin.php:isExternalReferrer()
944 $blen = strlen($base);
946 if (!empty($this->_dbi)) {
947 // check same hosts in referer and request and remove them
948 $ext_where = " AND LEFT(referer,$blen) <> " . $this->_dbi->quote($base)
949 . " AND LEFT(referer,$blen) <> LEFT(CONCAT(" . $this->_dbi->quote(SERVER_URL) . ",request_uri),$blen)";
950 return $this->_read_sql_query("(referer <>'' AND NOT(ISNULL(referer)))"
951 . ($external_only ? $ext_where : '')
952 . " ORDER BY time_stamp DESC"
953 . ($limit ? " LIMIT $limit" : ""));
955 $iter = new WikiDB_Array_generic_iter(0);
956 $logs =& $iter->_array;
957 while ($logentry = $this->read_file()) {
958 if (!empty($logentry->referer)
959 and (!$external_only or (substr($logentry->referer, 0, $blen) != $base))
961 $iter->_array[] = $logentry;
962 if ($limit and count($logs) > $limit)
966 $logs = array_reverse($logs);
967 $logs = array_slice($logs, 0, min($limit, count($logs)));
973 * Return iterator of matching host items reverse sorted (latest first).
975 function get_host($host, $since_minutes = 20)
977 if ($this->logtable) {
978 // mysql specific only:
979 return $this->read_sql("request_host=" . $this->_dbi->quote($host) . " AND time_stamp > " . (time() - $since_minutes * 60)
980 . " ORDER BY time_stamp DESC");
982 $iter = new WikiDB_Array_generic_iter();
983 $logs =& $iter->_array;
984 $logentry = new Request_AccessLogEntry($this);
985 while ($logentry->read_file()) {
986 if (!empty($logentry->referer)) {
987 $iter->_array[] = $logentry;
988 if ($limit and count($logs) > $limit)
990 $logentry = new Request_AccessLogEntry($this);
993 $logs = array_reverse($logs);
994 $logs = array_slice($logs, 0, min($limit, count($logs)));
1000 * Read sequentially all previous entries from log file.
1002 function read_file()
1005 if ($this->logfile) $this->logfile = ACCESS_LOG; // support Request_AccessLog::read
1007 if (empty($this->reader)) // start at the beginning
1008 $this->reader = fopen($this->logfile, "r");
1009 if ($s = fgets($this->reader)) {
1010 $entry = new Request_AccessLogEntry($this);
1011 if (preg_match('/^(\S+)\s(\S+)\s(\S+)\s\[(.+?)\] "([^"]+)" (\d+) (\d+) "([^"]*)" "([^"]*)"$/', $s, $m)) {
1012 list(, $entry->host, $entry->ident, $entry->user, $entry->time,
1013 $entry->request, $entry->status, $entry->size,
1014 $entry->referer, $entry->user_agent) = $m;
1017 } else { // until the end
1018 fclose($this->reader);
1023 function _read_sql_query($where = '')
1025 $dbh =& $GLOBALS['request']->_dbi;
1026 $log_tbl =& $this->logtable;
1027 return $dbh->genericSqlIter("SELECT *,request_uri as request,request_time as time,remote_user as user,"
1028 . "remote_host as host,agent as user_agent"
1030 . ($where ? " WHERE $where" : ""));
1033 function read_sql($where = '')
1035 if (empty($this->sqliter))
1036 $this->sqliter = $this->_read_sql_query($where);
1037 return $this->sqliter->next();
1040 /* done in request->finish() before the db is closed */
1041 function write_sql()
1043 $dbh =& $GLOBALS['request']->_dbi;
1044 if (isset($this->entries) and $dbh and $dbh->isOpen())
1045 foreach ($this->entries as $entry) {
1046 $entry->write_sql();
1050 /* done in the shutdown callback */
1051 function write_file()
1053 if (isset($this->entries) and $this->logfile)
1054 foreach ($this->entries as $entry) {
1055 $entry->write_file();
1057 unset($this->entries);
1060 /* in an ideal world... */
1063 if ($this->logfile) $this->write_file();
1064 if ($this->logtable) $this->write_sql();
1065 unset($this->entries);
1069 class Request_AccessLogEntry
1074 * The log entry will be automatically appended to the log file or
1075 * SQL table when the current request terminates.
1077 * If you want to modify a Request_AccessLogEntry before it gets
1078 * written (e.g. via the setStatus and setSize methods) you should
1079 * use an '&' on the constructor, so that you're working with the
1080 * original (rather than a copy) object.
1083 * $log_entry = & new Request_AccessLogEntry("/tmp/wiki_access_log");
1084 * $log_entry->setStatus(401);
1085 * $log_entry->push($request);
1090 function Request_AccessLogEntry(&$accesslog)
1092 $this->_accesslog = $accesslog;
1093 $this->logfile = $accesslog->logfile;
1094 $this->time = time();
1095 $this->status = 200; // see setStatus()
1096 $this->size = 0; // see setSize()
1100 * @param $request object Request object for current request.
1102 function push(&$request)
1104 $this->host = $request->get('REMOTE_HOST');
1105 $this->ident = $request->get('REMOTE_IDENT');
1108 $user = $request->getUser();
1109 if ($user->isAuthenticated())
1110 $this->user = $user->UserName();
1113 $this->request = join(' ', array($request->get('REQUEST_METHOD'),
1114 $request->get('REQUEST_URI'),
1115 $request->get('SERVER_PROTOCOL')));
1116 $this->referer = (string)$request->get('HTTP_REFERER');
1117 $this->user_agent = (string)$request->get('HTTP_USER_AGENT');
1121 * Set result status code.
1123 * @param $status integer HTTP status code.
1125 function setStatus($status)
1127 $this->status = $status;
1131 * Set response size.
1133 * @param $size integer
1135 function setSize($size = 0)
1137 $this->size = (int)$size;
1140 function setDuration($seconds)
1142 // Pear DB does not correctly quote , in floats using ?. e.g. in european locales.
1144 $this->duration = strtr(sprintf("%f", $seconds), ",", ".");
1148 * Get time zone offset.
1150 * This is a static member function.
1152 * @param $time integer Unix timestamp (defaults to current time).
1153 * @return string Zone offset, e.g. "-0800" for PST.
1155 function _zone_offset($time = false)
1159 $offset = date("Z", $time);
1165 $offhours = floor($offset / 3600);
1166 $offmins = $offset / 60 - $offhours * 60;
1167 return sprintf("%s%02d%02d", $negoffset, $offhours, $offmins);
1171 * Format time in NCSA format.
1173 * This is a static member function.
1175 * @param $time integer Unix timestamp (defaults to current time).
1176 * @return string Formatted date & time.
1178 function _ncsa_time($time = false)
1182 return date("d/M/Y:H:i:s", $time) .
1183 " " . $this->_zone_offset();
1188 if ($this->_accesslog->logfile) $this->write_file();
1189 if ($this->_accesslog->logtable) $this->write_sql();
1193 * Write entry to log file.
1195 function write_file()
1197 $entry = sprintf('%s %s %s [%s] "%s" %d %d "%s" "%s"',
1198 $this->host, $this->ident, $this->user,
1199 $this->_ncsa_time($this->time),
1200 $this->request, $this->status, $this->size,
1201 $this->referer, $this->user_agent);
1202 if (!empty($this->_accesslog->reader)) {
1203 fclose($this->_accesslog->reader);
1204 unset($this->_accesslog->reader);
1206 //Error log doesn't provide locking.
1207 //error_log("$entry\n", 3, $this->logfile);
1209 if (($fp = fopen($this->logfile, "a"))) {
1210 flock($fp, LOCK_EX);
1211 fputs($fp, "$entry\n");
1216 /* This is better been done by apache mod_log_sql */
1217 /* If ACCESS_LOG_SQL & 2 we do write it by our own */
1218 function write_sql()
1222 $dbh =& $request->_dbi;
1223 if ($dbh and $dbh->isOpen() and $this->_accesslog->logtable) {
1224 //$log_tbl =& $this->_accesslog->logtable;
1225 if ($request->get('REQUEST_METHOD') == "POST") {
1226 // strangely HTTP_POST_VARS doesn't contain all posted vars.
1227 $args = $_POST; // copy not ref. clone not needed on hashes
1229 if (!empty($args['auth']['passwd'])) $args['auth']['passwd'] = '<not displayed>';
1230 if (!empty($args['dbadmin']['passwd'])) $args['dbadmin']['passwd'] = '<not displayed>';
1231 if (!empty($args['pref']['passwd'])) $args['pref']['passwd'] = '<not displayed>';
1232 if (!empty($args['pref']['passwd2'])) $args['pref']['passwd2'] = '<not displayed>';
1233 $this->request_args = substr(serialize($args), 0, 254); // if VARCHAR(255) is used.
1235 $this->request_args = $request->get('QUERY_STRING');
1237 $this->request_method = $request->get('REQUEST_METHOD');
1238 $this->request_uri = $request->get('REQUEST_URI');
1239 // duration problem: sprintf "%f" might use comma e.g. "100,201" in european locales
1240 $dbh->_backend->write_accesslog($this);
1246 * Shutdown callback.
1249 * @see Request_AccessLogEntry
1251 function Request_AccessLogEntry_shutdown_function()
1255 if (isset($request->_accesslog->entries) and $request->_accesslog->logfile)
1256 foreach ($request->_accesslog->entries as $entry) {
1257 $entry->write_file();
1259 unset($request->_accesslog->entries);
1264 function HTTP_ETag($val, $is_weak = false)
1266 $this->_val = wikihash($val);
1267 $this->_weak = $is_weak;
1272 * Strong comparison: If either (or both) tag is weak, they
1275 function equals($that, $strong_match = false)
1277 if ($this->_val != $that->_val)
1279 if ($strong_match and ($this->_weak or $that->_weak))
1286 $quoted = '"' . addslashes($this->_val) . '"';
1287 return $this->_weak ? "W/$quoted" : $quoted;
1290 /** Parse tag from header.
1292 * This is a static member function.
1294 function parse($strval)
1296 if (!preg_match(':^(W/)?"(.+)"$:i', trim($strval), $m))
1297 return false; // parse failed
1298 list(, $weak, $str) = $m;
1299 return new HTTP_ETag(stripslashes($str), $weak);
1302 function matches($taglist, $strong_match = false)
1304 $taglist = trim($taglist);
1306 if ($taglist == '*') {
1308 return !$this->_weak;
1313 while (preg_match('@^(W/)?"((?:\\\\.|[^"])*)"\s*,?\s*@i',
1315 list($match, $weak, $str) = $m;
1316 $taglist = substr($taglist, strlen($match));
1317 $tag = new HTTP_ETag(stripslashes($str), $weak);
1318 if ($this->equals($tag, $strong_match)) {
1326 // Possible results from the HTTP_ValidatorSet::_check*() methods.
1327 // (Higher numerical values take precedence.)
1328 define ('_HTTP_VAL_PASS', 0); // Test is irrelevant
1329 define ('_HTTP_VAL_NOT_MODIFIED', 1); // Test passed, content not changed
1330 define ('_HTTP_VAL_MODIFIED', 2); // Test failed, content changed
1331 define ('_HTTP_VAL_FAILED', 3); // Precondition failed.
1333 class HTTP_ValidatorSet
1335 function HTTP_ValidatorSet($validators)
1337 $this->_mtime = $this->_weak = false;
1338 $this->_tag = array();
1340 foreach ($validators as $key => $val) {
1341 if ($key == '%mtime') {
1342 $this->_mtime = $val;
1343 } elseif ($key == '%weak') {
1345 $this->_weak = true;
1347 $this->_tag[$key] = $val;
1352 function append($that)
1354 if (is_array($that))
1355 $that = new HTTP_ValidatorSet($that);
1357 // Pick the most recent mtime
1358 if (isset($that->_mtime))
1359 if (!isset($this->_mtime) || $that->_mtime > $this->_mtime)
1360 $this->_mtime = $that->_mtime;
1362 // If either is weak, we're weak
1363 if (!empty($that->_weak))
1364 $this->_weak = true;
1365 if (is_array($this->_tag))
1366 $this->_tag = array_merge($this->_tag, $that->_tag);
1368 $this->_tag = $that->_tag;
1375 return new HTTP_ETag($this->_tag, $this->_weak);
1378 function getModificationTime()
1380 return $this->_mtime;
1383 function checkConditionalRequest(&$request)
1385 $result = max($this->_checkIfUnmodifiedSince($request),
1386 $this->_checkIfModifiedSince($request),
1387 $this->_checkIfMatch($request),
1388 $this->_checkIfNoneMatch($request));
1390 if ($result == _HTTP_VAL_PASS || $result == _HTTP_VAL_MODIFIED)
1391 return false; // "please proceed with normal processing"
1392 elseif ($result == _HTTP_VAL_FAILED)
1393 return 412; // "412 Precondition Failed"
1394 elseif ($result == _HTTP_VAL_NOT_MODIFIED)
1395 return 304; // "304 Not Modified"
1397 trigger_error("Ack, shouldn't get here", E_USER_ERROR);
1401 function _checkIfUnmodifiedSince(&$request)
1403 if ($this->_mtime !== false) {
1404 $since = ParseRfc1123DateTime($request->get("HTTP_IF_UNMODIFIED_SINCE"));
1405 if ($since !== false && $this->_mtime > $since)
1406 return _HTTP_VAL_FAILED;
1408 return _HTTP_VAL_PASS;
1411 function _checkIfModifiedSince(&$request)
1413 if ($this->_mtime !== false and $request->isGetOrHead()) {
1414 $since = ParseRfc1123DateTime($request->get("HTTP_IF_MODIFIED_SINCE"));
1415 if ($since !== false) {
1416 if ($this->_mtime <= $since)
1417 return _HTTP_VAL_NOT_MODIFIED;
1418 return _HTTP_VAL_MODIFIED;
1421 return _HTTP_VAL_PASS;
1424 function _checkIfMatch(&$request)
1426 if ($this->_tag && ($taglist = $request->get("HTTP_IF_MATCH"))) {
1427 $tag = $this->getETag();
1428 if (!$tag->matches($taglist, 'strong'))
1429 return _HTTP_VAL_FAILED;
1431 return _HTTP_VAL_PASS;
1434 function _checkIfNoneMatch(&$request)
1436 if ($this->_tag && ($taglist = $request->get("HTTP_IF_NONE_MATCH"))) {
1437 $tag = $this->getETag();
1438 $strong_compare = !$request->isGetOrHead();
1440 if ($tag->matches($taglist, $strong_compare)) {
1441 if ($request->isGetOrHead())
1442 return _HTTP_VAL_NOT_MODIFIED;
1444 return _HTTP_VAL_FAILED;
1446 return _HTTP_VAL_MODIFIED;
1449 return _HTTP_VAL_PASS;
1456 // c-basic-offset: 4
1457 // c-hanging-comment-ender-p: nil
1458 // indent-tabs-mode: nil