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
23 // backward compatibility for PHP < 4.2.0
24 if (!function_exists('ob_clean')) {
34 $this->_fix_magic_quotes_gpc();
35 $this->_fix_multipart_form_data();
37 switch($this->get('REQUEST_METHOD')) {
40 $this->args = &$GLOBALS['HTTP_GET_VARS'];
43 $this->args = &$GLOBALS['HTTP_POST_VARS'];
46 $this->args = array();
50 $this->session = new Request_SessionVars;
51 $this->cookies = new Request_CookieVars;
53 if (ACCESS_LOG or ACCESS_LOG_SQL) {
54 $this->_accesslog = new Request_AccessLog(ACCESS_LOG, ACCESS_LOG_SQL);
57 $GLOBALS['request'] = $this;
61 if (!empty($GLOBALS['HTTP_SERVER_VARS']))
62 $vars = &$GLOBALS['HTTP_SERVER_VARS'];
63 elseif (!empty($GLOBALS['HTTP_ENV_VARS']))
64 $vars = &$GLOBALS['HTTP_ENV_VARS']; // cgi or other servers than Apache
66 trigger_error("Serious php configuration error!"
67 ." No HTTP_SERVER_VARS and HTTP_ENV_VARS vars available."
68 ." These should get defined in lib/prepend.php",
71 if (isset($vars[$key]))
76 $addr = $vars['REMOTE_ADDR'];
77 if (defined('ENABLE_REVERSE_DNS') && ENABLE_REVERSE_DNS)
78 return $vars[$key] = gethostbyaddr($addr);
86 function getArg($key) {
87 if (isset($this->args[$key]))
88 return $this->args[$key];
96 function setArg($key, $val) {
98 unset($this->args[$key]);
100 $this->args[$key] = $val;
103 // Well oh well. Do we really want to pass POST params back as GET?
104 function getURLtoSelf($args = false, $exclude = array()) {
105 $get_args = $this->args;
107 $get_args = array_merge($get_args, $args);
109 // leave out empty arg values
110 foreach ($get_args as $g => $v) {
111 if ($v === false or $v === '') unset($get_args[$g]);
114 // Err... good point...
116 if ($this->isPost()) {
117 $exclude = array_merge($exclude, array('action','auth'));
118 //$get_args = $args; // or only the provided
120 trigger_error("Request::getURLtoSelf() should probably not be from POST",
125 foreach ($exclude as $ex) {
126 if (!empty($get_args[$ex])) unset($get_args[$ex]);
129 $pagename = $get_args['pagename'];
130 unset ($get_args['pagename']);
131 if (!empty($get_args['action']) and $get_args['action'] == 'browse')
132 unset($get_args['action']);
134 return WikiURL($pagename, $get_args);
138 return $this->get("REQUEST_METHOD") == "POST";
141 function isGetOrHead () {
142 return in_array($this->get('REQUEST_METHOD'),
143 array('GET', 'HEAD'));
146 function httpVersion() {
147 if (!preg_match('@HTTP\s*/\s*(\d+.\d+)@', $this->get('SERVER_PROTOCOL'), $m))
149 return (float) $m[1];
152 /* Redirects after edit may fail if no theme signature image is defined.
153 * Set DISABLE_HTTP_REDIRECT = true then.
155 function redirect($url, $noreturn = true) {
156 $bogus = defined('DISABLE_HTTP_REDIRECT') && DISABLE_HTTP_REDIRECT;
159 header("Location: $url");
161 * "302 Found" is not really meant to be sent in response
162 * to a POST. Worse still, according to (both HTTP 1.0
163 * and 1.1) spec, the user, if it is sent, the user agent
164 * is supposed to use the same method to fetch the
165 * redirected URI as the original.
167 * That means if we redirect from a POST, the user-agent
168 * supposed to generate another POST. Not what we want.
169 * (We do this after a page save after all.)
171 * Fortunately, most/all browsers don't do that.
173 * "303 See Other" is what we really want. But it only
176 * FIXME: this is still not spec compliant for HTTP
179 $status = $this->httpVersion() >= 1.1 ? 303 : 302;
180 $this->setStatus($status);
184 $this->discardOutput(); // This might print the gzip headers. Not good.
185 $this->buffer_output(false);
187 include_once('lib/Template.php');
188 $tmpl = new Template('redirect', $this, array('REDIRECT_URL' => $url));
193 // Safari needs window.location.href = targeturl
195 function redirect(url) {
196 if (typeof location.replace == 'function')
197 location.replace(url);
198 else if (typeof location.assign == 'function')
199 location.assign(url);
200 else if (self.location.href)
201 self.location.href = url;
203 window.location = url;
205 redirect('" . addslashes($url) . "')");
209 /** Set validators for this response.
211 * This sets a (possibly incomplete) set of validators
214 * The validator set can be extended using appendValidators().
216 * When you're all done setting and appending validators, you
217 * must call checkValidators() to check them and set the
218 * appropriate headers in the HTTP response.
222 * $request->setValidators(array('pagename' => $pagename,
223 * '%mtime' => $rev->get('mtime')));
225 * // Wups... response content depends on $otherpage, too...
226 * $request->appendValidators(array('otherpage' => $otherpagerev->getPageName(),
227 * '%mtime' => $otherpagerev->get('mtime')));
229 * // After all validators have been set:
230 * $request->checkValidators();
232 function setValidators($validator_set) {
233 if (is_array($validator_set))
234 $validator_set = new HTTP_ValidatorSet($validator_set);
235 $this->_validators = $validator_set;
238 /** Append more validators for this response.
239 * i.e dependencies on other pages mtimes
240 * now it may be called in init also to simplify client code.
242 function appendValidators($validator_set) {
243 if (!isset($this->_validators)) {
244 $this->setValidators($validator_set);
247 $this->_validators->append($validator_set);
250 /** Check validators and set headers in HTTP response
252 * This sets the appropriate "Last-Modified" and "ETag"
253 * headers in the HTTP response.
255 * Additionally, if the validators match any(all) conditional
256 * headers in the HTTP request, this method will not return, but
257 * instead will send "304 Not Modified" or "412 Precondition
258 * Failed" (as appropriate) back to the client.
260 function checkValidators() {
261 $validators = &$this->_validators;
263 // Set validator headers
264 if (!empty($this->_is_buffering_output) or !headers_sent()) {
265 if (($etag = $validators->getETag()) !== false)
266 header("ETag: " . $etag->asString());
267 if (($mtime = $validators->getModificationTime()) !== false)
268 header("Last-Modified: " . Rfc1123DateTime($mtime));
270 // Set cache control headers
271 $this->cacheControl();
274 if (CACHE_CONTROL == 'NO_CACHE')
275 return; // don't check conditionals...
277 // Check conditional headers in request
278 $status = $validators->checkConditionalRequest($this);
280 // Return short response due to failed conditionals
281 $this->setStatus($status);
283 $this->discardOutput();
289 /** Set the cache control headers in the HTTP response.
291 function cacheControl($strategy=CACHE_CONTROL, $max_age=CACHE_CONTROL_MAX_AGE) {
292 if ($strategy == 'NO_CACHE') {
293 $cache_control = "no-cache"; // better set private. See Pear HTTP_Header
296 elseif ($strategy == 'ALLOW_STALE' && $max_age > 0) {
297 $cache_control = sprintf("max-age=%d", $max_age);
300 $cache_control = "must-revalidate";
303 header("Cache-Control: $cache_control");
304 header("Expires: " . Rfc1123DateTime(time() + $max_age));
305 header("Vary: Cookie"); // FIXME: add more here?
308 function setStatus($status) {
309 if (preg_match('|^HTTP/.*?\s(\d+)|i', $status, $m)) {
314 $status = (integer) $status;
315 $reason = array('200' => 'OK',
317 '303' => 'See Other',
318 '304' => 'Not Modified',
319 '400' => 'Bad Request',
320 '401' => 'Unauthorized',
321 '403' => 'Forbidden',
322 '404' => 'Not Found',
323 '412' => 'Precondition Failed');
324 // FIXME: is it always okay to send HTTP/1.1 here, even for older clients?
325 header(sprintf("HTTP/1.1 %d %s", $status, $reason[$status]));
328 if (isset($this->_log_entry))
329 $this->_log_entry->setStatus($status);
332 function buffer_output($compress = true) {
333 // FIXME: disables sessions (some byte before all headers_sent())
334 /*if (defined('USECACHE') and !USECACHE) {
335 $this->_is_buffering_output = false;
338 if (defined('COMPRESS_OUTPUT')) {
339 if (!COMPRESS_OUTPUT)
342 elseif (!check_php_version(4,2,3))
344 elseif (isCGI()) // necessary?
347 if ($this->getArg('start_debug')) $compress = false;
348 if ($this->getArg('nocache'))
351 // Should we compress even when apache_note is not available?
352 // sf.net bug #933183 and http://bugs.php.net/17557
353 // This effectively eliminates CGI, but all other servers also. hmm.
355 and (!function_exists('ob_gzhandler')
356 or !function_exists('apache_note')))
359 // "output handler 'ob_gzhandler' cannot be used twice"
360 // http://www.php.net/ob_gzhandler
361 if ($compress and ini_get("zlib.output_compression"))
364 // New: we check for the client Accept-Encoding: "gzip" presence also
365 // This should eliminate a lot or reported problems.
367 and (!$this->get("HTTP_ACCEPT_ENCODING")
368 or !strstr($this->get("HTTP_ACCEPT_ENCODING"), "gzip")))
371 // Most RSS clients are NOT(!) application/xml gzip compatible yet.
372 // Even if they are sending the accept-encoding gzip header!
373 // wget is, Mozilla, and MSIE no.
374 // Of the RSS readers only MagpieRSS 0.5.2 is. http://www.rssgov.com/rssparsers.html
375 // See also http://phpwiki.sourceforge.net/phpwiki/KnownBugs
377 and $this->getArg('format')
378 and strstr($this->getArg('format'), 'rss'))
382 ob_start('phpwiki_gzhandler');
384 // TODO: dont send a length or get the gzip'ed data length.
385 $this->_is_compressing_output = true;
386 header("Content-Encoding: gzip");
388 * Attempt to prevent Apache from doing the dreaded double-gzip.
390 * It would be better if we could detect when apache was going
391 * to zip for us, and then let it ... but I have yet to figure
392 * out how to do that.
394 if (function_exists('apache_note'))
395 @apache_note('no-gzip', 1);
398 // Now we alway buffer output.
399 // This is so we can set HTTP headers (e.g. for redirect)
401 // FIXME: change the name of this method.
403 $this->_is_compressing_output = false;
405 $this->_is_buffering_output = true;
406 $this->_ob_get_length = 0;
409 function discardOutput() {
410 if (!empty($this->_is_buffering_output)) {
411 if (ob_get_length()) ob_clean();
412 $this->_is_buffering_output = false;
414 trigger_error("Not buffering output", E_USER_NOTICE);
419 * Longer texts need too much memory on tiny or memory-limit=8MB systems.
420 * We might want to flush our buffer and restart again.
421 * (This would be fine if php would release its memory)
422 * Note that this must not be called inside Template expansion or other
423 * sections with ob_buffering.
425 function chunkOutput() {
426 if (!empty($this->_is_buffering_output)
428 (function_exists('ob_get_level') and @ob_get_level()))
430 $this->_do_chunked_output = true;
431 if (empty($this->_ob_get_length)) $this->_ob_get_length = 0;
432 $this->_ob_get_length += ob_get_length();
433 while (@ob_end_flush());
440 $this->_finishing = true;
441 if (!empty($this->_accesslog)) {
442 $this->_accesslog->push($this);
443 if (empty($this->_do_chunked_output) and empty($this->_ob_get_length))
444 $this->_ob_get_length = ob_get_length();
445 $this->_accesslog->setSize($this->_ob_get_length);
447 if ($RUNTIMER) $this->_accesslog->setDuration($RUNTIMER->getTime());
448 // sql logging must be done before the db is closed.
449 if (isset($this->_accesslog->logtable))
450 $this->_accesslog->write_sql();
453 if (!empty($this->_is_buffering_output)) {
454 /* This cannot work because it might destroy xml markup */
456 if (0 and $GLOBALS['SearchHighLightQuery'] and check_php_version(4,2)) {
457 $html = str_replace($GLOBALS['SearchHighLightQuery'],
458 '<span class="search-term">'.$GLOBALS['SearchHighLightQuery'].'</span>',
461 header(sprintf("Content-Length: %d", strlen($html)));
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) {
491 return $this->session->get($key);
493 function setSessionVar($key, $val) {
494 if ($key == 'wiki_user') {
495 if (empty($val->page))
496 $val->page = $this->getArg('pagename');
497 if (empty($val->action))
498 $val->action = $this->getArg('action');
499 // avoid recursive objects and session resource handles
500 // avoid overlarge session data (max 4000 byte!)
501 if (isset($val->_group)) {
502 unset($val->_group->_request);
503 unset($val->_group->user);
505 if (ENABLE_USER_NEW) {
506 unset($val->_HomePagehandle);
507 unset($val->_auth_dbi);
510 unset($val->_authdbi);
511 unset($val->_homepage);
512 unset($val->_request);
515 return $this->session->set($key, $val);
517 function deleteSessionVar($key) {
518 return $this->session->delete($key);
521 function getCookieVar($key) {
522 return $this->cookies->get($key);
524 function setCookieVar($key, $val, $lifetime_in_days = false, $path = false) {
525 return $this->cookies->set($key, $val, $lifetime_in_days, $path);
527 function deleteCookieVar($key) {
528 return $this->cookies->delete($key);
531 function getUploadedFile($key) {
532 return Request_UploadedFile::getUploadedFile($key);
536 function _fix_magic_quotes_gpc() {
537 $needs_fix = array('HTTP_POST_VARS',
544 if (get_magic_quotes_gpc()) {
545 foreach ($needs_fix as $vars)
546 $this->_stripslashes($GLOBALS[$vars]);
550 function _stripslashes(&$var) {
551 if (is_array($var)) {
552 foreach ($var as $key => $val)
553 $this->_stripslashes($var[$key]);
555 elseif (is_string($var))
556 $var = stripslashes($var);
559 function _fix_multipart_form_data () {
560 if (preg_match('|^multipart/form-data|', $this->get('CONTENT_TYPE')))
561 $this->_strip_leading_nl($GLOBALS['HTTP_POST_VARS']);
564 function _strip_leading_nl(&$var) {
565 if (is_array($var)) {
566 foreach ($var as $key => $val)
567 $this->_strip_leading_nl($var[$key]);
569 elseif (is_string($var))
570 $var = preg_replace('|^\r?\n?|', '', $var);
574 class Request_SessionVars {
575 function Request_SessionVars() {
576 // Prevent cacheing problems with IE 5
577 session_cache_limiter('none');
579 // Avoid to get a notice if session is already started,
580 // for example if session.auto_start is activated
586 $vars = &$GLOBALS['HTTP_SESSION_VARS'];
587 if (isset($vars[$key]))
589 if (isset($_SESSION) and isset($_SESSION[$key])) // php-5.2
590 return $_SESSION[$key];
594 function set($key, $val) {
595 $vars = &$GLOBALS['HTTP_SESSION_VARS'];
596 if (!function_usable('get_cfg_var') or get_cfg_var('register_globals')) {
597 // This is funky but necessary, at least in some PHP's
598 $GLOBALS[$key] = $val;
601 if (isset($_SESSION)) // php-5.2
602 $_SESSION[$key] = $val;
603 session_register($key);
606 function delete($key) {
607 $vars = &$GLOBALS['HTTP_SESSION_VARS'];
608 if (!function_usable('ini_get') or ini_get('register_globals'))
609 unset($GLOBALS[$key]);
610 if (DEBUG) trigger_error("delete session $key", E_USER_WARNING);
612 session_unregister($key);
616 class Request_CookieVars {
619 $vars = &$GLOBALS['HTTP_COOKIE_VARS'];
620 if (isset($vars[$key])) {
621 @$decode = base64_decode($vars[$key]);
622 if (strlen($decode) > 3 and substr($decode,1,1) == ':') {
623 @$val = unserialize($decode);
627 @$val = urldecode($vars[$key]);
634 function get_old($key) {
635 $vars = &$GLOBALS['HTTP_COOKIE_VARS'];
636 if (isset($vars[$key])) {
637 @$decode = base64_decode($vars[$key]);
638 if (strlen($decode) > 3 and substr($decode,1,1) == ':') {
639 @$val = unserialize($decode);
643 @$val = unserialize($vars[$key]);
653 function set($key, $val, $persist_days = false, $path = false) {
654 // if already defined, ignore
655 if (defined('MAIN_setUser') and $key = getCookieName()) return;
656 if (defined('WIKI_XMLRPC') and WIKI_XMLRPC) return;
658 $vars = &$GLOBALS['HTTP_COOKIE_VARS'];
659 if (is_numeric($persist_days)) {
660 $expires = time() + (24 * 3600) * $persist_days;
665 if (is_array($val) or is_object($val))
666 $packedval = base64_encode(serialize($val));
668 $packedval = urlencode($val);
669 $vars[$key] = $packedval;
670 @$_COOKIE[$key] = $packedval;
672 @setcookie($key, $packedval, $expires, $path);
674 @setcookie($key, $packedval, $expires);
677 function delete($key) {
678 static $deleted = array();
679 if (isset($deleted[$key])) return;
680 if (defined('WIKI_XMLRPC') and WIKI_XMLRPC) return;
682 $vars = &$GLOBALS['HTTP_COOKIE_VARS'];
683 if (!defined('COOKIE_DOMAIN'))
684 @setcookie($key, '', 0);
686 @setcookie($key, '', 0, COOKIE_DOMAIN);
687 unset($GLOBALS['HTTP_COOKIE_VARS'][$key]);
688 unset($_COOKIE[$key]);
695 You must set "upload_tmp_dir" = "/tmp/" or "C:/tmp/"
696 Best on the same drive as apache, with forward slashes
697 and with ending slash!
698 Otherwise "\\" => "" and the uploaded file will not be found.
700 class Request_UploadedFile {
701 function getUploadedFile($postname) {
702 global $HTTP_POST_FILES;
704 // Against php5 with !ini_get('register-long-arrays'). See Bug #1180115
705 if (empty($HTTP_POST_FILES) and !empty($_FILES))
706 $HTTP_POST_FILES =& $_FILES;
707 if (!isset($HTTP_POST_FILES[$postname]))
710 $fileinfo =& $HTTP_POST_FILES[$postname];
711 if ($fileinfo['error']) {
712 // See https://sourceforge.net/forum/message.php?msg_id=3093651
713 $err = (int) $fileinfo['error'];
714 // errmsgs by Shilad Sen
717 trigger_error(_("Upload error: file too big"), E_USER_WARNING);
720 trigger_error(_("Upload error: file too big"), E_USER_WARNING);
723 trigger_error(_("Upload error: file only partially received"), E_USER_WARNING);
726 trigger_error(_("Upload error: no file selected"), E_USER_WARNING);
729 trigger_error(_("Upload error: unknown error #") . $err, E_USER_WARNING);
734 // With windows/php 4.2.1 is_uploaded_file() always returns false.
735 // Be sure that upload_tmp_dir ends with a slash!
736 if (!is_uploaded_file($fileinfo['tmp_name'])) {
738 if (!$tmp_file = get_cfg_var('upload_tmp_dir')) {
739 $tmp_file = dirname(tempnam('', ''));
741 $tmp_file .= '/' . basename($fileinfo['tmp_name']);
742 /* ending slash in php.ini upload_tmp_dir is required. */
743 if (realpath(ereg_replace('/+', '/', $tmp_file)) != realpath($fileinfo['tmp_name'])) {
744 trigger_error(sprintf("Uploaded tmpfile illegal: %s != %s.",$tmp_file, $fileinfo['tmp_name']).
746 "Probably illegal TEMP environment or upload_tmp_dir setting. ".
747 "Esp. on WINDOWS be sure to set upload_tmp_dir in php.ini to use forward slashes and ".
748 "end with a slash. upload_tmp_dir = \"C:/WINDOWS/TEMP/\" is good suggestion.",
753 trigger_error(sprintf("Workaround for PHP/Windows is_uploaded_file() problem for %s.",
754 $fileinfo['tmp_name'])."\n".
755 "Probably illegal TEMP environment or upload_tmp_dir setting.",
761 trigger_error(sprintf("Uploaded tmpfile %s not found.", $fileinfo['tmp_name'])."\n".
762 " Probably illegal TEMP environment or upload_tmp_dir setting.",
766 return new Request_UploadedFile($fileinfo);
769 function Request_UploadedFile($fileinfo) {
770 $this->_info = $fileinfo;
774 return $this->_info['size'];
778 return $this->_info['name'];
782 return $this->_info['type'];
785 function getTmpName() {
786 return $this->_info['tmp_name'];
790 if ( ($fd = fopen($this->_info['tmp_name'], "rb")) ) {
791 if ($this->getSize() < filesize($this->_info['tmp_name'])) {
792 // FIXME: Some PHP's (or is it some browsers?) put
793 // HTTP/MIME headers in the file body, some don't.
795 // At least, I think that's the case. I know I used
796 // to need this code, now I don't.
798 // This code is more-or-less untested currently.
800 // Dump HTTP headers.
801 while ( ($header = fgets($fd, 4096)) ) {
802 if (trim($header) == '') {
805 else if (!preg_match('/^content-(length|type):/i', $header)) {
815 function getContents() {
817 $data = fread($fd, $this->getSize());
824 * Create NCSA "combined" log entry for current request.
825 * Also needed for advanced spam prevention.
826 * global object holding global state (sql or file, entries, to dump)
828 class Request_AccessLog {
830 * @param $logfile string Log file name.
832 function Request_AccessLog ($logfile, $do_sql = false) {
833 //global $request; // request not yet initialized!
835 $this->logfile = $logfile;
836 if ($logfile and !is_writeable($logfile)) {
838 (sprintf(_("%s is not writable."), _("The PhpWiki access log file"))
840 . sprintf(_("Please ensure that %s is writable, or redefine %s in config/config.ini."),
841 sprintf(_("the file '%s'"), ACCESS_LOG),
845 //$request->_accesslog =& $this;
846 //if (empty($request->_accesslog->entries))
847 register_shutdown_function("Request_AccessLogEntry_shutdown_function");
851 if (!in_array($DBParams['dbtype'], array('SQL','ADODB'))) {
852 trigger_error("Unsupported database backend for ACCESS_LOG_SQL.\nNeed DATABASE_TYPE=SQL or ADODB");
854 //$this->_dbi =& $request->_dbi;
855 $this->logtable = (!empty($DBParams['prefix']) ? $DBParams['prefix'] : '')."accesslog";
858 $this->entries = array();
859 $this->entries[] = new Request_AccessLogEntry($this);
862 function _do($cmd, &$arg) {
864 for ($i=0; $i < count($this->entries);$i++)
865 $this->entries[$i]->$cmd($arg);
867 function push(&$request) { $this->_do('push',$request); }
868 function setSize($arg) { $this->_do('setSize',$arg); }
869 function setStatus($arg) { $this->_do('setStatus',$arg); }
870 function setDuration($arg) { $this->_do('setDuration',$arg); }
873 * Read sequentially all previous entries from the beginning.
874 * while ($logentry = Request_AccessLogEntry::read()) ;
875 * For internal log analyzers: RecentReferrers, WikiAccessRestrictions
878 return $this->logtable ? $this->read_sql() : $this->read_file();
882 * Return iterator of referer items reverse sorted (latest first).
884 function get_referer($limit=15, $external_only=false) {
885 if ($external_only) { // see stdlin.php:isExternalReferrer()
887 $blen = strlen($base);
889 if (!empty($this->_dbi)) {
890 // check same hosts in referer and request and remove them
891 $ext_where = " AND LEFT(referer,$blen) <> ".$this->_dbi->quote($base)
892 ." AND LEFT(referer,$blen) <> LEFT(CONCAT(".$this->_dbi->quote(SERVER_URL).",request_uri),$blen)";
893 return $this->_read_sql_query("(referer <>'' AND NOT(ISNULL(referer)))"
894 .($external_only ? $ext_where : '')
895 ." ORDER BY time_stamp DESC"
896 .($limit ? " LIMIT $limit" : ""));
898 $iter = new WikiDB_Array_generic_iter(0);
899 $logs =& $iter->_array;
900 while ($logentry = $this->read_file()) {
901 if (!empty($logentry->referer)
902 and (!$external_only or (substr($logentry->referer,0,$blen) != $base)))
904 $iter->_array[] = $logentry;
905 if ($limit and count($logs) > $limit)
909 $logs = array_reverse($logs);
910 $logs = array_slice($logs,0,min($limit,count($logs)));
916 * Return iterator of matching host items reverse sorted (latest first).
918 function get_host($host, $since_minutes=20) {
919 if ($this->logtable) {
920 // mysql specific only:
921 return $this->read_sql("request_host=".$this->_dbi->quote($host)." AND time_stamp > ". (time()-$since_minutes*60)
922 ." ORDER BY time_stamp DESC");
924 $iter = new WikiDB_Array_generic_iter();
925 $logs =& $iter->_array;
926 $logentry = new Request_AccessLogEntry($this);
927 while ($logentry->read_file()) {
928 if (!empty($logentry->referer)) {
929 $iter->_array[] = $logentry;
930 if ($limit and count($logs) > $limit)
932 $logentry = new Request_AccessLogEntry($this);
935 $logs = array_reverse($logs);
936 $logs = array_slice($logs,0,min($limit,count($logs)));
942 * Read sequentially all previous entries from log file.
944 function read_file() {
946 if ($this->logfile) $this->logfile = ACCESS_LOG; // support Request_AccessLog::read
948 if (empty($this->reader)) // start at the beginning
949 $this->reader = fopen($this->logfile, "r");
950 if ($s = fgets($this->reader)) {
951 $entry = new Request_AccessLogEntry($this);
952 if (preg_match('/^(\S+)\s(\S+)\s(\S+)\s\[(.+?)\] "([^"]+)" (\d+) (\d+) "([^"]*)" "([^"]*)"$/',$s,$m)) {
953 list(,$entry->host, $entry->ident, $entry->user, $entry->time,
954 $entry->request, $entry->status, $entry->size,
955 $entry->referer, $entry->user_agent) = $m;
958 } else { // until the end
959 fclose($this->reader);
963 function _read_sql_query($where='') {
964 $dbh =& $GLOBALS['request']->_dbi;
965 $log_tbl =& $this->logtable;
966 return $dbh->genericSqlIter("SELECT *,request_uri as request,request_time as time,remote_user as user,"
967 ."remote_host as host,agent as user_agent"
969 . ($where ? " WHERE $where" : ""));
971 function read_sql($where='') {
972 if (empty($this->sqliter))
973 $this->sqliter = $this->_read_sql_query($where);
974 return $this->sqliter->next();
977 /* done in request->finish() before the db is closed */
978 function write_sql() {
979 $dbh =& $GLOBALS['request']->_dbi;
980 if (isset($this->entries) and $dbh and $dbh->isOpen())
981 foreach ($this->entries as $entry) {
985 /* done in the shutdown callback */
986 function write_file() {
987 if (isset($this->entries) and $this->logfile)
988 foreach ($this->entries as $entry) {
989 $entry->write_file();
991 unset($this->entries);
993 /* in an ideal world... */
995 if ($this->logfile) $this->write_file();
996 if ($this->logtable) $this->write_sql();
997 unset($this->entries);
1001 class Request_AccessLogEntry
1006 * The log entry will be automatically appended to the log file or
1007 * SQL table when the current request terminates.
1009 * If you want to modify a Request_AccessLogEntry before it gets
1010 * written (e.g. via the setStatus and setSize methods) you should
1011 * use an '&' on the constructor, so that you're working with the
1012 * original (rather than a copy) object.
1015 * $log_entry = & new Request_AccessLogEntry("/tmp/wiki_access_log");
1016 * $log_entry->setStatus(401);
1017 * $log_entry->push($request);
1022 function Request_AccessLogEntry (&$accesslog) {
1023 $this->_accesslog = $accesslog;
1024 $this->logfile = $accesslog->logfile;
1025 $this->time = time();
1026 $this->status = 200; // see setStatus()
1027 $this->size = 0; // see setSize()
1031 * @param $request object Request object for current request.
1033 function push(&$request) {
1034 $this->host = $request->get('REMOTE_HOST');
1035 $this->ident = $request->get('REMOTE_IDENT');
1038 $user = $request->getUser();
1039 if ($user->isAuthenticated())
1040 $this->user = $user->UserName();
1043 $this->request = join(' ', array($request->get('REQUEST_METHOD'),
1044 $request->get('REQUEST_URI'),
1045 $request->get('SERVER_PROTOCOL')));
1046 $this->referer = (string) $request->get('HTTP_REFERER');
1047 $this->user_agent = (string) $request->get('HTTP_USER_AGENT');
1051 * Set result status code.
1053 * @param $status integer HTTP status code.
1055 function setStatus ($status) {
1056 $this->status = $status;
1060 * Set response size.
1062 * @param $size integer
1064 function setSize ($size=0) {
1065 $this->size = (int)$size;
1067 function setDuration ($seconds) {
1068 // Pear DB does not correctly quote , in floats using ?. e.g. in european locales.
1070 $this->duration = strtr(sprintf("%f", $seconds),",",".");
1074 * Get time zone offset.
1076 * This is a static member function.
1078 * @param $time integer Unix timestamp (defaults to current time).
1079 * @return string Zone offset, e.g. "-0800" for PST.
1081 function _zone_offset ($time = false) {
1084 $offset = date("Z", $time);
1090 $offhours = floor($offset / 3600);
1091 $offmins = $offset / 60 - $offhours * 60;
1092 return sprintf("%s%02d%02d", $negoffset, $offhours, $offmins);
1096 * Format time in NCSA format.
1098 * This is a static member function.
1100 * @param $time integer Unix timestamp (defaults to current time).
1101 * @return string Formatted date & time.
1103 function _ncsa_time($time = false) {
1106 return date("d/M/Y:H:i:s", $time) .
1107 " " . $this->_zone_offset();
1111 if ($this->_accesslog->logfile) $this->write_file();
1112 if ($this->_accesslog->logtable) $this->write_sql();
1116 * Write entry to log file.
1118 function write_file() {
1119 $entry = sprintf('%s %s %s [%s] "%s" %d %d "%s" "%s"',
1120 $this->host, $this->ident, $this->user,
1121 $this->_ncsa_time($this->time),
1122 $this->request, $this->status, $this->size,
1123 $this->referer, $this->user_agent);
1124 if (!empty($this->_accesslog->reader)) {
1125 fclose($this->_accesslog->reader);
1126 unset($this->_accesslog->reader);
1128 //Error log doesn't provide locking.
1129 //error_log("$entry\n", 3, $this->logfile);
1131 if (($fp = fopen($this->logfile, "a"))) {
1132 flock($fp, LOCK_EX);
1133 fputs($fp, "$entry\n");
1138 /* This is better been done by apache mod_log_sql */
1139 /* If ACCESS_LOG_SQL & 2 we do write it by our own */
1140 function write_sql() {
1143 $dbh =& $request->_dbi;
1144 if ($dbh and $dbh->isOpen() and $this->_accesslog->logtable) {
1145 //$log_tbl =& $this->_accesslog->logtable;
1146 if ($request->get('REQUEST_METHOD') == "POST") {
1147 // strangely HTTP_POST_VARS doesn't contain all posted vars.
1148 if (check_php_version(4,2))
1149 $args = $_POST; // copy not ref. clone not needed on hashes
1151 $args = $GLOBALS['HTTP_POST_VARS'];
1153 if (!empty($args['auth']['passwd'])) $args['auth']['passwd'] = '<not displayed>';
1154 if (!empty($args['dbadmin']['passwd'])) $args['dbadmin']['passwd'] = '<not displayed>';
1155 if (!empty($args['pref']['passwd'])) $args['pref']['passwd'] = '<not displayed>';
1156 if (!empty($args['pref']['passwd2'])) $args['pref']['passwd2'] = '<not displayed>';
1157 $this->request_args = substr(serialize($args),0,254); // if VARCHAR(255) is used.
1159 $this->request_args = $request->get('QUERY_STRING');
1161 $this->request_method = $request->get('REQUEST_METHOD');
1162 $this->request_uri = $request->get('REQUEST_URI');
1163 // duration problem: sprintf "%f" might use comma e.g. "100,201" in european locales
1164 $dbh->_backend->write_accesslog($this);
1170 * Shutdown callback.
1173 * @see Request_AccessLogEntry
1175 function Request_AccessLogEntry_shutdown_function () {
1178 if (isset($request->_accesslog->entries) and $request->_accesslog->logfile)
1179 foreach ($request->_accesslog->entries as $entry) {
1180 $entry->write_file();
1182 unset($request->_accesslog->entries);
1187 function HTTP_ETag($val, $is_weak=false) {
1188 $this->_val = wikihash($val);
1189 $this->_weak = $is_weak;
1194 * Strong comparison: If either (or both) tag is weak, they
1197 function equals($that, $strong_match=false) {
1198 if ($this->_val != $that->_val)
1200 if ($strong_match and ($this->_weak or $that->_weak))
1206 function asString() {
1207 $quoted = '"' . addslashes($this->_val) . '"';
1208 return $this->_weak ? "W/$quoted" : $quoted;
1211 /** Parse tag from header.
1213 * This is a static member function.
1215 function parse($strval) {
1216 if (!preg_match(':^(W/)?"(.+)"$:i', trim($strval), $m))
1217 return false; // parse failed
1218 list(,$weak,$str) = $m;
1219 return new HTTP_ETag(stripslashes($str), $weak);
1222 function matches($taglist, $strong_match=false) {
1223 $taglist = trim($taglist);
1225 if ($taglist == '*') {
1227 return ! $this->_weak;
1232 while (preg_match('@^(W/)?"((?:\\\\.|[^"])*)"\s*,?\s*@i',
1234 list($match, $weak, $str) = $m;
1235 $taglist = substr($taglist, strlen($match));
1236 $tag = new HTTP_ETag(stripslashes($str), $weak);
1237 if ($this->equals($tag, $strong_match)) {
1245 // Possible results from the HTTP_ValidatorSet::_check*() methods.
1246 // (Higher numerical values take precedence.)
1247 define ('_HTTP_VAL_PASS', 0); // Test is irrelevant
1248 define ('_HTTP_VAL_NOT_MODIFIED', 1); // Test passed, content not changed
1249 define ('_HTTP_VAL_MODIFIED', 2); // Test failed, content changed
1250 define ('_HTTP_VAL_FAILED', 3); // Precondition failed.
1252 class HTTP_ValidatorSet {
1253 function HTTP_ValidatorSet($validators) {
1254 $this->_mtime = $this->_weak = false;
1255 $this->_tag = array();
1257 foreach ($validators as $key => $val) {
1258 if ($key == '%mtime') {
1259 $this->_mtime = $val;
1261 elseif ($key == '%weak') {
1263 $this->_weak = true;
1266 $this->_tag[$key] = $val;
1271 function append($that) {
1272 if (is_array($that))
1273 $that = new HTTP_ValidatorSet($that);
1275 // Pick the most recent mtime
1276 if (isset($that->_mtime))
1277 if (!isset($this->_mtime) || $that->_mtime > $this->_mtime)
1278 $this->_mtime = $that->_mtime;
1280 // If either is weak, we're weak
1281 if (!empty($that->_weak))
1282 $this->_weak = true;
1283 if (is_array($this->_tag))
1284 $this->_tag = array_merge($this->_tag, $that->_tag);
1286 $this->_tag = $that->_tag;
1289 function getETag() {
1292 return new HTTP_ETag($this->_tag, $this->_weak);
1295 function getModificationTime() {
1296 return $this->_mtime;
1299 function checkConditionalRequest (&$request) {
1300 $result = max($this->_checkIfUnmodifiedSince($request),
1301 $this->_checkIfModifiedSince($request),
1302 $this->_checkIfMatch($request),
1303 $this->_checkIfNoneMatch($request));
1305 if ($result == _HTTP_VAL_PASS || $result == _HTTP_VAL_MODIFIED)
1306 return false; // "please proceed with normal processing"
1307 elseif ($result == _HTTP_VAL_FAILED)
1308 return 412; // "412 Precondition Failed"
1309 elseif ($result == _HTTP_VAL_NOT_MODIFIED)
1310 return 304; // "304 Not Modified"
1312 trigger_error("Ack, shouldn't get here", E_USER_ERROR);
1316 function _checkIfUnmodifiedSince(&$request) {
1317 if ($this->_mtime !== false) {
1318 $since = ParseRfc1123DateTime($request->get("HTTP_IF_UNMODIFIED_SINCE"));
1319 if ($since !== false && $this->_mtime > $since)
1320 return _HTTP_VAL_FAILED;
1322 return _HTTP_VAL_PASS;
1325 function _checkIfModifiedSince(&$request) {
1326 if ($this->_mtime !== false and $request->isGetOrHead()) {
1327 $since = ParseRfc1123DateTime($request->get("HTTP_IF_MODIFIED_SINCE"));
1328 if ($since !== false) {
1329 if ($this->_mtime <= $since)
1330 return _HTTP_VAL_NOT_MODIFIED;
1331 return _HTTP_VAL_MODIFIED;
1334 return _HTTP_VAL_PASS;
1337 function _checkIfMatch(&$request) {
1338 if ($this->_tag && ($taglist = $request->get("HTTP_IF_MATCH"))) {
1339 $tag = $this->getETag();
1340 if (!$tag->matches($taglist, 'strong'))
1341 return _HTTP_VAL_FAILED;
1343 return _HTTP_VAL_PASS;
1346 function _checkIfNoneMatch(&$request) {
1347 if ($this->_tag && ($taglist = $request->get("HTTP_IF_NONE_MATCH"))) {
1348 $tag = $this->getETag();
1349 $strong_compare = ! $request->isGetOrHead();
1351 if ($tag->matches($taglist, $strong_compare)) {
1352 if ($request->isGetOrHead())
1353 return _HTTP_VAL_NOT_MODIFIED;
1355 return _HTTP_VAL_FAILED;
1357 return _HTTP_VAL_MODIFIED;
1360 return _HTTP_VAL_PASS;
1367 // c-basic-offset: 4
1368 // c-hanging-comment-ender-p: nil
1369 // indent-tabs-mode: nil