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.
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 (isCGI()) // necessary?
337 if ($this->getArg('start_debug')) $compress = false;
338 if ($this->getArg('nocache'))
341 // Should we compress even when apache_note is not available?
342 // sf.net bug #933183 and http://bugs.php.net/17557
343 // This effectively eliminates CGI, but all other servers also. hmm.
345 and (!function_exists('ob_gzhandler')
346 or !function_exists('apache_note')))
349 // "output handler 'ob_gzhandler' cannot be used twice"
350 // http://www.php.net/ob_gzhandler
351 if ($compress and ini_get("zlib.output_compression"))
354 // New: we check for the client Accept-Encoding: "gzip" presence also
355 // This should eliminate a lot or reported problems.
357 and (!$this->get("HTTP_ACCEPT_ENCODING")
358 or !strstr($this->get("HTTP_ACCEPT_ENCODING"), "gzip")))
361 // Most RSS clients are NOT(!) application/xml gzip compatible yet.
362 // Even if they are sending the accept-encoding gzip header!
363 // wget is, Mozilla, and MSIE no.
364 // Of the RSS readers only MagpieRSS 0.5.2 is. http://www.rssgov.com/rssparsers.html
365 // See also http://phpwiki.sourceforge.net/phpwiki/KnownBugs
367 and $this->getArg('format')
368 and strstr($this->getArg('format'), 'rss'))
372 ob_start('phpwiki_gzhandler');
374 // TODO: dont send a length or get the gzip'ed data length.
375 $this->_is_compressing_output = true;
376 header("Content-Encoding: gzip");
378 * Attempt to prevent Apache from doing the dreaded double-gzip.
380 * It would be better if we could detect when apache was going
381 * to zip for us, and then let it ... but I have yet to figure
382 * out how to do that.
384 if (function_exists('apache_note'))
385 @apache_note('no-gzip', 1);
388 // Now we alway buffer output.
389 // This is so we can set HTTP headers (e.g. for redirect)
391 // FIXME: change the name of this method.
393 $this->_is_compressing_output = false;
395 $this->_is_buffering_output = true;
396 $this->_ob_get_length = 0;
399 function discardOutput() {
400 if (!empty($this->_is_buffering_output)) {
401 if (ob_get_length()) ob_clean();
402 $this->_is_buffering_output = false;
404 trigger_error("Not buffering output", E_USER_NOTICE);
409 * Longer texts need too much memory on tiny or memory-limit=8MB systems.
410 * We might want to flush our buffer and restart again.
411 * (This would be fine if php would release its memory)
412 * Note that this must not be called inside Template expansion or other
413 * sections with ob_buffering.
415 function chunkOutput() {
416 if (!empty($this->_is_buffering_output)
418 (function_exists('ob_get_level') and @ob_get_level()))
420 $this->_do_chunked_output = true;
421 if (empty($this->_ob_get_length)) $this->_ob_get_length = 0;
422 $this->_ob_get_length += ob_get_length();
423 while (@ob_end_flush());
430 $this->_finishing = true;
431 if (!empty($this->_accesslog)) {
432 $this->_accesslog->push($this);
433 if (empty($this->_do_chunked_output) and empty($this->_ob_get_length))
434 $this->_ob_get_length = ob_get_length();
435 $this->_accesslog->setSize($this->_ob_get_length);
437 if ($RUNTIMER) $this->_accesslog->setDuration($RUNTIMER->getTime());
438 // sql logging must be done before the db is closed.
439 if (isset($this->_accesslog->logtable))
440 $this->_accesslog->write_sql();
443 if (!empty($this->_is_buffering_output)) {
444 // if _is_compressing_output then ob_get_length() returns
445 // the uncompressed length, not the gzip'ed as required.
446 if (!headers_sent() and !$this->_is_compressing_output) {
447 // php url-rewriting miscalculates the ob length. fixes bug #1376007
448 if (ini_get('use_trans_sid') == 'off') {
449 if (empty($this->_do_chunked_output)) {
450 $this->_ob_get_length = ob_get_length();
452 header(sprintf("Content-Length: %d", $this->_ob_get_length));
455 $this->_is_buffering_output = false;
457 } elseif (function_exists('ob_get_level') and @ob_get_level()) {
460 session_write_close();
461 if (!empty($this->_dbi)) {
462 $this->_dbi->close();
469 function getSessionVar($key) {
470 return $this->session->get($key);
472 function setSessionVar($key, $val) {
473 if ($key == 'wiki_user') {
474 if (empty($val->page))
475 $val->page = $this->getArg('pagename');
476 if (empty($val->action))
477 $val->action = $this->getArg('action');
478 // avoid recursive objects and session resource handles
479 // avoid overlarge session data (max 4000 byte!)
480 if (isset($val->_group)) {
481 unset($val->_group->_request);
482 unset($val->_group->user);
484 if (ENABLE_USER_NEW) {
485 unset($val->_HomePagehandle);
486 unset($val->_auth_dbi);
489 unset($val->_authdbi);
490 unset($val->_homepage);
491 unset($val->_request);
494 return $this->session->set($key, $val);
496 function deleteSessionVar($key) {
497 return $this->session->delete($key);
500 function getCookieVar($key) {
501 return $this->cookies->get($key);
503 function setCookieVar($key, $val, $lifetime_in_days = false, $path = false) {
504 return $this->cookies->set($key, $val, $lifetime_in_days, $path);
506 function deleteCookieVar($key) {
507 return $this->cookies->delete($key);
510 function getUploadedFile($key) {
511 return Request_UploadedFile::getUploadedFile($key);
515 function _fix_magic_quotes_gpc() {
516 $needs_fix = array('HTTP_POST_VARS',
523 if (get_magic_quotes_gpc()) {
524 foreach ($needs_fix as $vars)
525 $this->_stripslashes($GLOBALS[$vars]);
529 function _stripslashes(&$var) {
530 if (is_array($var)) {
531 foreach ($var as $key => $val)
532 $this->_stripslashes($var[$key]);
534 elseif (is_string($var))
535 $var = stripslashes($var);
538 function _fix_multipart_form_data () {
539 if (preg_match('|^multipart/form-data|', $this->get('CONTENT_TYPE')))
540 $this->_strip_leading_nl($GLOBALS['HTTP_POST_VARS']);
543 function _strip_leading_nl(&$var) {
544 if (is_array($var)) {
545 foreach ($var as $key => $val)
546 $this->_strip_leading_nl($var[$key]);
548 elseif (is_string($var))
549 $var = preg_replace('|^\r?\n?|', '', $var);
553 class Request_SessionVars {
554 function Request_SessionVars() {
555 // Prevent cacheing problems with IE 5
556 session_cache_limiter('none');
558 // Avoid to get a notice if session is already started,
559 // for example if session.auto_start is activated
565 $vars = &$GLOBALS['HTTP_SESSION_VARS'];
566 if (isset($vars[$key]))
568 if (isset($_SESSION) and isset($_SESSION[$key])) // php-5.2
569 return $_SESSION[$key];
573 function set($key, $val) {
574 $vars = &$GLOBALS['HTTP_SESSION_VARS'];
575 if (!function_usable('get_cfg_var') or get_cfg_var('register_globals')) {
576 // This is funky but necessary, at least in some PHP's
577 $GLOBALS[$key] = $val;
580 if (isset($_SESSION)) // php-5.2
581 $_SESSION[$key] = $val;
582 if (!check_php_version(5,3))
583 session_register($key);
586 function delete($key) {
587 $vars = &$GLOBALS['HTTP_SESSION_VARS'];
588 if (!function_usable('ini_get') or ini_get('register_globals'))
589 unset($GLOBALS[$key]);
590 if (DEBUG) trigger_error("delete session $key", E_USER_WARNING);
592 if (isset($_SESSION)) // php-5.2
593 unset($_SESSION[$key]);
594 if (!check_php_version(5,3))
595 session_unregister($key);
599 class Request_CookieVars {
602 $vars = &$GLOBALS['HTTP_COOKIE_VARS'];
603 if (isset($vars[$key])) {
604 @$decode = base64_decode($vars[$key]);
605 if (strlen($decode) > 3 and substr($decode,1,1) == ':') {
606 @$val = unserialize($decode);
610 @$val = urldecode($vars[$key]);
617 function get_old($key) {
618 $vars = &$GLOBALS['HTTP_COOKIE_VARS'];
619 if (isset($vars[$key])) {
620 @$decode = base64_decode($vars[$key]);
621 if (strlen($decode) > 3 and substr($decode,1,1) == ':') {
622 @$val = unserialize($decode);
626 @$val = unserialize($vars[$key]);
636 function set($key, $val, $persist_days = false, $path = false) {
637 // if already defined, ignore
638 if (defined('MAIN_setUser') and $key = getCookieName()) return;
639 if (defined('WIKI_XMLRPC') and WIKI_XMLRPC) return;
641 $vars = &$GLOBALS['HTTP_COOKIE_VARS'];
642 if (is_numeric($persist_days)) {
643 $expires = time() + (24 * 3600) * $persist_days;
648 if (is_array($val) or is_object($val))
649 $packedval = base64_encode(serialize($val));
651 $packedval = urlencode($val);
652 $vars[$key] = $packedval;
653 @$_COOKIE[$key] = $packedval;
655 @setcookie($key, $packedval, $expires, $path);
657 @setcookie($key, $packedval, $expires);
660 function delete($key) {
661 static $deleted = array();
662 if (isset($deleted[$key])) return;
663 if (defined('WIKI_XMLRPC') and WIKI_XMLRPC) return;
665 $vars = &$GLOBALS['HTTP_COOKIE_VARS'];
666 if (!defined('COOKIE_DOMAIN'))
667 @setcookie($key, '', 0);
669 @setcookie($key, '', 0, COOKIE_DOMAIN);
670 unset($GLOBALS['HTTP_COOKIE_VARS'][$key]);
671 unset($_COOKIE[$key]);
678 You must set "upload_tmp_dir" = "/tmp/" or "C:/tmp/"
679 Best on the same drive as apache, with forward slashes
680 and with ending slash!
681 Otherwise "\\" => "" and the uploaded file will not be found.
683 class Request_UploadedFile {
684 function getUploadedFile($postname) {
685 global $HTTP_POST_FILES;
687 // Against php5 with !ini_get('register-long-arrays'). See Bug #1180115
688 if (empty($HTTP_POST_FILES) and !empty($_FILES))
689 $HTTP_POST_FILES =& $_FILES;
690 if (!isset($HTTP_POST_FILES[$postname]))
693 $fileinfo =& $HTTP_POST_FILES[$postname];
694 if ($fileinfo['error']) {
695 // See https://sourceforge.net/forum/message.php?msg_id=3093651
696 $err = (int) $fileinfo['error'];
697 // errmsgs by Shilad Sen
700 trigger_error(_("Upload error: file too big"), E_USER_WARNING);
703 trigger_error(_("Upload error: file too big"), E_USER_WARNING);
706 trigger_error(_("Upload error: file only partially received"), E_USER_WARNING);
709 trigger_error(_("Upload error: no file selected"), E_USER_WARNING);
712 trigger_error(_("Upload error: unknown error #") . $err, E_USER_WARNING);
717 // With windows/php 4.2.1 is_uploaded_file() always returns false.
718 // Be sure that upload_tmp_dir ends with a slash!
719 if (!is_uploaded_file($fileinfo['tmp_name'])) {
721 if (!$tmp_file = get_cfg_var('upload_tmp_dir')) {
722 $tmp_file = dirname(tempnam('', ''));
724 $tmp_file .= '/' . basename($fileinfo['tmp_name']);
725 /* ending slash in php.ini upload_tmp_dir is required. */
726 if (realpath(ereg_replace('/+', '/', $tmp_file)) != realpath($fileinfo['tmp_name'])) {
727 trigger_error(sprintf("Uploaded tmpfile illegal: %s != %s.",$tmp_file, $fileinfo['tmp_name']).
729 "Probably illegal TEMP environment or upload_tmp_dir setting. ".
730 "Esp. on WINDOWS be sure to set upload_tmp_dir in php.ini to use forward slashes and ".
731 "end with a slash. upload_tmp_dir = \"C:/WINDOWS/TEMP/\" is good suggestion.",
736 trigger_error(sprintf("Workaround for PHP/Windows is_uploaded_file() problem for %s.",
737 $fileinfo['tmp_name'])."\n".
738 "Probably illegal TEMP environment or upload_tmp_dir setting.",
744 trigger_error(sprintf("Uploaded tmpfile %s not found.", $fileinfo['tmp_name'])."\n".
745 " Probably illegal TEMP environment or upload_tmp_dir setting.",
749 return new Request_UploadedFile($fileinfo);
752 function Request_UploadedFile($fileinfo) {
753 $this->_info = $fileinfo;
757 return $this->_info['size'];
761 return $this->_info['name'];
765 return $this->_info['type'];
768 function getTmpName() {
769 return $this->_info['tmp_name'];
773 if ( ($fd = fopen($this->_info['tmp_name'], "rb")) ) {
774 if ($this->getSize() < filesize($this->_info['tmp_name'])) {
775 // FIXME: Some PHP's (or is it some browsers?) put
776 // HTTP/MIME headers in the file body, some don't.
778 // At least, I think that's the case. I know I used
779 // to need this code, now I don't.
781 // This code is more-or-less untested currently.
783 // Dump HTTP headers.
784 while ( ($header = fgets($fd, 4096)) ) {
785 if (trim($header) == '') {
788 else if (!preg_match('/^content-(length|type):/i', $header)) {
798 function getContents() {
800 $data = fread($fd, $this->getSize());
807 * Create NCSA "combined" log entry for current request.
808 * Also needed for advanced spam prevention.
809 * global object holding global state (sql or file, entries, to dump)
811 class Request_AccessLog {
813 * @param $logfile string Log file name.
815 function Request_AccessLog ($logfile, $do_sql = false) {
816 //global $request; // request not yet initialized!
818 $this->logfile = $logfile;
819 if ($logfile and !is_writeable($logfile)) {
821 (sprintf(_("%s is not writable."), _("The PhpWiki access log file"))
823 . sprintf(_("Please ensure that %s is writable, or redefine %s in config/config.ini."),
824 sprintf(_("the file '%s'"), ACCESS_LOG),
828 //$request->_accesslog =& $this;
829 //if (empty($request->_accesslog->entries))
830 register_shutdown_function("Request_AccessLogEntry_shutdown_function");
834 if (!in_array($DBParams['dbtype'], array('SQL','ADODB'))) {
835 trigger_error("Unsupported database backend for ACCESS_LOG_SQL.\nNeed DATABASE_TYPE=SQL or ADODB");
837 //$this->_dbi =& $request->_dbi;
838 $this->logtable = (!empty($DBParams['prefix']) ? $DBParams['prefix'] : '')."accesslog";
841 $this->entries = array();
842 $this->entries[] = new Request_AccessLogEntry($this);
845 function _do($cmd, &$arg) {
847 for ($i=0; $i < count($this->entries);$i++)
848 $this->entries[$i]->$cmd($arg);
850 function push(&$request) { $this->_do('push',$request); }
851 function setSize($arg) { $this->_do('setSize',$arg); }
852 function setStatus($arg) { $this->_do('setStatus',$arg); }
853 function setDuration($arg) { $this->_do('setDuration',$arg); }
856 * Read sequentially all previous entries from the beginning.
857 * while ($logentry = Request_AccessLogEntry::read()) ;
858 * For internal log analyzers: RecentReferrers, WikiAccessRestrictions
861 return $this->logtable ? $this->read_sql() : $this->read_file();
865 * Return iterator of referer items reverse sorted (latest first).
867 function get_referer($limit=15, $external_only=false) {
868 if ($external_only) { // see stdlin.php:isExternalReferrer()
870 $blen = strlen($base);
872 if (!empty($this->_dbi)) {
873 // check same hosts in referer and request and remove them
874 $ext_where = " AND LEFT(referer,$blen) <> ".$this->_dbi->quote($base)
875 ." AND LEFT(referer,$blen) <> LEFT(CONCAT(".$this->_dbi->quote(SERVER_URL).",request_uri),$blen)";
876 return $this->_read_sql_query("(referer <>'' AND NOT(ISNULL(referer)))"
877 .($external_only ? $ext_where : '')
878 ." ORDER BY time_stamp DESC"
879 .($limit ? " LIMIT $limit" : ""));
881 $iter = new WikiDB_Array_generic_iter(0);
882 $logs =& $iter->_array;
883 while ($logentry = $this->read_file()) {
884 if (!empty($logentry->referer)
885 and (!$external_only or (substr($logentry->referer,0,$blen) != $base)))
887 $iter->_array[] = $logentry;
888 if ($limit and count($logs) > $limit)
892 $logs = array_reverse($logs);
893 $logs = array_slice($logs,0,min($limit,count($logs)));
899 * Return iterator of matching host items reverse sorted (latest first).
901 function get_host($host, $since_minutes=20) {
902 if ($this->logtable) {
903 // mysql specific only:
904 return $this->read_sql("request_host=".$this->_dbi->quote($host)." AND time_stamp > ". (time()-$since_minutes*60)
905 ." ORDER BY time_stamp DESC");
907 $iter = new WikiDB_Array_generic_iter();
908 $logs =& $iter->_array;
909 $logentry = new Request_AccessLogEntry($this);
910 while ($logentry->read_file()) {
911 if (!empty($logentry->referer)) {
912 $iter->_array[] = $logentry;
913 if ($limit and count($logs) > $limit)
915 $logentry = new Request_AccessLogEntry($this);
918 $logs = array_reverse($logs);
919 $logs = array_slice($logs,0,min($limit,count($logs)));
925 * Read sequentially all previous entries from log file.
927 function read_file() {
929 if ($this->logfile) $this->logfile = ACCESS_LOG; // support Request_AccessLog::read
931 if (empty($this->reader)) // start at the beginning
932 $this->reader = fopen($this->logfile, "r");
933 if ($s = fgets($this->reader)) {
934 $entry = new Request_AccessLogEntry($this);
935 if (preg_match('/^(\S+)\s(\S+)\s(\S+)\s\[(.+?)\] "([^"]+)" (\d+) (\d+) "([^"]*)" "([^"]*)"$/',$s,$m)) {
936 list(,$entry->host, $entry->ident, $entry->user, $entry->time,
937 $entry->request, $entry->status, $entry->size,
938 $entry->referer, $entry->user_agent) = $m;
941 } else { // until the end
942 fclose($this->reader);
946 function _read_sql_query($where='') {
947 $dbh =& $GLOBALS['request']->_dbi;
948 $log_tbl =& $this->logtable;
949 return $dbh->genericSqlIter("SELECT *,request_uri as request,request_time as time,remote_user as user,"
950 ."remote_host as host,agent as user_agent"
952 . ($where ? " WHERE $where" : ""));
954 function read_sql($where='') {
955 if (empty($this->sqliter))
956 $this->sqliter = $this->_read_sql_query($where);
957 return $this->sqliter->next();
960 /* done in request->finish() before the db is closed */
961 function write_sql() {
962 $dbh =& $GLOBALS['request']->_dbi;
963 if (isset($this->entries) and $dbh and $dbh->isOpen())
964 foreach ($this->entries as $entry) {
968 /* done in the shutdown callback */
969 function write_file() {
970 if (isset($this->entries) and $this->logfile)
971 foreach ($this->entries as $entry) {
972 $entry->write_file();
974 unset($this->entries);
976 /* in an ideal world... */
978 if ($this->logfile) $this->write_file();
979 if ($this->logtable) $this->write_sql();
980 unset($this->entries);
984 class Request_AccessLogEntry
989 * The log entry will be automatically appended to the log file or
990 * SQL table when the current request terminates.
992 * If you want to modify a Request_AccessLogEntry before it gets
993 * written (e.g. via the setStatus and setSize methods) you should
994 * use an '&' on the constructor, so that you're working with the
995 * original (rather than a copy) object.
998 * $log_entry = & new Request_AccessLogEntry("/tmp/wiki_access_log");
999 * $log_entry->setStatus(401);
1000 * $log_entry->push($request);
1005 function Request_AccessLogEntry (&$accesslog) {
1006 $this->_accesslog = $accesslog;
1007 $this->logfile = $accesslog->logfile;
1008 $this->time = time();
1009 $this->status = 200; // see setStatus()
1010 $this->size = 0; // see setSize()
1014 * @param $request object Request object for current request.
1016 function push(&$request) {
1017 $this->host = $request->get('REMOTE_HOST');
1018 $this->ident = $request->get('REMOTE_IDENT');
1021 $user = $request->getUser();
1022 if ($user->isAuthenticated())
1023 $this->user = $user->UserName();
1026 $this->request = join(' ', array($request->get('REQUEST_METHOD'),
1027 $request->get('REQUEST_URI'),
1028 $request->get('SERVER_PROTOCOL')));
1029 $this->referer = (string) $request->get('HTTP_REFERER');
1030 $this->user_agent = (string) $request->get('HTTP_USER_AGENT');
1034 * Set result status code.
1036 * @param $status integer HTTP status code.
1038 function setStatus ($status) {
1039 $this->status = $status;
1043 * Set response size.
1045 * @param $size integer
1047 function setSize ($size=0) {
1048 $this->size = (int)$size;
1050 function setDuration ($seconds) {
1051 // Pear DB does not correctly quote , in floats using ?. e.g. in european locales.
1053 $this->duration = strtr(sprintf("%f", $seconds),",",".");
1057 * Get time zone offset.
1059 * This is a static member function.
1061 * @param $time integer Unix timestamp (defaults to current time).
1062 * @return string Zone offset, e.g. "-0800" for PST.
1064 function _zone_offset ($time = false) {
1067 $offset = date("Z", $time);
1073 $offhours = floor($offset / 3600);
1074 $offmins = $offset / 60 - $offhours * 60;
1075 return sprintf("%s%02d%02d", $negoffset, $offhours, $offmins);
1079 * Format time in NCSA format.
1081 * This is a static member function.
1083 * @param $time integer Unix timestamp (defaults to current time).
1084 * @return string Formatted date & time.
1086 function _ncsa_time($time = false) {
1089 return date("d/M/Y:H:i:s", $time) .
1090 " " . $this->_zone_offset();
1094 if ($this->_accesslog->logfile) $this->write_file();
1095 if ($this->_accesslog->logtable) $this->write_sql();
1099 * Write entry to log file.
1101 function write_file() {
1102 $entry = sprintf('%s %s %s [%s] "%s" %d %d "%s" "%s"',
1103 $this->host, $this->ident, $this->user,
1104 $this->_ncsa_time($this->time),
1105 $this->request, $this->status, $this->size,
1106 $this->referer, $this->user_agent);
1107 if (!empty($this->_accesslog->reader)) {
1108 fclose($this->_accesslog->reader);
1109 unset($this->_accesslog->reader);
1111 //Error log doesn't provide locking.
1112 //error_log("$entry\n", 3, $this->logfile);
1114 if (($fp = fopen($this->logfile, "a"))) {
1115 flock($fp, LOCK_EX);
1116 fputs($fp, "$entry\n");
1121 /* This is better been done by apache mod_log_sql */
1122 /* If ACCESS_LOG_SQL & 2 we do write it by our own */
1123 function write_sql() {
1126 $dbh =& $request->_dbi;
1127 if ($dbh and $dbh->isOpen() and $this->_accesslog->logtable) {
1128 //$log_tbl =& $this->_accesslog->logtable;
1129 if ($request->get('REQUEST_METHOD') == "POST") {
1130 // strangely HTTP_POST_VARS doesn't contain all posted vars.
1131 $args = $_POST; // copy not ref. clone not needed on hashes
1133 if (!empty($args['auth']['passwd'])) $args['auth']['passwd'] = '<not displayed>';
1134 if (!empty($args['dbadmin']['passwd'])) $args['dbadmin']['passwd'] = '<not displayed>';
1135 if (!empty($args['pref']['passwd'])) $args['pref']['passwd'] = '<not displayed>';
1136 if (!empty($args['pref']['passwd2'])) $args['pref']['passwd2'] = '<not displayed>';
1137 $this->request_args = substr(serialize($args),0,254); // if VARCHAR(255) is used.
1139 $this->request_args = $request->get('QUERY_STRING');
1141 $this->request_method = $request->get('REQUEST_METHOD');
1142 $this->request_uri = $request->get('REQUEST_URI');
1143 // duration problem: sprintf "%f" might use comma e.g. "100,201" in european locales
1144 $dbh->_backend->write_accesslog($this);
1150 * Shutdown callback.
1153 * @see Request_AccessLogEntry
1155 function Request_AccessLogEntry_shutdown_function () {
1158 if (isset($request->_accesslog->entries) and $request->_accesslog->logfile)
1159 foreach ($request->_accesslog->entries as $entry) {
1160 $entry->write_file();
1162 unset($request->_accesslog->entries);
1167 function HTTP_ETag($val, $is_weak=false) {
1168 $this->_val = wikihash($val);
1169 $this->_weak = $is_weak;
1174 * Strong comparison: If either (or both) tag is weak, they
1177 function equals($that, $strong_match=false) {
1178 if ($this->_val != $that->_val)
1180 if ($strong_match and ($this->_weak or $that->_weak))
1186 function asString() {
1187 $quoted = '"' . addslashes($this->_val) . '"';
1188 return $this->_weak ? "W/$quoted" : $quoted;
1191 /** Parse tag from header.
1193 * This is a static member function.
1195 function parse($strval) {
1196 if (!preg_match(':^(W/)?"(.+)"$:i', trim($strval), $m))
1197 return false; // parse failed
1198 list(,$weak,$str) = $m;
1199 return new HTTP_ETag(stripslashes($str), $weak);
1202 function matches($taglist, $strong_match=false) {
1203 $taglist = trim($taglist);
1205 if ($taglist == '*') {
1207 return ! $this->_weak;
1212 while (preg_match('@^(W/)?"((?:\\\\.|[^"])*)"\s*,?\s*@i',
1214 list($match, $weak, $str) = $m;
1215 $taglist = substr($taglist, strlen($match));
1216 $tag = new HTTP_ETag(stripslashes($str), $weak);
1217 if ($this->equals($tag, $strong_match)) {
1225 // Possible results from the HTTP_ValidatorSet::_check*() methods.
1226 // (Higher numerical values take precedence.)
1227 define ('_HTTP_VAL_PASS', 0); // Test is irrelevant
1228 define ('_HTTP_VAL_NOT_MODIFIED', 1); // Test passed, content not changed
1229 define ('_HTTP_VAL_MODIFIED', 2); // Test failed, content changed
1230 define ('_HTTP_VAL_FAILED', 3); // Precondition failed.
1232 class HTTP_ValidatorSet {
1233 function HTTP_ValidatorSet($validators) {
1234 $this->_mtime = $this->_weak = false;
1235 $this->_tag = array();
1237 foreach ($validators as $key => $val) {
1238 if ($key == '%mtime') {
1239 $this->_mtime = $val;
1241 elseif ($key == '%weak') {
1243 $this->_weak = true;
1246 $this->_tag[$key] = $val;
1251 function append($that) {
1252 if (is_array($that))
1253 $that = new HTTP_ValidatorSet($that);
1255 // Pick the most recent mtime
1256 if (isset($that->_mtime))
1257 if (!isset($this->_mtime) || $that->_mtime > $this->_mtime)
1258 $this->_mtime = $that->_mtime;
1260 // If either is weak, we're weak
1261 if (!empty($that->_weak))
1262 $this->_weak = true;
1263 if (is_array($this->_tag))
1264 $this->_tag = array_merge($this->_tag, $that->_tag);
1266 $this->_tag = $that->_tag;
1269 function getETag() {
1272 return new HTTP_ETag($this->_tag, $this->_weak);
1275 function getModificationTime() {
1276 return $this->_mtime;
1279 function checkConditionalRequest (&$request) {
1280 $result = max($this->_checkIfUnmodifiedSince($request),
1281 $this->_checkIfModifiedSince($request),
1282 $this->_checkIfMatch($request),
1283 $this->_checkIfNoneMatch($request));
1285 if ($result == _HTTP_VAL_PASS || $result == _HTTP_VAL_MODIFIED)
1286 return false; // "please proceed with normal processing"
1287 elseif ($result == _HTTP_VAL_FAILED)
1288 return 412; // "412 Precondition Failed"
1289 elseif ($result == _HTTP_VAL_NOT_MODIFIED)
1290 return 304; // "304 Not Modified"
1292 trigger_error("Ack, shouldn't get here", E_USER_ERROR);
1296 function _checkIfUnmodifiedSince(&$request) {
1297 if ($this->_mtime !== false) {
1298 $since = ParseRfc1123DateTime($request->get("HTTP_IF_UNMODIFIED_SINCE"));
1299 if ($since !== false && $this->_mtime > $since)
1300 return _HTTP_VAL_FAILED;
1302 return _HTTP_VAL_PASS;
1305 function _checkIfModifiedSince(&$request) {
1306 if ($this->_mtime !== false and $request->isGetOrHead()) {
1307 $since = ParseRfc1123DateTime($request->get("HTTP_IF_MODIFIED_SINCE"));
1308 if ($since !== false) {
1309 if ($this->_mtime <= $since)
1310 return _HTTP_VAL_NOT_MODIFIED;
1311 return _HTTP_VAL_MODIFIED;
1314 return _HTTP_VAL_PASS;
1317 function _checkIfMatch(&$request) {
1318 if ($this->_tag && ($taglist = $request->get("HTTP_IF_MATCH"))) {
1319 $tag = $this->getETag();
1320 if (!$tag->matches($taglist, 'strong'))
1321 return _HTTP_VAL_FAILED;
1323 return _HTTP_VAL_PASS;
1326 function _checkIfNoneMatch(&$request) {
1327 if ($this->_tag && ($taglist = $request->get("HTTP_IF_NONE_MATCH"))) {
1328 $tag = $this->getETag();
1329 $strong_compare = ! $request->isGetOrHead();
1331 if ($tag->matches($taglist, $strong_compare)) {
1332 if ($request->isGetOrHead())
1333 return _HTTP_VAL_NOT_MODIFIED;
1335 return _HTTP_VAL_FAILED;
1337 return _HTTP_VAL_MODIFIED;
1340 return _HTTP_VAL_PASS;
1347 // c-basic-offset: 4
1348 // c-hanging-comment-ender-p: nil
1349 // indent-tabs-mode: nil