2 rcs_id('$Id: Request.php,v 1.43 2004-03-12 20:59:17 rurban Exp $');
5 // backward compatibility for PHP < 4.2.0
6 if (!function_exists('ob_clean')) {
17 $this->_fix_magic_quotes_gpc();
18 $this->_fix_multipart_form_data();
20 switch($this->get('REQUEST_METHOD')) {
23 $this->args = &$GLOBALS['HTTP_GET_VARS'];
26 $this->args = &$GLOBALS['HTTP_POST_VARS'];
29 $this->args = array();
33 $this->session = new Request_SessionVars;
34 $this->cookies = new Request_CookieVars;
37 if (! is_writeable(ACCESS_LOG)) {
39 (sprintf(_("%s is not writable."), _("The PhpWiki access log file"))
41 . sprintf(_("Please ensure that %s is writable, or redefine %s in index.php."),
42 sprintf(_("the file '%s'"), ACCESS_LOG),
47 $this->_log_entry = & new Request_AccessLogEntry($this,
51 $GLOBALS['request'] = $this;
55 if (!empty($GLOBALS['HTTP_SERVER_VARS']))
56 $vars = &$GLOBALS['HTTP_SERVER_VARS'];
57 else // cgi or other servers than Apache
58 $vars = &$GLOBALS['_ENV'];
60 if (isset($vars[$key]))
65 $addr = $vars['REMOTE_ADDR'];
66 if (defined('ENABLE_REVERSE_DNS') && ENABLE_REVERSE_DNS)
67 return $vars[$key] = gethostbyaddr($addr);
75 function getArg($key) {
76 if (isset($this->args[$key]))
77 return $this->args[$key];
85 function setArg($key, $val) {
87 unset($this->args[$key]);
89 $this->args[$key] = $val;
92 // Well oh well. Do we really want to pass POST params back as GET?
93 function getURLtoSelf($args = false, $exclude = array()) {
94 $get_args = $this->args;
96 $get_args = array_merge($get_args, $args);
98 // Err... good point...
100 if ($this->isPost()) {
101 $exclude = array_merge($exclude, array('action','auth'));
102 //$get_args = $args; // or only the provided
104 trigger_error("Request::getURLtoSelf() should probably not be from POST",
109 foreach ($exclude as $ex) {
110 if (!empty($get_args[$ex])) unset($get_args[$ex]);
113 $pagename = $get_args['pagename'];
114 unset ($get_args['pagename']);
115 if (!empty($get_args['action']) and $get_args['action'] == 'browse')
116 unset($get_args['action']);
118 return WikiURL($pagename, $get_args);
122 return $this->get("REQUEST_METHOD") == "POST";
125 function isGetOrHead () {
126 return in_array($this->get('REQUEST_METHOD'),
127 array('GET', 'HEAD'));
130 function httpVersion() {
131 if (!preg_match('@HTTP\s*/\s*(\d+.\d+)@', $this->get('SERVER_PROTOCOL'), $m))
133 return (float) $m[1];
136 function redirect($url, $noreturn=true) {
137 $bogus = defined('DISABLE_HTTP_REDIRECT') and DISABLE_HTTP_REDIRECT;
140 header("Location: $url");
142 * "302 Found" is not really meant to be sent in response
143 * to a POST. Worse still, according to (both HTTP 1.0
144 * and 1.1) spec, the user, if it is sent, the user agent
145 * is supposed to use the same method to fetch the
146 * redirected URI as the original.
148 * That means if we redirect from a POST, the user-agent
149 * supposed to generate another POST. Not what we want.
150 * (We do this after a page save after all.)
152 * Fortunately, most/all browsers don't do that.
154 * "303 See Other" is what we really want. But it only
157 * FIXME: this is still not spec compliant for HTTP
160 $status = $this->httpVersion() >= 1.1 ? 303 : 302;
162 $this->setStatus($status);
166 include_once('lib/Template.php');
167 $this->discardOutput();
168 $tmpl = new Template('redirect', $this, array('REDIRECT_URL' => $url));
174 function redirect(url) {
175 if (typeof location.replace == 'function')
176 location.replace(url);
177 else if (typeof location.assign == 'function')
178 location.assign(url);
180 window.location = url;
182 redirect('" . addslashes($url) . "')");
186 /** Set validators for this response.
188 * This sets a (possibly incomplete) set of validators
191 * The validator set can be extended using appendValidators().
193 * When you're all done setting and appending validators, you
194 * must call checkValidators() to check them and set the
195 * appropriate headers in the HTTP response.
199 * $request->setValidators(array('pagename' => $pagename,
200 * '%mtime' => $rev->get('mtime')));
202 * // Wups... response content depends on $otherpage, too...
203 * $request->appendValidators(array('otherpage' => $otherpagerev->getPageName(),
204 * '%mtime' => $otherpagerev->get('mtime')));
206 * // After all validators have been set:
207 * $request->checkValidators();
209 function setValidators($validator_set) {
210 if (is_array($validator_set))
211 $validator_set = new HTTP_ValidatorSet($validator_set);
212 $this->_validators = $validator_set;
215 /** Append validators for this response.
217 * This appends additional validators to this response.
218 * You must call setValidators() before calling this method.
220 function appendValidators($validator_set) {
221 $this->_validators->append($validator_set);
224 /** Check validators and set headers in HTTP response
226 * This sets the appropriate "Last-Modified" and "ETag"
227 * headers in the HTTP response.
229 * Additionally, if the validators match any(all) conditional
230 * headers in the HTTP request, this method will not return, but
231 * instead will send "304 Not Modified" or "412 Precondition
232 * Failed" (as appropriate) back to the client.
234 function checkValidators() {
235 $validators = &$this->_validators;
237 // Set validator headers
238 if (($etag = $validators->getETag()) !== false)
239 header("ETag: " . $etag->asString());
240 if (($mtime = $validators->getModificationTime()) !== false)
241 header("Last-Modified: " . Rfc1123DateTime($mtime));
243 // Set cache control headers
244 $this->cacheControl();
246 if (CACHE_CONTROL == 'NONE')
247 return; // don't check conditionals...
249 // Check conditional headers in request
250 $status = $validators->checkConditionalRequest($this);
252 // Return short response due to failed conditionals
253 $this->setStatus($status);
255 $this->discardOutput();
261 /** Set the cache control headers in the HTTP response.
263 function cacheControl($strategy=CACHE_CONTROL, $max_age=CACHE_CONTROL_MAX_AGE) {
264 if ($strategy == 'NONE') {
265 $cache_control = "no-cache";
268 elseif ($strategy == 'ALLOW_STALE' && $max_age > 0) {
269 $cache_control = sprintf("max-age=%d", $max_age);
272 $cache_control = "must-revalidate";
275 header("Cache-Control: $cache_control");
276 header("Expires: " . Rfc1123DateTime(time() + $max_age));
277 header("Vary: Cookie"); // FIXME: add more here?
280 function setStatus($status) {
281 if (preg_match('|^HTTP/.*?\s(\d+)|i', $status, $m)) {
286 $status = (integer) $status;
287 $reason = array('200' => 'OK',
289 '303' => 'See Other',
290 '304' => 'Not Modified',
291 '400' => 'Bad Request',
292 '401' => 'Unauthorized',
293 '403' => 'Forbidden',
294 '404' => 'Not Found',
295 '412' => 'Precondition Failed');
296 // FIXME: is it always okay to send HTTP/1.1 here, even for older clients?
297 header(sprintf("HTTP/1.1 %d %s", $status, $reason[$status]));
300 if (isset($this->_log_entry))
301 $this->_log_entry->setStatus($status);
304 function buffer_output($compress = true) {
305 if (defined('COMPRESS_OUTPUT')) {
306 if (!COMPRESS_OUTPUT)
309 elseif (!function_exists('version_compare')
310 || version_compare(phpversion(), '4.2.3', "<")) {
314 if (!function_exists('ob_gzhandler'))
318 ob_start('ob_gzhandler');
320 * Attempt to prevent Apache from doing the dreaded double-gzip.
322 * It would be better if we could detect when apache was going
323 * to zip for us, and then let it ... but I have yet to figure
324 * out how to do that.
326 @apache_note('no-gzip', 1);
329 // Now we alway buffer output.
330 // This is so we can set HTTP headers (e.g. for redirect)
332 // FIXME: change the name of this method.
335 $this->_is_buffering_output = true;
338 function discardOutput() {
339 if (!empty($this->_is_buffering_output))
342 trigger_error("Not buffering output", E_USER_NOTICE);
346 if (!empty($this->_is_buffering_output)) {
347 //header(sprintf("Content-Length: %d", ob_get_length()));
353 function getSessionVar($key) {
354 return $this->session->get($key);
356 function setSessionVar($key, $val) {
357 return $this->session->set($key, $val);
359 function deleteSessionVar($key) {
360 return $this->session->delete($key);
363 function getCookieVar($key) {
364 return $this->cookies->get($key);
366 function setCookieVar($key, $val, $lifetime_in_days = false) {
367 return $this->cookies->set($key, $val, $lifetime_in_days);
369 function deleteCookieVar($key) {
370 return $this->cookies->delete($key);
373 function getUploadedFile($key) {
374 return Request_UploadedFile::getUploadedFile($key);
378 function _fix_magic_quotes_gpc() {
379 $needs_fix = array('HTTP_POST_VARS',
386 if (get_magic_quotes_gpc()) {
387 foreach ($needs_fix as $vars)
388 $this->_stripslashes($GLOBALS[$vars]);
392 function _stripslashes(&$var) {
393 if (is_array($var)) {
394 foreach ($var as $key => $val)
395 $this->_stripslashes($var[$key]);
397 elseif (is_string($var))
398 $var = stripslashes($var);
401 function _fix_multipart_form_data () {
402 if (preg_match('|^multipart/form-data|', $this->get('CONTENT_TYPE')))
403 $this->_strip_leading_nl($GLOBALS['HTTP_POST_VARS']);
406 function _strip_leading_nl(&$var) {
407 if (is_array($var)) {
408 foreach ($var as $key => $val)
409 $this->_strip_leading_nl($var[$key]);
411 elseif (is_string($var))
412 $var = preg_replace('|^\r?\n?|', '', $var);
416 class Request_SessionVars {
417 function Request_SessionVars() {
418 // Prevent cacheing problems with IE 5
419 session_cache_limiter('none');
425 $vars = &$GLOBALS['HTTP_SESSION_VARS'];
426 if (isset($vars[$key]))
431 function set($key, $val) {
432 $vars = &$GLOBALS['HTTP_SESSION_VARS'];
433 if ($key == 'wiki_user') {
434 $val->page = $GLOBALS['request']->getArg('pagename');
435 $val->action = $GLOBALS['request']->getArg('action');
437 if (!function_usable('ini_get') or ini_get('register_globals')) {
438 // This is funky but necessary, at least in some PHP's
439 $GLOBALS[$key] = $val;
442 session_register($key);
445 function delete($key) {
446 $vars = &$GLOBALS['HTTP_SESSION_VARS'];
447 if (!function_usable('ini_get') or ini_get('register_globals'))
448 unset($GLOBALS[$key]);
450 session_unregister($key);
454 class Request_CookieVars {
457 $vars = &$GLOBALS['HTTP_COOKIE_VARS'];
458 if (isset($vars[$key])) {
459 @$val = unserialize(base64_decode($vars[$key]));
466 function set($key, $val, $persist_days = false) {
467 $vars = &$GLOBALS['HTTP_COOKIE_VARS'];
469 if (is_numeric($persist_days)) {
470 $expires = time() + (24 * 3600) * $persist_days;
476 $packedval = base64_encode(serialize($val));
477 $vars[$key] = $packedval;
478 setcookie($key, $packedval, $expires, '/');
481 function delete($key) {
482 $vars = &$GLOBALS['HTTP_COOKIE_VARS'];
490 You must set "upload_tmp_dir" = "/tmp/" or "C:/tmp/"
491 Best on the same drive as apache, with foreard slashes
492 and with ending slash!
493 Otherwise "\\" => "" and the uploaded file will not be found.
495 class Request_UploadedFile {
496 function getUploadedFile($postname) {
497 global $HTTP_POST_FILES;
499 if (!isset($HTTP_POST_FILES[$postname]))
502 $fileinfo = &$HTTP_POST_FILES[$postname];
503 if ($fileinfo['error']) {
504 trigger_error("Upload error: #" . $fileinfo['error'],
509 // With windows/php 4.2.1 is_uploaded_file() always returns false.
510 if (!is_uploaded_file($fileinfo['tmp_name'])) {
512 if (!$tmp_file = get_cfg_var('upload_tmp_dir')) {
513 $tmp_file = dirname(tempnam('', ''));
515 $tmp_file .= '/' . basename($fileinfo['tmp_name']);
516 /* but ending slash in php.ini upload_tmp_dir is required. */
517 if (ereg_replace('/+', '/', $tmp_file) != $fileinfo['tmp_name']) {
518 trigger_error(sprintf("Uploaded tmpfile illegal: %s != %s",$tmp_file, $fileinfo['tmp_name']),
522 trigger_error(sprintf("Workaround for PHP/Windows is_uploaded_file() problem for %s.",
523 $fileinfo['tmp_name'])."\n".
524 "Probably illegal TEMP environment setting.",E_USER_NOTICE);
527 trigger_error(sprintf("Uploaded tmpfile %s not found.",$fileinfo['tmp_name'])."\n".
528 " Probably illegal TEMP environment setting.",
532 return new Request_UploadedFile($fileinfo);
535 function Request_UploadedFile($fileinfo) {
536 $this->_info = $fileinfo;
540 return $this->_info['size'];
544 return $this->_info['name'];
548 return $this->_info['type'];
551 function getTmpName() {
552 return $this->_info['tmp_name'];
556 if ( ($fd = fopen($this->_info['tmp_name'], "rb")) ) {
557 if ($this->getSize() < filesize($this->_info['tmp_name'])) {
558 // FIXME: Some PHP's (or is it some browsers?) put
559 // HTTP/MIME headers in the file body, some don't.
561 // At least, I think that's the case. I know I used
562 // to need this code, now I don't.
564 // This code is more-or-less untested currently.
566 // Dump HTTP headers.
567 while ( ($header = fgets($fd, 4096)) ) {
568 if (trim($header) == '') {
571 else if (!preg_match('/^content-(length|type):/i', $header)) {
581 function getContents() {
583 $data = fread($fd, $this->getSize());
590 * Create NCSA "combined" log entry for current request.
592 class Request_AccessLogEntry
597 * The log entry will be automatically appended to the log file
598 * when the current request terminates.
600 * If you want to modify a Request_AccessLogEntry before it gets
601 * written (e.g. via the setStatus and setSize methods) you should
602 * use an '&' on the constructor, so that you're working with the
603 * original (rather than a copy) object.
606 * $log_entry = & new Request_AccessLogEntry($req, "/tmp/wiki_access_log");
607 * $log_entry->setStatus(401);
611 * @param $request object Request object for current request.
612 * @param $logfile string Log file name.
614 function Request_AccessLogEntry (&$request, $logfile) {
615 $this->logfile = $logfile;
617 $this->host = $request->get('REMOTE_HOST');
618 $this->ident = $request->get('REMOTE_IDENT');
621 $this->user = '-'; // FIXME: get logged-in user name
622 $this->time = time();
623 $this->request = join(' ', array($request->get('REQUEST_METHOD'),
624 $request->get('REQUEST_URI'),
625 $request->get('SERVER_PROTOCOL')));
628 $this->referer = (string) $request->get('HTTP_REFERER');
629 $this->user_agent = (string) $request->get('HTTP_USER_AGENT');
631 global $Request_AccessLogEntry_entries;
632 if (!isset($Request_AccessLogEntry_entries)) {
633 register_shutdown_function("Request_AccessLogEntry_shutdown_function");
635 $Request_AccessLogEntry_entries[] = &$this;
639 * Set result status code.
641 * @param $status integer HTTP status code.
643 function setStatus ($status) {
644 $this->status = $status;
650 * @param $size integer
652 function setSize ($size) {
657 * Get time zone offset.
659 * This is a static member function.
661 * @param $time integer Unix timestamp (defaults to current time).
662 * @return string Zone offset, e.g. "-0800" for PST.
664 function _zone_offset ($time = false) {
667 $offset = date("Z", $time);
673 $offhours = floor($offset / 3600);
674 $offmins = $offset / 60 - $offhours * 60;
675 return sprintf("%s%02d%02d", $negoffset, $offhours, $offmins);
679 * Format time in NCSA format.
681 * This is a static member function.
683 * @param $time integer Unix timestamp (defaults to current time).
684 * @return string Formatted date & time.
686 function _ncsa_time($time = false) {
690 return date("d/M/Y:H:i:s", $time) .
691 " " . $this->_zone_offset();
695 * Write entry to log file.
698 $entry = sprintf('%s %s %s [%s] "%s" %d %d "%s" "%s"',
699 $this->host, $this->ident, $this->user,
700 $this->_ncsa_time($this->time),
701 $this->request, $this->status, $this->size,
702 $this->referer, $this->user_agent);
704 //Error log doesn't provide locking.
705 //error_log("$entry\n", 3, $this->logfile);
708 if (($fp = fopen($this->logfile, "a"))) {
710 fputs($fp, "$entry\n");
720 * @see Request_AccessLogEntry
722 function Request_AccessLogEntry_shutdown_function ()
724 global $Request_AccessLogEntry_entries;
726 foreach ($Request_AccessLogEntry_entries as $entry) {
729 unset($Request_AccessLogEntry_entries);
734 function HTTP_ETag($val, $is_weak=false) {
735 $this->_val = hash($val);
736 $this->_weak = $is_weak;
741 * Strong comparison: If either (or both) tag is weak, they
744 function equals($that, $strong_match=false) {
745 if ($this->_val != $that->_val)
747 if ($strong_match and ($this->_weak or $that->_weak))
753 function asString() {
754 $quoted = '"' . addslashes($this->_val) . '"';
755 return $this->_weak ? "W/$quoted" : $quoted;
758 /** Parse tag from header.
760 * This is a static member function.
762 function parse($strval) {
763 if (!preg_match(':^(W/)?"(.+)"$:i', trim($strval), $m))
764 return false; // parse failed
765 list(,$weak,$str) = $m;
766 return new HTTP_ETag(stripslashes($str), $weak);
769 function matches($taglist, $strong_match=false) {
770 $taglist = trim($taglist);
772 if ($taglist == '*') {
774 return ! $this->_weak;
779 while (preg_match('@^(W/)?"((?:\\\\.|[^"])*)"\s*,?\s*@i',
781 list($match, $weak, $str) = $m;
782 $taglist = substr($taglist, strlen($match));
783 $tag = new HTTP_ETag(stripslashes($str), $weak);
784 if ($this->equals($tag, $strong_match)) {
792 // Possible results from the HTTP_ValidatorSet::_check*() methods.
793 // (Higher numerical values take precedence.)
794 define ('_HTTP_VAL_PASS', 0); // Test is irrelevant
795 define ('_HTTP_VAL_NOT_MODIFIED', 1); // Test passed, content not changed
796 define ('_HTTP_VAL_MODIFIED', 2); // Test failed, content changed
797 define ('_HTTP_VAL_FAILED', 3); // Precondition failed.
799 class HTTP_ValidatorSet {
800 function HTTP_ValidatorSet($validators) {
801 $this->_mtime = $this->_weak = false;
802 $this->_tag = array();
804 foreach ($validators as $key => $val) {
805 if ($key == '%mtime') {
806 $this->_mtime = $val;
808 elseif ($key == '%weak') {
813 $this->_tag[$key] = $val;
818 function append($that) {
820 $that = new HTTP_ValidatorSet($that);
822 // Pick the most recent mtime
823 if (isset($that->_mtime))
824 if (!isset($this->_mtime) || $that->_mtime > $this->_mtime)
825 $this->_mtime = $that->_mtime;
827 // If either is weak, we're weak
828 if (!empty($that->_weak))
831 $this->_tag = array_merge($this->_tag, $that->_tag);
837 return new HTTP_ETag($this->_tag, $this->_weak);
840 function getModificationTime() {
841 return $this->_mtime;
844 function checkConditionalRequest (&$request) {
845 $result = max($this->_checkIfUnmodifiedSince($request),
846 $this->_checkIfModifiedSince($request),
847 $this->_checkIfMatch($request),
848 $this->_checkIfNoneMatch($request));
850 if ($result == _HTTP_VAL_PASS || $result == _HTTP_VAL_MODIFIED)
851 return false; // "please proceed with normal processing"
852 elseif ($result == _HTTP_VAL_FAILED)
853 return 412; // "412 Precondition Failed"
854 elseif ($result == _HTTP_VAL_NOT_MODIFIED)
855 return 304; // "304 Not Modified"
857 trigger_error("Ack, shouldn't get here", E_USER_ERROR);
861 function _checkIfUnmodifiedSince(&$request) {
862 if ($this->_mtime !== false) {
863 $since = ParseRfc1123DateTime($request->get("HTTP_IF_UNMODIFIED_SINCE"));
864 if ($since !== false && $this->_mtime > $since)
865 return _HTTP_VAL_FAILED;
867 return _HTTP_VAL_PASS;
870 function _checkIfModifiedSince(&$request) {
871 if ($this->_mtime !== false and $request->isGetOrHead()) {
872 $since = ParseRfc1123DateTime($request->get("HTTP_IF_MODIFIED_SINCE"));
873 if ($since !== false) {
874 if ($this->_mtime <= $since)
875 return _HTTP_VAL_NOT_MODIFIED;
876 return _HTTP_VAL_MODIFIED;
879 return _HTTP_VAL_PASS;
882 function _checkIfMatch(&$request) {
883 if ($this->_tag && ($taglist = $request->get("HTTP_IF_MATCH"))) {
884 $tag = $this->getETag();
885 if (!$tag->matches($taglist, 'strong'))
886 return _HTTP_VAL_FAILED;
888 return _HTTP_VAL_PASS;
891 function _checkIfNoneMatch(&$request) {
892 if ($this->_tag && ($taglist = $request->get("HTTP_IF_NONE_MATCH"))) {
893 $tag = $this->getETag();
894 $strong_compare = ! $request->isGetOrHead();
896 if ($tag->matches($taglist, $strong_compare)) {
897 if ($request->isGetOrHead())
898 return _HTTP_VAL_NOT_MODIFIED;
900 return _HTTP_VAL_FAILED;
902 return _HTTP_VAL_MODIFIED;
905 return _HTTP_VAL_PASS;
910 // $Log: not supported by cvs2svn $
911 // Revision 1.42 2004/03/10 15:38:48 rurban
912 // store current user->page and ->action in session for WhoIsOnline
913 // better WhoIsOnline icon
914 // fixed WhoIsOnline warnings
916 // Revision 1.41 2004/02/27 01:25:14 rurban
917 // Workarounds for upload handling
919 // Revision 1.40 2004/02/26 01:39:51 rurban
922 // Revision 1.39 2004/02/24 15:14:57 rurban
923 // fixed action=upload problems on Win32, and remove Merge Edit buttons: file does not exist anymore
925 // Revision 1.38 2004/01/25 10:26:02 rurban
926 // fixed bug [ 541193 ] HTTP_SERVER_VARS are Apache specific
927 // http://sourceforge.net/tracker/index.php?func=detail&aid=541193&group_id=6121&atid=106121
928 // CGI and other servers than apache populate _ENV and not _SERVER
930 // Revision 1.37 2003/12/26 06:41:16 carstenklapp
931 // Bugfix: Try to defer OS errors about session.save_path and ACCESS_LOG,
932 // so they don't prevent IE from partially (or not at all) rendering the
933 // page. This should help a little for the IE user who encounters trouble
934 // when setting up a new PhpWiki for the first time.
941 // c-hanging-comment-ender-p: nil
942 // indent-tabs-mode: nil