Open Journal Systems  2.4.8
 All Classes Namespaces Functions Variables Groups Pages
PKPRequest.inc.php
1 <?php
2 
17 class PKPRequest {
18  //
19  // Internal state - please do not reference directly
20  //
22  var $_router = null;
24  var $_dispatcher = null;
26  var $_requestVars = null;
28  var $_basePath;
30  var $_requestPath;
32  var $_isRestfulUrlsEnabled;
34  var $_isPathInfoEnabled;
36  var $_serverHost;
38  var $_baseUrl;
40  var $_protocol;
41 
42 
47  function &getRouter() {
48  return $this->_router;
49  }
50 
55  function setRouter(&$router) {
56  $this->_router =& $router;
57  }
58 
63  function setDispatcher(&$dispatcher) {
64  $this->_dispatcher =& $dispatcher;
65  }
66 
71  function &getDispatcher() {
72  return $this->_dispatcher;
73  }
74 
75 
80  function redirectUrl($url) {
82 
83  if (HookRegistry::call('Request::redirect', array(&$url))) {
84  return;
85  }
86 
87  header("Location: $url");
88  exit();
89  }
90 
95  function redirectUrlJson($url) {
96  import('lib.pkp.classes.core.JSONMessage');
97  $json = new JSONMessage(true);
98  $json->setEvent('redirectRequested', $url);
99  return $json->getString();
100  }
101 
105  function redirectSSL() {
106  $_this =& PKPRequest::_checkThis();
107 
108  // Note that we are intentionally skipping PKP processing of REQUEST_URI and QUERY_STRING for a protocol redirect
109  // This processing is deferred to the redirected (target) URI
110  $url = 'https://' . $_this->getServerHost() . $_SERVER['REQUEST_URI'];
111  $queryString = $_SERVER['QUERY_STRING'];
112  if (!empty($queryString)) $url .= "?$queryString";
113  $_this->redirectUrl($url);
114  }
115 
119  function redirectNonSSL() {
120  $_this =& PKPRequest::_checkThis();
121 
122  // Note that we are intentionally skipping PKP processing of REQUEST_URI and QUERY_STRING for a protocol redirect
123  // This processing is deferred to the redirected (target) URI
124  $url = 'http://' . $_this->getServerHost() . $_SERVER['REQUEST_URI'];
125  $queryString = $_SERVER['QUERY_STRING'];
126  if (!empty($queryString)) $url .= "?$queryString";
127  $_this->redirectUrl($url);
128  }
129 
134  function getIfModifiedSince() {
135  if (!isset($_SERVER['HTTP_IF_MODIFIED_SINCE'])) return null;
136  return strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']);
137  }
138 
143  function getBaseUrl() {
144  $_this =& PKPRequest::_checkThis();
145 
146  if (!isset($_this->_baseUrl)) {
147  $serverHost = $_this->getServerHost(false);
148  if ($serverHost !== false) {
149  // Auto-detection worked.
150  $_this->_baseUrl = $_this->getProtocol() . '://' . $_this->getServerHost() . $_this->getBasePath();
151  } else {
152  // Auto-detection didn't work (e.g. this is a command-line call); use configuration param
153  $_this->_baseUrl = Config::getVar('general', 'base_url');
154  }
155  HookRegistry::call('Request::getBaseUrl', array(&$_this->_baseUrl));
156  }
157 
158  return $_this->_baseUrl;
159  }
160 
165  function getBasePath() {
166  $_this =& PKPRequest::_checkThis();
167 
168  if (!isset($_this->_basePath)) {
169  # Strip the PHP filename off of the script's executed path
170  # We expect the SCRIPT_NAME to look like /path/to/file.php
171  # If the SCRIPT_NAME ends in /, assume this is the directory and the script's actual name is masked as the DirectoryIndex
172  # If the SCRIPT_NAME ends in neither / or .php, assume the the script's actual name is masked and we need to avoid stripping the terminal directory
173  $path = preg_replace('#/[^/]*$#', '', $_SERVER['SCRIPT_NAME'].(substr($_SERVER['SCRIPT_NAME'], -1) == '/' || preg_match('#.php$#i', $_SERVER['SCRIPT_NAME']) ? '' : '/'));
174 
175  // Encode charcters which need to be encoded in a URL.
176  // Simply using rawurlencode() doesn't work because it
177  // also encodes characters which are valid in a URL (i.e. @, $).
178  $parts = explode('/', $path);
179  foreach ($parts as $i => $part) {
180  $pieces = array_map(array($this, 'encodeBasePathFragment'), str_split($part));
181  $parts[$i] = implode('', $pieces);
182  }
183  $_this->_basePath = implode('/', $parts);
184 
185  if ($_this->_basePath == '/' || $_this->_basePath == '\\') {
186  $_this->_basePath = '';
187  }
188  HookRegistry::call('Request::getBasePath', array(&$_this->_basePath));
189  }
190 
191  return $_this->_basePath;
192  }
193 
200  function encodeBasePathFragment($fragment) {
201  if (!preg_match('/[A-Za-z0-9-._~!$&\'()*+,;=:@]/', $fragment)) {
202  return rawurlencode($fragment);
203  }
204  return $fragment;
205  }
206 
211  function getIndexUrl() {
212  static $indexUrl;
213 
214  $_this =& PKPRequest::_checkThis();
215  if (!isset($indexUrl)) {
216  $indexUrl = $_this->_delegateToRouter('getIndexUrl');
217 
218  // Call legacy hook
219  HookRegistry::call('Request::getIndexUrl', array(&$indexUrl));
220  }
221 
222  return $indexUrl;
223  }
224 
229  function getCompleteUrl() {
230  $_this =& PKPRequest::_checkThis();
231 
232  static $completeUrl;
233 
234  if (!isset($completeUrl)) {
235  $completeUrl = $_this->getRequestUrl();
236  $queryString = $_this->getQueryString();
237  if (!empty($queryString)) $completeUrl .= "?$queryString";
238  HookRegistry::call('Request::getCompleteUrl', array(&$completeUrl));
239  }
240 
241  return $completeUrl;
242  }
243 
248  function getRequestUrl() {
249  $_this =& PKPRequest::_checkThis();
250 
251  static $requestUrl;
252 
253  if (!isset($requestUrl)) {
254  $requestUrl = $_this->getProtocol() . '://' . $_this->getServerHost() . $_this->getRequestPath();
255  HookRegistry::call('Request::getRequestUrl', array(&$requestUrl));
256  }
257 
258  return $requestUrl;
259  }
260 
265  function getQueryString() {
267 
268  static $queryString;
269 
270  if (!isset($queryString)) {
271  $queryString = isset($_SERVER['QUERY_STRING'])?$_SERVER['QUERY_STRING']:'';
272  HookRegistry::call('Request::getQueryString', array(&$queryString));
273  }
274 
275  return $queryString;
276  }
277 
284  function getQueryArray() {
285  $_this =& PKPRequest::_checkThis();
286 
287  $queryString = $_this->getQueryString();
288  $queryArray = array();
289 
290  if (isset($queryString)) {
291  parse_str($queryString, $queryArray);
292  }
293 
294  // Filter out disable_path_info reserved parameters
295  foreach (array_merge(Application::getContextList(), array('path', 'page', 'op')) as $varName) {
296  if (isset($queryArray[$varName])) unset($queryArray[$varName]);
297  }
298 
299  return $queryArray;
300  }
301 
306  function getRequestPath() {
307  $_this =& PKPRequest::_checkThis();
308 
309  if (!isset($_this->_requestPath)) {
310  if ($_this->isRestfulUrlsEnabled()) {
311  $_this->_requestPath = $_this->getBasePath();
312  } else {
313  $_this->_requestPath = $_SERVER['SCRIPT_NAME'];
314  }
315 
316  if ($_this->isPathInfoEnabled()) {
317  $_this->_requestPath .= isset($_SERVER['PATH_INFO']) ? $_SERVER['PATH_INFO'] : '';
318  }
319  HookRegistry::call('Request::getRequestPath', array(&$_this->_requestPath));
320  }
321  return $_this->_requestPath;
322  }
323 
330  function getServerHost($default = null, $includePort = true) {
331  if ($default === null) $default = 'localhost';
332 
333  $_this =& PKPRequest::_checkThis();
334 
335  if (!isset($_this->_serverHost)) {
336  $_this->_serverHost = isset($_SERVER['HTTP_X_FORWARDED_HOST']) ? $_SERVER['HTTP_X_FORWARDED_HOST']
337  : (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST']
338  : (isset($_SERVER['HOSTNAME']) ? $_SERVER['HOSTNAME']
339  : null));
340 
341  HookRegistry::call('Request::getServerHost', array(&$_this->_serverHost, &$default, &$includePort));
342  }
343 
344  $host = $_this->_serverHost === null ? $default : $_this->_serverHost;
345 
346  if (!$includePort) {
347  // Strip the port number, if one is included. (#3912)
348  return preg_replace("/:\d*$/", '', $host);
349  }
350 
351  return $host;
352  }
353 
358  function getProtocol() {
359  $_this =& PKPRequest::_checkThis();
360 
361  if (!isset($_this->_protocol)) {
362  $_this->_protocol = (!isset($_SERVER['HTTPS']) || strtolower_codesafe($_SERVER['HTTPS']) != 'on') ? 'http' : 'https';
363  HookRegistry::call('Request::getProtocol', array(&$_this->_protocol));
364  }
365  return $_this->_protocol;
366  }
367 
372  function getRequestMethod() {
374 
375  $requestMethod = (isset($_SERVER['REQUEST_METHOD']) ? $_SERVER['REQUEST_METHOD'] : '');
376  return $requestMethod;
377  }
378 
383  function isPost() {
384  $_this =& PKPRequest::_checkThis();
385 
386  return ($_this->getRequestMethod() == 'POST');
387  }
388 
393  function isGet() {
394  $_this =& PKPRequest::_checkThis();
395 
396  return ($_this->getRequestMethod() == 'GET');
397  }
398 
403  function getRemoteAddr() {
405 
406  $ipaddr =& Registry::get('remoteIpAddr'); // Reference required.
407  if (is_null($ipaddr)) {
408  if (isset($_SERVER['HTTP_X_FORWARDED_FOR']) &&
409  Config::getVar('general', 'trust_x_forwarded_for', true) &&
410  preg_match_all('/([0-9.a-fA-F:]+)/', $_SERVER['HTTP_X_FORWARDED_FOR'], $matches)) {
411  } else if (isset($_SERVER['REMOTE_ADDR']) &&
412  preg_match_all('/([0-9.a-fA-F:]+)/', $_SERVER['REMOTE_ADDR'], $matches)) {
413  } else if (preg_match_all('/([0-9.a-fA-F:]+)/', getenv('REMOTE_ADDR'), $matches)) {
414  } else {
415  $ipaddr = '';
416  }
417 
418  if (!isset($ipaddr)) {
419  // If multiple addresses are listed, take the last. (Supports ipv6.)
420  $ipaddr = $matches[0][count($matches[0])-1];
421  }
422  HookRegistry::call('Request::getRemoteAddr', array(&$ipaddr));
423  }
424  return $ipaddr;
425  }
426 
431  function getRemoteDomain() {
432  $_this =& PKPRequest::_checkThis();
433 
434  static $remoteDomain;
435  if (!isset($remoteDomain)) {
436  $remoteDomain = null;
437  $remoteDomain = @getHostByAddr($_this->getRemoteAddr());
438  HookRegistry::call('Request::getRemoteDomain', array(&$remoteDomain));
439  }
440  return $remoteDomain;
441  }
442 
447  function getUserAgent() {
449 
450  static $userAgent;
451  if (!isset($userAgent)) {
452  if (isset($_SERVER['HTTP_USER_AGENT'])) {
453  $userAgent = $_SERVER['HTTP_USER_AGENT'];
454  }
455  if (!isset($userAgent) || empty($userAgent)) {
456  $userAgent = getenv('HTTP_USER_AGENT');
457  }
458  if (!isset($userAgent) || $userAgent == false) {
459  $userAgent = '';
460  }
461  HookRegistry::call('Request::getUserAgent', array(&$userAgent));
462  }
463  return $userAgent;
464  }
465 
470  function isBot() {
471  $_this =& PKPRequest::_checkThis();
472 
473  static $isBot;
474  if (!isset($isBot)) {
475  $userAgent = $_this->getUserAgent();
476  $isBot = Core::isUserAgentBot($userAgent);
477  }
478  return $isBot;
479  }
480 
484  function isPathInfoEnabled() {
485  $_this =& PKPRequest::_checkThis();
486 
487  if (!isset($_this->_isPathInfoEnabled)) {
488  $_this->_isPathInfoEnabled = Config::getVar('general', 'disable_path_info')?false:true;
489  }
490  return $_this->_isPathInfoEnabled;
491  }
492 
496  function isRestfulUrlsEnabled() {
497  $_this =& PKPRequest::_checkThis();
498 
499  if (!isset($_this->_isRestfulUrlsEnabled)) {
500  $_this->_isRestfulUrlsEnabled = Config::getVar('general', 'restful_urls')?true:false;
501  }
502  return $_this->_isRestfulUrlsEnabled;
503  }
504 
509  function &getSite() {
511 
512  $site =& Registry::get('site', true, null);
513  if ($site === null) {
514  $siteDao =& DAORegistry::getDAO('SiteDAO');
515  $site =& $siteDao->getSite();
516  // PHP bug? This is needed for some reason or extra queries results.
517  Registry::set('site', $site);
518  }
519 
520  return $site;
521  }
522 
527  function &getSession() {
529 
530  $session =& Registry::get('session', true, null);
531 
532  if ($session === null) {
533  $sessionManager =& SessionManager::getManager();
534  $session = $sessionManager->getUserSession();
535  }
536 
537  return $session;
538  }
539 
544  function &getUser() {
546 
547  $user =& Registry::get('user', true, null);
548  if ($user === null) {
549  $sessionManager =& SessionManager::getManager();
550  $session =& $sessionManager->getUserSession();
551  $user =& $session->getUser();
552  }
553 
554  return $user;
555  }
556 
561  function getUserVar($key) {
562  $_this =& PKPRequest::_checkThis();
563 
564  // Get all vars (already cleaned)
565  $vars =& $_this->getUserVars();
566 
567  if (isset($vars[$key])) {
568  return $vars[$key];
569  } else {
570  return null;
571  }
572  }
573 
578  function &getUserVars() {
579  $_this =& PKPRequest::_checkThis();
580 
581  if (!isset($_this->_requestVars)) {
582  $_this->_requestVars = array_merge($_GET, $_POST);
583  $_this->cleanUserVar($_this->_requestVars);
584  }
585 
586  return $_this->_requestVars;
587  }
588 
601  function getUserDateVar($prefix, $defaultDay = null, $defaultMonth = null, $defaultYear = null, $defaultHour = 0, $defaultMinute = 0, $defaultSecond = 0) {
602  $_this =& PKPRequest::_checkThis();
603 
604  $monthPart = $_this->getUserVar($prefix . 'Month');
605  $dayPart = $_this->getUserVar($prefix . 'Day');
606  $yearPart = $_this->getUserVar($prefix . 'Year');
607  $hourPart = $_this->getUserVar($prefix . 'Hour');
608  $minutePart = $_this->getUserVar($prefix . 'Minute');
609  $secondPart = $_this->getUserVar($prefix . 'Second');
610 
611  switch ($_this->getUserVar($prefix . 'Meridian')) {
612  case 'pm':
613  if (is_numeric($hourPart) && $hourPart != 12) $hourPart += 12;
614  break;
615  case 'am':
616  default:
617  // Do nothing.
618  break;
619  }
620 
621  if (empty($dayPart)) $dayPart = $defaultDay;
622  if (empty($monthPart)) $monthPart = $defaultMonth;
623  if (empty($yearPart)) $yearPart = $defaultYear;
624  if (empty($hourPart)) $hourPart = $defaultHour;
625  if (empty($minutePart)) $minutePart = $defaultMinute;
626  if (empty($secondPart)) $secondPart = $defaultSecond;
627 
628  if (empty($monthPart) || empty($dayPart) || empty($yearPart)) return null;
629  return mktime($hourPart, $minutePart, $secondPart, $monthPart, $dayPart, $yearPart);
630  }
631 
637  function cleanUserVar(&$var) {
638  $_this =& PKPRequest::_checkThis();
639 
640  if (isset($var) && is_array($var)) {
641  foreach ($var as $key => $value) {
642  $_this->cleanUserVar($var[$key]);
643  }
644  } else if (isset($var)) {
645  $var = Core::cleanVar(get_magic_quotes_gpc() ? stripslashes($var) : $var);
646 
647  } else {
648  return null;
649  }
650  }
651 
656  function getCookieVar($key) {
657  $_this =& PKPRequest::_checkThis();
658 
659  if (isset($_COOKIE[$key])) {
660  $value = $_COOKIE[$key];
661  $_this->cleanUserVar($value);
662  return $value;
663  } else {
664  return null;
665  }
666  }
667 
674  function setCookieVar($key, $value, $expire = 0) {
675  $_this =& PKPRequest::_checkThis();
676 
677  $basePath = $_this->getBasePath();
678  if (!$basePath) $basePath = '/';
679 
680  setcookie($key, $value, $expire, $basePath);
681  $_COOKIE[$key] = $value;
682  }
683 
694  function redirect($context = null, $page = null, $op = null, $path = null, $params = null, $anchor = null) {
695  $_this =& PKPRequest::_checkThis();
696  $dispatcher =& $_this->getDispatcher();
697  $_this->redirectUrl($dispatcher->url($_this, ROUTE_PAGE, $context, $page, $op, $path, $params, $anchor));
698  }
699 
704  function &getContext() {
705  $_this =& PKPRequest::_checkThis();
706  return $_this->_delegateToRouter('getContext');
707  }
708 
713  function getRequestedContextPath($contextLevel = null) {
714  $_this =& PKPRequest::_checkThis();
715 
716  // Emulate the old behavior of getRequestedContextPath for
717  // backwards compatibility.
718  if (is_null($contextLevel)) {
719  return $_this->_delegateToRouter('getRequestedContextPaths');
720  } else {
721  return array($_this->_delegateToRouter('getRequestedContextPath', $contextLevel));
722  }
723  }
724 
729  function getRequestedPage() {
730  $_this =& PKPRequest::_checkThis();
731  return $_this->_delegateToRouter('getRequestedPage');
732  }
733 
738  function getRequestedOp() {
739  $_this =& PKPRequest::_checkThis();
740  return $_this->_delegateToRouter('getRequestedOp');
741  }
742 
747  function getRequestedArgs() {
748  $_this =& PKPRequest::_checkThis();
749  return $_this->_delegateToRouter('getRequestedArgs');
750  }
751 
756  function url($context = null, $page = null, $op = null, $path = null,
757  $params = null, $anchor = null, $escape = false) {
758  $_this =& PKPRequest::_checkThis();
759  return $_this->_delegateToRouter('url', $context, $page, $op, $path,
760  $params, $anchor, $escape);
761  }
762 
777  function &_checkThis() {
778  if (isset($this) && is_a($this, 'PKPRequest')) {
779  return $this;
780  } else {
781  // This call is deprecated. We don't trigger a
782  // deprecation error, though, as there are so
783  // many instances of this error that it has a
784  // performance impact and renders the error
785  // log virtually useless when deprecation
786  // warnings are switched on.
787  // FIXME: Fix enough instances of this error so that
788  // we can put a deprecation warning in here.
789  $instance =& Registry::get('request');
790  assert(!is_null($instance));
791  return $instance;
792  }
793  }
794 
808  function &_delegateToRouter($method) {
809  // This call is deprecated. We don't trigger a
810  // deprecation error, though, as there are so
811  // many instances of this error that it has a
812  // performance impact and renders the error
813  // log virtually useless when deprecation
814  // warnings are switched on.
815  // FIXME: Fix enough instances of this error so that
816  // we can put a deprecation warning in here.
817  $_this =& PKPRequest::_checkThis();
818  $router =& $_this->getRouter();
819 
820  if (is_null($router)) {
821  assert(false);
822  $nullValue = null;
823  return $nullValue;
824  }
825 
826  // Construct the method call
827  $callable = array($router, $method);
828 
829  // Get additional parameters but replace
830  // the first parameter (currently the
831  // method to be called) with the request
832  // as all router methods required the request
833  // as their first parameter.
834  $parameters = func_get_args();
835  $parameters[0] =& $_this;
836 
837  $returner = call_user_func_array($callable, $parameters);
838  return $returner;
839  }
840 }
841 
842 ?>
setDispatcher(&$dispatcher)
redirectUrl($url)
getRequestedContextPath($contextLevel=null)
redirect($context=null, $page=null, $op=null, $path=null, $params=null, $anchor=null)
Class to represent a JSON (Javascript Object Notation) message.
getUserDateVar($prefix, $defaultDay=null, $defaultMonth=null, $defaultYear=null, $defaultHour=0, $defaultMinute=0, $defaultSecond=0)
isUserAgentBot($userAgent, $botRegexpsFile=USER_AGENTS_FILE)
Definition: Core.inc.php:138
set($key, &$value)
getVar($section, $key, $default=null)
Definition: Config.inc.php:34
setRouter(&$router)
url($context=null, $page=null, $op=null, $path=null, $params=null, $anchor=null, $escape=false)
& getDAO($name, $dbconn=null)
setCookieVar($key, $value, $expire=0)
cleanVar($var)
Definition: Core.inc.php:49
getServerHost($default=null, $includePort=true)
& _delegateToRouter($method)
call($hookName, $args=null)
redirectUrlJson($url)
& get($key, $createIfEmpty=false, $createWithDefault=null)
Class providing operations associated with HTTP requests.
encodeBasePathFragment($fragment)
cleanUserVar(&$var)
getCookieVar($key)