[ Index ]

PHP Cross Reference of Joomla 2.5.4 DE

title

Body

[close]

/libraries/joomla/application/ -> application.php (source)

   1  <?php
   2  /**
   3   * @package     Joomla.Platform
   4   * @subpackage  Application
   5   *
   6   * @copyright   Copyright (C) 2005 - 2012 Open Source Matters, Inc. All rights reserved.
   7   * @license     GNU General Public License version 2 or later; see LICENSE
   8   */
   9  
  10  defined('JPATH_PLATFORM') or die;
  11  
  12  jimport('joomla.application.input');
  13  jimport('joomla.event.dispatcher');
  14  jimport('joomla.environment.response');
  15  
  16  /**
  17   * Base class for a Joomla! application.
  18   *
  19   * Acts as a Factory class for application specific objects and provides many
  20   * supporting API functions. Derived clases should supply the route(), dispatch()
  21   * and render() functions.
  22   *
  23   * @package     Joomla.Platform
  24   * @subpackage  Application
  25   * @since       11.1
  26   */
  27  
  28  class JApplication extends JObject
  29  {
  30      /**
  31       * The client identifier.
  32       *
  33       * @var    integer
  34       * @since  11.1
  35       */
  36      protected $clientId = null;
  37  
  38      /**
  39       * The client identifier.
  40       *
  41       * @var    integer
  42       * @since  11.1
  43       * @deprecated use $clientId or declare as private
  44       */
  45      protected $_clientId = null;
  46  
  47      /**
  48       * The application message queue.
  49       *
  50       * @var    array
  51       * @since  11.1
  52       */
  53      protected $messageQueue = array();
  54  
  55      /**
  56       * The application message queue.
  57       *
  58       * @var    array
  59       * @since  11.1
  60       * @deprecated use $messageQueue or declare as private
  61       */
  62      protected $_messageQueue = array();
  63  
  64      /**
  65       * The name of the application.
  66       *
  67       * @var    array
  68       * @since  11.1
  69       */
  70      protected $name = null;
  71  
  72      /**
  73       * The name of the application.
  74       *
  75       * @var    array
  76       * @since  11.1
  77       * @deprecated use $name or declare as private
  78       */
  79      protected $_name = null;
  80  
  81      /**
  82       * The scope of the application.
  83       *
  84       * @var    string
  85       * @since  11.1
  86       */
  87      public $scope = null;
  88  
  89      /**
  90       * The time the request was made.
  91       *
  92       * @var    date
  93       * @since  11.1
  94       */
  95      public $requestTime = null;
  96  
  97      /**
  98       * The time the request was made as Unix timestamp.
  99       *
 100       * @var    integer
 101       * @since  11.1
 102       */
 103      public $startTime = null;
 104  
 105      /**
 106       * The application input object.
 107       *
 108       * @var    JInput
 109       * @since  11.2
 110       */
 111      public $input = null;
 112  
 113      /**
 114       * @var    array  JApplication instances container.
 115       * @since  11.3
 116       */
 117      protected static $instances = array();
 118  
 119      /**
 120       * Class constructor.
 121       *
 122       * @param   array  $config  A configuration array including optional elements such as session
 123       * session_name, clientId and others. This is not exhaustive.
 124       *
 125       * @since   11.1
 126       */
 127  	public function __construct($config = array())
 128      {
 129          jimport('joomla.error.profiler');
 130  
 131          // Set the view name.
 132          $this->_name = $this->getName();
 133  
 134          // Only set the clientId if available.
 135          if (isset($config['clientId']))
 136          {
 137              $this->_clientId = $config['clientId'];
 138          }
 139  
 140          // Enable sessions by default.
 141          if (!isset($config['session']))
 142          {
 143              $config['session'] = true;
 144          }
 145  
 146          // Create the input object
 147          if (class_exists('JInput'))
 148          {
 149              $this->input = new JInput;
 150          }
 151  
 152          // Set the session default name.
 153          if (!isset($config['session_name']))
 154          {
 155              $config['session_name'] = $this->_name;
 156          }
 157  
 158          // Set the default configuration file.
 159          if (!isset($config['config_file']))
 160          {
 161              $config['config_file'] = 'configuration.php';
 162          }
 163  
 164          // Create the configuration object.
 165          if (file_exists(JPATH_CONFIGURATION . '/' . $config['config_file']))
 166          {
 167              $this->_createConfiguration(JPATH_CONFIGURATION . '/' . $config['config_file']);
 168          }
 169  
 170          // Create the session if a session name is passed.
 171          if ($config['session'] !== false)
 172          {
 173              $this->_createSession(self::getHash($config['session_name']));
 174          }
 175  
 176          $this->set('requestTime', gmdate('Y-m-d H:i'));
 177  
 178          // Used by task system to ensure that the system doesn't go over time.
 179          $this->set('startTime', JProfiler::getmicrotime());
 180      }
 181  
 182      /**
 183       * Returns the global JApplication object, only creating it if it
 184       * doesn't already exist.
 185       *
 186       * @param   mixed   $client  A client identifier or name.
 187       * @param   array   $config  An optional associative array of configuration settings.
 188       * @param   string  $prefix  A prefix for class names
 189       *
 190       * @return  JApplication A JApplication object.
 191       *
 192       * @since   11.1
 193       */
 194  	public static function getInstance($client, $config = array(), $prefix = 'J')
 195      {
 196          if (empty(self::$instances[$client]))
 197          {
 198              // Load the router object.
 199              $info = JApplicationHelper::getClientInfo($client, true);
 200  
 201              $path = $info->path . '/includes/application.php';
 202              if (file_exists($path))
 203              {
 204                  include_once $path;
 205  
 206                  // Create a JRouter object.
 207                  $classname = $prefix . ucfirst($client);
 208                  $instance = new $classname($config);
 209              }
 210              else
 211              {
 212                  $error = JError::raiseError(500, JText::sprintf('JLIB_APPLICATION_ERROR_APPLICATION_LOAD', $client));
 213                  return $error;
 214              }
 215  
 216              self::$instances[$client] = &$instance;
 217          }
 218  
 219          return self::$instances[$client];
 220      }
 221  
 222      /**
 223       * Initialise the application.
 224       *
 225       * @param   array  $options  An optional associative array of configuration settings.
 226       *
 227       * @return  void
 228       *
 229       * @since   11.1
 230       */
 231  	public function initialise($options = array())
 232      {
 233          // Set the language in the class.
 234          $config = JFactory::getConfig();
 235  
 236          // Check that we were given a language in the array (since by default may be blank).
 237          if (isset($options['language']))
 238          {
 239              $config->set('language', $options['language']);
 240          }
 241  
 242          // Set user specific editor.
 243          $user = JFactory::getUser();
 244          $editor = $user->getParam('editor', $this->getCfg('editor'));
 245          if (!JPluginHelper::isEnabled('editors', $editor))
 246          {
 247              $editor = $this->getCfg('editor');
 248              if (!JPluginHelper::isEnabled('editors', $editor))
 249              {
 250                  $editor = 'none';
 251              }
 252          }
 253  
 254          $config->set('editor', $editor);
 255  
 256          // Trigger the onAfterInitialise event.
 257          JPluginHelper::importPlugin('system');
 258          $this->triggerEvent('onAfterInitialise');
 259      }
 260  
 261      /**
 262       * Route the application.
 263       *
 264       * Routing is the process of examining the request environment to determine which
 265       * component should receive the request. The component optional parameters
 266       * are then set in the request object to be processed when the application is being
 267       * dispatched.
 268       *
 269       * @return  void
 270       *
 271       * @since   11.1
 272       */
 273  	public function route()
 274      {
 275          // Get the full request URI.
 276          $uri = clone JURI::getInstance();
 277  
 278          $router = $this->getRouter();
 279          $result = $router->parse($uri);
 280  
 281          JRequest::set($result, 'get', false);
 282  
 283          // Trigger the onAfterRoute event.
 284          JPluginHelper::importPlugin('system');
 285          $this->triggerEvent('onAfterRoute');
 286      }
 287  
 288      /**
 289       * Dispatch the application.
 290       *
 291       * Dispatching is the process of pulling the option from the request object and
 292       * mapping them to a component. If the component does not exist, it handles
 293       * determining a default component to dispatch.
 294       *
 295       * @param   string  $component  The component to dispatch.
 296       *
 297       * @return  void
 298       *
 299       * @since   11.1
 300       */
 301  	public function dispatch($component = null)
 302      {
 303          $document = JFactory::getDocument();
 304  
 305          $document->setTitle($this->getCfg('sitename') . ' - ' . JText::_('JADMINISTRATION'));
 306          $document->setDescription($this->getCfg('MetaDesc'));
 307  
 308          $contents = JComponentHelper::renderComponent($component);
 309          $document->setBuffer($contents, 'component');
 310  
 311          // Trigger the onAfterDispatch event.
 312          JPluginHelper::importPlugin('system');
 313          $this->triggerEvent('onAfterDispatch');
 314      }
 315  
 316      /**
 317       * Render the application.
 318       *
 319       * Rendering is the process of pushing the document buffers into the template
 320       * placeholders, retrieving data from the document and pushing it into
 321       * the JResponse buffer.
 322       *
 323       * @return  void
 324       *
 325       * @since   11.1
 326       */
 327  	public function render()
 328      {
 329          $params = array('template' => $this->getTemplate(), 'file' => 'index.php', 'directory' => JPATH_THEMES, 'params' => $template->params);
 330  
 331          // Parse the document.
 332          $document = JFactory::getDocument();
 333          $document->parse($params);
 334  
 335          // Trigger the onBeforeRender event.
 336          JPluginHelper::importPlugin('system');
 337          $this->triggerEvent('onBeforeRender');
 338  
 339          // Render the document.
 340          $caching = ($this->getCfg('caching') >= 2) ? true : false;
 341          JResponse::setBody($document->render($caching, $params));
 342  
 343          // Trigger the onAfterRender event.
 344          $this->triggerEvent('onAfterRender');
 345      }
 346  
 347      /**
 348       * Exit the application.
 349       *
 350       * @param   integer  $code  Exit code
 351       *
 352       * @return  void     Exits the application.
 353       *
 354       * @since    11.1
 355       */
 356  	public function close($code = 0)
 357      {
 358          exit($code);
 359      }
 360  
 361      /**
 362       * Redirect to another URL.
 363       *
 364       * Optionally enqueues a message in the system message queue (which will be displayed
 365       * the next time a page is loaded) using the enqueueMessage method. If the headers have
 366       * not been sent the redirect will be accomplished using a "301 Moved Permanently"
 367       * code in the header pointing to the new location. If the headers have already been
 368       * sent this will be accomplished using a JavaScript statement.
 369       *
 370       * @param   string   $url      The URL to redirect to. Can only be http/https URL
 371       * @param   string   $msg      An optional message to display on redirect.
 372       * @param   string   $msgType  An optional message type. Defaults to message.
 373       * @param   boolean  $moved    True if the page is 301 Permanently Moved, otherwise 303 See Other is assumed.
 374       *
 375       * @return  void  Calls exit().
 376       *
 377       * @since   11.1
 378       *
 379       * @see     JApplication::enqueueMessage()
 380       */
 381  	public function redirect($url, $msg = '', $msgType = 'message', $moved = false)
 382      {
 383          // Check for relative internal links.
 384          if (preg_match('#^index2?\.php#', $url))
 385          {
 386              $url = JURI::base() . $url;
 387          }
 388  
 389          // Strip out any line breaks.
 390          $url = preg_split("/[\r\n]/", $url);
 391          $url = $url[0];
 392  
 393          // If we don't start with a http we need to fix this before we proceed.
 394          // We could validly start with something else (e.g. ftp), though this would
 395          // be unlikely and isn't supported by this API.
 396          if (!preg_match('#^http#i', $url))
 397          {
 398              $uri = JURI::getInstance();
 399              $prefix = $uri->toString(array('scheme', 'user', 'pass', 'host', 'port'));
 400  
 401              if ($url[0] == '/')
 402              {
 403                  // We just need the prefix since we have a path relative to the root.
 404                  $url = $prefix . $url;
 405              }
 406              else
 407              {
 408                  // It's relative to where we are now, so lets add that.
 409                  $parts = explode('/', $uri->toString(array('path')));
 410                  array_pop($parts);
 411                  $path = implode('/', $parts) . '/';
 412                  $url = $prefix . $path . $url;
 413              }
 414          }
 415  
 416          // If the message exists, enqueue it.
 417          if (trim($msg))
 418          {
 419              $this->enqueueMessage($msg, $msgType);
 420          }
 421  
 422          // Persist messages if they exist.
 423          if (count($this->_messageQueue))
 424          {
 425              $session = JFactory::getSession();
 426              $session->set('application.queue', $this->_messageQueue);
 427          }
 428  
 429          // If the headers have been sent, then we cannot send an additional location header
 430          // so we will output a javascript redirect statement.
 431          if (headers_sent())
 432          {
 433              echo "<script>document.location.href='" . htmlspecialchars($url) . "';</script>\n";
 434          }
 435          else
 436          {
 437              $document = JFactory::getDocument();
 438              jimport('joomla.environment.browser');
 439              $navigator = JBrowser::getInstance();
 440              jimport('phputf8.utils.ascii');
 441              if ($navigator->isBrowser('msie') && !utf8_is_ascii($url))
 442              {
 443                  // MSIE type browser and/or server cause issues when url contains utf8 character,so use a javascript redirect method
 444                  echo '<html><head><meta http-equiv="content-type" content="text/html; charset=' . $document->getCharset() . '" />'
 445                      . '<script>document.location.href=\'' . htmlspecialchars($url) . '\';</script></head></html>';
 446              }
 447              elseif (!$moved and $navigator->isBrowser('konqueror'))
 448              {
 449                  // WebKit browser (identified as konqueror by Joomla!) - Do not use 303, as it causes subresources
 450                  // reload (https://bugs.webkit.org/show_bug.cgi?id=38690)
 451                  echo '<html><head><meta http-equiv="content-type" content="text/html; charset=' . $document->getCharset() . '" />'
 452                      . '<meta http-equiv="refresh" content="0; url=' . htmlspecialchars($url) . '" /></head></html>';
 453              }
 454              else
 455              {
 456                  // All other browsers, use the more efficient HTTP header method
 457                  header($moved ? 'HTTP/1.1 301 Moved Permanently' : 'HTTP/1.1 303 See other');
 458                  header('Location: ' . $url);
 459                  header('Content-Type: text/html; charset=' . $document->getCharset());
 460              }
 461          }
 462          $this->close();
 463      }
 464  
 465      /**
 466       * Enqueue a system message.
 467       *
 468       * @param   string  $msg   The message to enqueue.
 469       * @param   string  $type  The message type. Default is message.
 470       *
 471       * @return  void
 472       *
 473       * @since   11.1
 474       */
 475  	public function enqueueMessage($msg, $type = 'message')
 476      {
 477          // For empty queue, if messages exists in the session, enqueue them first.
 478          if (!count($this->_messageQueue))
 479          {
 480              $session = JFactory::getSession();
 481              $sessionQueue = $session->get('application.queue');
 482  
 483              if (count($sessionQueue))
 484              {
 485                  $this->_messageQueue = $sessionQueue;
 486                  $session->set('application.queue', null);
 487              }
 488          }
 489  
 490          // Enqueue the message.
 491          $this->_messageQueue[] = array('message' => $msg, 'type' => strtolower($type));
 492      }
 493  
 494      /**
 495       * Get the system message queue.
 496       *
 497       * @return  array  The system message queue.
 498       *
 499       * @since   11.1
 500       */
 501  	public function getMessageQueue()
 502      {
 503          // For empty queue, if messages exists in the session, enqueue them.
 504          if (!count($this->_messageQueue))
 505          {
 506              $session = JFactory::getSession();
 507              $sessionQueue = $session->get('application.queue');
 508  
 509              if (count($sessionQueue))
 510              {
 511                  $this->_messageQueue = $sessionQueue;
 512                  $session->set('application.queue', null);
 513              }
 514          }
 515  
 516          return $this->_messageQueue;
 517      }
 518  
 519      /**
 520       * Gets a configuration value.
 521       *
 522       * An example is in application/japplication-getcfg.php Getting a configuration
 523       *
 524       * @param   string  $varname  The name of the value to get.
 525       * @param   string  $default  Default value to return
 526       *
 527       * @return  mixed  The user state.
 528       *
 529       * @since   11.1
 530       */
 531  	public function getCfg($varname, $default = null)
 532      {
 533          $config = JFactory::getConfig();
 534          return $config->get('' . $varname, $default);
 535      }
 536  
 537      /**
 538       * Method to get the application name.
 539       *
 540       * The dispatcher name is by default parsed using the classname, or it can be set
 541       * by passing a $config['name'] in the class constructor.
 542       *
 543       * @return  string  The name of the dispatcher.
 544       *
 545       * @since   11.1
 546       */
 547  	public function getName()
 548      {
 549          $name = $this->_name;
 550  
 551          if (empty($name))
 552          {
 553              $r = null;
 554              if (!preg_match('/J(.*)/i', get_class($this), $r))
 555              {
 556                  JError::raiseError(500, JText::_('JLIB_APPLICATION_ERROR_APPLICATION_GET_NAME'));
 557              }
 558              $name = strtolower($r[1]);
 559          }
 560  
 561          return $name;
 562      }
 563  
 564      /**
 565       * Gets a user state.
 566       *
 567       * @param   string  $key      The path of the state.
 568       * @param   mixed   $default  Optional default value, returned if the internal value is null.
 569       *
 570       * @return  mixed  The user state or null.
 571       *
 572       * @since   11.1
 573       */
 574  	public function getUserState($key, $default = null)
 575      {
 576          $session = JFactory::getSession();
 577          $registry = $session->get('registry');
 578  
 579          if (!is_null($registry))
 580          {
 581              return $registry->get($key, $default);
 582          }
 583  
 584          return $default;
 585      }
 586  
 587      /**
 588       * Sets the value of a user state variable.
 589       *
 590       * @param   string  $key    The path of the state.
 591       * @param   string  $value  The value of the variable.
 592       *
 593       * @return  mixed  The previous state, if one existed.
 594       *
 595       * @since   11.1
 596       */
 597  	public function setUserState($key, $value)
 598      {
 599          $session = JFactory::getSession();
 600          $registry = $session->get('registry');
 601  
 602          if (!is_null($registry))
 603          {
 604              return $registry->set($key, $value);
 605          }
 606  
 607          return null;
 608      }
 609  
 610      /**
 611       * Gets the value of a user state variable.
 612       *
 613       * @param   string  $key      The key of the user state variable.
 614       * @param   string  $request  The name of the variable passed in a request.
 615       * @param   string  $default  The default value for the variable if not found. Optional.
 616       * @param   string  $type     Filter for the variable, for valid values see {@link JFilterInput::clean()}. Optional.
 617       *
 618       * @return  The request user state.
 619       *
 620       * @since   11.1
 621       */
 622  	public function getUserStateFromRequest($key, $request, $default = null, $type = 'none')
 623      {
 624          $cur_state = $this->getUserState($key, $default);
 625          $new_state = JRequest::getVar($request, null, 'default', $type);
 626  
 627          // Save the new value only if it was set in this request.
 628          if ($new_state !== null)
 629          {
 630              $this->setUserState($key, $new_state);
 631          }
 632          else
 633          {
 634              $new_state = $cur_state;
 635          }
 636  
 637          return $new_state;
 638      }
 639  
 640      /**
 641       * Registers a handler to a particular event group.
 642       *
 643       * @param   string  $event    The event name.
 644       * @param   mixed   $handler  The handler, a function or an instance of a event object.
 645       *
 646       * @return  void
 647       *
 648       * @since   11.1
 649       */
 650  	public static function registerEvent($event, $handler)
 651      {
 652          $dispatcher = JDispatcher::getInstance();
 653          $dispatcher->register($event, $handler);
 654      }
 655  
 656      /**
 657       * Calls all handlers associated with an event group.
 658       *
 659       * @param   string  $event  The event name.
 660       * @param   array   $args   An array of arguments.
 661       *
 662       * @return  array  An array of results from each function call.
 663       *
 664       * @since   11.1
 665       */
 666  	public function triggerEvent($event, $args = null)
 667      {
 668          $dispatcher = JDispatcher::getInstance();
 669  
 670          return $dispatcher->trigger($event, $args);
 671      }
 672  
 673      /**
 674       * Login authentication function.
 675       *
 676       * Username and encoded password are passed the onUserLogin event which
 677       * is responsible for the user validation. A successful validation updates
 678       * the current session record with the user's details.
 679       *
 680       * Username and encoded password are sent as credentials (along with other
 681       * possibilities) to each observer (authentication plugin) for user
 682       * validation.  Successful validation will update the current session with
 683       * the user details.
 684       *
 685       * @param   array  $credentials  Array('username' => string, 'password' => string)
 686       * @param   array  $options      Array('remember' => boolean)
 687       *
 688       * @return  boolean  True on success.
 689       *
 690       * @since   11.1
 691       */
 692  	public function login($credentials, $options = array())
 693      {
 694          // Get the global JAuthentication object.
 695          jimport('joomla.user.authentication');
 696  
 697          $authenticate = JAuthentication::getInstance();
 698          $response = $authenticate->authenticate($credentials, $options);
 699  
 700          if ($response->status === JAuthentication::STATUS_SUCCESS)
 701          {
 702              // validate that the user should be able to login (different to being authenticated)
 703              // this permits authentication plugins blocking the user
 704              $authorisations = $authenticate->authorise($response, $options);
 705              foreach ($authorisations as $authorisation)
 706              {
 707                  $denied_states = array(JAuthentication::STATUS_EXPIRED, JAuthentication::STATUS_DENIED);
 708                  if (in_array($authorisation->status, $denied_states))
 709                  {
 710                      // Trigger onUserAuthorisationFailure Event.
 711                      $this->triggerEvent('onUserAuthorisationFailure', array((array) $authorisation));
 712  
 713                      // If silent is set, just return false.
 714                      if (isset($options['silent']) && $options['silent'])
 715                      {
 716                          return false;
 717                      }
 718  
 719                      // Return the error.
 720                      switch ($authorisation->status)
 721                      {
 722                          case JAuthentication::STATUS_EXPIRED:
 723                              return JError::raiseWarning('102002', JText::_('JLIB_LOGIN_EXPIRED'));
 724                              break;
 725                          case JAuthentication::STATUS_DENIED:
 726                              return JError::raiseWarning('102003', JText::_('JLIB_LOGIN_DENIED'));
 727                              break;
 728                          default:
 729                              return JError::raiseWarning('102004', JText::_('JLIB_LOGIN_AUTHORISATION'));
 730                              break;
 731                      }
 732                  }
 733              }
 734  
 735              // Import the user plugin group.
 736              JPluginHelper::importPlugin('user');
 737  
 738              // OK, the credentials are authenticated and user is authorised.  Lets fire the onLogin event.
 739              $results = $this->triggerEvent('onUserLogin', array((array) $response, $options));
 740  
 741              /*
 742               * If any of the user plugins did not successfully complete the login routine
 743               * then the whole method fails.
 744               *
 745               * Any errors raised should be done in the plugin as this provides the ability
 746               * to provide much more information about why the routine may have failed.
 747               */
 748  
 749              if (!in_array(false, $results, true))
 750              {
 751                  // Set the remember me cookie if enabled.
 752                  if (isset($options['remember']) && $options['remember'])
 753                  {
 754                      jimport('joomla.utilities.simplecrypt');
 755  
 756                      // Create the encryption key, apply extra hardening using the user agent string.
 757                      $key = self::getHash(@$_SERVER['HTTP_USER_AGENT']);
 758  
 759                      $crypt = new JSimpleCrypt($key);
 760                      $rcookie = $crypt->encrypt(serialize($credentials));
 761                      $lifetime = time() + 365 * 24 * 60 * 60;
 762  
 763                      // Use domain and path set in config for cookie if it exists.
 764                      $cookie_domain = $this->getCfg('cookie_domain', '');
 765                      $cookie_path = $this->getCfg('cookie_path', '/');
 766                      setcookie(self::getHash('JLOGIN_REMEMBER'), $rcookie, $lifetime, $cookie_path, $cookie_domain);
 767                  }
 768  
 769                  return true;
 770              }
 771          }
 772  
 773          // Trigger onUserLoginFailure Event.
 774          $this->triggerEvent('onUserLoginFailure', array((array) $response));
 775  
 776          // If silent is set, just return false.
 777          if (isset($options['silent']) && $options['silent'])
 778          {
 779              return false;
 780          }
 781  
 782          // If status is success, any error will have been raised by the user plugin
 783          if ($response->status !== JAuthentication::STATUS_SUCCESS)
 784          {
 785              JError::raiseWarning('102001', $response->error_message);
 786          }
 787  
 788          return false;
 789      }
 790  
 791      /**
 792       * Logout authentication function.
 793       *
 794       * Passed the current user information to the onUserLogout event and reverts the current
 795       * session record back to 'anonymous' parameters.
 796       * If any of the authentication plugins did not successfully complete
 797       * the logout routine then the whole method fails. Any errors raised
 798       * should be done in the plugin as this provides the ability to give
 799       * much more information about why the routine may have failed.
 800       *
 801       * @param   integer  $userid   The user to load - Can be an integer or string - If string, it is converted to ID automatically
 802       * @param   array    $options  Array('clientid' => array of client id's)
 803       *
 804       * @return  boolean  True on success
 805       *
 806       * @since   11.1
 807       */
 808  	public function logout($userid = null, $options = array())
 809      {
 810          // Get a user object from the JApplication.
 811          $user = JFactory::getUser($userid);
 812  
 813          // Build the credentials array.
 814          $parameters['username'] = $user->get('username');
 815          $parameters['id'] = $user->get('id');
 816  
 817          // Set clientid in the options array if it hasn't been set already.
 818          if (!isset($options['clientid']))
 819          {
 820              $options['clientid'] = $this->getClientId();
 821          }
 822  
 823          // Import the user plugin group.
 824          JPluginHelper::importPlugin('user');
 825  
 826          // OK, the credentials are built. Lets fire the onLogout event.
 827          $results = $this->triggerEvent('onUserLogout', array($parameters, $options));
 828  
 829          // Check if any of the plugins failed. If none did, success.
 830  
 831          if (!in_array(false, $results, true))
 832          {
 833              // Use domain and path set in config for cookie if it exists.
 834              $cookie_domain = $this->getCfg('cookie_domain', '');
 835              $cookie_path = $this->getCfg('cookie_path', '/');
 836              setcookie(self::getHash('JLOGIN_REMEMBER'), false, time() - 86400, $cookie_path, $cookie_domain);
 837  
 838              return true;
 839          }
 840  
 841          // Trigger onUserLoginFailure Event.
 842          $this->triggerEvent('onUserLogoutFailure', array($parameters));
 843  
 844          return false;
 845      }
 846  
 847      /**
 848       * Gets the name of the current template.
 849       *
 850       * @param   array  $params  An optional associative array of configuration settings
 851       *
 852       * @return  string  System is the fallback.
 853       *
 854       * @since   11.1
 855       */
 856  	public function getTemplate($params = false)
 857      {
 858          return 'system';
 859      }
 860  
 861      /**
 862       * Returns the application JRouter object.
 863       *
 864       * @param   string  $name     The name of the application.
 865       * @param   array   $options  An optional associative array of configuration settings.
 866       *
 867       * @return  JRouter  A JRouter object
 868       *
 869       * @since   11.1
 870       */
 871  	static public function getRouter($name = null, array $options = array())
 872      {
 873          if (!isset($name))
 874          {
 875              $app = JFactory::getApplication();
 876              $name = $app->getName();
 877          }
 878  
 879          jimport('joomla.application.router');
 880          $router = JRouter::getInstance($name, $options);
 881  
 882          if ($router instanceof Exception)
 883          {
 884              return null;
 885          }
 886  
 887          return $router;
 888      }
 889  
 890      /**
 891       * This method transliterates a string into an URL
 892       * safe string or returns a URL safe UTF-8 string
 893       * based on the global configuration
 894       *
 895       * @param   string  $string  String to process
 896       *
 897       * @return  string  Processed string
 898       *
 899       * @since   11.1
 900       */
 901  	static public function stringURLSafe($string)
 902      {
 903          if (JFactory::getConfig()->get('unicodeslugs') == 1)
 904          {
 905              $output = JFilterOutput::stringURLUnicodeSlug($string);
 906          }
 907          else
 908          {
 909              $output = JFilterOutput::stringURLSafe($string);
 910          }
 911  
 912          return $output;
 913      }
 914  
 915      /**
 916       * Returns the application JPathway object.
 917       *
 918       * @param   string  $name     The name of the application.
 919       * @param   array   $options  An optional associative array of configuration settings.
 920       *
 921       * @return  JPathway  A JPathway object
 922       *
 923       * @since   11.1
 924       */
 925  	public function getPathway($name = null, $options = array())
 926      {
 927          if (!isset($name))
 928          {
 929              $name = $this->_name;
 930          }
 931  
 932          jimport('joomla.application.pathway');
 933          $pathway = JPathway::getInstance($name, $options);
 934  
 935          if ($pathway instanceof Exception)
 936          {
 937              return null;
 938          }
 939  
 940          return $pathway;
 941      }
 942  
 943      /**
 944       * Returns the application JPathway object.
 945       *
 946       * @param   string  $name     The name of the application/client.
 947       * @param   array   $options  An optional associative array of configuration settings.
 948       *
 949       * @return  JMenu  JMenu object.
 950       *
 951       * @since   11.1
 952       */
 953  	public function getMenu($name = null, $options = array())
 954      {
 955          if (!isset($name))
 956          {
 957              $name = $this->_name;
 958          }
 959  
 960          jimport('joomla.application.menu');
 961          $menu = JMenu::getInstance($name, $options);
 962  
 963          if ($menu instanceof Exception)
 964          {
 965              return null;
 966          }
 967  
 968          return $menu;
 969      }
 970  
 971      /**
 972       * Provides a secure hash based on a seed
 973       *
 974       * @param   string  $seed  Seed string.
 975       *
 976       * @return  string  A secure hash
 977       *
 978       * @since   11.1
 979       */
 980  	public static function getHash($seed)
 981      {
 982          return md5(JFactory::getConfig()->get('secret') . $seed);
 983      }
 984  
 985      /**
 986       * Create the configuration registry.
 987       *
 988       * @param   string  $file  The path to the configuration file
 989       *
 990       * @return   object  A JConfig object
 991       *
 992       * @since   11.1
 993       */
 994  	protected function _createConfiguration($file)
 995      {
 996          JLoader::register('JConfig', $file);
 997  
 998          // Create the JConfig object.
 999          $config = new JConfig;
1000  
1001          // Get the global configuration object.
1002          $registry = JFactory::getConfig();
1003  
1004          // Load the configuration values into the registry.
1005          $registry->loadObject($config);
1006  
1007          return $config;
1008      }
1009  
1010      /**
1011       * Create the user session.
1012       *
1013       * Old sessions are flushed based on the configuration value for the cookie
1014       * lifetime. If an existing session, then the last access time is updated.
1015       * If a new session, a session id is generated and a record is created in
1016       * the #__sessions table.
1017       *
1018       * @param   string  $name  The sessions name.
1019       *
1020       * @return  JSession  JSession on success. May call exit() on database error.
1021       *
1022       * @since   11.1
1023       */
1024  	protected function _createSession($name)
1025      {
1026          $options = array();
1027          $options['name'] = $name;
1028  
1029          switch ($this->_clientId)
1030          {
1031              case 0:
1032                  if ($this->getCfg('force_ssl') == 2)
1033                  {
1034                      $options['force_ssl'] = true;
1035                  }
1036                  break;
1037  
1038              case 1:
1039                  if ($this->getCfg('force_ssl') >= 1)
1040                  {
1041                      $options['force_ssl'] = true;
1042                  }
1043                  break;
1044          }
1045  
1046          $session = JFactory::getSession($options);
1047  
1048          //TODO: At some point we need to get away from having session data always in the db.
1049  
1050          $db = JFactory::getDBO();
1051  
1052          // Remove expired sessions from the database.
1053          $time = time();
1054          if ($time % 2)
1055          {
1056              // The modulus introduces a little entropy, making the flushing less accurate
1057              // but fires the query less than half the time.
1058              $query = $db->getQuery(true);
1059              $query->delete($query->qn('#__session'))
1060                  ->where($query->qn('time') . ' < ' . $query->q((int) ($time - $session->getExpire())));
1061  
1062              $db->setQuery($query);
1063              $db->query();
1064          }
1065  
1066          // Check to see the the session already exists.
1067          if (($this->getCfg('session_handler') != 'database' && ($time % 2 || $session->isNew()))
1068              || ($this->getCfg('session_handler') == 'database' && $session->isNew()))
1069          {
1070              $this->checkSession();
1071          }
1072  
1073          return $session;
1074      }
1075  
1076      /**
1077       * Checks the user session.
1078       *
1079       * If the session record doesn't exist, initialise it.
1080       * If session is new, create session variables
1081       *
1082       * @return  void
1083       *
1084       * @since   11.1
1085       */
1086  	public function checkSession()
1087      {
1088          $db = JFactory::getDBO();
1089          $session = JFactory::getSession();
1090          $user = JFactory::getUser();
1091  
1092          $query = $db->getQuery(true);
1093          $query->select($query->qn('session_id'))
1094              ->from($query->qn('#__session'))
1095              ->where($query->qn('session_id') . ' = ' . $query->q($session->getId()));
1096  
1097          $db->setQuery($query, 0, 1);
1098          $exists = $db->loadResult();
1099  
1100          // If the session record doesn't exist initialise it.
1101          if (!$exists)
1102          {
1103              $query->clear();
1104              if ($session->isNew())
1105              {
1106                  $query->insert($query->qn('#__session'))
1107                      ->columns($query->qn('session_id') . ', ' . $query->qn('client_id') . ', ' . $query->qn('time'))
1108                      ->values($query->q($session->getId()) . ', ' . (int) $this->getClientId() . ', ' . $query->q((int) time()));
1109                  $db->setQuery($query);
1110              }
1111              else
1112              {
1113                  $query->insert($query->qn('#__session'))
1114                      ->columns(
1115                          $query->qn('session_id') . ', ' . $query->qn('client_id') . ', ' . $query->qn('guest') . ', ' .
1116                          $query->qn('time') . ', ' . $query->qn('userid') . ', ' . $query->qn('username')
1117                      )
1118                      ->values(
1119                          $query->q($session->getId()) . ', ' . (int) $this->getClientId() . ', ' . (int) $user->get('guest') . ', ' .
1120                          $query->q((int) $session->get('session.timer.start')) . ', ' . (int) $user->get('id') . ', ' . $query->q($user->get('username'))
1121                      );
1122  
1123                  $db->setQuery($query);
1124              }
1125  
1126              // If the insert failed, exit the application.
1127              if (!$db->query())
1128              {
1129                  jexit($db->getErrorMSG());
1130              }
1131  
1132              // Session doesn't exist yet, so create session variables
1133              if ($session->isNew())
1134              {
1135                  $session->set('registry', new JRegistry('session'));
1136                  $session->set('user', new JUser);
1137              }
1138          }
1139      }
1140  
1141      /**
1142       * Gets the client id of the current running application.
1143       *
1144       * @return  integer  A client identifier.
1145       *
1146       * @since   11.1
1147       */
1148  	public function getClientId()
1149      {
1150          return $this->_clientId;
1151      }
1152  
1153      /**
1154       * Is admin interface?
1155       *
1156       * @return  boolean  True if this application is administrator.
1157       *
1158       * @since   11.1
1159       */
1160  	public function isAdmin()
1161      {
1162          return ($this->_clientId == 1);
1163      }
1164  
1165      /**
1166       * Is site interface?
1167       *
1168       * @return  boolean  True if this application is site.
1169       *
1170       * @since   11.1
1171       */
1172  	public function isSite()
1173      {
1174          return ($this->_clientId == 0);
1175      }
1176  
1177      /**
1178       * Method to determine if the host OS is  Windows
1179       *
1180       * @return  boolean  True if Windows OS
1181       *
1182       * @since   11.1
1183       */
1184  	public static function isWinOS()
1185      {
1186          return strtoupper(substr(PHP_OS, 0, 3)) === 'WIN';
1187      }
1188  
1189      /**
1190       * Returns the response as a string.
1191       *
1192       * @return  string  The response
1193       *
1194       * @since   11.1
1195       */
1196  	public function __toString()
1197      {
1198          $compress = $this->getCfg('gzip', false);
1199  
1200          return JResponse::toString($compress);
1201      }
1202  }


Generated: Tue Apr 3 11:40:28 2012 Cross-referenced by PHPXref 0.7.1