File manager - Edit - /home/ferretapmx/public_html/Application.zip
Back
PK #�\� _г г CMSApplication.phpnu �[��� <?php /** * Joomla! Content Management System * * @copyright (C) 2013 Open Source Matters, Inc. <https://www.joomla.org> * @license GNU General Public License version 2 or later; see LICENSE.txt */ namespace Joomla\CMS\Application; use Joomla\Application\SessionAwareWebApplicationTrait; use Joomla\Application\Web\WebClient; use Joomla\CMS\Authentication\Authentication; use Joomla\CMS\Event\Application\AfterCompressEvent; use Joomla\CMS\Event\Application\AfterInitialiseEvent; use Joomla\CMS\Event\Application\AfterRenderEvent; use Joomla\CMS\Event\Application\AfterRespondEvent; use Joomla\CMS\Event\Application\AfterRouteEvent; use Joomla\CMS\Event\Application\BeforeRenderEvent; use Joomla\CMS\Event\Application\BeforeRespondEvent; use Joomla\CMS\Event\ErrorEvent; use Joomla\CMS\Event\User\AfterLoginEvent; use Joomla\CMS\Event\User\AfterLogoutEvent; use Joomla\CMS\Event\User\AuthorisationFailureEvent; use Joomla\CMS\Event\User\LoginEvent; use Joomla\CMS\Event\User\LoginFailureEvent; use Joomla\CMS\Event\User\LogoutEvent; use Joomla\CMS\Event\User\LogoutFailureEvent; use Joomla\CMS\Exception\ExceptionHandler; use Joomla\CMS\Extension\ExtensionManagerTrait; use Joomla\CMS\Factory; use Joomla\CMS\Filter\InputFilter; use Joomla\CMS\Input\Input; use Joomla\CMS\Language\LanguageFactoryInterface; use Joomla\CMS\Language\Text; use Joomla\CMS\Log\Log; use Joomla\CMS\Menu\AbstractMenu; use Joomla\CMS\Menu\MenuFactoryInterface; use Joomla\CMS\Pathway\Pathway; use Joomla\CMS\Plugin\PluginHelper; use Joomla\CMS\Profiler\Profiler; use Joomla\CMS\Router\Route; use Joomla\CMS\Router\Router; use Joomla\CMS\Session\MetadataManager; use Joomla\CMS\Session\Session; use Joomla\CMS\Uri\Uri; use Joomla\DI\Container; use Joomla\DI\ContainerAwareInterface; use Joomla\DI\ContainerAwareTrait; use Joomla\Registry\Registry; use Joomla\String\StringHelper; // phpcs:disable PSR1.Files.SideEffects \defined('_JEXEC') or die; // phpcs:enable PSR1.Files.SideEffects /** * Joomla! CMS Application class * * @since 3.2 */ abstract class CMSApplication extends WebApplication implements ContainerAwareInterface, CMSWebApplicationInterface { use ContainerAwareTrait; use ExtensionManagerTrait; use ExtensionNamespaceMapper; use SessionAwareWebApplicationTrait; /** * Array of options for the \JDocument object * * @var array * @since 3.2 */ protected $docOptions = []; /** * Application instances container. * * @var CmsApplication[] * @since 3.2 */ protected static $instances = []; /** * The scope of the application. * * @var string * @since 3.2 */ public $scope = null; /** * The client identifier. * * @var integer * @since 4.0.0 */ protected $clientId = null; /** * The application message queue. * * @var array * @since 4.0.0 */ protected $messageQueue = []; /** * The name of the application. * * @var string * @since 4.0.0 */ protected $name = null; /** * The profiler instance * * @var Profiler * @since 3.2 */ protected $profiler = null; /** * Currently active template * * @var object * @since 3.2 */ protected $template = null; /** * The pathway object * * @var Pathway * @since 4.0.0 */ protected $pathway = null; /** * The authentication plugin type * * @var string * @since 4.0.0 */ protected $authenticationPluginType = 'authentication'; /** * Menu instances container. * * @var AbstractMenu[] * @since 4.2.0 */ protected $menus = []; /** * The menu factory * * @var MenuFactoryInterface * * @since 4.2.0 */ private $menuFactory; /** * Class constructor. * * @param ?Input $input An optional argument to provide dependency injection for the application's input * object. If the argument is a JInput object that object will become the * application's input object, otherwise a default input object is created. * @param ?Registry $config An optional argument to provide dependency injection for the application's config * object. If the argument is a Registry object that object will become the * application's config object, otherwise a default config object is created. * @param ?WebClient $client An optional argument to provide dependency injection for the application's client * object. If the argument is a WebClient object that object will become the * application's client object, otherwise a default client object is created. * @param ?Container $container Dependency injection container. * * @since 3.2 */ public function __construct(?Input $input = null, ?Registry $config = null, ?WebClient $client = null, ?Container $container = null) { $container = $container ?: new Container(); $this->setContainer($container); parent::__construct($input, $config, $client); // If JDEBUG is defined, load the profiler instance if (\defined('JDEBUG') && JDEBUG) { $this->profiler = Profiler::getInstance('Application'); } // Enable sessions by default. if ($this->config->get('session') === null) { $this->config->set('session', true); } // Set the session default name. if ($this->config->get('session_name') === null) { $this->config->set('session_name', $this->getName()); } } /** * Checks the user session. * * If the session record doesn't exist, initialise it. * If session is new, create session variables * * @return void * * @since 3.2 * @throws \RuntimeException */ public function checkSession() { $this->getContainer()->get(MetadataManager::class)->createOrUpdateRecord($this->getSession(), $this->getIdentity()); } /** * Enqueue a system message. * * @param string $msg The message to enqueue. * @param string $type The message type. Default is message. * * @return void * * @since 3.2 */ public function enqueueMessage($msg, $type = self::MSG_INFO) { // Don't add empty messages. if ($msg === null || trim($msg) === '') { return; } $inputFilter = InputFilter::getInstance( [], [], InputFilter::ONLY_BLOCK_DEFINED_TAGS, InputFilter::ONLY_BLOCK_DEFINED_ATTRIBUTES ); // Build the message array and apply the HTML InputFilter with the default blacklist to the message $message = [ 'message' => $inputFilter->clean($msg, 'html'), 'type' => $inputFilter->clean(strtolower($type), 'cmd'), ]; // Get the messages of the session and add the new message if it is not already in the queue. if (!\in_array($message, $this->getMessageQueue())) { // Enqueue the message. $this->messageQueue[] = $message; } } /** * Ensure several core system input variables are not arrays. * * @return void * * @since 3.9 */ private function sanityCheckSystemVariables() { $input = $this->input; // Get invalid input variables $invalidInputVariables = array_filter( ['option', 'view', 'format', 'lang', 'Itemid', 'template', 'templateStyle', 'task'], function ($systemVariable) use ($input) { return $input->exists($systemVariable) && \is_array($input->getRaw($systemVariable)); } ); // Unset invalid system variables foreach ($invalidInputVariables as $systemVariable) { $input->set($systemVariable, null); } // Stop when there are invalid variables if ($invalidInputVariables) { throw new \RuntimeException('Invalid input, aborting application.'); } } /** * Execute the application. * * @return void * * @since 3.2 */ public function execute() { try { $this->sanityCheckSystemVariables(); $this->setupLogging(); $this->createExtensionNamespaceMap(); // Perform application routines. $this->doExecute(); // If we have an application document object, render it. if ($this->document instanceof \Joomla\CMS\Document\Document) { // Render the application output. $this->render(); } // If gzip compression is enabled in configuration and the server is compliant, compress the output. if ($this->get('gzip') && !\ini_get('zlib.output_compression') && \ini_get('output_handler') !== 'ob_gzhandler') { $this->compress(); // Trigger the onAfterCompress event. $this->dispatchEvent( 'onAfterCompress', new AfterCompressEvent('onAfterCompress', ['subject' => $this]) ); } } catch (\Throwable $throwable) { $event = new ErrorEvent( 'onError', [ 'subject' => $throwable, 'application' => $this, ] ); // Trigger the onError event. $this->dispatchEvent('onError', $event); ExceptionHandler::handleException($event->getError()); } // Trigger the onBeforeRespond event. $this->dispatchEvent( 'onBeforeRespond', new BeforeRespondEvent('onBeforeRespond', ['subject' => $this]) ); // Send the application response. $this->respond(); // Trigger the onAfterRespond event. $this->dispatchEvent( 'onAfterRespond', new AfterRespondEvent('onAfterRespond', ['subject' => $this]) ); } /** * Check if the user is required to reset their password. * * If the user is required to reset their password will be redirected to the page that manage the password reset. * * @param string $option The option that manage the password reset * @param string $view The view that manage the password reset * @param string $layout The layout of the view that manage the password reset * @param string $tasks Permitted tasks * * @return void * * @throws \Exception * @deprecated 5.2.3 will be removed in 7.0 * Use $this->checkUserRequiresReset() instead. */ protected function checkUserRequireReset($option, $view, $layout, $tasks) { $name = $this->getName(); $urls = []; if ($this->get($name . '_reset_password_override', 0)) { $tasks = $this->get($name . '_reset_password_tasks', ''); } // Check task if (!empty($tasks)) { $tasks = explode(',', $tasks); foreach ($tasks as $task) { [$option, $t] = explode('/', $task); $urls[] = ['option' => $option, 'task' => $t]; } } $this->checkUserRequiresReset($option, $view, $layout, $urls); } /** * Check if the user is required to reset their password. * * If the user is required to reset their password will be redirected to the page that manage the password reset. * * @param string $option The option that manage the password reset * @param string $view The view that manage the password reset * @param string $layout The layout of the view that manage the password reset * @param array $urls Multi-dimensional array of permitted urls. Ex: [['option' => 'com_users', 'view' => 'profile'],...] * * @return void * * @throws \Exception */ protected function checkUserRequiresReset($option, $view, $layout, $urls = []) { // Password reset is not required for the user, no need to check it further if (!$this->getIdentity()->requireReset) { return; } /* * By default user profile edit page is used. * That page allows you to change more than just the password and might not be the desired behavior. * This allows a developer to override the page that manage the password reset. * (can be configured using the file: configuration.php, or if extended, through the global configuration form) */ $name = $this->getName(); if ($this->get($name . '_reset_password_override', 0)) { $option = $this->get($name . '_reset_password_option', ''); $view = $this->get($name . '_reset_password_view', ''); $layout = $this->get($name . '_reset_password_layout', ''); $urls = $this->get($name . '_reset_password_urls', $urls); } /** * The page which manage password reset always need to accessible, so if the current page * is managing password reset page, no need to check it further */ if ( $this->input->getCmd('option', '') === $option && $this->input->getCmd('view', '') === $view && $this->input->getCmd('layout', '') == $layout ) { return; } // If the current URL matches an entry in $urls, we do not redirect foreach ($urls as $url) { $match = true; foreach ($url as $key => $value) { if ($this->input->getCmd($key) !== $value) { /** * The current URL does not meet this entry, get out of this loop * and check next entry */ $match = false; break; } } // The current URL meet the entry, no redirect is needed, just return early if ($match) { return; } } // Redirect to the profile edit page $this->enqueueMessage(Text::_('JGLOBAL_PASSWORD_RESET_REQUIRED'), 'notice'); $url = Route::_('index.php?option=' . $option . '&view=' . $view . '&layout=' . $layout, false); // In the administrator we need a different URL if ($this->isClient('administrator')) { $user = $this->getIdentity(); $url = Route::_( 'index.php?option=' . $option . '&task=' . $view . '.' . $layout . '&id=' . $user->id, false ); } $this->redirect($url); } /** * Gets a configuration value. * * @param string $varname The name of the value to get. * @param string $default Default value to return * * @return mixed The user state. * * @since 3.2 * * @deprecated 3.2 will be removed in 6.0 * Use get() instead * Example: Factory::getApplication()->get($varname, $default); */ public function getCfg($varname, $default = null) { try { Log::add( \sprintf('%s() is deprecated and will be removed in 6.0. Use Factory->getApplication()->get() instead.', __METHOD__), Log::WARNING, 'deprecated' ); } catch (\RuntimeException) { // Informational log only } return $this->get($varname, $default); } /** * Gets the client id of the current running application. * * @return integer A client identifier. * * @since 3.2 */ public function getClientId() { return $this->clientId; } /** * Returns a reference to the global CmsApplication object, only creating it if it doesn't already exist. * * This method must be invoked as: $web = CmsApplication::getInstance(); * * @param string $name The name (optional) of the CmsApplication class to instantiate. * @param string $prefix The class name prefix of the object. * @param ?Container $container An optional dependency injection container to inject into the application. * * @return CmsApplication * * @since 3.2 * @throws \RuntimeException * @deprecated 4.0 will be removed in 6.0 * Use the application service from the DI container instead * Example: Factory::getContainer()->get($name); */ public static function getInstance($name = null, $prefix = '\JApplication', ?Container $container = null) { if (empty(static::$instances[$name])) { // Create a CmsApplication object. $classname = $prefix . ucfirst($name); if (!$container) { $container = Factory::getContainer(); } if ($container->has($classname)) { static::$instances[$name] = $container->get($classname); } elseif (class_exists($classname)) { // @todo This creates an implicit hard requirement on the ApplicationCms constructor static::$instances[$name] = new $classname(null, null, null, $container); } else { throw new \RuntimeException(Text::sprintf('JLIB_APPLICATION_ERROR_APPLICATION_LOAD', $name), 500); } static::$instances[$name]->loadIdentity(Factory::getUser()); } return static::$instances[$name]; } /** * Returns the application \JMenu object. * * @param string $name The name of the application/client. * @param array $options An optional associative array of configuration settings. * * @return AbstractMenu * * @since 3.2 */ public function getMenu($name = null, $options = []) { if (!isset($name)) { $name = $this->getName(); } // Inject this application object into the \JMenu tree if one isn't already specified if (!isset($options['app'])) { $options['app'] = $this; } if (\array_key_exists($name, $this->menus)) { return $this->menus[$name]; } if ($this->menuFactory === null) { @trigger_error('Menu factory must be set in 5.0', E_USER_DEPRECATED); $this->menuFactory = $this->getContainer()->get(MenuFactoryInterface::class); } $this->menus[$name] = $this->menuFactory->createMenu($name, $options); // Make sure the abstract menu has the instance too, is needed for BC and will be removed with version 5 AbstractMenu::$instances[$name] = $this->menus[$name]; return $this->menus[$name]; } /** * Get the system message queue. * * @param boolean $clear Clear the messages currently attached to the application object * * @return array The system message queue. * * @since 3.2 */ public function getMessageQueue($clear = false) { // For empty queue, if messages exists in the session, enqueue them. if (!\count($this->messageQueue)) { $sessionQueue = $this->getSession()->get('application.queue', []); if ($sessionQueue) { $this->messageQueue = $sessionQueue; $this->getSession()->set('application.queue', []); } } $messageQueue = $this->messageQueue; if ($clear) { $this->messageQueue = []; } return $messageQueue; } /** * Gets the name of the current running application. * * @return string The name of the application. * * @since 3.2 */ public function getName() { return $this->name; } /** * Returns the application Pathway object. * * @return Pathway * * @since 3.2 */ public function getPathway() { if (!$this->pathway) { $resourceName = ucfirst($this->getName()) . 'Pathway'; if (!$this->getContainer()->has($resourceName)) { throw new \RuntimeException( Text::sprintf('JLIB_APPLICATION_ERROR_PATHWAY_LOAD', $this->getName()), 500 ); } $this->pathway = $this->getContainer()->get($resourceName); } return $this->pathway; } /** * Returns the application Router object. * * @param string $name The name of the application. * @param array $options An optional associative array of configuration settings. * * @return Router * * @since 3.2 * * @deprecated 4.3 will be removed in 6.0 * Inject the router or load it from the dependency injection container * Example: Factory::getContainer()->get($name); */ public static function getRouter($name = null, array $options = []) { $app = Factory::getApplication(); if (!isset($name)) { $name = $app->getName(); } $options['mode'] = $app->get('sef'); return Router::getInstance($name, $options); } /** * Gets the name of the current template. * * @param boolean $params An optional associative array of configuration settings * * @return string|\stdClass The name of the template if the params argument is false. The template object if the params argument is true. * * @since 3.2 */ public function getTemplate($params = false) { if ($params) { $template = new \stdClass(); $template->template = 'system'; $template->params = new Registry(); $template->inheritable = 0; $template->parent = ''; return $template; } return 'system'; } /** * Gets a user state. * * @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. * * @since 3.2 */ public function getUserState($key, $default = null) { $registry = $this->getSession()->get('registry'); if ($registry !== null) { return $registry->get($key, $default); } return $default; } /** * 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. Optional. * @see \Joomla\CMS\Filter\InputFilter::clean() for valid values. * * @return mixed The request user state. * * @since 3.2 */ public function getUserStateFromRequest($key, $request, $default = null, $type = 'none') { $cur_state = $this->getUserState($key, $default); $new_state = $this->input->get($request, null, $type); if ($new_state === null) { return $cur_state; } // Save the new value only if it was set in this request. $this->setUserState($key, $new_state); return $new_state; } /** * Initialise the application. * * @param array $options An optional associative array of configuration settings. * * @return void * * @since 3.2 */ protected function initialiseApp($options = []) { // Check that we were given a language in the array (since by default may be blank). if (isset($options['language'])) { $this->set('language', $options['language']); } // Build our language object $lang = $this->getContainer()->get(LanguageFactoryInterface::class)->createLanguage($this->get('language'), $this->get('debug_lang')); // Load the language to the API $this->loadLanguage($lang); // Register the language object with Factory Factory::$language = $this->getLanguage(); // Load the library language files $this->loadLibraryLanguage(); // Set user specific editor. $user = Factory::getUser(); $editor = $user->getParam('editor', $this->get('editor')); if (!PluginHelper::isEnabled('editors', $editor)) { $editor = $this->get('editor'); if (!PluginHelper::isEnabled('editors', $editor)) { $editor = 'none'; } } $this->set('editor', $editor); // Load the behaviour plugins PluginHelper::importPlugin('behaviour', null, true, $this->getDispatcher()); // Trigger the onAfterInitialise event. PluginHelper::importPlugin('system', null, true, $this->getDispatcher()); $this->dispatchEvent( 'onAfterInitialise', new AfterInitialiseEvent('onAfterInitialise', ['subject' => $this]) ); } /** * Checks if HTTPS is forced in the client configuration. * * @param integer $clientId An optional client id (defaults to current application client). * * @return boolean True if is forced for the client, false otherwise. * * @since 3.7.3 */ public function isHttpsForced($clientId = null) { $clientId = (int) ($clientId ?? $this->getClientId()); $forceSsl = (int) $this->get('force_ssl'); if ($clientId === 0 && $forceSsl === 2) { return true; } if ($clientId === 1 && $forceSsl >= 1) { return true; } return false; } /** * Check the client interface by name. * * @param string $identifier String identifier for the application interface * * @return boolean True if this application is of the given type client interface. * * @since 3.7.0 */ public function isClient($identifier) { return $this->getName() === $identifier; } /** * Load the library language files for the application * * @return void * * @since 3.6.3 */ protected function loadLibraryLanguage() { $this->getLanguage()->load('lib_joomla', JPATH_ADMINISTRATOR); } /** * 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 * the user details. * * @param array $credentials Array('username' => string, 'password' => string) * @param array $options Array('remember' => boolean) * * @return boolean|\Exception True on success, false if failed or silent handling is configured, or a \Exception object on authentication error. * * @since 3.2 */ public function login($credentials, $options = []) { // Get the global Authentication object. $authenticate = Authentication::getInstance($this->authenticationPluginType); $response = $authenticate->authenticate($credentials, $options); $dispatcher = $this->getDispatcher(); // Import the user plugin group. PluginHelper::importPlugin('user', null, true, $dispatcher); if ($response->status === Authentication::STATUS_SUCCESS) { /* * 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); $denied_states = Authentication::STATUS_EXPIRED | Authentication::STATUS_DENIED; foreach ($authorisations as $authorisation) { if ((int) $authorisation->status & $denied_states) { // Trigger onUserAuthorisationFailure Event. $dispatcher->dispatch('onUserAuthorisationFailure', new AuthorisationFailureEvent('onUserAuthorisationFailure', [ 'subject' => (array) $authorisation, 'options' => $options, ])); // If silent is set, just return false. if (isset($options['silent']) && $options['silent']) { return false; } // Return the error. switch ($authorisation->status) { case Authentication::STATUS_EXPIRED: $this->enqueueMessage(Text::_('JLIB_LOGIN_EXPIRED'), 'error'); return false; case Authentication::STATUS_DENIED: $this->enqueueMessage(Text::_('JLIB_LOGIN_DENIED'), 'error'); return false; default: $this->enqueueMessage(Text::_('JLIB_LOGIN_AUTHORISATION'), 'error'); return false; } } } // OK, the credentials are authenticated and user is authorised. Let's fire the onLogin event. $loginEvent = new LoginEvent('onUserLogin', ['subject' => (array) $response, 'options' => $options]); $dispatcher->dispatch('onUserLogin', $loginEvent); $results = $loginEvent['result'] ?? []; /* * 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. */ $user = Factory::getUser(); if ($response->type === 'Cookie') { $user->cookieLogin = true; } if (!\in_array(false, $results, true)) { $options['user'] = $user; $options['responseType'] = $response->type; // The user is successfully logged in. Run the after login events $dispatcher->dispatch('onUserAfterLogin', new AfterLoginEvent('onUserAfterLogin', [ 'options' => $options, 'subject' => (array) $response, ])); return true; } } // Trigger onUserLoginFailure Event. $dispatcher->dispatch('onUserLoginFailure', new LoginFailureEvent('onUserLoginFailure', [ 'subject' => (array) $response, 'options' => $options, ])); // If silent is set, just return false. if (isset($options['silent']) && $options['silent']) { return false; } // If status is success, any error will have been raised by the user plugin if ($response->status !== Authentication::STATUS_SUCCESS) { $this->getLogger()->warning($response->error_message, ['category' => 'jerror']); } return false; } /** * 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 * * @since 3.2 */ public function logout($userid = null, $options = []) { // Get a user object from the Application. $user = Factory::getUser($userid); $dispatcher = $this->getDispatcher(); // Build the credentials array. $parameters = [ 'username' => $user->username, 'id' => $user->id, ]; // Set clientid in the options array if it hasn't been set already and shared sessions are not enabled. if (!$this->get('shared_session', '0') && !isset($options['clientid'])) { $options['clientid'] = $this->getClientId(); } // Import the user plugin group. PluginHelper::importPlugin('user', null, true, $dispatcher); // OK, the credentials are built. Lets fire the onLogout event. $logoutEvent = new LogoutEvent('onUserLogout', ['subject' => $parameters, 'options' => $options]); $dispatcher->dispatch('onUserLogout', $logoutEvent); $results = $logoutEvent['result'] ?? []; // Check if any of the plugins failed. If none did, success. if (!\in_array(false, $results, true)) { $options['username'] = $user->username; $dispatcher->dispatch('onUserAfterLogout', new AfterLogoutEvent('onUserAfterLogout', [ 'options' => $options, 'subject' => $parameters, ])); return true; } // Trigger onUserLogoutFailure Event. $dispatcher->dispatch('onUserLogoutFailure', new LogoutFailureEvent('onUserLogoutFailure', [ 'subject' => $parameters, 'options' => $options, ])); return false; } /** * Redirect to another URL. * * If the headers have not been sent the redirect will be accomplished using a "301 Moved Permanently" * or "303 See Other" 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 integer $status The HTTP 1.1 status code to be provided. 303 is assumed by default. * * @return void * * @since 3.2 */ public function redirect($url, $status = 303) { // Persist messages if they exist. if (\count($this->messageQueue)) { $this->getSession()->set('application.queue', $this->messageQueue); } // Hand over processing to the parent now parent::redirect($url, $status); } /** * Rendering is the process of pushing the document buffers into the template * placeholders, retrieving data from the document and pushing it into * the application response buffer. * * @return void * * @since 3.2 */ protected function render() { // Setup the document options. $this->docOptions['template'] = $this->get('theme'); $this->docOptions['file'] = $this->get('themeFile', 'index.php'); $this->docOptions['params'] = $this->get('themeParams'); $this->docOptions['csp_nonce'] = $this->get('csp_nonce'); $this->docOptions['templateInherits'] = $this->get('themeInherits'); if ($this->get('themes.base')) { $this->docOptions['directory'] = $this->get('themes.base'); } else { // Fall back to constants. $this->docOptions['directory'] = \defined('JPATH_THEMES') ? JPATH_THEMES : (\defined('JPATH_BASE') ? JPATH_BASE : __DIR__) . '/themes'; } // Parse the document. $this->document->parse($this->docOptions); // Trigger the onBeforeRender event. PluginHelper::importPlugin('system', null, true, $this->getDispatcher()); $this->dispatchEvent( 'onBeforeRender', new BeforeRenderEvent('onBeforeRender', ['subject' => $this]) ); $caching = false; if ($this->isClient('site') && $this->get('caching') && $this->get('caching', 2) == 2 && !$this->getIdentity()->id) { $caching = true; } // Render the document. $data = $this->document->render($caching, $this->docOptions); // Set the application output data. $this->setBody($data); // Trigger the onAfterRender event. $this->dispatchEvent( 'onAfterRender', new AfterRenderEvent('onAfterRender', ['subject' => $this]) ); // Mark afterRender in the profiler. JDEBUG ? $this->profiler->mark('afterRender') : null; } /** * Route the application. * * 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 * dispatched. * * @return void * * @since 3.2 * * @deprecated 4.0 will be removed in 6.0 * Implement the route functionality in the extending class, this here will be removed without replacement */ protected function route() { // Get the full request URI. $uri = clone Uri::getInstance(); $router = static::getRouter(); $result = $router->parse($uri, true); $active = $this->getMenu()->getActive(); if ( $active !== null && $active->type === 'alias' && $active->getParams()->get('alias_redirect') && \in_array($this->input->getMethod(), ['GET', 'HEAD'], true) ) { $item = $this->getMenu()->getItem($active->getParams()->get('aliasoptions')); if ($item !== null) { $oldUri = clone Uri::getInstance(); if ($oldUri->getVar('Itemid') == $active->id) { $oldUri->setVar('Itemid', $item->id); } $base = Uri::base(true); $oldPath = StringHelper::strtolower(substr($oldUri->getPath(), \strlen($base) + 1)); $activePathPrefix = StringHelper::strtolower($active->route); $position = strpos($oldPath, $activePathPrefix); if ($position !== false) { $oldUri->setPath($base . '/' . substr_replace($oldPath, $item->route, $position, \strlen($activePathPrefix))); $this->setHeader('Expires', 'Wed, 17 Aug 2005 00:00:00 GMT', true); $this->setHeader('Last-Modified', gmdate('D, d M Y H:i:s') . ' GMT', true); $this->setHeader('Cache-Control', 'no-store, no-cache, must-revalidate', false); $this->sendHeaders(); $this->redirect((string) $oldUri, 301); } } } foreach ($result as $key => $value) { $this->input->def($key, $value); } // Trigger the onAfterRoute event. PluginHelper::importPlugin('system', null, true, $this->getDispatcher()); $this->dispatchEvent( 'onAfterRoute', new AfterRouteEvent('onAfterRoute', ['subject' => $this]) ); } /** * Sets the value of a user state variable. * * @param string $key The path of the state. * @param mixed $value The value of the variable. * * @return mixed The previous state, if one existed. Null otherwise. * * @since 3.2 */ public function setUserState($key, $value) { $session = $this->getSession(); $registry = $session->get('registry'); if ($registry !== null) { return $registry->set($key, $value); } return null; } /** * Sends all headers prior to returning the string * * @param boolean $compress If true, compress the data * * @return string * * @since 3.2 */ public function toString($compress = false) { // Don't compress something if the server is going to do it anyway. Waste of time. if ($compress && !\ini_get('zlib.output_compression') && \ini_get('output_handler') !== 'ob_gzhandler') { $this->compress(); } if ($this->allowCache() === false) { $this->setHeader('Cache-Control', 'no-cache', false); } $this->sendHeaders(); return $this->getBody(); } /** * Method to determine a hash for anti-spoofing variable names * * @param boolean $forceNew If true, force a new token to be created * * @return string Hashed var name * * @since 4.0.0 */ public function getFormToken($forceNew = false) { /** @var Session $session */ $session = $this->getSession(); return $session::getFormToken($forceNew); } /** * Checks for a form token in the request. * * Use in conjunction with getFormToken. * * @param string $method The request method in which to look for the token key. * * @return boolean True if found and valid, false otherwise. * * @since 4.0.0 */ public function checkToken($method = 'post') { /** @var Session $session */ $session = $this->getSession(); return $session::checkToken($method); } /** * Flag if the application instance is a CLI or web based application. * * Helper function, you should use the native PHP functions to detect if it is a CLI application. * * @return boolean * * @since 4.0.0 * * @deprecated 4.0 will be removed in 6.0 * Will be removed without replacements */ public function isCli() { return false; } /** * No longer used * * @return boolean * * @since 4.0.0 * * @throws \Exception * * @deprecated 4.2 will be removed in 6.0 * Will be removed without replacements */ protected function isTwoFactorAuthenticationRequired(): bool { return false; } /** * No longer used * * @return boolean * * @since 4.0.0 * * @throws \Exception * * @deprecated 4.2 will be removed in 6.0 * Will be removed without replacements */ private function hasUserConfiguredTwoFactorAuthentication(): bool { return false; } /** * Setup logging functionality. * * @return void * * @since 4.0.0 */ private function setupLogging(): void { // Add InMemory logger that will collect all log entries to allow to display them later by extensions if ($this->get('debug')) { Log::addLogger(['logger' => 'inmemory']); } // Log the deprecated API. if ($this->get('log_deprecated')) { Log::addLogger(['text_file' => 'deprecated.php'], Log::ALL, ['deprecated']); } // We only log errors unless Site Debug is enabled $logLevels = Log::ERROR | Log::CRITICAL | Log::ALERT | Log::EMERGENCY; if ($this->get('debug')) { $logLevels = Log::ALL; } Log::addLogger(['text_file' => 'joomla_core_errors.php'], $logLevels, ['system']); // Log everything (except deprecated APIs, these are logged separately with the option above). if ($this->get('log_everything')) { Log::addLogger(['text_file' => 'everything.php'], Log::ALL, ['deprecated', 'deprecation-notes', 'databasequery'], true); } if ($this->get('log_categories')) { $priority = 0; foreach ($this->get('log_priorities', ['all']) as $p) { $const = '\\Joomla\\CMS\\Log\\Log::' . strtoupper($p); if (\defined($const)) { $priority |= \constant($const); } } // Split into an array at any character other than alphabet, numbers, _, ., or - $categories = preg_split('/[^\w.-]+/', $this->get('log_categories', ''), -1, PREG_SPLIT_NO_EMPTY); $mode = (bool) $this->get('log_category_mode', false); if (!$categories) { return; } Log::addLogger(['text_file' => 'custom-logging.php'], $priority, $categories, $mode); } } /** * Sets the internal menu factory. * * @param MenuFactoryInterface $menuFactory The menu factory * * @return void * * @since 4.2.0 */ public function setMenuFactory(MenuFactoryInterface $menuFactory): void { $this->menuFactory = $menuFactory; } } PK #�\���s s DaemonApplication.phpnu �[��� <?php /** * Joomla! Content Management System * * @copyright (C) 2012 Open Source Matters, Inc. <https://www.joomla.org> * @license GNU General Public License version 2 or later; see LICENSE.txt */ namespace Joomla\CMS\Application; use Joomla\CMS\Event\Application\AfterExecuteEvent; use Joomla\CMS\Event\Application\BeforeExecuteEvent; use Joomla\CMS\Event\Application\DaemonForkEvent; use Joomla\CMS\Event\Application\DaemonReceiveSignalEvent; use Joomla\CMS\Input\Cli; use Joomla\CMS\Log\Log; use Joomla\Event\DispatcherInterface; use Joomla\Filesystem\Folder; use Joomla\Registry\Registry; // phpcs:disable PSR1.Files.SideEffects \defined('_JEXEC') or die; // phpcs:enable PSR1.Files.SideEffects /** * Class to turn CliApplication applications into daemons. It requires CLI and PCNTL support built into PHP. * * @link https://www.php.net/manual/en/book.pcntl.php * @link https://www.php.net/manual/en/features.commandline.php * @since 1.7.0 */ abstract class DaemonApplication extends CliApplication { /** * @var array The available POSIX signals to be caught by default. * @link https://www.php.net/manual/pcntl.constants.php * @since 1.7.0 */ protected static $signals = [ 'SIGHUP', 'SIGINT', 'SIGQUIT', 'SIGILL', 'SIGTRAP', 'SIGABRT', 'SIGIOT', 'SIGBUS', 'SIGFPE', 'SIGUSR1', 'SIGSEGV', 'SIGUSR2', 'SIGPIPE', 'SIGALRM', 'SIGTERM', 'SIGSTKFLT', 'SIGCLD', 'SIGCHLD', 'SIGCONT', 'SIGTSTP', 'SIGTTIN', 'SIGTTOU', 'SIGURG', 'SIGXCPU', 'SIGXFSZ', 'SIGVTALRM', 'SIGPROF', 'SIGWINCH', 'SIGPOLL', 'SIGIO', 'SIGPWR', 'SIGSYS', 'SIGBABY', 'SIG_BLOCK', 'SIG_UNBLOCK', 'SIG_SETMASK', ]; /** * @var boolean True if the daemon is in the process of exiting. * @since 1.7.0 */ protected $exiting = false; /** * @var integer The parent process id. * @since 3.0.0 */ protected $parentId = 0; /** * @var integer The process id of the daemon. * @since 1.7.0 */ protected $processId = 0; /** * @var boolean True if the daemon is currently running. * @since 1.7.0 */ protected $running = false; /** * Class constructor. * * @param ?Cli $input An optional argument to provide dependency injection for the application's * input object. If the argument is a JInputCli object that object will become * the application's input object, otherwise a default input object is created. * @param ?Registry $config An optional argument to provide dependency injection for the application's * config object. If the argument is a Registry object that object will become * the application's config object, otherwise a default config object is created. * @param ?DispatcherInterface $dispatcher An optional argument to provide dependency injection for the application's * event dispatcher. If the argument is a DispatcherInterface object that object will become * the application's event dispatcher, if it is null then the default event dispatcher * will be created based on the application's loadDispatcher() method. * * @since 1.7.0 */ public function __construct(?Cli $input = null, ?Registry $config = null, ?DispatcherInterface $dispatcher = null) { // Verify that the process control extension for PHP is available. if (!\defined('SIGHUP')) { Log::add('The PCNTL extension for PHP is not available.', Log::ERROR); throw new \RuntimeException('The PCNTL extension for PHP is not available.'); } // Verify that POSIX support for PHP is available. if (!\function_exists('posix_getpid')) { Log::add('The POSIX extension for PHP is not available.', Log::ERROR); throw new \RuntimeException('The POSIX extension for PHP is not available.'); } // Call the parent constructor. parent::__construct($input, $config, null, null, $dispatcher); // Set some system limits. if (\function_exists('set_time_limit')) { set_time_limit($this->config->get('max_execution_time', 0)); } if ($this->config->get('max_memory_limit') !== null) { ini_set('memory_limit', $this->config->get('max_memory_limit', '256M')); } // Flush content immediately. ob_implicit_flush(); } /** * Method to handle POSIX signals. * * @param integer $signal The received POSIX signal. * * @return void * * @since 1.7.0 * @see pcntl_signal() * @throws \RuntimeException */ public static function signal($signal) { // Log all signals sent to the daemon. Log::add('Received signal: ' . $signal, Log::DEBUG); // Let's make sure we have an application instance. if (!is_subclass_of(static::$instance, CliApplication::class)) { Log::add('Cannot find the application instance.', Log::EMERGENCY); throw new \RuntimeException('Cannot find the application instance.'); } // Fire the onReceiveSignal event. static::$instance->getDispatcher()->dispatch( 'onReceiveSignal', new DaemonReceiveSignalEvent('onReceiveSignal', [ 'signal' => $signal, 'subject' => static::$instance, ]) ); switch ($signal) { case SIGINT: case SIGTERM: // Handle shutdown tasks if (static::$instance->running && static::$instance->isActive()) { static::$instance->shutdown(); } else { static::$instance->close(); } break; case SIGHUP: // Handle restart tasks if (static::$instance->running && static::$instance->isActive()) { static::$instance->shutdown(true); } else { static::$instance->close(); } break; case SIGCHLD: // A child process has died while (static::$instance->pcntlWait($signal, WNOHANG || WUNTRACED) > 0) { usleep(1000); } break; case SIGCLD: while (static::$instance->pcntlWait($signal, WNOHANG) > 0) { $signal = static::$instance->pcntlChildExitStatus($signal); } break; default: break; } } /** * Check to see if the daemon is active. This does not assume that $this daemon is active, but * only if an instance of the application is active as a daemon. * * @return boolean True if daemon is active. * * @since 1.7.0 */ public function isActive() { // Get the process id file location for the application. $pidFile = $this->config->get('application_pid_file'); // If the process id file doesn't exist then the daemon is obviously not running. if (!is_file($pidFile)) { return false; } // Read the contents of the process id file as an integer. $fp = fopen($pidFile, 'r'); $pid = fread($fp, filesize($pidFile)); $pid = (int) $pid; fclose($fp); // Check to make sure that the process id exists as a positive integer. if (!$pid) { return false; } // Check to make sure the process is active by pinging it and ensure it responds. if (!posix_kill($pid, 0)) { // No response so remove the process id file and log the situation. @ unlink($pidFile); Log::add('The process found based on PID file was unresponsive.', Log::WARNING); return false; } return true; } /** * Load an object or array into the application configuration object. * * @param mixed $data Either an array or object to be loaded into the configuration object. * * @return DaemonApplication Instance of $this to allow chaining. * * @since 1.7.0 */ public function loadConfiguration($data) { /* * Setup some application metadata options. This is useful if we ever want to write out startup scripts * or just have some sort of information available to share about things. */ // The application author name. This string is used in generating startup scripts and has // a maximum of 50 characters. $tmp = (string) $this->config->get('author_name', 'Joomla Platform'); $this->config->set('author_name', (\strlen($tmp) > 50) ? substr($tmp, 0, 50) : $tmp); // The application author email. This string is used in generating startup scripts. $tmp = (string) $this->config->get('author_email', 'admin@joomla.org'); $this->config->set('author_email', filter_var($tmp, FILTER_VALIDATE_EMAIL)); // The application name. This string is used in generating startup scripts. $tmp = (string) $this->config->get('application_name', 'DaemonApplication'); $this->config->set('application_name', (string) preg_replace('/[^A-Z0-9_-]/i', '', $tmp)); // The application description. This string is used in generating startup scripts. $tmp = (string) $this->config->get('application_description', 'A generic Joomla Platform application.'); $this->config->set('application_description', filter_var($tmp, FILTER_SANITIZE_STRING)); /* * Setup the application path options. This defines the default executable name, executable directory, * and also the path to the daemon process id file. */ // The application executable daemon. This string is used in generating startup scripts. $tmp = (string) $this->config->get('application_executable', basename($this->input->executable)); $this->config->set('application_executable', $tmp); // The home directory of the daemon. $tmp = (string) $this->config->get('application_directory', \dirname($this->input->executable)); $this->config->set('application_directory', $tmp); // The pid file location. This defaults to a path inside the /tmp directory. $name = $this->config->get('application_name'); $tmp = (string) $this->config->get('application_pid_file', strtolower('/tmp/' . $name . '/' . $name . '.pid')); $this->config->set('application_pid_file', $tmp); /* * Setup the application identity options. It is important to remember if the default of 0 is set for * either UID or GID then changing that setting will not be attempted as there is no real way to "change" * the identity of a process from some user to root. */ // The user id under which to run the daemon. $tmp = (int) $this->config->get('application_uid', 0); $options = ['options' => ['min_range' => 0, 'max_range' => 65000]]; $this->config->set('application_uid', filter_var($tmp, FILTER_VALIDATE_INT, $options)); // The group id under which to run the daemon. $tmp = (int) $this->config->get('application_gid', 0); $options = ['options' => ['min_range' => 0, 'max_range' => 65000]]; $this->config->set('application_gid', filter_var($tmp, FILTER_VALIDATE_INT, $options)); // Option to kill the daemon if it cannot switch to the chosen identity. $tmp = (bool) $this->config->get('application_require_identity', 1); $this->config->set('application_require_identity', $tmp); /* * Setup the application runtime options. By default our execution time limit is infinite obviously * because a daemon should be constantly running unless told otherwise. The default limit for memory * usage is 256M, which admittedly is a little high, but remember it is a "limit" and PHP's memory * management leaves a bit to be desired :-) */ // The maximum execution time of the application in seconds. Zero is infinite. $tmp = $this->config->get('max_execution_time'); if ($tmp !== null) { $this->config->set('max_execution_time', (int) $tmp); } // The maximum amount of memory the application can use. $tmp = $this->config->get('max_memory_limit', '256M'); if ($tmp !== null) { $this->config->set('max_memory_limit', (string) $tmp); } return $this; } /** * Execute the daemon. * * @return void * * @since 1.7.0 */ public function execute() { // Trigger the onBeforeExecute event $this->dispatchEvent( 'onBeforeExecute', new BeforeExecuteEvent('onBeforeExecute', ['subject' => $this, 'container' => $this->getContainer()]) ); // Enable basic garbage collection. gc_enable(); Log::add('Starting ' . $this->name, Log::INFO); // Set off the process for becoming a daemon. if ($this->daemonize()) { // Declare ticks to start signal monitoring. When you declare ticks, PCNTL will monitor // incoming signals after each tick and call the relevant signal handler automatically. declare(ticks=1); // Start the main execution loop. while (true) { // Perform basic garbage collection. $this->gc(); // Don't completely overload the CPU. usleep(1000); // Execute the main application logic. $this->doExecute(); } } else { // We were not able to daemonize the application so log the failure and die gracefully. Log::add('Starting ' . $this->name . ' failed', Log::INFO); } // Trigger the onAfterExecute event. $this->dispatchEvent( 'onAfterExecute', new AfterExecuteEvent('onAfterExecute', ['subject' => $this]) ); } /** * Restart daemon process. * * @return void * * @since 1.7.0 */ public function restart() { Log::add('Stopping ' . $this->name, Log::INFO); $this->shutdown(true); } /** * Stop daemon process. * * @return void * * @since 1.7.0 */ public function stop() { Log::add('Stopping ' . $this->name, Log::INFO); $this->shutdown(); } /** * Method to change the identity of the daemon process and resources. * * @return boolean True if identity successfully changed * * @since 1.7.0 * @see posix_setuid() */ protected function changeIdentity() { // Get the group and user ids to set for the daemon. $uid = (int) $this->config->get('application_uid', 0); $gid = (int) $this->config->get('application_gid', 0); // Get the application process id file path. $file = $this->config->get('application_pid_file'); // Change the user id for the process id file if necessary. if ($uid && (fileowner($file) != $uid) && (!@ chown($file, $uid))) { Log::add('Unable to change user ownership of the process id file.', Log::ERROR); return false; } // Change the group id for the process id file if necessary. if ($gid && (filegroup($file) != $gid) && (!@ chgrp($file, $gid))) { Log::add('Unable to change group ownership of the process id file.', Log::ERROR); return false; } // Set the correct home directory for the process. if ($uid && ($info = posix_getpwuid($uid)) && is_dir($info['dir'])) { system('export HOME="' . $info['dir'] . '"'); } // Change the user id for the process necessary. if ($uid && (posix_getuid() != $uid) && (!@ posix_setuid($uid))) { Log::add('Unable to change user ownership of the process.', Log::ERROR); return false; } // Change the group id for the process necessary. if ($gid && (posix_getgid() != $gid) && (!@ posix_setgid($gid))) { Log::add('Unable to change group ownership of the process.', Log::ERROR); return false; } // Get the user and group information based on uid and gid. $user = posix_getpwuid($uid); $group = posix_getgrgid($gid); Log::add('Changed daemon identity to ' . $user['name'] . ':' . $group['name'], Log::INFO); return true; } /** * Method to put the application into the background. * * @return boolean * * @since 1.7.0 * @throws \RuntimeException */ protected function daemonize() { // Is there already an active daemon running? if ($this->isActive()) { Log::add($this->name . ' daemon is still running. Exiting the application.', Log::EMERGENCY); return false; } // Reset Process Information $this->processId = 0; $this->running = false; // Detach process! try { // Check if we should run in the foreground. if (!$this->input->get('f')) { // Detach from the terminal. $this->detach(); } else { // Setup running values. $this->exiting = false; $this->running = true; // Set the process id. $this->processId = (int) posix_getpid(); $this->parentId = $this->processId; } } catch (\RuntimeException) { Log::add('Unable to fork.', Log::EMERGENCY); return false; } // Verify the process id is valid. if ($this->processId < 1) { Log::add('The process id is invalid; the fork failed.', Log::EMERGENCY); return false; } // Clear the umask. @ umask(0); // Write out the process id file for concurrency management. if (!$this->writeProcessIdFile()) { Log::add('Unable to write the pid file at: ' . $this->config->get('application_pid_file'), Log::EMERGENCY); return false; } // Attempt to change the identity of user running the process. if (!$this->changeIdentity()) { // If the identity change was required then we need to return false. if ($this->config->get('application_require_identity')) { Log::add('Unable to change process owner.', Log::CRITICAL); return false; } Log::add('Unable to change process owner.', Log::WARNING); } // Setup the signal handlers for the daemon. if (!$this->setupSignalHandlers()) { return false; } // Change the current working directory to the application working directory. @ chdir($this->config->get('application_directory')); return true; } /** * This is truly where the magic happens. This is where we fork the process and kill the parent * process, which is essentially what turns the application into a daemon. * * @return void * * @since 3.0.0 * @throws \RuntimeException */ protected function detach() { Log::add('Detaching the ' . $this->name . ' daemon.', Log::DEBUG); // Attempt to fork the process. $pid = $this->fork(); // If the pid is positive then we successfully forked, and can close this application. if ($pid) { // Add the log entry for debugging purposes and exit gracefully. Log::add('Ending ' . $this->name . ' parent process', Log::DEBUG); $this->close(); } else { // We are in the forked child process. // Setup some protected values. $this->exiting = false; $this->running = true; // Set the parent to self. $this->parentId = $this->processId; } } /** * Method to fork the process. * * @return integer The child process id to the parent process, zero to the child process. * * @since 1.7.0 * @throws \RuntimeException */ protected function fork() { // Attempt to fork the process. $pid = $this->pcntlFork(); // If the fork failed, throw an exception. if ($pid === -1) { throw new \RuntimeException('The process could not be forked.'); } if ($pid === 0) { // Update the process id for the child. $this->processId = (int) posix_getpid(); } else { // Log the fork in the parent. // Log the fork. Log::add('Process forked ' . $pid, Log::DEBUG); } // Trigger the onFork event. $this->postFork(); return $pid; } /** * Method to perform basic garbage collection and memory management in the sense of clearing the * stat cache. We will probably call this method pretty regularly in our main loop. * * @return void * * @since 1.7.0 */ protected function gc() { // Perform generic garbage collection. gc_collect_cycles(); // Clear the stat cache so it doesn't blow up memory. clearstatcache(); } /** * Method to attach the DaemonApplication signal handler to the known signals. Applications * can override these handlers by using the pcntl_signal() function and attaching a different * callback method. * * @return boolean * * @since 1.7.0 * @see pcntl_signal() */ protected function setupSignalHandlers() { // We add the error suppression for the loop because on some platforms some constants are not defined. foreach (self::$signals as $signal) { // Ignore signals that are not defined. if (!\defined($signal) || !\is_int(\constant($signal)) || (\constant($signal) === 0)) { // Define the signal to avoid notices. Log::add('Signal "' . $signal . '" not defined. Defining it as null.', Log::DEBUG); \define($signal, null); // Don't listen for signal. continue; } // Attach the signal handler for the signal. if (!$this->pcntlSignal(\constant($signal), ['DaemonApplication', 'signal'])) { Log::add(\sprintf('Unable to reroute signal handler: %s', $signal), Log::EMERGENCY); return false; } } return true; } /** * Method to shut down the daemon and optionally restart it. * * @param boolean $restart True to restart the daemon on exit. * * @return void * * @since 1.7.0 */ protected function shutdown($restart = false) { // If we are already exiting, chill. if ($this->exiting) { return; } // If not, now we are. $this->exiting = true; // If we aren't already daemonized then just kill the application. if (!$this->running && !$this->isActive()) { Log::add('Process was not daemonized yet, just halting current process', Log::INFO); $this->close(); } // Only read the pid for the parent file. if ($this->parentId == $this->processId) { // Read the contents of the process id file as an integer. $fp = fopen($this->config->get('application_pid_file'), 'r'); $pid = fread($fp, filesize($this->config->get('application_pid_file'))); $pid = (int) $pid; fclose($fp); // Remove the process id file. @ unlink($this->config->get('application_pid_file')); // If we are supposed to restart the daemon we need to execute the same command. if ($restart) { $this->close(exec(implode(' ', $GLOBALS['argv']) . ' > /dev/null &')); } else { // If we are not supposed to restart the daemon let's just kill -9. passthru('kill -9 ' . $pid); $this->close(); } } } /** * Method to write the process id file out to disk. * * @return boolean * * @since 1.7.0 */ protected function writeProcessIdFile() { // Verify the process id is valid. if ($this->processId < 1) { Log::add('The process id is invalid.', Log::EMERGENCY); return false; } // Get the application process id file path. $file = $this->config->get('application_pid_file'); if (empty($file)) { Log::add('The process id file path is empty.', Log::ERROR); return false; } // Make sure that the folder where we are writing the process id file exists. $folder = \dirname($file); if (!is_dir($folder) && !Folder::create($folder)) { Log::add('Unable to create directory: ' . $folder, Log::ERROR); return false; } // Write the process id file out to disk. if (!file_put_contents($file, $this->processId)) { Log::add('Unable to write process id file: ' . $file, Log::ERROR); return false; } // Make sure the permissions for the process id file are accurate. if (!chmod($file, 0644)) { Log::add('Unable to adjust permissions for the process id file: ' . $file, Log::ERROR); return false; } return true; } /** * Method to handle post-fork triggering of the onFork event. * * @return void * * @since 3.0.0 */ protected function postFork() { // Trigger the onFork event. $this->dispatchEvent( 'onFork', new DaemonForkEvent('onFork', ['subject' => $this]) ); } /** * Method to return the exit code of a terminated child process. * * @param integer $status The status parameter is the status parameter supplied to a successful call to pcntl_waitpid(). * * @return integer The child process exit code. * * @see pcntl_wexitstatus() * @since 1.7.3 */ protected function pcntlChildExitStatus($status) { return pcntl_wexitstatus($status); } /** * Method to return the exit code of a terminated child process. * * @return integer On success, the PID of the child process is returned in the parent's thread * of execution, and a 0 is returned in the child's thread of execution. On * failure, a -1 will be returned in the parent's context, no child process * will be created, and a PHP error is raised. * * @see pcntl_fork() * @since 1.7.3 */ protected function pcntlFork() { return pcntl_fork(); } /** * Method to install a signal handler. * * @param integer $signal The signal number. * @param callable $handler The signal handler which may be the name of a user created function, * or method, or either of the two global constants SIG_IGN or SIG_DFL. * @param boolean $restart Specifies whether system call restarting should be used when this * signal arrives. * * @return boolean True on success. * * @see pcntl_signal() * @since 1.7.3 */ protected function pcntlSignal($signal, $handler, $restart = true) { return pcntl_signal($signal, $handler, $restart); } /** * Method to wait on or return the status of a forked child. * * @param integer &$status Status information. * @param integer $options If wait3 is available on your system (mostly BSD-style systems), * you can provide the optional options parameter. * * @return integer The process ID of the child which exited, -1 on error or zero if WNOHANG * was provided as an option (on wait3-available systems) and no child was available. * * @see pcntl_wait() * @since 1.7.3 */ protected function pcntlWait(&$status, $options = 0) { return pcntl_wait($status, $options); } } PK #�\��X9 9 ApiApplication.phpnu �[��� <?php /** * Joomla! Content Management System * * @copyright (C) 2019 Open Source Matters, Inc. <https://www.joomla.org> * @license GNU General Public License version 2 or later; see LICENSE.txt */ namespace Joomla\CMS\Application; use Joomla\Application\Web\WebClient; use Joomla\CMS\Access\Exception\AuthenticationFailed; use Joomla\CMS\Component\ComponentHelper; use Joomla\CMS\Event\Application\AfterApiRouteEvent; use Joomla\CMS\Event\Application\AfterDispatchEvent; use Joomla\CMS\Event\Application\AfterInitialiseDocumentEvent; use Joomla\CMS\Event\Application\BeforeApiRouteEvent; use Joomla\CMS\Factory; use Joomla\CMS\Plugin\PluginHelper; use Joomla\CMS\Router\ApiRouter; use Joomla\CMS\Router\Exception\RouteNotFoundException; use Joomla\CMS\Uri\Uri; use Joomla\DI\Container; use Joomla\Input\Json as JInputJson; use Joomla\Registry\Registry; use Negotiation\Accept; use Negotiation\Exception\InvalidArgument; use Negotiation\Negotiator; // phpcs:disable PSR1.Files.SideEffects \defined('_JEXEC') or die; // phpcs:enable PSR1.Files.SideEffects /** * Joomla! API Application class * * @since 4.0.0 */ final class ApiApplication extends CMSApplication { /** * Maps extension types to their * * @var array * @since 4.0.0 */ protected $formatMapper = []; /** * The authentication plugin type * * @var string * @since 4.0.0 */ protected $authenticationPluginType = 'api-authentication'; /** * Class constructor. * * @param ?JInputJson $input An optional argument to provide dependency injection for the application's input * object. If the argument is a JInput object that object will become the * application's input object, otherwise a default input object is created. * @param ?Registry $config An optional argument to provide dependency injection for the application's config * object. If the argument is a Registry object that object will become the * application's config object, otherwise a default config object is created. * @param ?WebClient $client An optional argument to provide dependency injection for the application's client * object. If the argument is a WebClient object that object will become the * application's client object, otherwise a default client object is created. * @param ?Container $container Dependency injection container. * * @since 4.0.0 */ public function __construct(?JInputJson $input = null, ?Registry $config = null, ?WebClient $client = null, ?Container $container = null) { // Register the application name $this->name = 'api'; // Register the client ID $this->clientId = 3; // Execute the parent constructor parent::__construct($input, $config, $client, $container); $this->addFormatMap('application/json', 'json'); $this->addFormatMap('application/vnd.api+json', 'jsonapi'); // Set the root in the URI based on the application name Uri::root(null, str_ireplace('/' . $this->getName(), '', Uri::base(true))); } /** * Method to run the application routines. * * Most likely you will want to instantiate a controller and execute it, or perform some sort of task directly. * * @return void * * @since 4.0.0 */ protected function doExecute() { // Initialise the application $this->initialiseApp(); // Mark afterInitialise in the profiler. JDEBUG ? $this->profiler->mark('afterInitialise') : null; // Route the application $this->route(); // Mark afterApiRoute in the profiler. JDEBUG ? $this->profiler->mark('afterApiRoute') : null; // Dispatch the application $this->dispatch(); // Mark afterDispatch in the profiler. JDEBUG ? $this->profiler->mark('afterDispatch') : null; } /** * Adds a mapping from a content type to the format stored. Note the format type cannot be overwritten. * * @param string $contentHeader The content header * @param string $format The content type format * * @return void * * @since 4.0.0 */ public function addFormatMap($contentHeader, $format) { if (!\array_key_exists($contentHeader, $this->formatMapper)) { $this->formatMapper[$contentHeader] = $format; } } /** * Rendering is the process of pushing the document buffers into the template * placeholders, retrieving data from the document and pushing it into * the application response buffer. * * @return void * * @since 4.0.0 * * @note Rendering should be overridden to get rid of the theme files. */ protected function render() { // Render the document $this->setBody($this->document->render($this->allowCache())); } /** * Method to send the application response to the client. All headers will be sent prior to the main application output data. * * @param array $options An optional argument to enable CORS. (Temporary) * * @return void * * @since 4.0.0 */ protected function respond($options = []) { // Set the Joomla! API signature $this->setHeader('X-Powered-By', 'JoomlaAPI/1.0', true); $forceCORS = (int) $this->get('cors'); if ($forceCORS) { /** * Enable CORS (Cross-origin resource sharing) * Obtain allowed CORS origin from Global Settings. * Set to * (=all) if not set. */ $allowedOrigin = $this->get('cors_allow_origin', '*'); $this->setHeader('Access-Control-Allow-Origin', $allowedOrigin, true); $this->setHeader('Access-Control-Allow-Headers', 'Authorization'); if ($this->input->server->getString('HTTP_ORIGIN', null) !== null) { $this->setHeader('Access-Control-Allow-Origin', $this->input->server->getString('HTTP_ORIGIN'), true); $this->setHeader('Access-Control-Allow-Credentials', 'true', true); } } // Parent function can be overridden later on for debugging. parent::respond(); } /** * Gets the name of the current template. * * @param boolean $params True to return the template parameters * * @return string|\stdClass * * @since 4.0.0 */ public function getTemplate($params = false) { // The API application should not need to use a template if ($params) { $template = new \stdClass(); $template->template = 'system'; $template->params = new Registry(); $template->inheritable = 0; $template->parent = ''; return $template; } return 'system'; } /** * Route the application. * * 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 * dispatched. * * @return void * * @since 4.0.0 */ protected function route() { $router = $this->getContainer()->get(ApiRouter::class); // Trigger the onBeforeApiRoute event. PluginHelper::importPlugin('webservices', null, true, $this->getDispatcher()); $this->dispatchEvent( 'onBeforeApiRoute', new BeforeApiRouteEvent('onBeforeApiRoute', ['router' => $router, 'subject' => $this]) ); $caught404 = false; $method = $this->input->getMethod(); try { $this->handlePreflight($method, $router); $route = $router->parseApiRoute($method); } catch (RouteNotFoundException $e) { $caught404 = true; } /** * Now we have an API perform content negotiation to ensure we have a valid header. Assume if the route doesn't * tell us otherwise it uses the plain JSON API */ $priorities = ['application/vnd.api+json']; if (!$caught404 && \array_key_exists('format', $route['vars'])) { $priorities = $route['vars']['format']; } $negotiator = new Negotiator(); try { $mediaType = $negotiator->getBest($this->input->server->getString('HTTP_ACCEPT'), $priorities); } catch (InvalidArgument $e) { $mediaType = null; } // If we can't find a match bail with a 406 - Not Acceptable if ($mediaType === null) { throw new Exception\NotAcceptable('Could not match accept header', 406); } /** @var Accept $mediaType */ $format = $mediaType->getValue(); if (\array_key_exists($mediaType->getValue(), $this->formatMapper)) { $format = $this->formatMapper[$mediaType->getValue()]; } $this->input->set('format', $format); if ($caught404) { throw $e; } $this->input->set('controller', $route['controller']); $this->input->set('task', $route['task']); foreach ($route['vars'] as $key => $value) { // We inject the format directly above based on the negotiated format. We do not want the array of possible // formats provided by the plugin! if ($key === 'format') { continue; } // We inject the component key into the option parameter in global input for b/c with the other applications if ($key === 'component') { $this->input->set('option', $route['vars'][$key]); continue; } if ($this->input->getMethod() === 'POST') { $this->input->post->set($key, $value); } else { $this->input->set($key, $value); } } $this->dispatchEvent( 'onAfterApiRoute', new AfterApiRouteEvent('onAfterApiRoute', ['subject' => $this]) ); if (!isset($route['vars']['public']) || $route['vars']['public'] === false) { if (!$this->login(['username' => ''], ['silent' => true, 'action' => 'core.login.api'])) { throw new AuthenticationFailed(); } } } /** * Handles preflight requests. * * @param String $method The REST verb * * @param ApiRouter $router The API Routing object * * @return void * * @since 4.0.0 */ protected function handlePreflight($method, $router) { /** * If not an OPTIONS request or CORS is not enabled, * there's nothing useful to do here. */ if ($method !== 'OPTIONS' || !(int) $this->get('cors')) { return; } // Extract routes matching current route from all known routes. $matchingRoutes = $router->getMatchingRoutes(); // Extract exposed methods from matching routes. $matchingRoutesMethods = array_unique( array_reduce( $matchingRoutes, function ($carry, $route) { return array_merge($carry, $route->getMethods()); }, [] ) ); /** * Obtain allowed CORS origin from Global Settings. * Set to * (=all) if not set. */ $allowedOrigin = $this->get('cors_allow_origin', '*'); /** * Obtain allowed CORS headers from Global Settings. * Set to sensible default if not set. */ $allowedHeaders = $this->get('cors_allow_headers', 'Content-Type,X-Joomla-Token'); /** * Obtain allowed CORS methods from Global Settings. * Set to methods exposed by current route if not set. */ $allowedMethods = $this->get('cors_allow_methods', implode(',', $matchingRoutesMethods)); // No use to go through the regular route handling hassle, // so let's simply output the headers and exit. $this->setHeader('status', '204'); $this->setHeader('Access-Control-Allow-Origin', $allowedOrigin); $this->setHeader('Access-Control-Allow-Headers', $allowedHeaders); $this->setHeader('Access-Control-Allow-Methods', $allowedMethods); $this->sendHeaders(); $this->close(); } /** * Returns the application Router object. * * @return ApiRouter * * @since 4.0.0 * * @deprecated 4.3 will be removed in 6.0 * Inject the router or load it from the dependency injection container * Example: * Factory::getContainer()->get(ApiRouter::class); * */ public function getApiRouter() { return $this->getContainer()->get(ApiRouter::class); } /** * Dispatch the application * * @param string $component The component which is being rendered. * * @return void * * @since 4.0.0 */ public function dispatch($component = null) { // Get the component if not set. if (!$component) { $component = $this->input->get('option', null); } // Load the document to the API $this->loadDocument(); // Set up the params $document = Factory::getDocument(); // Trigger the onAfterInitialiseDocument event. PluginHelper::importPlugin('system', null, true, $this->getDispatcher()); $this->dispatchEvent( 'onAfterInitialiseDocument', new AfterInitialiseDocumentEvent('onAfterInitialiseDocument', ['subject' => $this, 'document' => $document]) ); $contents = ComponentHelper::renderComponent($component); $document->setBuffer($contents, ['type' => 'component']); // Trigger the onAfterDispatch event. $this->dispatchEvent( 'onAfterDispatch', new AfterDispatchEvent('onAfterDispatch', ['subject' => $this]) ); } } PK #�\��i� CMSApplicationInterface.phpnu �[��� <?php /** * Joomla! Content Management System * * @copyright (C) 2017 Open Source Matters, Inc. <https://www.joomla.org> * @license GNU General Public License version 2 or later; see LICENSE.txt */ namespace Joomla\CMS\Application; use Joomla\Application\ConfigurationAwareApplicationInterface; use Joomla\CMS\Extension\ExtensionManagerInterface; use Joomla\CMS\Language\Language; use Joomla\CMS\User\User; use Joomla\Input\Input; // phpcs:disable PSR1.Files.SideEffects \defined('_JEXEC') or die; // phpcs:enable PSR1.Files.SideEffects /** * Interface defining a Joomla! CMS Application class * * @since 4.0.0 * @note In Joomla 6 this interface will no longer extend EventAwareInterface * @property-read Input $input {@deprecated 4.0 will be removed in 6.0} The Joomla Input property. Deprecated in favour of getInput() */ interface CMSApplicationInterface extends ExtensionManagerInterface, ConfigurationAwareApplicationInterface, EventAwareInterface { /** * Constant defining an enqueued emergency message * * @var string * @since 4.0.0 */ public const MSG_EMERGENCY = 'emergency'; /** * Constant defining an enqueued alert message * * @var string * @since 4.0.0 */ public const MSG_ALERT = 'alert'; /** * Constant defining an enqueued critical message * * @var string * @since 4.0.0 */ public const MSG_CRITICAL = 'critical'; /** * Constant defining an enqueued error message * * @var string * @since 4.0.0 */ public const MSG_ERROR = 'error'; /** * Constant defining an enqueued warning message * * @var string * @since 4.0.0 */ public const MSG_WARNING = 'warning'; /** * Constant defining an enqueued notice message * * @var string * @since 4.0.0 */ public const MSG_NOTICE = 'notice'; /** * Constant defining an enqueued info message * * @var string * @since 4.0.0 */ public const MSG_INFO = 'info'; /** * Constant defining an enqueued debug message * * @var string * @since 4.0.0 */ public const MSG_DEBUG = 'debug'; /** * Constant defining an enqueued message message * * @var string * @since 5.4.2 */ public const MSG_MESSAGE = 'message'; /** * Constant defining an enqueued success message * * @var string * @since 5.4.2 */ public const MSG_SUCCESS = 'success'; /** * Enqueue a system message. * * @param string $msg The message to enqueue. * @param string $type The message type. * * @return void * * @since 4.0.0 */ public function enqueueMessage($msg, $type = self::MSG_INFO); /** * Get the system message queue. * * @return array The system message queue. * * @since 4.0.0 */ public function getMessageQueue(); /** * Check the client interface by name. * * @param string $identifier String identifier for the application interface * * @return boolean True if this application is of the given type client interface. * * @since 4.0.0 */ public function isClient($identifier); /** * Flag if the application instance is a CLI or web based application. * * Helper function, you should use the native PHP functions to detect if it is a CLI application. * * @return boolean * * @since 4.0.0 * * @deprecated 4.0 will be removed in 6.0 * Will be removed without replacement. CLI will be handled by the joomla/console package instead */ public function isCli(); /** * Get the application identity. * * @return User|null A User object or null if not set. * * @since 4.0.0 */ public function getIdentity(); /** * Method to get the application input object. * * @return Input * * @since 4.0.0 */ public function getInput(): Input; /** * Method to get the application language object. * * @return Language The language object * * @since 4.0.0 */ public function getLanguage(); /** * Gets the name of the current running application. * * @return string The name of the application. * * @since 4.0.0 */ public function getName(); /** * Allows the application to load a custom or default identity. * * @param ?User $identity An optional identity object. If omitted, the factory user is created. * * @return $this * * @since 4.0.0 */ public function loadIdentity(?User $identity = null); } PK #�\3�ɞz �z SiteApplication.phpnu �[��� <?php /** * Joomla! Content Management System * * @copyright (C) 2005 Open Source Matters, Inc. <https://www.joomla.org> * @license GNU General Public License version 2 or later; see LICENSE.txt */ namespace Joomla\CMS\Application; use Joomla\Application\Web\WebClient; use Joomla\CMS\Cache\CacheControllerFactoryAwareTrait; use Joomla\CMS\Cache\Controller\OutputController; use Joomla\CMS\Component\ComponentHelper; use Joomla\CMS\Event\Application\AfterDispatchEvent; use Joomla\CMS\Event\Application\AfterInitialiseDocumentEvent; use Joomla\CMS\Event\Application\AfterRouteEvent; use Joomla\CMS\Factory; use Joomla\CMS\Filter\InputFilter; use Joomla\CMS\Input\Input; use Joomla\CMS\Language\LanguageHelper; use Joomla\CMS\Language\Text; use Joomla\CMS\Plugin\PluginHelper; use Joomla\CMS\Router\Route; use Joomla\CMS\Router\SiteRouter; use Joomla\CMS\Uri\Uri; use Joomla\DI\Container; use Joomla\Registry\Registry; use Joomla\String\StringHelper; // phpcs:disable PSR1.Files.SideEffects \defined('_JEXEC') or die; // phpcs:enable PSR1.Files.SideEffects /** * Joomla! Site Application class * * @since 3.2 */ final class SiteApplication extends CMSApplication { use CacheControllerFactoryAwareTrait; use MultiFactorAuthenticationHandler; /** * Option to filter by language * * @var boolean * @since 4.0.0 */ protected $language_filter = false; /** * Option to detect language by the browser * * @var boolean * @since 4.0.0 */ protected $detect_browser = false; /** * The registered URL parameters. * * @var object * @since 4.3.0 */ public $registeredurlparams; /** * Class constructor. * * @param ?Input $input An optional argument to provide dependency injection for the application's input * object. If the argument is a JInput object that object will become the * application's input object, otherwise a default input object is created. * @param ?Registry $config An optional argument to provide dependency injection for the application's config * object. If the argument is a Registry object that object will become the * application's config object, otherwise a default config object is created. * @param ?WebClient $client An optional argument to provide dependency injection for the application's client * object. If the argument is a WebClient object that object will become the * application's client object, otherwise a default client object is created. * @param ?Container $container Dependency injection container. * * @since 3.2 */ public function __construct(?Input $input = null, ?Registry $config = null, ?WebClient $client = null, ?Container $container = null) { // Register the application name $this->name = 'site'; // Register the client ID $this->clientId = 0; // Execute the parent constructor parent::__construct($input, $config, $client, $container); } /** * Check if the user can access the application * * @param integer $itemid The item ID to check authorisation for * * @return void * * @since 3.2 * * @throws \Exception When you are not authorised to view the home page menu item */ protected function authorise($itemid) { $menus = $this->getMenu(); $user = Factory::getUser(); if (!$menus->authorise($itemid)) { if ($user->id == 0) { // Set the data $this->setUserState('users.login.form.data', ['return' => Uri::getInstance()->toString()]); $url = Route::_('index.php?option=com_users&view=login', false); $this->enqueueMessage(Text::_('JGLOBAL_YOU_MUST_LOGIN_FIRST'), 'error'); $this->redirect($url); } else { // Get the home page menu item $home_item = $menus->getDefault($this->getLanguage()->getTag()); // If we are already in the homepage raise an exception if ($menus->getActive()->id == $home_item->id) { throw new \Exception(Text::_('JERROR_ALERTNOAUTHOR'), 403); } // Otherwise redirect to the homepage and show an error $this->enqueueMessage(Text::_('JERROR_ALERTNOAUTHOR'), 'error'); $this->redirect(Route::_('index.php?Itemid=' . $home_item->id, false)); } } } /** * Dispatch the application * * @param string $component The component which is being rendered. * * @return void * * @since 3.2 */ public function dispatch($component = null) { // Get the component if not set. if (!$component) { $component = $this->input->getCmd('option', null); } // Load the document to the API $this->loadDocument(); // Set up the params $document = $this->getDocument(); $params = $this->getParams(); // Register the document object with Factory Factory::$document = $document; switch ($document->getType()) { case 'html': // Set up the language LanguageHelper::getLanguages('lang_code'); // Set metadata $document->setMetaData('rights', $this->get('MetaRights')); // Get the template $template = $this->getTemplate(true); // Store the template and its params to the config $this->set('theme', $template->template); $this->set('themeParams', $template->params); // Add Asset registry files $wr = $document->getWebAssetManager()->getRegistry(); if ($component) { $wr->addExtensionRegistryFile($component); } if ($template->parent) { $wr->addTemplateRegistryFile($template->parent, $this->getClientId()); } $wr->addTemplateRegistryFile($template->template, $this->getClientId()); break; case 'feed': $document->setBase(htmlspecialchars(Uri::current())); break; } $document->setTitle($params->get('page_title')); $document->setDescription($params->get('page_description')); // Add version number or not based on global configuration if ($this->get('MetaVersion', 0)) { $document->setGenerator('Joomla! - Open Source Content Management - Version ' . JVERSION); } else { $document->setGenerator('Joomla! - Open Source Content Management'); } // Trigger the onAfterInitialiseDocument event. PluginHelper::importPlugin('system', null, true, $this->getDispatcher()); $this->dispatchEvent( 'onAfterInitialiseDocument', new AfterInitialiseDocumentEvent('onAfterInitialiseDocument', ['subject' => $this, 'document' => $document]) ); $contents = ComponentHelper::renderComponent($component); $document->setBuffer($contents, ['type' => 'component']); // Trigger the onAfterDispatch event. $this->dispatchEvent( 'onAfterDispatch', new AfterDispatchEvent('onAfterDispatch', ['subject' => $this]) ); } /** * Method to run the Web application routines. * * @return void * * @since 3.2 */ protected function doExecute() { // Initialise the application $this->initialiseApp(); // Mark afterInitialise in the profiler. JDEBUG ? $this->profiler->mark('afterInitialise') : null; // Route the application $this->route(); // Mark afterRoute in the profiler. JDEBUG ? $this->profiler->mark('afterRoute') : null; if (!$this->isHandlingMultiFactorAuthentication()) { /* * Check if the user is required to reset their password * * Before $this->route(); "option" and "view" can't be safely read using: * $this->input->getCmd('option'); or $this->input->getCmd('view'); * ex: due of the sef urls */ $this->checkUserRequiresReset('com_users', 'profile', 'edit', [ ['option' => 'com_users', 'task' => 'profile.save'], ['option' => 'com_users', 'task' => 'profile.apply'], ['option' => 'com_users', 'task' => 'user.logout'], ['option' => 'com_users', 'task' => 'user.menulogout'], ['option' => 'com_users', 'task' => 'captive.validate'], ['option' => 'com_users', 'view' => 'captive'], ['option' => 'com_users', 'view' => 'methods'], ['option' => 'com_users', 'view' => 'method'], ['option' => 'com_users', 'task' => 'method.add'], ['option' => 'com_users', 'task' => 'method.save'], ]); } // Dispatch the application $this->dispatch(); // Mark afterDispatch in the profiler. JDEBUG ? $this->profiler->mark('afterDispatch') : null; } /** * Return the current state of the detect browser option. * * @return boolean * * @since 3.2 */ public function getDetectBrowser() { return $this->detect_browser; } /** * Return the current state of the language filter. * * @return boolean * * @since 3.2 */ public function getLanguageFilter() { return $this->language_filter; } /** * Get the application parameters * * @param string $option The component option * * @return Registry The parameters object * * @since 3.2 */ public function getParams($option = null) { static $params = []; $hash = '__default'; if (!empty($option)) { $hash = $option; } if (!isset($params[$hash])) { // Get component parameters if (!$option) { $option = $this->input->getCmd('option', null); } // Get new instance of component global parameters $params[$hash] = clone ComponentHelper::getParams($option); // Get menu parameters $menus = $this->getMenu(); $menu = $menus->getActive(); // Get language $lang_code = $this->getLanguage()->getTag(); $languages = LanguageHelper::getLanguages('lang_code'); $title = $this->get('sitename'); if (isset($languages[$lang_code]) && $languages[$lang_code]->metadesc) { $description = $languages[$lang_code]->metadesc; } else { $description = $this->get('MetaDesc'); } $rights = $this->get('MetaRights'); $robots = $this->get('robots'); // Retrieve com_menu global settings $temp = clone ComponentHelper::getParams('com_menus'); // Lets cascade the parameters if we have menu item parameters if (\is_object($menu)) { // Get show_page_heading from com_menu global settings $params[$hash]->def('show_page_heading', $temp->get('show_page_heading')); $params[$hash]->merge($menu->getParams()); $title = $menu->title; } else { // Merge com_menu global settings $params[$hash]->merge($temp); // If supplied, use page title $title = $temp->get('page_title', $title); } $params[$hash]->def('page_title', $title); $params[$hash]->def('page_description', $description); $params[$hash]->def('page_rights', $rights); $params[$hash]->def('robots', $robots); } return $params[$hash]; } /** * Return a reference to the Router object. * * @param string $name The name of the application. * @param array $options An optional associative array of configuration settings. * * @return \Joomla\CMS\Router\Router * * @since 3.2 * * @deprecated 4.3 will be removed in 6.0 * Inject the router or load it from the dependency injection container * Example: Factory::getContainer()->get(SiteRouter::class); */ public static function getRouter($name = 'site', array $options = []) { return parent::getRouter($name, $options); } /** * Gets the name of the current template. * * @param boolean $params True to return the template parameters * * @return string|\stdClass The name of the template if the params argument is false. The template object if the params argument is true. * * @since 3.2 * @throws \InvalidArgumentException */ public function getTemplate($params = false) { if (\is_object($this->template)) { if ($this->template->parent) { if (!is_file(JPATH_THEMES . '/' . $this->template->template . '/index.php')) { if (!is_file(JPATH_THEMES . '/' . $this->template->parent . '/index.php')) { throw new \InvalidArgumentException(Text::sprintf('JERROR_COULD_NOT_FIND_TEMPLATE', $this->template->template)); } } } elseif (!is_file(JPATH_THEMES . '/' . $this->template->template . '/index.php')) { throw new \InvalidArgumentException(Text::sprintf('JERROR_COULD_NOT_FIND_TEMPLATE', $this->template->template)); } if ($params) { return $this->template; } return $this->template->template; } // Get the id of the active menu item $menu = $this->getMenu(); $item = $menu->getActive(); if (!$item) { $item = $menu->getItem($this->input->getInt('Itemid', null)); } $id = 0; if (\is_object($item)) { // Valid item retrieved $id = $item->template_style_id; } $tid = $this->input->getUint('templateStyle', 0); if (is_numeric($tid) && (int) $tid > 0) { $id = (int) $tid; } /** @var OutputController $cache */ $cache = $this->getCacheControllerFactory()->createCacheController('output', ['defaultgroup' => 'com_templates']); if ($this->getLanguageFilter()) { $tag = $this->getLanguage()->getTag(); } else { $tag = ''; } $cacheId = 'templates0' . $tag; if ($cache->contains($cacheId)) { $templates = $cache->get($cacheId); } else { $templates = $this->bootComponent('templates')->getMVCFactory() ->createModel('Style', 'Administrator')->getSiteTemplates(); foreach ($templates as &$template) { // Create home element if ($template->home == 1 && !isset($template_home) || $this->getLanguageFilter() && $template->home == $tag) { $template_home = clone $template; } $template->params = new Registry($template->params); } // Unset the $template reference to the last $templates[n] item cycled in the foreach above to avoid editing it later unset($template); // Add home element, after loop to avoid double execution if (isset($template_home)) { $template_home->params = new Registry($template_home->params); $templates[0] = $template_home; } $cache->store($templates, $cacheId); } $template = $templates[$id] ?? $templates[0]; // Allows for overriding the active template from the request $template_override = $this->input->getCmd('template', ''); // Only set template override if it is a valid template (= it exists and is enabled) if (!empty($template_override)) { if (is_file(JPATH_THEMES . '/' . $template_override . '/index.php')) { foreach ($templates as $tmpl) { if ($tmpl->template === $template_override) { $template = $tmpl; break; } } } } // Need to filter the default value as well $template->template = InputFilter::getInstance()->clean($template->template, 'cmd'); // Fallback template if (!empty($template->parent)) { if (!is_file(JPATH_THEMES . '/' . $template->template . '/index.php')) { if (!is_file(JPATH_THEMES . '/' . $template->parent . '/index.php')) { $this->enqueueMessage(Text::_('JERROR_ALERTNOTEMPLATE'), 'error'); // Try to find data for 'cassiopeia' template $original_tmpl = $template->template; foreach ($templates as $tmpl) { if ($tmpl->template === 'cassiopeia') { $template = $tmpl; break; } } // Check, the data were found and if template really exists if (!is_file(JPATH_THEMES . '/' . $template->template . '/index.php')) { throw new \InvalidArgumentException(Text::sprintf('JERROR_COULD_NOT_FIND_TEMPLATE', $original_tmpl)); } } } } elseif (!is_file(JPATH_THEMES . '/' . $template->template . '/index.php')) { $this->enqueueMessage(Text::_('JERROR_ALERTNOTEMPLATE'), 'error'); // Try to find data for 'cassiopeia' template $original_tmpl = $template->template; foreach ($templates as $tmpl) { if ($tmpl->template === 'cassiopeia') { $template = $tmpl; break; } } // Check, the data were found and if template really exists if (!is_file(JPATH_THEMES . '/' . $template->template . '/index.php')) { throw new \InvalidArgumentException(Text::sprintf('JERROR_COULD_NOT_FIND_TEMPLATE', $original_tmpl)); } } // Cache the result $this->template = $template; if ($params) { return $template; } return $template->template; } /** * Initialise the application. * * @param array $options An optional associative array of configuration settings. * * @return void * * @since 3.2 */ protected function initialiseApp($options = []) { $user = Factory::getUser(); // If the user is a guest we populate it with the guest user group. if ($user->guest) { $guestUsergroup = ComponentHelper::getParams('com_users')->get('guest_usergroup', 1); $user->groups = [$guestUsergroup]; } if ($plugin = PluginHelper::getPlugin('system', 'languagefilter')) { $pluginParams = new Registry($plugin->params); $this->setLanguageFilter(true); $this->setDetectBrowser($pluginParams->get('detect_browser', 1) == 1); } if (empty($options['language'])) { // Detect the specified language $lang = $this->input->getString('language', null); // Make sure that the user's language exists if ($lang && LanguageHelper::exists($lang)) { $options['language'] = $lang; } } if (empty($options['language']) && $this->getLanguageFilter()) { // Detect cookie language $lang = $this->input->cookie->get(md5($this->get('secret') . 'language'), null, 'string'); // Make sure that the user's language exists if ($lang && LanguageHelper::exists($lang)) { $options['language'] = $lang; } } if (empty($options['language'])) { // Detect user language $lang = $user->getParam('language'); // Make sure that the user's language exists if ($lang && LanguageHelper::exists($lang)) { $options['language'] = $lang; } } if (empty($options['language']) && $this->getDetectBrowser()) { // Detect browser language $lang = LanguageHelper::detectLanguage(); // Make sure that the user's language exists if ($lang && LanguageHelper::exists($lang)) { $options['language'] = $lang; } } if (empty($options['language'])) { // Detect default language $params = ComponentHelper::getParams('com_languages'); $options['language'] = $params->get('site', $this->get('language', 'en-GB')); } // One last check to make sure we have something if (!LanguageHelper::exists($options['language'])) { $lang = $this->config->get('language', 'en-GB'); if (LanguageHelper::exists($lang)) { $options['language'] = $lang; } else { // As a last ditch fail to english $options['language'] = 'en-GB'; } } // Finish initialisation parent::initialiseApp($options); } /** * Load the library language files for the application * * @return void * * @since 3.6.3 */ protected function loadLibraryLanguage() { /* * Try the lib_joomla file in the current language (without allowing the loading of the file in the default language) * Fallback to the default language if necessary */ $this->getLanguage()->load('lib_joomla', JPATH_SITE) || $this->getLanguage()->load('lib_joomla', JPATH_ADMINISTRATOR); } /** * Login authentication function * * @param array $credentials Array('username' => string, 'password' => string) * @param array $options Array('remember' => boolean) * * @return boolean True on success. * * @since 3.2 */ public function login($credentials, $options = []) { // Set the application login entry point if (!\array_key_exists('entry_url', $options)) { $options['entry_url'] = Uri::base() . 'index.php?option=com_users&task=user.login'; } // Set the access control action to check. $options['action'] = 'core.login.site'; $result = parent::login($credentials, $options); if (!($result instanceof \Exception) && $result) { // Check if the user is required to reset their password $this->checkUserRequiresReset('com_users', 'profile', 'edit', [ ['option' => 'com_users', 'task' => 'profile.save'], ['option' => 'com_users', 'task' => 'profile.apply'], ['option' => 'com_users', 'task' => 'user.logout'], ['option' => 'com_users', 'task' => 'user.menulogout'], ['option' => 'com_users', 'task' => 'captive.validate'], ['option' => 'com_users', 'view' => 'captive'], ['option' => 'com_users', 'view' => 'methods'], ['option' => 'com_users', 'view' => 'method'], ['option' => 'com_users', 'task' => 'method.add'], ['option' => 'com_users', 'task' => 'method.save'], ]); } return $result; } /** * Rendering is the process of pushing the document buffers into the template * placeholders, retrieving data from the document and pushing it into * the application response buffer. * * @return void * * @since 3.2 */ protected function render() { switch ($this->document->getType()) { case 'feed': // No special processing for feeds break; case 'html': default: $template = $this->getTemplate(true); $file = $this->input->get('tmpl', 'index'); if ($file === 'offline' && !$this->get('offline')) { $this->set('themeFile', 'index.php'); } if ($this->get('offline') && !Factory::getUser()->authorise('core.login.offline')) { $this->setUserState('users.login.form.data', ['return' => Uri::getInstance()->toString()]); $this->set('themeFile', 'offline.php'); $this->setHeader('Status', '503 Service Temporarily Unavailable', 'true'); } if (!is_dir(JPATH_THEMES . '/' . $template->template) && !$this->get('offline')) { $this->set('themeFile', 'component.php'); } // Ensure themeFile is set by now if ($this->get('themeFile') == '') { $this->set('themeFile', $file . '.php'); } // Pass the parent template to the state $this->set('themeInherits', $template->parent); break; } parent::render(); } /** * Route the application. * * 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 * dispatched. * * @return void * * @since 3.2 */ protected function route() { // Get the full request URI. $uri = clone Uri::getInstance(); // It is not possible to inject the SiteRouter as it requires a SiteApplication // and we would end in an infinite loop $result = $this->getContainer()->get(SiteRouter::class)->parse($uri, true); $active = $this->getMenu()->getActive(); if ( $active !== null && $active->type === 'alias' && $active->getParams()->get('alias_redirect') && \in_array($this->input->getMethod(), ['GET', 'HEAD'], true) ) { $item = $this->getMenu()->getItem($active->getParams()->get('aliasoptions')); if ($item !== null) { $oldUri = clone Uri::getInstance(); if ($oldUri->getVar('Itemid') == $active->id) { $oldUri->setVar('Itemid', $item->id); } $base = Uri::base(true); $oldPath = StringHelper::strtolower(substr($oldUri->getPath(), \strlen($base) + 1)); $activePathPrefix = StringHelper::strtolower($active->route); $position = strpos($oldPath, $activePathPrefix); if ($position !== false) { $oldUri->setPath($base . '/' . substr_replace($oldPath, $item->route, $position, \strlen($activePathPrefix))); $this->setHeader('Expires', 'Wed, 17 Aug 2005 00:00:00 GMT', true); $this->setHeader('Last-Modified', gmdate('D, d M Y H:i:s') . ' GMT', true); $this->setHeader('Cache-Control', 'no-store, no-cache, must-revalidate', false); $this->sendHeaders(); $this->redirect((string) $oldUri, 301); } } } foreach ($result as $key => $value) { $this->input->def($key, $value); } // Trigger the onAfterRoute event. PluginHelper::importPlugin('system', null, true, $this->getDispatcher()); $this->dispatchEvent( 'onAfterRoute', new AfterRouteEvent('onAfterRoute', ['subject' => $this]) ); $Itemid = $this->input->getInt('Itemid', 0); $this->authorise($Itemid); } /** * Set the current state of the detect browser option. * * @param boolean $state The new state of the detect browser option * * @return boolean The previous state * * @since 3.2 */ public function setDetectBrowser($state = false) { $old = $this->getDetectBrowser(); $this->detect_browser = $state; return $old; } /** * Set the current state of the language filter. * * @param boolean $state The new state of the language filter * * @return boolean The previous state * * @since 3.2 */ public function setLanguageFilter($state = false) { $old = $this->getLanguageFilter(); $this->language_filter = $state; return $old; } /** * Overrides the default template that would be used * * @param \stdClass|string $template The template name or definition * @param mixed $styleParams The template style parameters * * @return void * * @since 3.2 */ public function setTemplate($template, $styleParams = null) { if (\is_object($template)) { $templateName = empty($template->template) ? '' : $template->template; $templateInheritable = empty($template->inheritable) ? 0 : $template->inheritable; $templateParent = empty($template->parent) ? '' : $template->parent; $templateParams = empty($template->params) ? $styleParams : $template->params; } else { $templateName = $template; $templateInheritable = 0; $templateParent = ''; $templateParams = $styleParams; } if (is_dir(JPATH_THEMES . '/' . $templateName)) { $this->template = new \stdClass(); $this->template->template = $templateName; if ($templateParams instanceof Registry) { $this->template->params = $templateParams; } else { $this->template->params = new Registry($templateParams); } $this->template->inheritable = $templateInheritable; $this->template->parent = $templateParent; // Store the template and its params to the config $this->set('theme', $this->template->template); $this->set('themeParams', $this->template->params); } } } PK #�\I�Q� � CLI/ColorStyle.phpnu �[��� <?php /** * Joomla! Content Management System * * @copyright (C) 2014 Open Source Matters, Inc. <https://www.joomla.org> * @license GNU General Public License version 2 or later; see LICENSE.txt */ namespace Joomla\CMS\Application\CLI; // phpcs:disable PSR1.Files.SideEffects \defined('_JEXEC') or die; // phpcs:enable PSR1.Files.SideEffects /** * Class defining ANSI-color styles for command line output * * @since 4.0.0 * * @deprecated 4.3 will be removed in 6.0 * Use the `joomla/console` package instead */ final class ColorStyle { /** * Known colors * * @var array * @since 4.0.0 */ private static $knownColors = [ 'black' => 0, 'red' => 1, 'green' => 2, 'yellow' => 3, 'blue' => 4, 'magenta' => 5, 'cyan' => 6, 'white' => 7, ]; /** * Known styles * * @var array * @since 4.0.0 */ private static $knownOptions = [ 'bold' => 1, 'underscore' => 4, 'blink' => 5, 'reverse' => 7, ]; /** * Foreground base value * * @var integer * @since 4.0.0 */ private static $fgBase = 30; /** * Background base value * * @var integer * @since 4.0.0 */ private static $bgBase = 40; /** * Foreground color * * @var integer * @since 4.0.0 */ private $fgColor = 0; /** * Background color * * @var integer * @since 4.0.0 */ private $bgColor = 0; /** * Array of style options * * @var array * @since 4.0.0 */ private $options = []; /** * Constructor * * @param string $fg Foreground color. * @param string $bg Background color. * @param array $options Style options. * * @since 4.0.0 * @throws \InvalidArgumentException */ public function __construct(string $fg = '', string $bg = '', array $options = []) { if ($fg) { if (!\array_key_exists($fg, static::$knownColors)) { throw new \InvalidArgumentException( \sprintf( 'Invalid foreground color "%1$s" [%2$s]', $fg, implode(', ', $this->getKnownColors()) ) ); } $this->fgColor = static::$fgBase + static::$knownColors[$fg]; } if ($bg) { if (!\array_key_exists($bg, static::$knownColors)) { throw new \InvalidArgumentException( \sprintf( 'Invalid background color "%1$s" [%2$s]', $bg, implode(', ', $this->getKnownColors()) ) ); } $this->bgColor = static::$bgBase + static::$knownColors[$bg]; } foreach ($options as $option) { if (!\array_key_exists($option, static::$knownOptions)) { throw new \InvalidArgumentException( \sprintf( 'Invalid option "%1$s" [%2$s]', $option, implode(', ', $this->getKnownOptions()) ) ); } $this->options[] = $option; } } /** * Convert to a string. * * @return string * * @since 4.0.0 */ public function __toString() { return $this->getStyle(); } /** * Create a color style from a parameter string. * * Example: fg=red;bg=blue;options=bold,blink * * @param string $string The parameter string. * * @return $this * * @since 4.0.0 * @throws \RuntimeException */ public static function fromString(string $string): self { $fg = ''; $bg = ''; $options = []; $parts = explode(';', $string); foreach ($parts as $part) { $subParts = explode('=', $part); if (\count($subParts) < 2) { continue; } switch ($subParts[0]) { case 'fg': $fg = $subParts[1]; break; case 'bg': $bg = $subParts[1]; break; case 'options': $options = explode(',', $subParts[1]); break; default: throw new \RuntimeException('Invalid option: ' . $subParts[0]); } } return new self($fg, $bg, $options); } /** * Get the translated color code. * * @return string * * @since 4.0.0 */ public function getStyle(): string { $values = []; if ($this->fgColor) { $values[] = $this->fgColor; } if ($this->bgColor) { $values[] = $this->bgColor; } foreach ($this->options as $option) { $values[] = static::$knownOptions[$option]; } return implode(';', $values); } /** * Get the known colors. * * @return string[] * * @since 4.0.0 */ public function getKnownColors(): array { return array_keys(static::$knownColors); } /** * Get the known options. * * @return string[] * * @since 4.0.0 */ public function getKnownOptions(): array { return array_keys(static::$knownOptions); } } PK #�\nDg�a a CLI/Output/Stdout.phpnu �[��� <?php /** * Joomla! Content Management System * * @copyright (C) 2014 Open Source Matters, Inc. <https://www.joomla.org> * @license GNU General Public License version 2 or later; see LICENSE.txt */ namespace Joomla\CMS\Application\CLI\Output; use Joomla\CMS\Application\CLI\CliOutput; // phpcs:disable PSR1.Files.SideEffects \defined('_JEXEC') or die; // phpcs:enable PSR1.Files.SideEffects /** * Output handler for writing command line output to the stdout interface * * @since 4.0.0 * * @deprecated 4.3 will be removed in 6.0 * Use the `joomla/console` package instead */ class Stdout extends CliOutput { /** * Write a string to standard output * * @param string $text The text to display. * @param boolean $nl True (default) to append a new line at the end of the output string. * * @return $this * * @codeCoverageIgnore * @since 4.0.0 */ public function out($text = '', $nl = true) { fwrite(STDOUT, $this->getProcessor()->process($text) . ($nl ? "\n" : null)); return $this; } } PK #�\��R` '