Source code for file /joomla/application/application.php
Documentation is available at application.php
* @version $Id: application.php 11409 2009-01-10 02:27:08Z willebil $
* @package Joomla.Framework
* @subpackage Application
* @copyright Copyright (C) 2005 - 2008 Open Source Matters. All rights reserved.
* @license GNU/GPL, see LICENSE.php
* Joomla! is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* See COPYRIGHT.php for copyright notices and details.
// Check to ensure this file is within the rest of the framework
* 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.
* @package Joomla.Framework
* @subpackage Application
* The application message queue.
* The name of the application
* The scope of the application
* @param integer A client identifier.
jimport('joomla.utilities.utility');
//Enable sessions by default
if(!isset
($config['session'])) {
$config['session'] =
true;
//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
$this->_createConfiguration(JPATH_CONFIGURATION.
DS.
$config['config_file']);
//create the session if a session name is passed
if($config['session'] !==
false) {
$this->set( 'requestTime', gmdate('Y-m-d H:i') );
* Returns a reference to the global JApplication object, only creating it if it
* This method must be invoked as:
* <pre> $menu = &JApplication::getInstance();</pre>
* @param mixed $id A client identifier or name.
* @param array $config An optional associative array of configuration settings.
* @return JApplication The appliction object.
function &getInstance($client, $config =
array(), $prefix =
'J')
if (!isset
( $instances )) {
if (empty($instances[$client]))
jimport('joomla.application.helper');
$path =
$info->path.
DS.
'includes'.
DS.
'application.php';
// Create a JRouter object
$classname =
$prefix.
ucfirst($client);
$instance =
new $classname($config);
$instances[$client] =
& $instance;
return $instances[$client];
* Initialise the application.
* @param array 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->setValue('config.language', $options['language']);
// Set user specific editor
$editor =
$user->getParam('editor', $this->getCfg('editor'));
$config->setValue('config.editor', $editor);
* 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);
* Dispatch the applicaiton.
* 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.
$document->setTitle( $this->getCfg('sitename' ).
' - ' .
JText::_( 'Administration' ));
$document->setDescription( $this->getCfg('MetaDesc') );
$document->setBuffer($contents, 'component');
* 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
'directory' =>
JPATH_THEMES
$data =
$document->render($this->getCfg('caching'), $params );
function close( $code =
0 ) {
* 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.
* @return none; calls exit().
* @see JApplication::enqueueMessage()
function redirect( $url, $msg=
'', $msgType=
'message' )
// 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
// its relative to where we are now, so lets add that
$parts =
explode('/', $uri->toString(Array('path')));
$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='$url';</script>\n";
//@ob_end_clean(); // clear output buffer
header( 'HTTP/1.1 301 Moved Permanently' );
header( 'Location: ' .
$url );
* Enqueue a system message.
* @param string $msg The message to enqueue.
* @param string $type The message type.
// 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 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.
* @param string The name of the value to get.
* @return mixed The user state.
* @example application/japplication-getcfg.php Getting a configuration value
return $config->getValue('config.' .
$varname);
* Method to get the application name
* The dispatcher name 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
JError::raiseError(500, "JApplication::getName() : Can\'t get or parse class name.");
* @param string The path of the state.
* @return mixed The user state.
$registry =
& $session->get('registry');
return $registry->getValue($key);
* Sets the value of a user state variable.
* @param string The path of the state.
* @param string The value of the variable.
* @return mixed The previous state, if one existed.
$registry =
& $session->get('registry');
return $registry->setValue($key, $value);
* Gets the value of a user state variable.
* @param string The key of the user state variable.
* @param string The name of the variable passed in a request.
* @param string The default value for the variable if not found. Optional.
* @param string Filter for the variable, for valid values see {@link JFilterInput::clean()}. Optional.
* @return The request user state.
$cur_state =
(!is_null($old_state)) ?
$old_state :
$default;
// Save the new value only if it was set in this request
if ($new_state !==
null) {
* Registers a handler to a particular event group.
* @param string The event name.
* @param mixed The handler, a function or an instance of a event object.
$dispatcher->register($event, $handler);
* Calls all handlers associated with an event group.
* @param string The event name.
* @param array An array of arguments.
* @return array An array of results from each function call.
return $dispatcher->trigger($event, $args);
* Login authentication function.
* Username and encoded password are passed the the onLoginUser event which
* is responsible for the user validation. A successful validation updates
* the current session record with the users 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 Array( 'username' => string, 'password' => string )
* @param array Array( 'remember' => boolean )
* @return boolean True on success.
function login($credentials, $options =
array())
// Get the global JAuthentication object
jimport( 'joomla.user.authentication');
$response =
$authenticate->authenticate($credentials, $options);
// Import the user plugin group
// OK, the credentials are authenticated. Lets fire the onLogin event
$results =
$this->triggerEvent('onLoginUser', 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.
// Set the remember me cookie if enabled
if (isset
($options['remember']) &&
$options['remember'])
jimport('joomla.utilities.simplecrypt');
jimport('joomla.utilities.utility');
//Create the encryption key, apply extra hardening using the user agent string
$rcookie =
$crypt->encrypt(serialize($credentials));
$lifetime =
time() +
365*
24*
60*
60;
// Trigger onLoginFailure Event
$this->triggerEvent('onLoginFailure', array((array)
$response));
// If silent is set, just return false
if (isset
($options['silent']) &&
$options['silent']) {
* Logout authentication function.
* Passed the current user information to the onLogoutUser event and reverts the current
* session record back to 'anonymous' parameters.
* @param int $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 )
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(empty($options['clientid'])) {
// Import the user plugin group
// OK, the credentials are built. Lets fire the onLogout event
$results =
$this->triggerEvent('onLogoutUser', array($parameters, $options));
* 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 provide
* much more information about why the routine may have failed.
// Trigger onLoginFailure Event
* Gets the name of the current template.
* Return a reference to the application JRouter object.
* @param array $options An optional associative array of configuration settings.
function &getRouter($name =
null, $options =
array())
jimport( 'joomla.application.router' );
* Return a reference to the application JPathway object.
* @param array $options An optional associative array of configuration settings.
* @return object JPathway.
function &getPathway($name =
null, $options =
array())
jimport( 'joomla.application.pathway' );
* Return a reference to the application JPathway object.
* @param array $options An optional associative array of configuration settings.
function &getMenu($name =
null, $options =
array())
jimport( 'joomla.application.menu' );
* Create the configuration registry
* @param string $file The path to the configuration file
function &_createConfiguration($file)
jimport( 'joomla.registry.registry' );
// 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 The sessions name.
* @return object JSession on success. May call exit() on database error.
function &_createSession( $name )
$options['name'] =
$name;
if($this->getCfg('force_ssl') ==
2) {
$options['force_ssl'] =
true;
if($this->getCfg('force_ssl') >=
1) {
$options['force_ssl'] =
true;
$storage->purge($session->getExpire());
// Session exists and is not expired, update time in session table
if ($storage->load($session->getId())) {
//Session doesn't exist yet, initalise and store it in the session table
$session->set('registry', new JRegistry('session'));
$session->set('user', new JUser());
if (!$storage->insert( $session->getId(), $this->getClientId())) {
jexit( $storage->getError());
* Gets the client id of the current running application.
* @return int A client identifier.
* @return boolean True if this application is administrator.
* @return boolean True if this application is site.
* Deprecated, use JPathWay->addItem() method instead.
* @deprecated As of version 1.5
* @see JPathWay::addItem()
* To provide backward compatability if no second parameter is set
if( defined( '_JLEGACY' ) &&
$link ==
'' )
$links =
preg_match_all ( '/<a[^>]+href="([^"]*)"[^>]*>([^<]*)<\/a>/ui', $name, $matches, PREG_SET_ORDER );
foreach( $matches AS $match) {
// Add each item to the pathway object
if( !$pathway->addItem( $match[2], $match[1] ) ) {
// Add item to the pathway object
if ($pathway->addItem($name, $link)) {
* Deprecated, use JPathway->getPathWayNames() method instead.
* @deprecated As of version 1.5
* @see JPathWay::getPathWayNames()
return $pathway->getPathWayNames();
* Deprecated, use JDocument->get( 'head' ) instead.
* @deprecated As of version 1.5
return $document->get('head');
* Deprecated, use JDocument->setMetaData instead.
* @deprecated As of version 1.5
* @param string Name of the metadata tag
* @param string Content of the metadata tag
* @param string Deprecated, ignored
* @param string Deprecated, ignored
* @see JDocument::setMetaData()
function addMetaTag( $name, $content, $prepend =
'', $append =
'' )
$document->setMetadata($name, $content);
* Deprecated, use JDocument->setMetaData instead.
* @deprecated As of version 1.5
* @param string Name of the metadata tag
* @param string Content of the metadata tag
* @see JDocument::setMetaData()
* Deprecated, use JDocument->setMetaData instead
* @deprecated As of version 1.5
* @param string Name of the metadata tag
* @param string Content of the metadata tag
* @see JDocument::setMetaData()
* Deprecated, use JDocument->addCustomTag instead (only when document type is HTML).
* @deprecated As of version 1.5
* @param string Valid HTML
* @see JDocumentHTML::addCustomTag()
if($document->getType() ==
'html') {
$document->addCustomTag($html);
* @deprecated As of version 1.5
$menus =
&JSite::getMenu();
return count($menus->getItems('type', 'content_blog_section'));
* @deprecated As of version 1.5
$menus =
&JSite::getMenu();
return count($menus->getItems('type', 'content_blog_category'));
* @deprecated As of version 1.5
$menus =
&JSite::getMenu();
return count($menus->getItems('type', 'content_blog_section'));
* @deprecated As of version 1.5
$menus =
&JSite::getMenu();
return count($menus->getItems('type', 'content_typed'));
* @deprecated As of version 1.5
$menus =
&JSite::getMenu();
return count($menus->getItems('type', 'content_item_link'));
* Deprecated, use JApplicationHelper::getPath instead.
* @deprecated As of version 1.5
* @see JApplicationHelper::getPath()
function getPath($varname, $user_option =
null)
jimport('joomla.application.helper');
* Deprecated, use JURI::base() instead.
* @deprecated As of version 1.5
function getBasePath($client=
0, $addTrailingSlash =
true)
* Deprecated, use JFactory::getUser instead.
* @deprecated As of version 1.5
* @see JFactory::getUser()
* Deprecated, use ContentHelper::getItemid instead.
* @deprecated As of version 1.5
* @see ContentHelperRoute::getArticleRoute()
require_once JPATH_SITE.
DS.
'components'.
DS.
'com_content'.
DS.
'helpers'.
DS.
'route.php';
// Load the article data to know what section/category it is in.
'category' => (int)
$article->catid,
'section' => (int)
$article->sectionid,
$item =
ContentHelperRoute::_findItem($needles);
$return =
is_object($item) ?
$item->id :
null;
* Deprecated, use JDocument::setTitle instead.
* @deprecated As of version 1.5
* @see JDocument::setTitle()
$document->setTitle($title);
* Deprecated, use JDocument::getTitle instead.
* @deprecated As of version 1.5
* @see JDocument::getTitle()
return $document->getTitle();