Source for file application.php
Documentation is available at application.php
* @subpackage Application
* @copyright Copyright (C) 2005 - 2013 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE
JLog::add('JApplication is deprecated.', JLog::WARNING, 'deprecated');
* Base class for a Joomla! application.
* Acts as a Factory class for application specific objects and provides many
* supporting API functions. Derived clases should supply the route(), dispatch()
* and render() functions.
* @subpackage Application
* @deprecated 4.0 Use JApplicationCms instead unless specified otherwise
* The application message queue.
* The name of the application.
* The scope of the application.
* The time the request was made.
* The time the request was made as Unix timestamp.
* @var JApplicationWebClient The application client object.
* @var array JApplication instances container.
protected static $instances =
array();
* @var boolean Indicates that strong encryption should be used.
* @note Default has been changed as of 3.2. If salted md5 is required it must be explictly set.
* @param array $config A configuration array including optional elements such as session
* session_name, clientId and others. This is not exhaustive.
// Only set the clientId if available.
if (isset
($config['clientId']))
// Enable sessions by default.
if (!isset
($config['session']))
$config['session'] =
true;
// Create the input object
// Set the session default name.
if (!isset
($config['session_name']))
$config['session_name'] =
$this->_name;
// Set the default configuration file.
if (!isset
($config['config_file']))
$config['config_file'] =
'configuration.php';
// Create the configuration object.
// Create the session if a session name is passed.
if ($config['session'] !==
false)
// Used by task system to ensure that the system doesn't go over time.
* Returns the global JApplicationCms object, only creating it if it
* @param mixed $client A client identifier or name.
* @param array $config An optional associative array of configuration settings.
* @param string $prefix A prefix for class names
* @return JApplicationCms A JApplicationCms object.
* @deprecated 4.0 Use JApplicationCms::getInstance() instead
* @note As of 3.2, this proxies to JApplicationCms::getInstance()
public static function getInstance($client, $config =
array(), $prefix =
'J')
* Initialise the application.
* @param array $options An optional associative array of configuration settings.
// Set the language in the class.
// Check that we were given a language in the array (since by default may be blank).
if (isset
($options['language']))
$config->set('language', $options['language']);
// Set user specific editor.
$editor =
$user->getParam('editor', $this->getCfg('editor'));
$editor =
$this->getCfg('editor');
$config->set('editor', $editor);
// Set the encryption to use. The availability of strong encryption must always be checked separately.
// Use JCrypt::hasStrongPasswordSupport() to check PHP for this support.
$userPluginParams->loadString($userPlugin->params);
$useStrongEncryption =
$userPluginParams->get('strong_passwords', 0);
$config->set('useStrongEncryption', $useStrongEncryption);
// Trigger the onAfterInitialise event.
* Routing is the process of examining the request environment to determine which
* component should receive the request. The component optional parameters
* are then set in the request object to be processed when the application is being
// Get the full request URI.
$result =
$router->parse($uri);
foreach ($result as $key =>
$value)
$this->input->def($key, $value);
// Trigger the onAfterRoute event.
* Dispatch the application.
* Dispatching is the process of pulling the option from the request object and
* mapping them to a component. If the component does not exist, it handles
* determining a default component to dispatch.
* @param string $component The component to dispatch.
public function dispatch($component =
null)
$document->setBuffer($contents, 'component');
// Trigger the onAfterDispatch event.
* Render the application.
* Rendering is the process of pushing the document buffers into the template
* placeholders, retrieving data from the document and pushing it into
$params =
array('template' =>
$template->template, 'file' =>
'index.php', 'directory' =>
JPATH_THEMES, 'params' =>
$template->params);
$document->parse($params);
// Trigger the onBeforeRender event.
$caching =
($this->getCfg('caching') >=
2) ?
true :
false;
// Trigger the onAfterRender event.
* Redirect to another URL.
* Optionally enqueues a message in the system message queue (which will be displayed
* the next time a page is loaded) using the enqueueMessage method. If the headers have
* not been sent the redirect will be accomplished using a "301 Moved Permanently"
* code in the header pointing to the new location. If the headers have already been
* sent this will be accomplished using a JavaScript statement.
* @param string $url The URL to redirect to. Can only be http/https URL
* @param string $msg An optional message to display on redirect.
* @param string $msgType An optional message type. Defaults to message.
* @param boolean $moved True if the page is 301 Permanently Moved, otherwise 303 See Other is assumed.
* @return void Calls exit().
* @see JApplication::enqueueMessage()
public function redirect($url, $msg =
'', $msgType =
'message', $moved =
false)
// Check for relative internal links.
// Strip out any line breaks.
* If we don't start with a http we need to fix this before we proceed.
* We could validly start with something else (e.g. ftp), though this would
* be unlikely and isn't supported by this API.
$prefix =
$uri->toString(array('scheme', 'user', 'pass', 'host', 'port'));
// We just need the prefix since we have a path relative to the root.
// It's relative to where we are now, so lets add that.
$parts =
explode('/', $uri->toString(array('path')));
$path =
implode('/', $parts) .
'/';
$url =
$prefix .
$path .
$url;
// If the message exists, enqueue it.
// Persist messages if they exist.
// If the headers have been sent, then we cannot send an additional location header
// so we will output a javascript redirect statement.
echo
"<script>document.location.href='" .
str_replace("'", "'", $url) .
"';</script>\n";
// MSIE type browser and/or server cause issues when url contains utf8 character,so use a javascript redirect method
echo
'<html><head><meta http-equiv="content-type" content="text/html; charset=' .
$document->getCharset() .
'" />'
.
'<script>document.location.href=\'' .
str_replace("'", "'", $url) .
'\';</script></head></html>';
// All other browsers, use the more efficient HTTP header method
header($moved ?
'HTTP/1.1 301 Moved Permanently' :
'HTTP/1.1 303 See other');
header('Content-Type: text/html; charset=' .
$document->getCharset());
* Enqueue a system message.
* @param string $msg The message to enqueue.
* @param string $type The message type. Default is message.
// For empty queue, if messages exists in the session, enqueue them first.
$sessionQueue =
$session->get('application.queue');
if (count($sessionQueue))
$session->set('application.queue', null);
* Get the system message queue.
* @return array The system message queue.
// For empty queue, if messages exists in the session, enqueue them.
$sessionQueue =
$session->get('application.queue');
if (count($sessionQueue))
$session->set('application.queue', null);
* Gets a configuration value.
* An example is in application/japplication-getcfg.php Getting a configuration
* @param string $varname The name of the value to get.
* @param string $default Default value to return
* @return mixed The user state.
public function getCfg($varname, $default =
null)
return $config->get('' .
$varname, $default);
* Method to get the application name.
* The dispatcher name is by default parsed using the classname, or it can be set
* by passing a $config['name'] in the class constructor.
* @return string The name of the dispatcher.
JLog::add(JText::_('JLIB_APPLICATION_ERROR_APPLICATION_GET_NAME'), JLog::WARNING, 'jerror');
* @param string $key The path of the state.
* @param mixed $default Optional default value, returned if the internal value is null.
* @return mixed The user state or null.
$registry =
$session->get('registry');
return $registry->get($key, $default);
* Sets the value of a user state variable.
* @param string $key The path of the state.
* @param string $value The value of the variable.
* @return mixed The previous state, if one existed.
$registry =
$session->get('registry');
return $registry->set($key, $value);
* Gets the value of a user state variable.
* @param string $key The key of the user state variable.
* @param string $request The name of the variable passed in a request.
* @param string $default The default value for the variable if not found. Optional.
* @param string $type Filter for the variable, for valid values see {@link JFilterInput::clean()}. Optional.
* @return The request user state.
$new_state =
$this->input->get($request, null, $type);
// Save the new value only if it was set in this request.
* Login authentication function.
* Username and encoded password are passed the onUserLogin event which
* is responsible for the user validation. A successful validation updates
* the current session record with the user's details.
* Username and encoded password are sent as credentials (along with other
* possibilities) to each observer (authentication plugin) for user
* validation. Successful validation will update the current session with
* @param array $credentials Array('username' => string, 'password' => string)
* @param array $options Array('remember' => boolean)
* @return boolean True on success.
public function login($credentials, $options =
array())
// Get the global JAuthentication object.
jimport('joomla.user.authentication');
$response =
$authenticate->authenticate($credentials, $options);
// Validate that the user should be able to login (different to being authenticated).
// This permits authentication plugins blocking the user
$authorisations =
$authenticate->authorise($response, $options);
foreach ($authorisations as $authorisation)
if (in_array($authorisation->status, $denied_states))
// Trigger onUserAuthorisationFailure Event.
$this->triggerEvent('onUserAuthorisationFailure', array((array)
$authorisation));
// If silent is set, just return false.
if (isset
($options['silent']) &&
$options['silent'])
switch ($authorisation->status)
// Import the user plugin group.
// OK, the credentials are authenticated and user is authorised. Let's fire the onLogin event.
$results =
$this->triggerEvent('onUserLogin', array((array)
$response, $options));
* If any of the user plugins did not successfully complete the login routine
* then the whole method fails.
* Any errors raised should be done in the plugin as this provides the ability
* to provide much more information about why the routine may have failed.
if ($response->type ==
'Cookie')
$user->set('cookieLogin', true);
if (in_array(false, $results, true) ==
false)
$options['user'] =
$user;
$options['responseType'] =
$response->type;
if (isset
($response->length) && isset
($response->secure) && isset
($response->lifetime))
$options['length'] =
$response->length;
$options['secure'] =
$response->secure;
$options['lifetime'] =
$response->lifetime;
// The user is successfully logged in. Run the after login events
// Trigger onUserLoginFailure Event.
$this->triggerEvent('onUserLoginFailure', array((array)
$response));
// If silent is set, just return false.
if (isset
($options['silent']) &&
$options['silent'])
// If status is success, any error will have been raised by the user plugin
JLog::add($response->error_message, JLog::WARNING, 'jerror');
* Logout authentication function.
* Passed the current user information to the onUserLogout event and reverts the current
* session record back to 'anonymous' parameters.
* If any of the authentication plugins did not successfully complete
* the logout routine then the whole method fails. Any errors raised
* should be done in the plugin as this provides the ability to give
* much more information about why the routine may have failed.
* @param integer $userid The user to load - Can be an integer or string - If string, it is converted to ID automatically
* @param array $options Array('clientid' => array of client id's)
* @return boolean True on success
public function logout($userid =
null, $options =
array())
// Get a user object from the JApplication.
// Build the credentials array.
$parameters['username'] =
$user->get('username');
$parameters['id'] =
$user->get('id');
// Set clientid in the options array if it hasn't been set already.
if (!isset
($options['clientid']))
// Import the user plugin group.
// OK, the credentials are built. Lets fire the onLogout event.
$results =
$this->triggerEvent('onUserLogout', array($parameters, $options));
$options['username'] =
$user->get('username');
$results =
$this->triggerEvent('onUserAfterLogout', array($options));
// Trigger onUserLoginFailure Event.
$this->triggerEvent('onUserLogoutFailure', array($parameters));
* Gets the name of the current template.
* @param boolean $params An optional associative array of configuration settings
* @return mixed System is the fallback.
$template =
new stdClass;
$template->template =
'system';
return $template->template;
* Returns the application JRouter object.
* @param string $name The name of the application.
* @param array $options An optional associative array of configuration settings.
* @return JRouter A JRouter object
static public function getRouter($name =
null, array $options =
array())
* This method transliterates a string into an URL
* safe string or returns a URL safe UTF-8 string
* based on the global configuration
* @param string $string String to process
* @return string Processed string
* @deprecated 4.0 Use JApplicationHelper::stringURLSafe instead
* Returns the application JPathway object.
* @param string $name The name of the application.
* @param array $options An optional associative array of configuration settings.
* @return JPathway A JPathway object
public function getPathway($name =
null, $options =
array())
* Returns the application JPathway object.
* @param string $name The name of the application/client.
* @param array $options An optional associative array of configuration settings.
* @return JMenu JMenu object.
public function getMenu($name =
null, $options =
array())
* Provides a secure hash based on a seed
* @param string $seed Seed string.
* @return string A secure hash
* @deprecated 4.0 Use JApplicationHelper::getHash instead
public static function getHash($seed)
* Create the configuration registry.
* @param string $file The path to the configuration file
* @return JConfig A JConfig object
// Create the JConfig object.
// Get the global configuration object.
// Load the configuration values into the registry.
$registry->loadObject($config);
* Create the user session.
* Old sessions are flushed based on the configuration value for the cookie
* lifetime. If an existing session, then the last access time is updated.
* If a new session, a session id is generated and a record is created in
* @param string $name The sessions name.
* @return JSession JSession on success. May call exit() on database error.
$options['name'] =
$name;
if ($this->getCfg('force_ssl') ==
2)
$options['force_ssl'] =
true;
if ($this->getCfg('force_ssl') >=
1)
$options['force_ssl'] =
true;
$this->registerEvent('onAfterSessionStart', array($this, 'afterSessionStart'));
// TODO: At some point we need to get away from having session data always in the db.
// Remove expired sessions from the database.
// The modulus introduces a little entropy, making the flushing less accurate
// but fires the query less than half the time.
$query =
$db->getQuery(true)
->delete($db->quoteName('#__session'))
->where($db->quoteName('time') .
' < ' .
$db->quote((int)
($time -
$session->getExpire())));
// Check to see the the session already exists.
$handler =
$this->getCfg('session_handler');
if (($handler !=
'database' &&
($time %
2 ||
$session->isNew()))
||
($handler ==
'database' &&
$session->isNew()))
* Checks the user session.
* If the session record doesn't exist, initialise it.
* If session is new, create session variables
$query =
$db->getQuery(true)
->select($db->quoteName('session_id'))
->from($db->quoteName('#__session'))
->where($db->quoteName('session_id') .
' = ' .
$db->quote($session->getId()));
$db->setQuery($query, 0, 1);
$exists =
$db->loadResult();
// If the session record doesn't exist initialise it.
$query->insert($db->quoteName('#__session'))
->columns($db->quoteName('session_id') .
', ' .
$db->quoteName('client_id') .
', ' .
$db->quoteName('time'))
->values($db->quote($session->getId()) .
', ' . (int)
$this->getClientId() .
', ' .
$db->quote((int)
time()));
$query->insert($db->quoteName('#__session'))
$db->quoteName('session_id') .
', ' .
$db->quoteName('client_id') .
', ' .
$db->quoteName('guest') .
', ' .
$db->quoteName('time') .
', ' .
$db->quoteName('userid') .
', ' .
$db->quoteName('username')
$db->quote($session->getId()) .
', ' . (int)
$this->getClientId() .
', ' . (int)
$user->get('guest') .
', ' .
$db->quote((int)
$session->get('session.timer.start')) .
', ' . (int)
$user->get('id') .
', ' .
$db->quote($user->get('username'))
// If the insert failed, exit the application.
catch
(RuntimeException $e)
* After the session has been started we need to populate it with some default values.
$session->set('registry', new JRegistry('session'));
$session->set('user', new JUser);
* Gets the client id of the current running application.
* @return integer A client identifier.
* @return boolean True if this application is administrator.
* @return boolean True if this application is site.
* Method to determine if the host OS is Windows
* @return boolean True if Windows OS
* @deprecated 13.3 (Platform) & 4.0 (CMS) Use the IS_WIN constant instead.
JLog::add('JApplication::isWinOS() is deprecated. Use the IS_WIN constant instead.', JLog::WARNING, 'deprecated');
* Determine if we are using a secure (SSL) connection.
* @return boolean True if using SSL, false if not.
return ((isset
($_SERVER['HTTPS']) &&
($_SERVER['HTTPS'] ==
'on')) ||
getenv('SSL_PROTOCOL_VERSION'));
* Returns the response as a string.
* @return string The response
$compress =
$this->getCfg('gzip', false);
Documentation generated on Tue, 19 Nov 2013 14:53:46 +0100 by phpDocumentor 1.4.3