PageRenderTime 63ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

/libraries/joomla/application/application.php

https://github.com/joebushi/joomla
PHP | 909 lines | 413 code | 114 blank | 382 comment | 52 complexity | 7509506eb85950cf9c81e238559ecae0 MD5 | raw file
Possible License(s): LGPL-2.1, Apache-2.0
  1. <?php
  2. /**
  3. * @version $Id$
  4. * @package Joomla.Framework
  5. * @subpackage Application
  6. * @copyright Copyright (C) 2005 - 2010 Open Source Matters, Inc. All rights reserved.
  7. * @license GNU General Public License version 2 or later; see LICENSE.txt
  8. */
  9. // No direct access.
  10. defined('JPATH_BASE') or die;
  11. /**
  12. * Base class for a Joomla! application.
  13. *
  14. * Acts as a Factory class for application specific objects and provides many
  15. * supporting API functions. Derived clases should supply the route(), dispatch()
  16. * and render() functions.
  17. *
  18. * @abstract
  19. * @package Joomla.Framework
  20. * @subpackage Application
  21. * @since 1.5
  22. */
  23. class JApplication extends JObject
  24. {
  25. /**
  26. * The client identifier.
  27. *
  28. * @var integer
  29. * @since 1.5
  30. */
  31. protected $_clientId = null;
  32. /**
  33. * The application message queue.
  34. *
  35. * @var array
  36. */
  37. protected $_messageQueue = array();
  38. /**
  39. * The name of the application.
  40. *
  41. * @var array
  42. */
  43. protected $_name = null;
  44. /**
  45. * The scope of the application.
  46. *
  47. * @var string
  48. */
  49. public $scope = null;
  50. /**
  51. * The time the request was made.
  52. *
  53. * @var date
  54. */
  55. public $requestTime = null;
  56. /**
  57. * The time the request was made as Unix timestamp.
  58. *
  59. * @var integer
  60. * @since 1.6
  61. */
  62. public $startTime = null;
  63. /**
  64. * Class constructor.
  65. *
  66. * @param integer A client identifier.
  67. */
  68. public function __construct($config = array())
  69. {
  70. jimport('joomla.utilities.utility');
  71. jimport('joomla.error.profiler');
  72. // Set the view name.
  73. $this->_name = $this->getName();
  74. $this->_clientId = $config['clientId'];
  75. // Enable sessions by default.
  76. if (!isset($config['session'])) {
  77. $config['session'] = true;
  78. }
  79. // Set the session default name.
  80. if (!isset($config['session_name'])) {
  81. $config['session_name'] = $this->_name;
  82. }
  83. // Set the default configuration file.
  84. if (!isset($config['config_file'])) {
  85. $config['config_file'] = 'configuration.php';
  86. }
  87. // Create the configuration object.
  88. $this->_createConfiguration(JPATH_CONFIGURATION.DS.$config['config_file']);
  89. // Create the session if a session name is passed.
  90. if ($config['session'] !== false) {
  91. $this->_createSession(JUtility::getHash($config['session_name']));
  92. }
  93. $this->set('requestTime', gmdate('Y-m-d H:i'));
  94. // Used by task system to ensure that the system doesn't go over time.
  95. $this->set('startTime', JProfiler::getmicrotime());
  96. }
  97. /**
  98. * Returns the global JApplication object, only creating it if it
  99. * doesn't already exist.
  100. *
  101. * @param mixed $id A client identifier or name.
  102. * @param array $config An optional associative array of configuration settings.
  103. * @return JApplication The appliction object.
  104. * @since 1.5
  105. */
  106. public static function getInstance($client, $config = array(), $prefix = 'J')
  107. {
  108. static $instances;
  109. if (!isset($instances)) {
  110. $instances = array();
  111. }
  112. if (empty($instances[$client]))
  113. {
  114. // Load the router object.
  115. jimport('joomla.application.helper');
  116. $info = &JApplicationHelper::getClientInfo($client, true);
  117. $path = $info->path.DS.'includes'.DS.'application.php';
  118. if (file_exists($path))
  119. {
  120. require_once $path;
  121. // Create a JRouter object.
  122. $classname = $prefix.ucfirst($client);
  123. $instance = new $classname($config);
  124. }
  125. else
  126. {
  127. $error = JError::raiseError(500, 'Unable to load application: '.$client);
  128. return $error;
  129. }
  130. $instances[$client] = &$instance;
  131. }
  132. return $instances[$client];
  133. }
  134. /**
  135. * Initialise the application.
  136. *
  137. * @param array An optional associative array of configuration settings.
  138. */
  139. public function initialise($options = array())
  140. {
  141. jimport('joomla.plugin.helper');
  142. // Set the language in the class.
  143. $config = &JFactory::getConfig();
  144. // Check that we were given a language in the array (since by default may be blank).
  145. if (isset($options['language'])) {
  146. $config->setValue('config.language', $options['language']);
  147. }
  148. // Set user specific editor.
  149. $user = &JFactory::getUser();
  150. $editor = $user->getParam('editor', $this->getCfg('editor'));
  151. $editor = JPluginHelper::isEnabled('editors', $editor) ? $editor : $this->getCfg('editor');
  152. $config->setValue('config.editor', $editor);
  153. // Trigger the onAfterInitialise event.
  154. JPluginHelper::importPlugin('system');
  155. $this->triggerEvent('onAfterInitialise');
  156. }
  157. /**
  158. * Route the application.
  159. *
  160. * Routing is the process of examining the request environment to determine which
  161. * component should receive the request. The component optional parameters
  162. * are then set in the request object to be processed when the application is being
  163. * dispatched.
  164. *
  165. * @abstract
  166. */
  167. public function route()
  168. {
  169. // Get the full request URI.
  170. $uri = clone JURI::getInstance();
  171. $router = &$this->getRouter();
  172. $result = $router->parse($uri);
  173. JRequest::set($result, 'get', false);
  174. // Trigger the onAfterRoute event.
  175. JPluginHelper::importPlugin('system');
  176. $this->triggerEvent('onAfterRoute');
  177. }
  178. /**
  179. * Dispatch the applicaiton.
  180. *
  181. * Dispatching is the process of pulling the option from the request object and
  182. * mapping them to a component. If the component does not exist, it handles
  183. * determining a default component to dispatch.
  184. *
  185. * @abstract
  186. */
  187. public function dispatch($component)
  188. {
  189. $document = &JFactory::getDocument();
  190. $document->setTitle($this->getCfg('sitename'). ' - ' .JText::_('Administration'));
  191. $document->setDescription($this->getCfg('MetaDesc'));
  192. $contents = JComponentHelper::renderComponent($component);
  193. $document->setBuffer($contents, 'component');
  194. // Trigger the onAfterDispatch event.
  195. JPluginHelper::importPlugin('system');
  196. $this->triggerEvent('onAfterDispatch');
  197. }
  198. /**
  199. * Render the application.
  200. *
  201. * Rendering is the process of pushing the document buffers into the template
  202. * placeholders, retrieving data from the document and pushing it into
  203. * the JResponse buffer.
  204. *
  205. * @abstract
  206. */
  207. public function render()
  208. {
  209. $params = array(
  210. 'template' => $this->getTemplate(),
  211. 'file' => 'index.php',
  212. 'directory' => JPATH_THEMES,
  213. 'params' => $template->params
  214. );
  215. // Parse the document.
  216. $document = &JFactory::getDocument();
  217. $document->parse($params);
  218. // Trigger the onBeforeRender event.
  219. JPluginHelper::importPlugin('system');
  220. $this->triggerEvent('onBeforeRender');
  221. // Render the document.
  222. JResponse::setBody($document->render($this->getCfg('caching'), $params));
  223. // Trigger the onAfterRender event.
  224. $this->triggerEvent('onAfterRender');
  225. }
  226. /**
  227. * Exit the application.
  228. *
  229. * @param int Exit code
  230. */
  231. public function close($code = 0) {
  232. exit($code);
  233. }
  234. /**
  235. * Redirect to another URL.
  236. *
  237. * Optionally enqueues a message in the system message queue (which will be displayed
  238. * the next time a page is loaded) using the enqueueMessage method. If the headers have
  239. * not been sent the redirect will be accomplished using a "301 Moved Permanently"
  240. * code in the header pointing to the new location. If the headers have already been
  241. * sent this will be accomplished using a JavaScript statement.
  242. *
  243. * @param string The URL to redirect to. Can only be http/https URL
  244. * @param string An optional message to display on redirect.
  245. * @param string An optional message type.
  246. * @param boolean True if the page is 301 Permanently Moved, otherwise 303 See Other is assumed.
  247. * @return none; calls exit().
  248. * @since 1.5
  249. * @see JApplication::enqueueMessage()
  250. */
  251. public function redirect($url, $msg='', $msgType='message', $moved = false)
  252. {
  253. // Check for relative internal links.
  254. if (preg_match('#^index[2]?.php#', $url)) {
  255. $url = JURI::base() . $url;
  256. }
  257. // Strip out any line breaks.
  258. $url = preg_split("/[\r\n]/", $url);
  259. $url = $url[0];
  260. // If we don't start with a http we need to fix this before we proceed.
  261. // We could validly start with something else (e.g. ftp), though this would
  262. // be unlikely and isn't supported by this API.
  263. if (!preg_match('#^http#i', $url)) {
  264. $uri = &JURI::getInstance();
  265. $prefix = $uri->toString(Array('scheme', 'user', 'pass', 'host', 'port'));
  266. if ($url[0] == '/') {
  267. // We just need the prefix since we have a path relative to the root.
  268. $url = $prefix . $url;
  269. } else {
  270. // It's relative to where we are now, so lets add that.
  271. $parts = explode('/', $uri->toString(Array('path')));
  272. array_pop($parts);
  273. $path = implode('/',$parts).'/';
  274. $url = $prefix . $path . $url;
  275. }
  276. }
  277. // If the message exists, enqueue it.
  278. if (trim($msg)) {
  279. $this->enqueueMessage($msg, $msgType);
  280. }
  281. // Persist messages if they exist.
  282. if (count($this->_messageQueue)) {
  283. $session = &JFactory::getSession();
  284. $session->set('application.queue', $this->_messageQueue);
  285. }
  286. // If the headers have been sent, then we cannot send an additional location header
  287. // so we will output a javascript redirect statement.
  288. if (headers_sent()) {
  289. echo "<script>document.location.href='$url';</script>\n";
  290. } else {
  291. header($moved ? 'HTTP/1.1 301 Moved Permanently' : 'HTTP/1.1 303 See other');
  292. header('Location: '.$url);
  293. }
  294. $this->close();
  295. }
  296. /**
  297. * Enqueue a system message.
  298. *
  299. * @param string $msg The message to enqueue.
  300. * @param string $type The message type.
  301. * @return void
  302. * @since 1.5
  303. */
  304. public function enqueueMessage($msg, $type = 'message')
  305. {
  306. // For empty queue, if messages exists in the session, enqueue them first.
  307. if (!count($this->_messageQueue))
  308. {
  309. $session = &JFactory::getSession();
  310. $sessionQueue = $session->get('application.queue');
  311. if (count($sessionQueue)) {
  312. $this->_messageQueue = $sessionQueue;
  313. $session->set('application.queue', null);
  314. }
  315. }
  316. // Enqueue the message.
  317. $this->_messageQueue[] = array('message' => $msg, 'type' => strtolower($type));
  318. }
  319. /**
  320. * Get the system message queue.
  321. *
  322. * @return The system message queue.
  323. * @since 1.5
  324. */
  325. public function getMessageQueue()
  326. {
  327. // For empty queue, if messages exists in the session, enqueue them.
  328. if (!count($this->_messageQueue))
  329. {
  330. $session = &JFactory::getSession();
  331. $sessionQueue = $session->get('application.queue');
  332. if (count($sessionQueue)) {
  333. $this->_messageQueue = $sessionQueue;
  334. $session->set('application.queue', null);
  335. }
  336. }
  337. return $this->_messageQueue;
  338. }
  339. /**
  340. * Gets a configuration value.
  341. *
  342. * @param string The name of the value to get.
  343. * @param string Default value to return
  344. * @return mixed The user state.
  345. * @example application/japplication-getcfg.php Getting a configuration value
  346. */
  347. public function getCfg($varname, $default=null)
  348. {
  349. $config = &JFactory::getConfig();
  350. return $config->getValue('config.' . $varname, $default);
  351. }
  352. /**
  353. * Method to get the application name.
  354. *
  355. * The dispatcher name by default parsed using the classname, or it can be set
  356. * by passing a $config['name'] in the class constructor.
  357. *
  358. * @return string The name of the dispatcher.
  359. * @since 1.5
  360. */
  361. public function getName()
  362. {
  363. $name = $this->_name;
  364. if (empty($name))
  365. {
  366. $r = null;
  367. if (!preg_match('/J(.*)/i', get_class($this), $r)) {
  368. JError::raiseError(500, "JApplication::getName() : Can\'t get or parse class name.");
  369. }
  370. $name = strtolower($r[1]);
  371. }
  372. return $name;
  373. }
  374. /**
  375. * Gets a user state.
  376. *
  377. * @param string The path of the state.
  378. * @return mixed The user state.
  379. */
  380. public function getUserState($key)
  381. {
  382. $session = &JFactory::getSession();
  383. $registry = $session->get('registry');
  384. if (!is_null($registry)) {
  385. return $registry->getValue($key);
  386. }
  387. return null;
  388. }
  389. /**
  390. * Sets the value of a user state variable.
  391. *
  392. * @param string The path of the state.
  393. * @param string The value of the variable.
  394. * @return mixed The previous state, if one existed.
  395. */
  396. public function setUserState($key, $value)
  397. {
  398. $session = &JFactory::getSession();
  399. $registry = &$session->get('registry');
  400. if (!is_null($registry)) {
  401. return $registry->setValue($key, $value);
  402. }
  403. return null;
  404. }
  405. /**
  406. * Gets the value of a user state variable.
  407. *
  408. * @param string The key of the user state variable.
  409. * @param string The name of the variable passed in a request.
  410. * @param string The default value for the variable if not found. Optional.
  411. * @param string Filter for the variable, for valid values see {@link JFilterInput::clean()}. Optional.
  412. * @return The request user state.
  413. */
  414. public function getUserStateFromRequest($key, $request, $default = null, $type = 'none')
  415. {
  416. $old_state = $this->getUserState($key);
  417. $cur_state = (!is_null($old_state)) ? $old_state : $default;
  418. $new_state = JRequest::getVar($request, null, 'default', $type);
  419. // Save the new value only if it was set in this request.
  420. if ($new_state !== null) {
  421. $this->setUserState($key, $new_state);
  422. } else {
  423. $new_state = $cur_state;
  424. }
  425. return $new_state;
  426. }
  427. /**
  428. * Registers a handler to a particular event group.
  429. *
  430. * @static
  431. * @param string The event name.
  432. * @param mixed The handler, a function or an instance of a event object.
  433. * @return void
  434. * @since 1.5
  435. */
  436. public static function registerEvent($event, $handler)
  437. {
  438. $dispatcher = &JDispatcher::getInstance();
  439. $dispatcher->register($event, $handler);
  440. }
  441. /**
  442. * Calls all handlers associated with an event group.
  443. *
  444. * @static
  445. * @param string The event name.
  446. * @param array An array of arguments.
  447. * @return array An array of results from each function call.
  448. * @since 1.5
  449. */
  450. function triggerEvent($event, $args=null)
  451. {
  452. $dispatcher = &JDispatcher::getInstance();
  453. return $dispatcher->trigger($event, $args);
  454. }
  455. /**
  456. * Login authentication function.
  457. *
  458. * Username and encoded password are passed the the onLoginUser event which
  459. * is responsible for the user validation. A successful validation updates
  460. * the current session record with the users details.
  461. *
  462. * Username and encoded password are sent as credentials (along with other
  463. * possibilities) to each observer (authentication plugin) for user
  464. * validation. Successful validation will update the current session with
  465. * the user details.
  466. *
  467. * @param array Array('username' => string, 'password' => string)
  468. * @param array Array('remember' => boolean)
  469. * @return boolean True on success.
  470. * @since 1.5
  471. */
  472. public function login($credentials, $options = array())
  473. {
  474. // Get the global JAuthentication object.
  475. jimport('joomla.user.authentication');
  476. $authenticate = & JAuthentication::getInstance();
  477. $response = $authenticate->authenticate($credentials, $options);
  478. if ($response->status === JAUTHENTICATE_STATUS_SUCCESS)
  479. {
  480. // Import the user plugin group.
  481. JPluginHelper::importPlugin('user');
  482. // OK, the credentials are authenticated. Lets fire the onLogin event.
  483. $results = $this->triggerEvent('onLoginUser', array((array)$response, $options));
  484. /*
  485. * If any of the user plugins did not successfully complete the login routine
  486. * then the whole method fails.
  487. *
  488. * Any errors raised should be done in the plugin as this provides the ability
  489. * to provide much more information about why the routine may have failed.
  490. */
  491. if (!in_array(false, $results, true))
  492. {
  493. // Set the remember me cookie if enabled.
  494. if (isset($options['remember']) && $options['remember'])
  495. {
  496. jimport('joomla.utilities.simplecrypt');
  497. jimport('joomla.utilities.utility');
  498. // Create the encryption key, apply extra hardening using the user agent string.
  499. $key = JUtility::getHash(@$_SERVER['HTTP_USER_AGENT']);
  500. $crypt = new JSimpleCrypt($key);
  501. $rcookie = $crypt->encrypt(serialize($credentials));
  502. $lifetime = time() + 365*24*60*60;
  503. // Use domain and path set in config for cookie if it exists.
  504. $cookie_domain = $this->getCfg('cookie_domain', '');
  505. $cookie_path = $this->getCfg('cookie_path', '/');
  506. setcookie( JUtility::getHash('JLOGIN_REMEMBER'), $rcookie, $lifetime, $cookie_path, $cookie_domain );
  507. }
  508. return true;
  509. }
  510. }
  511. // Trigger onLoginFailure Event.
  512. $this->triggerEvent('onLoginFailure', array((array)$response));
  513. // If silent is set, just return false.
  514. if (isset($options['silent']) && $options['silent']) {
  515. return false;
  516. }
  517. // Return the error.
  518. return JError::raiseWarning('SOME_ERROR_CODE', JText::_('E_LOGIN_AUTHENTICATE'));
  519. }
  520. /**
  521. * Logout authentication function.
  522. *
  523. * Passed the current user information to the onLogoutUser event and reverts the current
  524. * session record back to 'anonymous' parameters.
  525. *
  526. * @param int $userid The user to load - Can be an integer or string - If string, it is converted to ID automatically
  527. * @param array $options Array('clientid' => array of client id's)
  528. */
  529. public function logout($userid = null, $options = array())
  530. {
  531. // Initialise variables.
  532. $retval = false;
  533. // Get a user object from the JApplication.
  534. $user = &JFactory::getUser($userid);
  535. // Build the credentials array.
  536. $parameters['username'] = $user->get('username');
  537. $parameters['id'] = $user->get('id');
  538. // Set clientid in the options array if it hasn't been set already.
  539. if (empty($options['clientid'])) {
  540. $options['clientid'][] = $this->getClientId();
  541. }
  542. // Import the user plugin group.
  543. JPluginHelper::importPlugin('user');
  544. // OK, the credentials are built. Lets fire the onLogout event.
  545. $results = $this->triggerEvent('onLogoutUser', array($parameters, $options));
  546. /*
  547. * If any of the authentication plugins did not successfully complete
  548. * the logout routine then the whole method fails. Any errors raised
  549. * should be done in the plugin as this provides the ability to provide
  550. * much more information about why the routine may have failed.
  551. */
  552. if (!in_array(false, $results, true)) {
  553. // Use domain and path set in config for cookie if it exists.
  554. $cookie_domain = $this->getCfg('cookie_domain', '');
  555. $cookie_path = $this->getCfg('cookie_path', '/');
  556. setcookie(JUtility::getHash('JLOGIN_REMEMBER'), false, time() - 86400, $cookie_path, $cookie_domain );
  557. return true;
  558. }
  559. // Trigger onLoginFailure Event.
  560. $this->triggerEvent('onLogoutFailure', array($parameters));
  561. return false;
  562. }
  563. /**
  564. * Gets the name of the current template.
  565. *
  566. * @return string
  567. */
  568. public function getTemplate($params = false)
  569. {
  570. if($params)
  571. {
  572. $template = new stdClass();
  573. $template->template = 'system';
  574. $template->params = new JParameter();
  575. }
  576. return 'system';
  577. }
  578. /**
  579. * Returns the application JRouter object.
  580. *
  581. * @param array $options An optional associative array of configuration settings.
  582. * @return JRouter.
  583. * @since 1.5
  584. */
  585. static public function getRouter($name = null, array $options = array())
  586. {
  587. if (!isset($name)) {
  588. $name = $this->_name;
  589. }
  590. jimport('joomla.application.router');
  591. $router = &JRouter::getInstance($name, $options);
  592. if (JError::isError($router)) {
  593. return null;
  594. }
  595. return $router;
  596. }
  597. /**
  598. * This method transliterates a string into an URL
  599. * safe string or returns a URL safe UTF-8 string
  600. * based on the global configuration
  601. *
  602. * @param string $input String to process
  603. * @return string Processed string
  604. * @since 1.6
  605. */
  606. static public function stringURLSafe($string)
  607. {
  608. $app = &JFactory::getApplication();
  609. if (self::getCfg('unicodeslugs') == 1)
  610. {
  611. $output = JFilterOutput::stringURLUnicodeSlug($string);
  612. } else {
  613. $output = JFilterOutput::stringURLSafe($string);
  614. }
  615. return $output;
  616. }
  617. /**
  618. * Returns the application JPathway object.
  619. *
  620. * @param array $options An optional associative array of configuration settings.
  621. * @return object JPathway.
  622. * @since 1.5
  623. */
  624. public function getPathway($name = null, $options = array())
  625. {
  626. if (!isset($name)) {
  627. $name = $this->_name;
  628. }
  629. jimport('joomla.application.pathway');
  630. $pathway = &JPathway::getInstance($name, $options);
  631. if (JError::isError($pathway)) {
  632. return null;
  633. }
  634. return $pathway;
  635. }
  636. /**
  637. * Returns the application JPathway object.
  638. *
  639. * @param array $options An optional associative array of configuration settings.
  640. * @return object JMenu.
  641. * @since 1.5
  642. */
  643. public function getMenu($name = null, $options = array())
  644. {
  645. if (!isset($name)) {
  646. $name = $this->_name;
  647. }
  648. jimport('joomla.application.menu');
  649. $menu = &JMenu::getInstance($name, $options);
  650. if (JError::isError($menu)) {
  651. return null;
  652. }
  653. return $menu;
  654. }
  655. /**
  656. * Provides a secure hash based on a seed
  657. *
  658. * @param string Seed string
  659. * @return string
  660. */
  661. public static function getHash($seed)
  662. {
  663. $conf = &JFactory::getConfig();
  664. return md5($conf->getValue('config.secret') . $seed );
  665. }
  666. /**
  667. * Create the configuration registry.
  668. *
  669. * @param string $file The path to the configuration file.
  670. * return JConfig
  671. */
  672. protected function _createConfiguration($file)
  673. {
  674. jimport('joomla.registry.registry');
  675. require_once $file;
  676. // Create the JConfig object.
  677. $config = new JConfig();
  678. // Get the global configuration object.
  679. $registry = &JFactory::getConfig();
  680. // Load the configuration values into the registry.
  681. $registry->loadObject($config);
  682. return $config;
  683. }
  684. /**
  685. * Create the user session.
  686. *
  687. * Old sessions are flushed based on the configuration value for the cookie
  688. * lifetime. If an existing session, then the last access time is updated.
  689. * If a new session, a session id is generated and a record is created in
  690. * the #__sessions table.
  691. *
  692. * @param string The sessions name.
  693. * @return object JSession on success. May call exit() on database error.
  694. * @since 1.5
  695. */
  696. protected function _createSession($name)
  697. {
  698. $options = array();
  699. $options['name'] = $name;
  700. switch($this->_clientId) {
  701. case 0:
  702. if ($this->getCfg('force_ssl') == 2) {
  703. $options['force_ssl'] = true;
  704. }
  705. break;
  706. case 1:
  707. if ($this->getCfg('force_ssl') >= 1) {
  708. $options['force_ssl'] = true;
  709. }
  710. break;
  711. }
  712. $session = JFactory::getSession($options);
  713. //TODO: At some point we need to get away from having session data always in the db.
  714. // Remove expired sessions from the database.
  715. $db = JFactory::getDBO();
  716. $db->setQuery(
  717. 'DELETE FROM `#__session`' .
  718. ' WHERE `time` < '.(int) (time() - $session->getExpire())
  719. );
  720. $db->query();
  721. // Check to see the the session already exists.
  722. $db->setQuery(
  723. 'SELECT `session_id`' .
  724. ' FROM `#__session`' .
  725. ' WHERE `session_id` = '.$db->quote($session->getId())
  726. );
  727. $exists = $db->loadResult();
  728. // If the session doesn't exist initialise it.
  729. if (!$exists) {
  730. $db->setQuery(
  731. 'INSERT INTO `#__session` (`session_id`, `client_id`, `time`)' .
  732. ' VALUES ('.$db->quote($session->getId()).', '.(int) $this->getClientId().', '.(int) time().')'
  733. );
  734. // If the insert failed, exit the application.
  735. if (!$db->query()) {
  736. jexit($db->getErrorMSG());
  737. }
  738. //Session doesn't exist yet, initalise and store it in the session table
  739. $session->set('registry', new JRegistry('session'));
  740. $session->set('user', new JUser());
  741. }
  742. return $session;
  743. }
  744. /**
  745. * Gets the client id of the current running application.
  746. *
  747. * @return int A client identifier.
  748. * @since 1.5
  749. */
  750. public function getClientId()
  751. {
  752. return $this->_clientId;
  753. }
  754. /**
  755. * Is admin interface?
  756. *
  757. * @return boolean True if this application is administrator.
  758. * @since 1.0.2
  759. */
  760. public function isAdmin()
  761. {
  762. return ($this->_clientId == 1);
  763. }
  764. /**
  765. * Is site interface?
  766. *
  767. * @return boolean True if this application is site.
  768. * @since 1.5
  769. */
  770. public function isSite()
  771. {
  772. return ($this->_clientId == 0);
  773. }
  774. /**
  775. * Method to determine if the host OS is Windows
  776. *
  777. * @return true if Windows OS
  778. * @since 1.5
  779. * @static
  780. */
  781. static function isWinOS() {
  782. return strtoupper(substr(PHP_OS, 0, 3)) === 'WIN';
  783. }
  784. /**
  785. * Returns the response
  786. *
  787. * @return string
  788. * @since 1.6
  789. */
  790. public function __toString()
  791. {
  792. $compress = $this->getCfg('gzip', false);
  793. return JResponse::toString($compress);
  794. }
  795. }