Your IP : 216.73.216.50


Current Path : /proc/1908984/root/proc/self/root/proc/self/root/proc/2411249/cwd/
Upload File :
Current File : //proc/1908984/root/proc/self/root/proc/self/root/proc/2411249/cwd/Joomla.tar

Filesystem.php000064400000015403152355256530007417 0ustar00<?php
/**
 * @package   FOF
 * @copyright Copyright (c)2010-2022 Nicholas K. Dionysopoulos / Akeeba Ltd
 * @license   GNU General Public License version 3, or later
 */

namespace FOF40\Platform\Joomla;

defined('_JEXEC') || die;

use FOF40\Platform\Base\Filesystem as BaseFilesystem;
use Joomla\CMS\Filesystem\File;
use Joomla\CMS\Filesystem\Folder;
use Joomla\CMS\Filesystem\Path;

/**
 * Abstraction for Joomla! filesystem API
 */
class Filesystem extends BaseFilesystem
{
	/**
	 * Does the file exists?
	 *
	 * @param   $path  string   Path to the file to test
	 *
	 * @return  bool
	 */
	public function fileExists(string $path): bool
	{
		return File::exists($path);
	}

	/**
	 * Delete a file or array of files
	 *
	 * @param   mixed  $file  The file name or an array of file names
	 *
	 * @return  bool  True on success
	 *
	 */
	public function fileDelete($file): bool
	{
		if (!is_string($file) && !is_array($file))
		{
			throw new \InvalidArgumentException(sprintf('%s::%s -- $file expects a string or an array', __CLASS__, __METHOD__));
		}

		return File::delete($file);
	}

	/**
	 * Copies a file
	 *
	 * @param   string  $src          The path to the source file
	 * @param   string  $dest         The path to the destination file
	 * @param   string  $path         An optional base path to prefix to the file names
	 * @param   bool    $use_streams  True to use streams
	 *
	 * @return  bool  True on success
	 */
	public function fileCopy(string $src, string $dest, ?string $path = null, bool $use_streams = false): bool
	{
		return File::copy($src, $dest, $path, $use_streams);
	}

	/**
	 * Write contents to a file
	 *
	 * @param   string    $file         The full file path
	 * @param   string   &$buffer       The buffer to write
	 * @param   bool      $use_streams  Use streams
	 *
	 * @return  bool  True on success
	 */
	public function fileWrite(string $file, string &$buffer, bool $use_streams = false): bool
	{
		return File::write($file, $buffer, $use_streams);
	}

	/**
	 * Checks for snooping outside of the file system root.
	 *
	 * @param   string  $path  A file system path to check.
	 *
	 * @return  string  A cleaned version of the path or exit on error.
	 *
	 * @throws  \Exception
	 */
	public function pathCheck(string $path): string
	{
		return Path::check($path);
	}

	/**
	 * Function to strip additional / or \ in a path name.
	 *
	 * @param   string  $path  The path to clean.
	 * @param   string  $ds    Directory separator (optional).
	 *
	 * @return  string  The cleaned path.
	 *
	 * @throws  \UnexpectedValueException
	 */
	public function pathClean(string $path, string $ds = DIRECTORY_SEPARATOR): string
	{
		return Path::clean($path, $ds);
	}

	/**
	 * Searches the directory paths for a given file.
	 *
	 * @param   mixed   $paths  An path string or array of path strings to search in
	 * @param   string  $file   The file name to look for.
	 *
	 * @return  string|null   The full path and file name for the target file, or bool false if the file is not found
	 *                        in any of the paths.
	 */
	public function pathFind($paths, string $file): ?string
	{
		if (!is_string($paths) && !is_array($paths))
		{
			throw new \InvalidArgumentException(sprintf('%s::%s -- $paths expects a string or an array', __CLASS__, __METHOD__));
		}

		$ret = Path::find($paths, $file);

		if (($ret === false) || ($ret === ''))
		{
			return null;
		}

		return $ret;
	}

	/**
	 * Wrapper for the standard file_exists function
	 *
	 * @param   string  $path  Folder name relative to installation dir
	 *
	 * @return  bool  True if path is a folder
	 */
	public function folderExists(string $path): bool
	{
		try
		{
			return Folder::exists($path);
		}
		catch (\Exception $e)
		{
			return false;
		}
	}

	/**
	 * Utility function to read the files in a folder.
	 *
	 * @param   string  $path           The path of the folder to read.
	 * @param   string  $filter         A filter for file names.
	 * @param   mixed   $recurse        True to recursively search into sub-folders, or an integer to specify the
	 *                                  maximum depth.
	 * @param   bool    $full           True to return the full path to the file.
	 * @param   array   $exclude        Array with names of files which should not be shown in the result.
	 * @param   array   $excludefilter  Array of filter to exclude
	 * @param   bool    $naturalSort    False for asort, true for natsort
	 * @param   bool    $naturalSort    False for asort, true for natsort
	 *
	 * @return  array  Files in the given folder.
	 */
	public function folderFiles(string $path, string $filter = '.', bool $recurse = false, bool $full = false,
	                            array $exclude = [
		                            '.svn', 'CVS', '.DS_Store', '__MACOSX',
	                            ], array $excludefilter = ['^\..*', '.*~'], bool $naturalSort = false): array
	{
		// JFolder throws nonsense errors if the path is not a folder
		try
		{
			$path = Path::clean($path);
		}
		catch (\Exception $e)
		{
			return [];
		}

		if (!@is_dir($path))
		{
			return [];
		}

		// Now call JFolder
		return Folder::files($path, $filter, $recurse, $full, $exclude, $excludefilter, $naturalSort);
	}

	/**
	 * Utility function to read the folders in a folder.
	 *
	 * @param   string  $path           The path of the folder to read.
	 * @param   string  $filter         A filter for folder names.
	 * @param   mixed   $recurse        True to recursively search into sub-folders, or an integer to specify the
	 *                                  maximum depth.
	 * @param   bool    $full           True to return the full path to the folders.
	 * @param   array   $exclude        Array with names of folders which should not be shown in the result.
	 * @param   array   $excludefilter  Array with regular expressions matching folders which should not be shown in
	 *                                  the result.
	 *
	 * @return  array  Folders in the given folder.
	 */
	public function folderFolders(string $path, string $filter = '.', bool $recurse = false, bool $full = false, array $exclude = [
		'.svn', 'CVS', '.DS_Store', '__MACOSX',
	], array $excludefilter = ['^\..*']): array
	{
		// JFolder throws idiotic errors if the path is not a folder
		try
		{
			$path = Path::clean($path);
		}
		catch (\Exception $e)
		{
			return [];
		}

		if (!@is_dir($path))
		{
			return [];
		}

		// Now call JFolder
		return Folder::folders($path, $filter, $recurse, $full, $exclude, $excludefilter);
	}

	/**
	 * Create a folder -- and all necessary parent folders.
	 *
	 * @param   string   $path  A path to create from the base path.
	 * @param   integer  $mode  Directory permissions to set for folders created. 0755 by default.
	 *
	 * @return  bool  True if successful.
	 */
	public function folderCreate(string $path = '', int $mode = 0755): bool
	{
		return Folder::create($path, $mode);
	}
}
Platform.php000064400000115470152355256530007064 0ustar00<?php
/**
 * @package   FOF
 * @copyright Copyright (c)2010-2022 Nicholas K. Dionysopoulos / Akeeba Ltd
 * @license   GNU General Public License version 3, or later
 */

namespace FOF40\Platform\Joomla;

defined('_JEXEC') || die;

use ActionlogsModelActionlog;
use DateTime;
use DateTimeZone;
use Exception;
use FOF40\Container\Container;
use FOF40\Date\Date;
use FOF40\Date\DateDecorator;
use FOF40\Input\Input;
use FOF40\Platform\Base\Platform as BasePlatform;
use InvalidArgumentException;
use JDatabaseDriver;
use JEventDispatcher;
use Joomla\CMS\Application\ApplicationHelper;
use Joomla\CMS\Application\CliApplication;
use Joomla\CMS\Application\CliApplication as JApplicationCli;
use Joomla\CMS\Application\ConsoleApplication;
use Joomla\CMS\Authentication\Authentication;
use Joomla\CMS\Authentication\AuthenticationResponse;
use Joomla\CMS\Cache\Cache;
use Joomla\CMS\Document\Document;
use Joomla\CMS\Document\HtmlDocument;
use Joomla\CMS\Factory as JoomlaFactory;
use Joomla\CMS\Language\Language;
use Joomla\CMS\Log\Log;
use Joomla\CMS\MVC\Model\BaseDatabaseModel;
use Joomla\CMS\Plugin\PluginHelper;
use Joomla\CMS\Session\Session;
use Joomla\CMS\Uri\Uri;
use Joomla\CMS\User\User;
use Joomla\CMS\User\UserFactoryInterface;
use Joomla\CMS\User\UserHelper;
use Joomla\CMS\Version as JoomlaVersion;
use Joomla\Event\Event;
use Joomla\Registry\Registry;

/**
 * Part of the FOF Platform Abstraction Layer.
 *
 * This implements the platform class for Joomla! 3 and Joomla! 4
 *
 * @since    2.1
 */
class Platform extends BasePlatform
{
	/**
	 * Is this a CLI application?
	 *
	 * @var   bool
	 */
	protected static $isCLI;

	/**
	 * Is this an administrator application?
	 *
	 * @var   bool
	 */
	protected static $isAdmin;

	/**
	 * Is this an API application?
	 *
	 * @var   bool
	 */
	protected static $isApi;

	/**
	 * A fake session storage for CLI apps. Since CLI applications cannot have a session we are using a Registry object
	 * we manage internally.
	 *
	 * @var   Registry
	 */
	protected static $fakeSession;

	/**
	 * The table and table field cache object, used to speed up database access
	 *
	 * @var  Registry|null
	 */
	private $_cache;

	/**
	 * Public constructor.
	 *
	 * Overridden to cater for CLI applications not having access to a session object.
	 *
	 * @param   Container  $c  The component container
	 */
	public function __construct(Container $c)
	{
		parent::__construct($c);

		if ($this->isCli())
		{
			self::$fakeSession = new Registry();
		}
	}

	/**
	 * Checks if the current script is run inside a valid CMS execution
	 *
	 * @return bool
	 */
	public function checkExecution(): bool
	{
		return defined('_JEXEC');
	}

	/**
	 * Raises an error, using the logic requested by the CMS (PHP Exception or dedicated class)
	 *
	 * @param   integer  $code
	 * @param   string   $message
	 *
	 * @return  void
	 *
	 * @throws  Exception
	 *
	 * @deprecated 5.0 Use showErrorPage with a real exception instead
	 */
	public function raiseError(int $code, string $message): void
	{
		$this->showErrorPage(new Exception($message, $code));
	}

	/**
	 * Returns absolute path to directories used by the containing CMS/application.
	 *
	 * The return is a table with the following key:
	 * * root    Path to the site root
	 * * public  Path to the public area of the site
	 * * admin   Path to the administrative area of the site
	 * * api     Path to the API application area of the site
	 * * tmp     Path to the temp directory
	 * * log     Path to the log directory
	 *
	 * @return  array  A hash array with keys root, public, admin, tmp and log.
	 */
	public function getPlatformBaseDirs(): array
	{
		return [
			'root'   => JPATH_ROOT,
			'public' => JPATH_SITE,
			'media'  => JPATH_SITE . '/media',
			'admin'  => JPATH_ADMINISTRATOR,
			'api'    => defined('JPATH_API') ? JPATH_API : (JPATH_ROOT . '/api'),
			'tmp'    => JoomlaFactory::getConfig()->get('tmp_path'),
			'log'    => JoomlaFactory::getConfig()->get('log_path'),
		];
	}

	/**
	 * Returns the base (root) directories for a given component, i.e the application
	 * which is running inside our main application (CMS, web app).
	 *
	 * The return is a table with the following keys:
	 * * main    The normal location of component files. For a back-end Joomla!
	 *          component this is the administrator/components/com_example
	 *          directory.
	 * * alt    The alternate location of component files. For a back-end
	 *          Joomla! component this is the front-end directory, e.g.
	 *          components/com_example
	 * * site    The location of the component files serving the public part of
	 *          the application.
	 * * admin    The location of the component files serving the administrative
	 *          part of the application.
	 * * api    The location of the component files serving the API part of the application
	 *
	 * All paths MUST be absolute. All paths MAY be the same if the
	 * platform doesn't make a distinction between public and private parts,
	 * or when the component does not provide both a public and private part.
	 * All of the directories MUST be defined and non-empty.
	 *
	 * @param   string  $component  The name of the component. For Joomla! this
	 *                              is something like "com_example"
	 *
	 * @return  array  A hash array with keys main, alt, site and admin.
	 */
	public function getComponentBaseDirs(string $component): array
	{
		if (!$this->isBackend())
		{
			$mainPath = JPATH_SITE . '/components/' . $component;
			$altPath  = JPATH_ADMINISTRATOR . '/components/' . $component;
		}
		else
		{
			$mainPath = JPATH_ADMINISTRATOR . '/components/' . $component;
			$altPath  = JPATH_SITE . '/components/' . $component;
		}

		return [
			'main'  => $mainPath,
			'alt'   => $altPath,
			'site'  => JPATH_SITE . '/components/' . $component,
			'admin' => JPATH_ADMINISTRATOR . '/components/' . $component,
			'api'   => (defined('JPATH_API') ? JPATH_API : (JPATH_ROOT . '/api')) . '/components/' . $component,
		];
	}

	/**
	 * Returns the application's template name
	 *
	 * @param   null|array  $params  An optional associative array of configuration settings
	 *
	 * @return  string  The template name. "system" is the fallback.
	 */
	public function getTemplate(?array $params = null): string
	{
		try
		{
			return JoomlaFactory::getApplication()->getTemplate($params ?? false);
		}
		catch (Exception $e)
		{
			return 'system';
		}
	}

	/**
	 * Get application-specific suffixes to use with template paths. This allows
	 * you to look for view template overrides based on the application version.
	 *
	 * @return  array  A plain array of suffixes to try in template names
	 */
	public function getTemplateSuffixes(): array
	{
		$jversion     = new JoomlaVersion;
		$versionParts = explode('.', $jversion->getShortVersion());
		$majorVersion = array_shift($versionParts);

		return [
			'.j' . str_replace('.', '', $jversion->getHelpVersion()),
			'.j' . $majorVersion,
		];
	}

	/**
	 * Return the absolute path to the application's template overrides
	 * directory for a specific component. We will use it to look for template
	 * files instead of the regular component directories. If the application
	 * does not have such a thing as template overrides return an empty string.
	 *
	 * @param   string  $component  The name of the component for which to fetch the overrides
	 * @param   bool    $absolute   Should I return an absolute or relative path?
	 *
	 * @return  string  The path to the template overrides directory
	 */
	public function getTemplateOverridePath(string $component, bool $absolute = true): string
	{
		if (!$this->isCli())
		{
			if ($absolute)
			{
				$path = JPATH_THEMES . '/';
			}
			else
			{
				$path = $this->isBackend() ? 'administrator/templates/' : 'templates/';
			}

			$directory = (substr($component, 0, 7) == 'media:/') ? ('media/' . substr($component, 7)) : ('html/' . $component);

			$path .= $this->getTemplate() .
				'/' . $directory;
		}
		else
		{
			$path = '';
		}

		return $path;
	}

	/**
	 * Load the translation files for a given component.
	 *
	 * @param   string  $component  The name of the component, e.g. "com_example"
	 *
	 * @return  void
	 */
	public function loadTranslations(string $component): void
	{
		$paths = $this->isBackend() ? [JPATH_ROOT, JPATH_ADMINISTRATOR] : [JPATH_ADMINISTRATOR, JPATH_ROOT];

		$jlang = $this->getLanguage();
		$jlang->load($component, $paths[0], 'en-GB', true);
		$jlang->load($component, $paths[0], null, true);
		$jlang->load($component, $paths[1], 'en-GB', true);
		$jlang->load($component, $paths[1], null, true);
	}

	/**
	 * By default FOF will only use the Controller's onBefore* methods to
	 * perform user authorisation. In some cases, like the Joomla! back-end,
	 * you also need to perform component-wide user authorisation in the
	 * Dispatcher. This method MUST implement this authorisation check. If you
	 * do not need this in your platform, please always return true.
	 *
	 * @param   string  $component  The name of the component.
	 *
	 * @return  bool  True to allow loading the component, false to halt loading
	 */
	public function authorizeAdmin(string $component): bool
	{
		if ($this->isBackend())
		{
			// Master access check for the back-end, Joomla! 1.6 style.
			$user = $this->getUser();

			if (!$user->authorise('core.manage', $component)
				&& !$user->authorise('core.admin', $component)
			)
			{
				return false;
			}
		}

		return true;
	}

	/**
	 * Returns a user object.
	 *
	 * @param   integer  $id  The user ID to load. Skip or use null to retrieve
	 *                        the object for the currently logged in user.
	 *
	 * @return  User  The User object for the specified user
	 */
	public function getUser(?int $id = null): User
	{
		/**
		 * If I'm in CLI I need load the User directly, otherwise JoomlaFactory will check the session (which doesn't exist
		 * in CLI)
		 */
		if ($this->isCli())
		{
			if ($id)
			{
				return User::getInstance($id) ?? new User();
			}

			return new User();
		}

		// Joomla 3
		if (version_compare(JVERSION, '3.999.999', 'lt'))
		{
			return JoomlaFactory::getUser($id) ?? new User();
		}

		// Joomla 4
		if (is_null($id))
		{
			return JoomlaFactory::getApplication()->getIdentity() ?? new User();
		}

		return JoomlaFactory::getContainer()->get(UserFactoryInterface::class)->loadUserById($id) ?? new User();
	}

	/**
	 * Returns the Document object which handles this component's response. You
	 * may also return null and FOF will a. try to figure out the output type by
	 * examining the "format" input parameter (or fall back to "html") and b.
	 * FOF will not attempt to load CSS and Javascript files (as it doesn't make
	 * sense if there's no Document to handle them).
	 *
	 * @return  Document|null
	 */
	public function getDocument(): ?Document
	{
		$document = null;

		if (!$this->isCli())
		{
			try
			{
				$document = JoomlaFactory::getDocument();
			}
			catch (Exception $exc)
			{
				$document = null;
			}
		}

		return $document;
	}

	/**
	 * Returns an object to handle dates
	 *
	 * @param   mixed                     $time      The initial time
	 * @param   DateTimeZone|string|null  $tzOffset  The timezone offset
	 * @param   bool                      $locale    Should I try to load a specific class for current language?
	 *
	 * @return  Date object
	 */
	public function getDate(?string $time = 'now', $tzOffset = null, $locale = true): Date
	{
		$time = $time ?? $this->getDbo()->getNullDate() ?? 'now';

		if (!is_string($time) && (!is_object($time) || !($time instanceof DateTime)))
		{
			throw new InvalidArgumentException(sprintf('%s::%s -- $time expects a string or a DateTime object', __CLASS__, __METHOD__));
		}

		if ($locale)
		{
			// Work around a bug in Joomla! 3.7.0.
			if ($time == 'now')
			{
				$time = time();
			}

			$coreObject = JoomlaFactory::getDate($time, $tzOffset);

			return new DateDecorator($coreObject);
		}
		else
		{
			return new Date($time, $tzOffset);
		}
	}

	/**
	 * Return the Language instance of the CMS/application
	 *
	 * @return Language
	 */
	public function getLanguage(): Language
	{
		return JoomlaFactory::getLanguage();
	}

	/**
	 * Returns the database driver object of the CMS/application
	 *
	 * @return JDatabaseDriver
	 */
	public function getDbo(): JDatabaseDriver
	{
		return JoomlaFactory::getDbo();
	}

	/**
	 * This method will try retrieving a variable from the request (input) data.
	 * If it doesn't exist it will be loaded from the user state, typically
	 * stored in the session. If it doesn't exist there either, the $default
	 * value will be used. If $setUserState is set to true, the retrieved
	 * variable will be stored in the user session.
	 *
	 * @param   string  $key           The user state key for the variable
	 * @param   string  $request       The request variable name for the variable
	 * @param   Input   $input         The Input object with the request (input) data
	 * @param   mixed   $default       The default value. Default: null
	 * @param   string  $type          The filter type for the variable data. Default: none (no filtering)
	 * @param   bool    $setUserState  Should I set the user state with the fetched value?
	 *
	 * @return  mixed  The value of the variable
	 */
	public function getUserStateFromRequest(string $key, string $request, Input $input, $default = null, string $type = 'none', bool $setUserState = true)
	{
		if ($this->isCli())
		{
			$ret = $input->get($request, $default, $type);

			if ($ret === $default)
			{
				$input->set($request, $ret);
			}

			return $ret;
		}

		try
		{
			$app = JoomlaFactory::getApplication();
		}
		catch (Exception $e)
		{
			$app = null;
		}

		$old_state = (!is_null($app) && method_exists($app, 'getUserState')) ? $app->getUserState($key, $default) : null;

		$cur_state = (!is_null($old_state)) ? $old_state : $default;
		$new_state = $input->get($request, null, $type);

		// Save the new value only if it was set in this request
		if ($setUserState)
		{
			if ($new_state !== null)
			{
				$app->setUserState($key, $new_state);
			}
			else
			{
				$new_state = $cur_state;
			}
		}
		elseif (is_null($new_state))
		{
			$new_state = $cur_state;
		}

		return $new_state;
	}

	/**
	 * Load plugins of a specific type. Obviously this seems to only be required
	 * in the Joomla! CMS.
	 *
	 * @param   string  $type  The type of the plugins to be loaded
	 *
	 * @return void
	 *
	 * @codeCoverageIgnore
	 * @see PlatformInterface::importPlugin()
	 *
	 */
	public function importPlugin(string $type): void
	{
		// Should I actually run the plugins?
		$runPlugins = $this->isAllowPluginsInCli() || !$this->isCli();

		if ($runPlugins)
		{
			PluginHelper::importPlugin($type);
		}
	}

	/**
	 * Execute plugins (system-level triggers) and fetch back an array with
	 * their return values.
	 *
	 * @param   string  $event  The event (trigger) name, e.g. onBeforeScratchMyEar
	 * @param   array   $data   A hash array of data sent to the plugins as part of the trigger
	 *
	 * @return  array  A simple array containing the results of the plugins triggered
	 */
	public function runPlugins(string $event, array $data = []): array
	{
		// Should I actually run the plugins?
		$runPlugins = $this->isAllowPluginsInCli() || !$this->isCli();

		if ($runPlugins)
		{
			if (class_exists('JEventDispatcher'))
			{
				return JEventDispatcher::getInstance()->trigger($event, $data);
			}

			// If there's no JEventDispatcher try getting JApplication
			try
			{
				$app = JoomlaFactory::getApplication();
			}
			catch (Exception $e)
			{
				// If I can't get JApplication I cannot run the plugins.
				return [];
			}

			// Joomla 3 and 4 have triggerEvent
			if (method_exists($app, 'triggerEvent'))
			{
				return $app->triggerEvent($event, $data);
			}

			// Joomla 5 (and possibly some 4.x versions) don't have triggerEvent. Go through the Events dispatcher.
			if (method_exists($app, 'getDispatcher') && class_exists('Joomla\Event\Event'))
			{
				try
				{
					$dispatcher = $app->getDispatcher();
				}
				catch (\UnexpectedValueException $exception)
				{
					return [];
				}

				if ($data instanceof Event)
				{
					$eventObject = $data;
				}
				elseif (\is_array($data))
				{
					$eventObject = new Event($event, $data);
				}
				else
				{
					throw new \InvalidArgumentException('The plugin data must either be an event or an array');
				}

				$result = $dispatcher->dispatch($event, $eventObject);

				return !isset($result['result']) || \is_null($result['result']) ? [] : $result['result'];
			}

			// No viable way to run the plugins :(
			return [];
		}
		else
		{
			return [];
		}
	}

	/**
	 * Perform an ACL check. Please note that FOF uses by default the Joomla!
	 * CMS convention for ACL privileges, e.g core.edit for the edit privilege.
	 * If your platform uses different conventions you'll have to override the
	 * FOF defaults using fof.xml or by specialising the controller.
	 *
	 * @param   string       $action     The ACL privilege to check, e.g. core.edit
	 * @param   string|null  $assetname  The asset name to check, typically the component's name
	 *
	 * @return  bool  True if the user is allowed this action
	 */
	public function authorise(string $action, ?string $assetname = null): bool
	{
		if ($this->isCli())
		{
			return true;
		}

		$ret = JoomlaFactory::getUser()->authorise($action, $assetname);

		// Work around Joomla returning null instead of false in some cases.
		return (bool) $ret;
	}

	/**
	 * Is this the administrative section of the component?
	 *
	 * @return  bool
	 */
	public function isBackend(): bool
	{
		[$isCli, $isAdmin, $isApi] = $this->isCliAdminApi();

		return $isAdmin && !$isCli && !$isApi;
	}

	/**
	 * Is this the public section of the component?
	 *
	 * @param   bool  $strict  True to only confirm if we're under the 'site' client. False to confirm if we're under
	 *                         either 'site' or 'api' client (both are front-end access). The default is false which
	 *                         causes the method to return true when the application is either 'client' (HTML frontend)
	 *                         or 'api' (JSON frontend).
	 *
	 * @return  bool
	 */
	public function isFrontend(bool $strict = false): bool
	{
		[$isCli, $isAdmin, $isApi] = $this->isCliAdminApi();

		if ($strict)
		{
			return !$isAdmin && !$isCli && !$isApi;
		}

		return !$isAdmin && !$isCli;
	}

	/**
	 * Is this a component running in a CLI application?
	 *
	 * @return  bool
	 */
	public function isCli(): bool
	{
		[$isCli, $isAdmin, $isApi] = $this->isCliAdminApi();

		return !$isAdmin && !$isApi && $isCli;
	}

	/**
	 * Is this a component running under the API application?
	 *
	 * @return  bool
	 */
	public function isApi(): bool
	{
		[$isCli, $isAdmin, $isApi] = $this->isCliAdminApi();

		return $isApi && !$isAdmin && !$isCli;
	}

	/**
	 * Is the global FOF cache enabled?
	 *
	 * @return  bool
	 */
	public function isGlobalFOFCacheEnabled(): bool
	{
		return !(defined('JDEBUG') && JDEBUG);
	}

	/**
	 * Retrieves data from the cache. This is supposed to be used for system-side
	 * FOF data, not application data.
	 *
	 * @param   string       $key      The key of the data to retrieve
	 * @param   string|null  $default  The default value to return if the key is not found or the cache is not populated
	 *
	 * @return  string|null  The cached value
	 */
	public function getCache(string $key, ?string $default = null): ?string
	{
		$registry = $this->getCacheObject();

		return $registry->get($key, $default);
	}

	/**
	 * Saves something to the cache. This is supposed to be used for system-wide
	 * FOF data, not application data.
	 *
	 * @param   string  $key      The key of the data to save
	 * @param   string  $content  The actual data to save
	 *
	 * @return  bool  True on success
	 */
	public function setCache(string $key, string $content): bool
	{
		$registry = $this->getCacheObject();

		$registry->set($key, $content);

		return $this->saveCache();
	}

	/**
	 * Clears the cache of system-wide FOF data. You are supposed to call this in
	 * your components' installation script post-installation and post-upgrade
	 * methods or whenever you are modifying the structure of database tables
	 * accessed by FOF. Please note that FOF's cache never expires and is not
	 * purged by Joomla!. You MUST use this method to manually purge the cache.
	 *
	 * @return  bool  True on success
	 */
	public function clearCache(): bool
	{
		$false = false;
		$cache = JoomlaFactory::getCache('fof', '');

		return $cache->store($false, 'cache', 'fof');
	}

	/**
	 * Returns an object that holds the configuration of the current site.
	 *
	 * @return  Registry
	 *
	 * @codeCoverageIgnore
	 */
	public function getConfig(): Registry
	{
		return JoomlaFactory::getConfig();
	}

	/**
	 * logs in a user
	 *
	 * @param   array  $authInfo  Authentication information
	 *
	 * @return  bool  True on success
	 */
	public function loginUser(array $authInfo): bool
	{
		$options = ['remember' => false];

		$response         = new AuthenticationResponse();
		$response->type   = 'fof';
		$response->status = Authentication::STATUS_FAILURE;

		if (isset($authInfo['username']))
		{
			$authenticate = Authentication::getInstance();
			$response     = $authenticate->authenticate($authInfo, $options);
		}

		// Use our own authentication handler, onFOFUserAuthenticate, as a fallback
		if ($response->status != Authentication::STATUS_SUCCESS)
		{
			$this->container->platform->importPlugin('user');
			$this->container->platform->importPlugin('fof');
			$pluginResults = $this->container->platform->runPlugins('onFOFUserAuthenticate', [$authInfo, $options]);

			/**
			 * Loop through all plugin results until we find a successful login. On failure we fall back to Joomla's
			 * previous authentication response.
			 */
			foreach ($pluginResults as $result)
			{
				if (empty($result))
				{
					continue;
				}

				if (!is_object($result) || !($result instanceof AuthenticationResponse))
				{
					continue;
				}

				if ($result->status != Authentication::STATUS_SUCCESS)
				{
					continue;
				}

				$response = $result;

				break;
			}
		}

		// User failed to authenticate: maybe he enabled two factor authentication?
		// Let's try again "manually", skipping the check vs two factor auth
		// Due the big mess with encryption algorithms and libraries, we are doing this extra check only
		// if we're in Joomla 2.5.18+ or 3.2.1+
		if ($response->status != Authentication::STATUS_SUCCESS && method_exists('\Joomla\CMS\User\UserHelper', 'verifyPassword'))
		{
			$db     = JoomlaFactory::getDbo();
			$query  = $db->getQuery(true)
				->select($db->qn(['id', 'password']))
				->from('#__users')
				->where('username=' . $db->quote($authInfo['username']));
			$result = $db->setQuery($query)->loadObject();

			if ($result)
			{
				$match = UserHelper::verifyPassword($authInfo['password'], $result->password, $result->id);

				if ($match === true)
				{
					// Bring this in line with the rest of the system
					$user               = $this->getUser($result->id);
					$response->email    = $user->email;
					$response->fullname = $user->name;

					$response->language = $this->isBackend() ? $user->getParam('admin_language') : $user->getParam('language');

					$response->status        = Authentication::STATUS_SUCCESS;
					$response->error_message = '';
				}
			}
		}

		if ($response->status == Authentication::STATUS_SUCCESS)
		{
			$this->importPlugin('user');
			$results = $this->runPlugins('onLoginUser', [(array) $response, $options]);

			unset($results); // Just to make phpStorm happy

			$userid = UserHelper::getUserId($response->username);
			$user   = $this->getUser($userid);

			$session = $this->container->session;
			$session->set('user', $user);

			return true;
		}

		return false;
	}

	/**
	 * logs out a user
	 *
	 * @return  bool  True on success
	 */
	public function logoutUser(): bool
	{
		try
		{
			$app = JoomlaFactory::getApplication();
		}
		catch (Exception $e)
		{
			return false;
		}

		$user       = $this->getUser();
		$options    = ['remember' => false];
		$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 (!$app->get('shared_session', '0'))
		{
			$options['clientid'] = $app->getClientId();
		}

		$ret = $app->triggerEvent('onUserLogout', [$parameters, $options]);

		return !in_array(false, $ret, true);
	}

	/**
	 * Add a log file for FOF
	 *
	 * @param   string  $file
	 *
	 * @return  void
	 */
	public function logAddLogger($file): void
	{
		Log::addLogger(['text_file' => $file], Log::ALL, ['fof']);
	}

	/**
	 * Logs a deprecated practice. In Joomla! this results in the $message being output in the
	 * deprecated log file, found in your site's log directory.
	 *
	 * @param   string  $message  The deprecated practice log message
	 *
	 * @return  void
	 */
	public function logDeprecated(string $message): void
	{
		Log::add($message, Log::WARNING, 'deprecated');
	}

	/**
	 * Adds a message to the application's debug log
	 *
	 * @param   string  $message
	 *
	 * @return  void
	 *
	 * @codeCoverageIgnore
	 */
	public function logDebug(string $message): void
	{
		Log::add($message, Log::DEBUG, 'fof');
	}

	/** @inheritDoc */
	public function logUserAction($title, string $logText, string $extension, User $user = null): void
	{
		if (!is_string($title) && !is_array($title))
		{
			throw new InvalidArgumentException(sprintf('%s::%s -- $title expects a string or an array', __CLASS__, __METHOD__));
		}

		static $joomlaModelAdded = false;

		// User Actions Log is available only under Joomla 3.9+
		if (version_compare(JVERSION, '3.9', 'lt'))
		{
			return;
		}

		// Do not perform logging if we're under CLI. Even if we _could_ have a logged user in CLI, ActionlogsModelActionlog
		// model always uses JoomlaFactory to fetch the current user, fetching data from the session. This means that under the CLI
		// (where there is no session) such session is started, causing warnings because usually output was already started before
		if ($this->isCli())
		{
			return;
		}

		// Include required Joomla Model
		if (!$joomlaModelAdded)
		{
			BaseDatabaseModel::addIncludePath(JPATH_ROOT . '/administrator/components/com_actionlogs/models', 'ActionlogsModel');
			$joomlaModelAdded = true;
		}

		$user = $this->getUser();

		// No log for guest users
		if ($user->guest)
		{
			return;
		}

		$message = [
			'title'       => $title,
			'username'    => $user->username,
			'accountlink' => 'index.php?option=com_users&task=user.edit&id=' . $user->id,
		];

		if (is_array($title))
		{
			unset ($message['title']);

			$message = array_merge($message, $title);
		}

		/** @var ActionlogsModelActionlog $model * */
		try
		{
			$model = BaseDatabaseModel::getInstance('Actionlog', 'ActionlogsModel');
			$model->addLog([$message], $logText, $extension, $user->id);
		}
		catch (Exception $e)
		{
			// Ignore any error
		}
	}

	/**
	 * Returns the root URI for the request.
	 *
	 * @param   bool         $pathonly  If false, prepend the scheme, host and port information. Default is false.
	 * @param   string|null  $path      The path
	 *
	 * @return  string  The root URI string.
	 *
	 * @codeCoverageIgnore
	 */
	public function URIroot(bool $pathonly = false, ?string $path = null): string
	{
		return Uri::root($pathonly, $path);
	}

	/**
	 * Returns the base URI for the request.
	 *
	 * @param   bool  $pathonly  If false, prepend the scheme, host and port information. Default is false.
	 *
	 * @return  string  The base URI string
	 */
	public function URIbase(bool $pathonly = false): string
	{
		return Uri::base($pathonly);
	}

	/**
	 * Method to set a response header.  If the replace flag is set then all headers
	 * with the given name will be replaced by the new one (only if the current platform supports header caching)
	 *
	 * @param   string  $name     The name of the header to set.
	 * @param   string  $value    The value of the header to set.
	 * @param   bool    $replace  True to replace any headers with the same name.
	 *
	 * @return  void
	 *
	 * @codeCoverageIgnore
	 */
	public function setHeader(string $name, string $value, bool $replace = false): void
	{
		try
		{
			JoomlaFactory::getApplication()->setHeader($name, $value, $replace);
		}
		catch (Exception $e)
		{
			return;
		}
	}

	/**
	 * In platforms that perform header caching, send all headers.
	 *
	 * @return  void
	 *
	 * @codeCoverageIgnore
	 */
	public function sendHeaders(): void
	{
		try
		{
			JoomlaFactory::getApplication()->sendHeaders();
		}
		catch (Exception $e)
		{
			return;
		}
	}

	/**
	 * Immediately terminate the containing application's execution
	 *
	 * @param   int  $code  The result code which should be returned by the application
	 *
	 * @return  void
	 */
	public function closeApplication(int $code = 0): void
	{
		// Necessary workaround for broken System - Page Cache plugin in Joomla! 3.7.0
		$this->bugfixJoomlaCachePlugin();

		try
		{
			JoomlaFactory::getApplication()->close($code);
		}
		catch (Exception $e)
		{
			exit($code);
		}
	}

	/**
	 * Perform a redirection to a different page, optionally enqueuing a message for the user.
	 *
	 * @param   string  $url     The URL to redirect to
	 * @param   int     $status  (optional) The HTTP redirection status code, default 303 (See Other)
	 * @param   string  $msg     (optional) A message to enqueue
	 * @param   string  $type    (optional) The message type, e.g. 'message' (default), 'warning' or 'error'.
	 *
	 * @return  void
	 */
	public function redirect(string $url, int $status = 301, ?string $msg = null, string $type = 'message'): void
	{
		// Necessary workaround for broken System - Page Cache plugin in Joomla! 3.7.0
		$this->bugfixJoomlaCachePlugin();

		try
		{
			$app = JoomlaFactory::getApplication();
		}
		catch (Exception $e)
		{
			die(sprintf('Please go to <a href="%s">%1$s</a>', $url));
		}

		if (!empty($msg))
		{
			if (empty($type))
			{
				$type = 'message';
			}

			$app->enqueueMessage($msg, $type);
		}

		// Joomla 4: redirecting to index.php in the backend takes you to the frontend. I need to address that.
		$isJoomla4   = version_compare(JVERSION, '3.999.999', 'gt');
		$isBareIndex = substr($url, 0, 9) === 'index.php';

		if ($isJoomla4 && $isBareIndex && $this->isBackend())
		{
			$givenUri = new Uri($url);
			$newUri   = new Uri(Uri::base());

			$newUri->setQuery($givenUri->getQuery());

			if ($givenUri->getFragment())
			{
				$newUri->setFragment($givenUri->getFragment());
			}

			$url = $newUri->toString();
		}

		// Finally, do the redirection
		$app->redirect($url, $status);
	}

	/**
	 * Handle an exception in a way that results to an error page. We use this under Joomla! to work around a bug in
	 * Joomla! 3.7 which results in error pages leading to white pages because Joomla's System - Page Cache plugin is
	 * broken.
	 *
	 * @param   Exception  $exception  The exception to handle
	 *
	 * @throws  Exception  We rethrow the exception
	 */
	public function showErrorPage(Exception $exception): void
	{
		// Necessary workaround for broken System - Page Cache plugin in Joomla! 3.7.0
		$this->bugfixJoomlaCachePlugin();

		throw $exception;
	}

	/**
	 * Set a variable in the user session
	 *
	 * @param   string       $name       The name of the variable to set
	 * @param   string|null  $value      (optional) The value to set it to, default is null
	 * @param   string       $namespace  (optional) The variable's namespace e.g. the component name. Default: 'default'
	 *
	 * @return  void
	 */
	public function setSessionVar(string $name, $value = null, string $namespace = 'default'): void
	{
		// CLI
		if ($this->isCli() && !class_exists('FOFApplicationCLI'))
		{
			static::$fakeSession->set("$namespace.$name", $value);

			return;
		}

		// Joomla 3
		if (version_compare(JVERSION, '3.9999.9999', 'le'))
		{
			$this->container->session->set($name, $value, $namespace);
		}

		// Joomla 4
		if (empty($namespace))
		{
			$this->container->session->set($name, $value);

			return;
		}

		$registry = $this->container->session->get('registry');

		if (is_null($registry))
		{
			$registry = new Registry();

			$this->container->session->set('registry', $registry);
		}

		$registry->set($namespace . '.' . $name, $value);
	}

	/**
	 * Get a variable from the user session
	 *
	 * @param   string  $name       The name of the variable to set
	 * @param   string  $default    (optional) The default value to return if the variable does not exit, default: null
	 * @param   string  $namespace  (optional) The variable's namespace e.g. the component name. Default: 'default'
	 *
	 * @return  mixed
	 */
	public function getSessionVar(string $name, $default = null, $namespace = 'default')
	{
		// CLI
		if ($this->isCli() && !class_exists('FOFApplicationCLI'))
		{
			return static::$fakeSession->get("$namespace.$name", $default);
		}

		// Joomla 3
		if (version_compare(JVERSION, '3.9999.9999', 'le'))
		{
			return $this->container->session->get($name, $default, $namespace);
		}

		// Joomla 4
		if (empty($namespace))
		{
			return $this->container->session->get($name, $default);
		}

		$registry = $this->container->session->get('registry');

		if (is_null($registry))
		{
			$registry = new Registry();

			$this->container->session->set('registry', $registry);
		}

		return $registry->get($namespace . '.' . $name, $default);
	}

	/**
	 * Unset a variable from the user session
	 *
	 * @param   string  $name       The name of the variable to unset
	 * @param   string  $namespace  (optional) The variable's namespace e.g. the component name. Default: 'default'
	 *
	 * @return  void
	 */
	public function unsetSessionVar(string $name, string $namespace = 'default'): void
	{
		$this->setSessionVar($name, null, $namespace);
	}

	/**
	 * Return the session token. Two types of tokens can be returned:
	 *
	 * Session token ($formToken == false): Used for anti-spam protection of forms. This is specific to a session
	 *   object.
	 *
	 * Form token ($formToken == true): A secure hash of the user ID with the session token. Both the session and the
	 *   user are fetched from the application container.
	 *
	 * @param   bool  $formToken  Should I return a form token?
	 * @param   bool  $forceNew   Should I force the creation of a new token?
	 *
	 * @return  mixed
	 */
	public function getToken(bool $formToken = false, bool $forceNew = false): string
	{
		// For CLI apps we implement our own fake token system
		if ($this->isCli())
		{
			$token = $this->getSessionVar('session.token');

			// Create a token
			if (is_null($token) || $forceNew)
			{
				$token = UserHelper::genRandomPassword(32);
				$this->setSessionVar('session.token', $token);
			}

			if (!$formToken)
			{
				return $token;
			}

			$user = $this->getUser();

			return ApplicationHelper::getHash($user->id . $token);
		}

		// Web application, go through the regular Joomla! API.
		if ($formToken)
		{
			return Session::getFormToken($forceNew);
		}

		return $this->container->session->getToken($forceNew);
	}

	/** @inheritDoc */
	public function addScriptOptions($key, $value, $merge = true)
	{
		/** @var HtmlDocument $document */
		$document = $this->getDocument();

		if (!method_exists($document, 'addScriptOptions'))
		{
			return;
		}

		$document->addScriptOptions($key, $value, $merge);
	}

	/** @inheritDoc */
	public function getScriptOptions($key = null)
	{
		/** @var HtmlDocument $document */
		$document = $this->getDocument();

		if (!method_exists($document, 'getScriptOptions'))
		{
			return [];
		}

		return $document->getScriptOptions($key);
	}

	/**
	 * Main function to detect if we're running in a CLI environment, if we're admin or if it's an API application
	 *
	 * @return  array  isCLI and isAdmin. It's not an associative array, so we can use list().
	 */
	protected function isCliAdminApi(): array
	{
		if (is_null(static::$isCLI) && is_null(static::$isAdmin))
		{
			static::$isCLI   = false;
			static::$isAdmin = false;
			static::$isApi   = false;

			try
			{
				if (is_null(JoomlaFactory::$application))
				{
					static::$isCLI   = true;
					static::$isAdmin = false;

					return [static::$isCLI, static::$isAdmin, static::$isApi];
				}

				$app           = JoomlaFactory::getApplication();
				static::$isCLI = $app instanceof Exception || $app instanceof CliApplication;

				if (class_exists('Joomla\CMS\Application\CliApplication'))
				{
					static::$isCLI = static::$isCLI || $app instanceof JApplicationCli;
				}

				if (class_exists('Joomla\CMS\Application\ConsoleApplication'))
				{
					static::$isCLI = static::$isCLI || ($app instanceof ConsoleApplication);
				}
			}
			catch (Exception $e)
			{
				static::$isCLI = true;
			}

			if (static::$isCLI)
			{
				return [static::$isCLI, static::$isAdmin, static::$isApi];
			}

			try
			{
				$app = JoomlaFactory::getApplication();
			}
			catch (Exception $e)
			{
				return [static::$isCLI, static::$isAdmin, static::$isApi];
			}

			if (method_exists($app, 'isAdmin'))
			{
				static::$isAdmin = $app->isAdmin();
			}
			elseif (method_exists($app, 'isClient'))
			{
				static::$isAdmin = $app->isClient('administrator');
				static::$isApi   = $app->isClient('api');
			}
		}

		return [static::$isCLI, static::$isAdmin, static::$isApi];
	}

	/**
	 * Gets a reference to the cache object, loading it from the disk if
	 * needed.
	 *
	 * @param   bool  $force  Should I forcibly reload the registry?
	 *
	 * @return  Registry
	 */
	private function &getCacheObject(bool $force = false): Registry
	{
		// Check if we have to load the cache file or we are forced to do that
		if (is_null($this->_cache) || $force)
		{
			// Try to get data from Joomla!'s cache
			$cache        = JoomlaFactory::getCache('fof', '');
			$this->_cache = $cache->get('cache', 'fof');

			$isRegistry = is_object($this->_cache);

			if ($isRegistry)
			{
				$isRegistry = $this->_cache instanceof Registry;
			}

			if (!$isRegistry)
			{
				// Create a new Registry object
				$this->_cache = new Registry();
			}
		}

		return $this->_cache;
	}

	/**
	 * Save the cache object back to disk
	 *
	 * @return  bool  True on success
	 */
	private function saveCache(): bool
	{
		// Get the Registry object of our cached data
		$registry = $this->getCacheObject();

		$cache = JoomlaFactory::getCache('fof', '');

		return $cache->store($registry, 'cache', 'fof');
	}

	/**
	 * Joomla! 3.7 has a broken System - Page Cache plugin. When this plugin is enabled it FORCES the caching of all
	 * pages as soon as Joomla! starts loading, before the plugin has a chance to request to not be cached. Event worse,
	 * in case of a redirection, it doesn't try to remove the cache lock. This means that the next request will be
	 * treated as though the result of the page should be cached. Since there is NO cache content for the page Joomla!
	 * returns an empty response with a 200 OK header. This will, of course, get in the way of every single attempt to
	 * perform a redirection in the frontend of the site.
	 *
	 * @return  void
	 */
	private function bugfixJoomlaCachePlugin(): void
	{
		// Only do something when the System - Cache plugin is activated
		if (!class_exists('PlgSystemCache'))
		{
			return;
		}

		// Forcibly uncache the current request
		$options = [
			'defaultgroup' => 'page',
			'browsercache' => false,
			'caching'      => false,
		];

		$cache_key = Uri::getInstance()->toString();
		Cache::getInstance('page', $options)->cache->remove($cache_key, 'page');
	}
}
Common.php000064400000015367152356642750006540 0ustar00<?php

use Nextend\Framework\Platform\Platform;

include_once(dirname(__FILE__) . '/Kses.php');

/**
 * Properly strips all HTML tags including script and style
 *
 * This differs from strip_tags() because it removes the contents of
 * the `<script>` and `<style>` tags. E.g. `strip_tags( '<script>something</script>' )`
 * will return 'something'. wp_strip_all_tags will return ''
 *
 * @param string $string        String containing HTML tags
 * @param bool   $remove_breaks Optional. Whether to remove left over line breaks and white space chars
 *
 * @return string The processed string.
 * @since 2.9.0
 *
 */
if (!function_exists('wp_strip_all_tags')) {
    function wp_strip_all_tags($string, $remove_breaks = false) {
        $string = preg_replace('@<(script|style)[^>]*?>.*?</\\1>@si', '', $string);
        $string = strip_tags($string);

        if ($remove_breaks) {
            $string = preg_replace('/[\r\n\t ]+/', ' ', $string);
        }

        return trim($string);
    }
}

if (!function_exists('wp_check_invalid_utf8')) {
    function wp_check_invalid_utf8($string, $strip = false) {
        $string = (string)$string;

        if (0 === strlen($string)) {
            return '';
        }

        // Store the site charset as a static to avoid multiple calls to get_option().
        static $is_utf8 = null;
        if (!isset($is_utf8)) {
            $is_utf8 = in_array(Platform::getCharset(), array(
                'utf8',
                'utf-8',
                'UTF8',
                'UTF-8'
            ), true);
        }
        if (!$is_utf8) {
            return $string;
        }

        // Check for support for utf8 in the installed PCRE library once and store the result in a static.
        static $utf8_pcre = null;
        if (!isset($utf8_pcre)) {
            // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
            $utf8_pcre = @preg_match('/^./u', 'a');
        }
        // We can't demand utf8 in the PCRE installation, so just return the string in those cases.
        if (!$utf8_pcre) {
            return $string;
        }

        // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged -- preg_match fails when it encounters invalid UTF8 in $string.
        if (1 === @preg_match('/^./us', $string)) {
            return $string;
        }

        // Attempt to strip the bad chars if requested (not recommended).
        if ($strip && function_exists('iconv')) {
            return iconv('utf-8', 'utf-8', $string);
        }

        return '';
    }
}

/**
 * Determines if a Unicode codepoint is valid.
 *
 * @param int $i Unicode codepoint.
 *
 * @return bool Whether or not the codepoint is a valid Unicode codepoint.
 * @since 2.7.0
 *
 */
if (!function_exists('valid_unicode')) {
    function valid_unicode($i) {
        return (0x9 == $i || 0xa == $i || 0xd == $i || (0x20 <= $i && $i <= 0xd7ff) || (0xe000 <= $i && $i <= 0xfffd) || (0x10000 <= $i && $i <= 0x10ffff));
    }
}

/**
 * Converts a number of special characters into their HTML entities.
 *
 * Specifically deals with: `&`, `<`, `>`, `"`, and `'`.
 *
 * `$quote_style` can be set to ENT_COMPAT to encode `"` to
 * `&quot;`, or ENT_QUOTES to do both. Default is ENT_NOQUOTES where no quotes are encoded.
 *
 * @param string       $string        The text which is to be encoded.
 * @param int|string   $quote_style   Optional. Converts double quotes if set to ENT_COMPAT,
 *                                    both single and double if set to ENT_QUOTES or none if set to ENT_NOQUOTES.
 *                                    Converts single and double quotes, as well as converting HTML
 *                                    named entities (that are not also XML named entities) to their
 *                                    code points if set to ENT_XML1. Also compatible with old values;
 *                                    converting single quotes if set to 'single',
 *                                    double if set to 'double' or both if otherwise set.
 *                                    Default is ENT_NOQUOTES.
 * @param false|string $charset       Optional. The character encoding of the string. Default false.
 * @param bool         $double_encode Optional. Whether to encode existing HTML entities. Default false.
 *
 * @return string The encoded text with HTML entities.
 * @since  5.5.0 `$quote_style` also accepts `ENT_XML1`.
 * @access private
 *
 * @since  1.2.2
 */
if (!function_exists('_wp_specialchars')) {
    function _wp_specialchars($string, $quote_style = ENT_NOQUOTES, $charset = false, $double_encode = false) {
        $string = (string)$string;

        if (0 === strlen($string)) {
            return '';
        }

        // Don't bother if there are no specialchars - saves some processing.
        if (!preg_match('/[&<>"\']/', $string)) {
            return $string;
        }

        // Account for the previous behaviour of the function when the $quote_style is not an accepted value.
        if (empty($quote_style)) {
            $quote_style = ENT_NOQUOTES;
        } elseif (ENT_XML1 === $quote_style) {
            $quote_style = ENT_QUOTES | ENT_XML1;
        } elseif (!in_array($quote_style, array(
            ENT_NOQUOTES,
            ENT_COMPAT,
            ENT_QUOTES,
            'single',
            'double'
        ), true)) {
            $quote_style = ENT_QUOTES;
        }

        // Store the site charset as a static to avoid multiple calls to wp_load_alloptions().
        if (!$charset) {
            static $_charset = null;
            if (!isset($_charset)) {
                $_charset = \Nextend\Framework\Platform\Platform::getCharset();
            }
            $charset = $_charset;
        }

        if (in_array($charset, array(
            'utf8',
            'utf-8',
            'UTF8'
        ), true)) {
            $charset = 'UTF-8';
        }

        $_quote_style = $quote_style;

        if ('double' === $quote_style) {
            $quote_style  = ENT_COMPAT;
            $_quote_style = ENT_COMPAT;
        } elseif ('single' === $quote_style) {
            $quote_style = ENT_NOQUOTES;
        }

        if (!$double_encode) {
            // Guarantee every &entity; is valid, convert &garbage; into &amp;garbage;
            // This is required for PHP < 5.4.0 because ENT_HTML401 flag is unavailable.
            $string = wp_kses_normalize_entities($string, ($quote_style & ENT_XML1) ? 'xml' : 'html');
        }

        $string = htmlspecialchars($string, $quote_style, $charset, $double_encode);

        // Back-compat.
        if ('single' === $_quote_style) {
            $string = str_replace("'", '&#039;', $string);
        }

        return $string;
    }
}Escape.php000064400000031704152356642750006501 0ustar00<?php

use Nextend\Framework\Platform\Platform;

/**
 * Escapes single quotes, `"`, `<`, `>`, `&`, and fixes line endings.
 *
 * Escapes text strings for echoing in JS. It is intended to be used for inline JS
 * (in a tag attribute, for example `onclick="..."`). Note that the strings have to
 * be in single quotes. The {@see 'js_escape'} filter is also applied here.
 *
 * @param string $text The text to be escaped.
 *
 * @return string Escaped text.
 * @since 2.8.0
 *
 */
if (!function_exists('esc_js')) {
    function esc_js($text) {
        $safe_text = wp_check_invalid_utf8($text);
        $safe_text = _wp_specialchars($safe_text, ENT_COMPAT);
        $safe_text = preg_replace('/&#(x)?0*(?(1)27|39);?/i', "'", stripslashes($safe_text));
        $safe_text = str_replace("\r", '', $safe_text);
        $safe_text = str_replace("\n", '\\n', addslashes($safe_text));

        return $safe_text;
    }
}

/**
 * Escaping for HTML blocks.
 *
 * @param string $text
 *
 * @return string
 * @since 2.8.0
 *
 */
if (!function_exists('esc_html')) {
    function esc_html($text) {
        $safe_text = wp_check_invalid_utf8($text);
        $safe_text = _wp_specialchars($safe_text, ENT_QUOTES);

        return $safe_text;
    }
}

/**
 * Escaping for HTML attributes.
 *
 * @param string $text
 *
 * @return string
 * @since 2.8.0
 *
 */
if (!function_exists('esc_attr')) {
    function esc_attr($text) {
        $safe_text = wp_check_invalid_utf8($text);
        $safe_text = _wp_specialchars($safe_text, ENT_QUOTES);

        return $safe_text;
    }
}

/**
 * Escaping for textarea values.
 *
 * @param string $text
 *
 * @return string
 * @since 3.1.0
 *
 */
if (!function_exists('esc_textarea')) {
    function esc_textarea($text) {
        return htmlspecialchars($text, ENT_QUOTES, Platform::getCharset());
    }
}

/**
 * Escaping for XML blocks.
 *
 * @param string $text Text to escape.
 *
 * @return string Escaped text.
 * @since 5.5.0
 *
 */
if (!function_exists('esc_xml')) {
    function esc_xml($text) {
        $safe_text = wp_check_invalid_utf8($text);

        $cdata_regex = '\<\!\[CDATA\[.*?\]\]\>';
        $regex       = <<<EOF
/
	(?=.*?{$cdata_regex})                 # lookahead that will match anything followed by a CDATA Section
	(?<non_cdata_followed_by_cdata>(.*?)) # the "anything" matched by the lookahead
	(?<cdata>({$cdata_regex}))            # the CDATA Section matched by the lookahead

|	                                      # alternative

	(?<non_cdata>(.*))                    # non-CDATA Section
/sx
EOF;

        $safe_text = (string)preg_replace_callback($regex, static function ($matches) {
            if (!isset($matches[0])) {
                return '';
            }

            if (isset($matches['non_cdata'])) {
                // escape HTML entities in the non-CDATA Section.
                return _wp_specialchars($matches['non_cdata'], ENT_XML1);
            }

            // Return the CDATA Section unchanged, escape HTML entities in the rest.
            return _wp_specialchars($matches['non_cdata_followed_by_cdata'], ENT_XML1) . $matches['cdata'];
        }, $safe_text);

        return $safe_text;
    }
}

/**
 * Checks and cleans a URL.
 *
 * A number of characters are removed from the URL. If the URL is for displaying
 * (the default behaviour) ampersands are also replaced. The {@see 'clean_url'} filter
 * is applied to the returned cleaned URL.
 *
 * @param string   $url       The URL to be cleaned.
 * @param string[] $protocols Optional. An array of acceptable protocols.
 *                            Defaults to return value of wp_allowed_protocols().
 * @param string   $_context  Private. Use esc_url_raw() for database usage.
 *
 * @return string The cleaned URL after the {@see 'clean_url'} filter is applied.
 *                An empty string is returned if `$url` specifies a protocol other than
 *                those in `$protocols`, or if `$url` contains an empty string.
 * @since 2.8.0
 *
 */
if (!function_exists('esc_url')) {
    function esc_url($url, $protocols = null, $_context = 'display') {
        $original_url = $url;

        if ('' === $url) {
            return $url;
        }

        $url = str_replace(' ', '%20', ltrim($url));
        $url = preg_replace('|[^a-z0-9-~+_.?#=!&;,/:%@$\|*\'()\[\]\\x80-\\xff]|i', '', $url);

        if ('' === $url) {
            return $url;
        }

        if (0 !== stripos($url, 'mailto:')) {
            $strip = array(
                '%0d',
                '%0a',
                '%0D',
                '%0A'
            );
            $url   = _deep_replace($strip, $url);
        }

        $url = str_replace(';//', '://', $url);
        /*
         * If the URL doesn't appear to contain a scheme, we presume
         * it needs http:// prepended (unless it's a relative link
         * starting with /, # or ?, or a PHP file).
         */
        if (strpos($url, ':') === false && !in_array($url[0], array(
                '/',
                '#',
                '?'
            ), true) && !preg_match('/^[a-z0-9-]+?\.php/i', $url)) {
            $url = 'http://' . $url;
        }

        // Replace ampersands and single quotes only when displaying.
        if ('display' === $_context) {
            $url = wp_kses_normalize_entities($url);
            $url = str_replace('&amp;', '&#038;', $url);
            $url = str_replace("'", '&#039;', $url);
        }

        if ((false !== strpos($url, '[')) || (false !== strpos($url, ']'))) {

            $parsed = wp_parse_url($url);
            $front  = '';

            if (isset($parsed['scheme'])) {
                $front .= $parsed['scheme'] . '://';
            } elseif ('/' === $url[0]) {
                $front .= '//';
            }

            if (isset($parsed['user'])) {
                $front .= $parsed['user'];
            }

            if (isset($parsed['pass'])) {
                $front .= ':' . $parsed['pass'];
            }

            if (isset($parsed['user']) || isset($parsed['pass'])) {
                $front .= '@';
            }

            if (isset($parsed['host'])) {
                $front .= $parsed['host'];
            }

            if (isset($parsed['port'])) {
                $front .= ':' . $parsed['port'];
            }

            $end_dirty = str_replace($front, '', $url);
            $end_clean = str_replace(array(
                '[',
                ']'
            ), array(
                '%5B',
                '%5D'
            ), $end_dirty);
            $url       = str_replace($end_dirty, $end_clean, $url);

        }

        if ('/' === $url[0]) {
            $good_protocol_url = $url;
        } else {
            if (!is_array($protocols)) {
                $protocols = wp_allowed_protocols();
            }
            $good_protocol_url = wp_kses_bad_protocol($url, $protocols);
            if (strtolower($good_protocol_url) != strtolower($url)) {
                return '';
            }
        }

        /**
         * Filters a string cleaned and escaped for output as a URL.
         *
         * @param string $good_protocol_url The cleaned URL to be returned.
         * @param string $original_url      The URL prior to cleaning.
         * @param string $_context          If 'display', replace ampersands and single quotes only.
         *
         * @since 2.3.0
         *
         */
        return $good_protocol_url;
    }
}

/**
 * Performs a deep string replace operation to ensure the values in $search are no longer present.
 *
 * Repeats the replacement operation until it no longer replaces anything so as to remove "nested" values
 * e.g. $subject = '%0%0%0DDD', $search ='%0D', $result ='' rather than the '%0%0DD' that
 * str_replace would return
 *
 * @param string|array $search  The value being searched for, otherwise known as the needle.
 *                              An array may be used to designate multiple needles.
 * @param string       $subject The string being searched and replaced on, otherwise known as the haystack.
 *
 * @return string The string with the replaced values.
 * @since  2.8.1
 * @access private
 *
 */
if (!function_exists('_deep_replace')) {
    function _deep_replace($search, $subject) {
        $subject = (string)$subject;

        $count = 1;
        while ($count) {
            $subject = str_replace($search, '', $subject, $count);
        }

        return $subject;
    }
}

/**
 * A wrapper for PHP's parse_url() function that handles consistency in the return values
 * across PHP versions.
 *
 * PHP 5.4.7 expanded parse_url()'s ability to handle non-absolute URLs, including
 * schemeless and relative URLs with "://" in the path. This function works around
 * those limitations providing a standard output on PHP 5.2~5.4+.
 *
 * Secondly, across various PHP versions, schemeless URLs containing a ":" in the query
 * are being handled inconsistently. This function works around those differences as well.
 *
 * @param string $url       The URL to parse.
 * @param int    $component The specific component to retrieve. Use one of the PHP
 *                          predefined constants to specify which one.
 *                          Defaults to -1 (= return all parts as an array).
 *
 * @return mixed False on parse failure; Array of URL components on success;
 *               When a specific component has been requested: null if the component
 *               doesn't exist in the given URL; a string or - in the case of
 *               PHP_URL_PORT - integer when it does. See parse_url()'s return values.
 * @since 4.4.0
 * @since 4.7.0 The `$component` parameter was added for parity with PHP's `parse_url()`.
 *
 * @link  https://www.php.net/manual/en/function.parse-url.php
 *
 */
if (!function_exists('wp_parse_url')) {
    function wp_parse_url($url, $component = -1) {
        $to_unset = array();
        $url      = (string)$url;

        if ('//' === substr($url, 0, 2)) {
            $to_unset[] = 'scheme';
            $url        = 'placeholder:' . $url;
        } elseif ('/' === substr($url, 0, 1)) {
            $to_unset[] = 'scheme';
            $to_unset[] = 'host';
            $url        = 'placeholder://placeholder' . $url;
        }

        $parts = parse_url($url);

        if (false === $parts) {
            // Parsing failure.
            return $parts;
        }

        // Remove the placeholder values.
        foreach ($to_unset as $key) {
            unset($parts[$key]);
        }

        return _get_component_from_parsed_url_array($parts, $component);
    }
}

/**
 * Retrieve a specific component from a parsed URL array.
 *
 * @param array|false $url_parts The parsed URL. Can be false if the URL failed to parse.
 * @param int         $component The specific component to retrieve. Use one of the PHP
 *                               predefined constants to specify which one.
 *                               Defaults to -1 (= return all parts as an array).
 *
 * @return mixed False on parse failure; Array of URL components on success;
 *               When a specific component has been requested: null if the component
 *               doesn't exist in the given URL; a string or - in the case of
 *               PHP_URL_PORT - integer when it does. See parse_url()'s return values.
 * @internal
 *
 * @since  4.7.0
 * @access private
 *
 * @link   https://www.php.net/manual/en/function.parse-url.php
 *
 */
if (!function_exists('_get_component_from_parsed_url_array')) {
    function _get_component_from_parsed_url_array($url_parts, $component = -1) {
        if (-1 === $component) {
            return $url_parts;
        }

        $key = _wp_translate_php_url_constant_to_key($component);
        if (false !== $key && is_array($url_parts) && isset($url_parts[$key])) {
            return $url_parts[$key];
        } else {
            return null;
        }
    }
}

/**
 * Translate a PHP_URL_* constant to the named array keys PHP uses.
 *
 * @param int $constant PHP_URL_* constant.
 *
 * @return string|false The named key or false.
 * @link   https://www.php.net/manual/en/url.constants.php
 *
 * @internal
 *
 * @since  4.7.0
 * @access private
 *
 */
if (!function_exists('_wp_translate_php_url_constant_to_key')) {
    function _wp_translate_php_url_constant_to_key($constant) {
        $translation = array(
            PHP_URL_SCHEME   => 'scheme',
            PHP_URL_HOST     => 'host',
            PHP_URL_PORT     => 'port',
            PHP_URL_USER     => 'user',
            PHP_URL_PASS     => 'pass',
            PHP_URL_PATH     => 'path',
            PHP_URL_QUERY    => 'query',
            PHP_URL_FRAGMENT => 'fragment',
        );

        if (isset($translation[$constant])) {
            return $translation[$constant];
        } else {
            return false;
        }
    }
}
JoomlaSecurity.php000064400000000462152356642750010247 0ustar00<?php

namespace Nextend\Security\Joomla;

use Nextend\Framework\Pattern\SingletonTrait;

class JoomlaSecurity {

    use SingletonTrait;

    protected function init() {
        include_once(dirname(__FILE__) . '/Common.php');
        include_once(dirname(__FILE__) . '/Escape.php');
    }
}Kses.php000064400000147522152356642750006214 0ustar00<?php

global $allowedentitynames, $allowedxmlentitynames;

$allowedentitynames = array(
    'nbsp',
    'iexcl',
    'cent',
    'pound',
    'curren',
    'yen',
    'brvbar',
    'sect',
    'uml',
    'copy',
    'ordf',
    'laquo',
    'not',
    'shy',
    'reg',
    'macr',
    'deg',
    'plusmn',
    'acute',
    'micro',
    'para',
    'middot',
    'cedil',
    'ordm',
    'raquo',
    'iquest',
    'Agrave',
    'Aacute',
    'Acirc',
    'Atilde',
    'Auml',
    'Aring',
    'AElig',
    'Ccedil',
    'Egrave',
    'Eacute',
    'Ecirc',
    'Euml',
    'Igrave',
    'Iacute',
    'Icirc',
    'Iuml',
    'ETH',
    'Ntilde',
    'Ograve',
    'Oacute',
    'Ocirc',
    'Otilde',
    'Ouml',
    'times',
    'Oslash',
    'Ugrave',
    'Uacute',
    'Ucirc',
    'Uuml',
    'Yacute',
    'THORN',
    'szlig',
    'agrave',
    'aacute',
    'acirc',
    'atilde',
    'auml',
    'aring',
    'aelig',
    'ccedil',
    'egrave',
    'eacute',
    'ecirc',
    'euml',
    'igrave',
    'iacute',
    'icirc',
    'iuml',
    'eth',
    'ntilde',
    'ograve',
    'oacute',
    'ocirc',
    'otilde',
    'ouml',
    'divide',
    'oslash',
    'ugrave',
    'uacute',
    'ucirc',
    'uuml',
    'yacute',
    'thorn',
    'yuml',
    'quot',
    'amp',
    'lt',
    'gt',
    'apos',
    'OElig',
    'oelig',
    'Scaron',
    'scaron',
    'Yuml',
    'circ',
    'tilde',
    'ensp',
    'emsp',
    'thinsp',
    'zwnj',
    'zwj',
    'lrm',
    'rlm',
    'ndash',
    'mdash',
    'lsquo',
    'rsquo',
    'sbquo',
    'ldquo',
    'rdquo',
    'bdquo',
    'dagger',
    'Dagger',
    'permil',
    'lsaquo',
    'rsaquo',
    'euro',
    'fnof',
    'Alpha',
    'Beta',
    'Gamma',
    'Delta',
    'Epsilon',
    'Zeta',
    'Eta',
    'Theta',
    'Iota',
    'Kappa',
    'Lambda',
    'Mu',
    'Nu',
    'Xi',
    'Omicron',
    'Pi',
    'Rho',
    'Sigma',
    'Tau',
    'Upsilon',
    'Phi',
    'Chi',
    'Psi',
    'Omega',
    'alpha',
    'beta',
    'gamma',
    'delta',
    'epsilon',
    'zeta',
    'eta',
    'theta',
    'iota',
    'kappa',
    'lambda',
    'mu',
    'nu',
    'xi',
    'omicron',
    'pi',
    'rho',
    'sigmaf',
    'sigma',
    'tau',
    'upsilon',
    'phi',
    'chi',
    'psi',
    'omega',
    'thetasym',
    'upsih',
    'piv',
    'bull',
    'hellip',
    'prime',
    'Prime',
    'oline',
    'frasl',
    'weierp',
    'image',
    'real',
    'trade',
    'alefsym',
    'larr',
    'uarr',
    'rarr',
    'darr',
    'harr',
    'crarr',
    'lArr',
    'uArr',
    'rArr',
    'dArr',
    'hArr',
    'forall',
    'part',
    'exist',
    'empty',
    'nabla',
    'isin',
    'notin',
    'ni',
    'prod',
    'sum',
    'minus',
    'lowast',
    'radic',
    'prop',
    'infin',
    'ang',
    'and',
    'or',
    'cap',
    'cup',
    'int',
    'sim',
    'cong',
    'asymp',
    'ne',
    'equiv',
    'le',
    'ge',
    'sub',
    'sup',
    'nsub',
    'sube',
    'supe',
    'oplus',
    'otimes',
    'perp',
    'sdot',
    'lceil',
    'rceil',
    'lfloor',
    'rfloor',
    'lang',
    'rang',
    'loz',
    'spades',
    'clubs',
    'hearts',
    'diams',
    'sup1',
    'sup2',
    'sup3',
    'frac14',
    'frac12',
    'frac34',
    'there4',
);

$allowedxmlentitynames = array(
    'amp',
    'lt',
    'gt',
    'apos',
    'quot',
);


/**
 * Filters text content and strips out disallowed HTML.
 *
 * This function makes sure that only the allowed HTML element names, attribute
 * names, attribute values, and HTML entities will occur in the given text string.
 *
 * This function expects unslashed data.
 *
 * @param string         $string            Text content to filter.
 * @param array[]|string $allowed_html      An array of allowed HTML elements and attributes,
 *                                          or a context name such as 'post'. See wp_kses_allowed_html()
 *                                          for the list of accepted context names.
 * @param string[]       $allowed_protocols Array of allowed URL protocols.
 *
 * @return string Filtered content containing only the allowed HTML.
 * @see   wp_allowed_protocols() for the default allowed protocols in link URLs.
 *
 * @since 1.0.0
 *
 * @see   wp_kses_post() for specifically filtering post content and fields.
 */
if (!function_exists('wp_kses')) {
    function wp_kses($string, $allowed_html, $allowed_protocols = array()) {
        if (empty($allowed_protocols)) {
            $allowed_protocols = wp_allowed_protocols();
        }

        $string = wp_kses_no_null($string, array('slash_zero' => 'keep'));
        $string = wp_kses_normalize_entities($string);

        return wp_kses_split($string, $allowed_html, $allowed_protocols);
    }
}

/**
 * Retrieve a list of protocols to allow in HTML attributes.
 *
 * @return string[] Array of allowed protocols. Defaults to an array containing 'http', 'https',
 *                  'ftp', 'ftps', 'mailto', 'news', 'irc', 'irc6', 'ircs', 'gopher', 'nntp', 'feed',
 *                  'telnet', 'mms', 'rtsp', 'sms', 'svn', 'tel', 'fax', 'xmpp', 'webcal', and 'urn'.
 *                  This covers all common link protocols, except for 'javascript' which should not
 *                  be allowed for untrusted users.
 * @since 4.3.0 Added 'webcal' to the protocols array.
 * @since 4.7.0 Added 'urn' to the protocols array.
 * @since 5.3.0 Added 'sms' to the protocols array.
 * @since 5.6.0 Added 'irc6' and 'ircs' to the protocols array.
 *
 * @see   wp_kses()
 * @see   esc_url()
 *
 * @since 3.3.0
 */
if (!function_exists('wp_allowed_protocols')) {
    function wp_allowed_protocols() {
        static $protocols = array();

        if (empty($protocols)) {
            $protocols = array(
                'http',
                'https',
                'ftp',
                'ftps',
                'mailto',
                'news',
                'irc',
                'irc6',
                'ircs',
                'gopher',
                'nntp',
                'feed',
                'telnet',
                'mms',
                'rtsp',
                'sms',
                'svn',
                'tel',
                'fax',
                'xmpp',
                'webcal',
                'urn'
            );
        }

        return $protocols;
    }
}

/**
 * Removes any invalid control characters in a text string.
 *
 * Also removes any instance of the `\0` string.
 *
 * @param string $string  Content to filter null characters from.
 * @param array  $options Set 'slash_zero' => 'keep' when '\0' is allowed. Default is 'remove'.
 *
 * @return string Filtered content.
 * @since 1.0.0
 *
 */
if (!function_exists('wp_kses_no_null')) {
    function wp_kses_no_null($string, $options = null) {
        if (!isset($options['slash_zero'])) {
            $options = array('slash_zero' => 'remove');
        }

        $string = preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F]/', '', $string);
        if ('remove' === $options['slash_zero']) {
            $string = preg_replace('/\\\\+0+/', '', $string);
        }

        return $string;
    }
}

/**
 * Converts lone less than signs.
 *
 * KSES already converts lone greater than signs.
 *
 * @param string $text Text to be converted.
 *
 * @return string Converted text.
 * @since 2.3.0
 *
 */
if (!function_exists('wp_pre_kses_less_than')) {
    function wp_pre_kses_less_than($text) {
        return preg_replace_callback('%<[^>]*?((?=<)|>|$)%', 'wp_pre_kses_less_than_callback', $text);
    }
}

/**
 * Callback function used by preg_replace.
 *
 * @param string[] $matches Populated by matches to preg_replace.
 *
 * @return string The text returned after esc_html if needed.
 * @since 2.3.0
 *
 */
if (!function_exists('wp_pre_kses_less_than_callback')) {
    function wp_pre_kses_less_than_callback($matches) {
        if (false === strpos($matches[0], '>')) {
            return esc_html($matches[0]);
        }

        return $matches[0];
    }
}

/**
 * Converts and fixes HTML entities.
 *
 * This function normalizes HTML entities. It will convert `AT&T` to the correct
 * `AT&amp;T`, `&#00058;` to `&#058;`, `&#XYZZY;` to `&amp;#XYZZY;` and so on.
 *
 * When `$context` is set to 'xml', HTML entities are converted to their code points.  For
 * example, `AT&T&hellip;&#XYZZY;` is converted to `AT&amp;T…&amp;#XYZZY;`.
 *
 * @param string $string  Content to normalize entities.
 * @param string $context Context for normalization. Can be either 'html' or 'xml'.
 *                        Default 'html'.
 *
 * @return string Content with normalized entities.
 * @since 5.5.0 Added `$context` parameter.
 *
 * @since 1.0.0
 */
if (!function_exists('wp_kses_normalize_entities')) {
    function wp_kses_normalize_entities($string, $context = 'html') {
        // Disarm all entities by converting & to &amp;
        $string = str_replace('&', '&amp;', $string);

        // Change back the allowed entities in our list of allowed entities.
        if ('xml' === $context) {
            $string = preg_replace_callback('/&amp;([A-Za-z]{2,8}[0-9]{0,2});/', 'wp_kses_xml_named_entities', $string);
        } else {
            $string = preg_replace_callback('/&amp;([A-Za-z]{2,8}[0-9]{0,2});/', 'wp_kses_named_entities', $string);
        }
        $string = preg_replace_callback('/&amp;#(0*[0-9]{1,7});/', 'wp_kses_normalize_entities2', $string);
        $string = preg_replace_callback('/&amp;#[Xx](0*[0-9A-Fa-f]{1,6});/', 'wp_kses_normalize_entities3', $string);

        return $string;
    }
}

/**
 * Callback for `wp_kses_normalize_entities()` regular expression.
 *
 * This function only accepts valid named entity references, which are finite,
 * case-sensitive, and highly scrutinized by XML validators.  HTML named entity
 * references are converted to their code points.
 *
 * @param array  $matches preg_replace_callback() matches array.
 *
 * @return string Correctly encoded entity.
 * @global array $allowedxmlentitynames
 *
 * @since 5.5.0
 *
 * @global array $allowedentitynames
 */
if (!function_exists('wp_kses_xml_named_entities')) {
    function wp_kses_xml_named_entities($matches) {
        global $allowedentitynames, $allowedxmlentitynames;

        if (empty($matches[1])) {
            return '';
        }

        $i = $matches[1];

        if (in_array($i, $allowedxmlentitynames, true)) {
            return "&$i;";
        } elseif (in_array($i, $allowedentitynames, true)) {
            return html_entity_decode("&$i;", ENT_HTML5);
        }

        return "&amp;$i;";
    }
}

/**
 * Callback for `wp_kses_normalize_entities()` regular expression.
 *
 * This function only accepts valid named entity references, which are finite,
 * case-sensitive, and highly scrutinized by HTML and XML validators.
 *
 * @param array  $matches preg_replace_callback() matches array.
 *
 * @return string Correctly encoded entity.
 * @since 3.0.0
 *
 * @global array $allowedentitynames
 *
 */
if (!function_exists('wp_kses_named_entities')) {
    function wp_kses_named_entities($matches) {
        global $allowedentitynames;

        if (empty($matches[1])) {
            return '';
        }

        $i = $matches[1];

        return (!in_array($i, $allowedentitynames, true)) ? "&amp;$i;" : "&$i;";
    }
}

/**
 * Callback for `wp_kses_normalize_entities()` regular expression.
 *
 * This function helps `wp_kses_normalize_entities()` to only accept 16-bit
 * values and nothing more for `&#number;` entities.
 *
 * @access private
 *
 * @param array $matches `preg_replace_callback()` matches array.
 *
 * @return string Correctly encoded entity.
 * @ignore
 * @since  1.0.0
 *
 */
if (!function_exists('wp_kses_normalize_entities2')) {
    function wp_kses_normalize_entities2($matches) {
        if (empty($matches[1])) {
            return '';
        }

        $i = $matches[1];
        if (valid_unicode($i)) {
            $i = str_pad(ltrim($i, '0'), 3, '0', STR_PAD_LEFT);
            $i = "&#$i;";
        } else {
            $i = "&amp;#$i;";
        }

        return $i;
    }
}

/**
 * Callback for `wp_kses_normalize_entities()` for regular expression.
 *
 * This function helps `wp_kses_normalize_entities()` to only accept valid Unicode
 * numeric entities in hex form.
 *
 * @param array $matches `preg_replace_callback()` matches array.
 *
 * @return string Correctly encoded entity.
 * @since  2.7.0
 * @access private
 * @ignore
 *
 */
if (!function_exists('wp_kses_normalize_entities3')) {
    function wp_kses_normalize_entities3($matches) {
        if (empty($matches[1])) {
            return '';
        }

        $hexchars = $matches[1];

        return (!valid_unicode(hexdec($hexchars))) ? "&amp;#x$hexchars;" : '&#x' . ltrim($hexchars, '0') . ';';
    }
}

/**
 * Searches for HTML tags, no matter how malformed.
 *
 * It also matches stray `>` characters.
 *
 * @param string          $string                 Content to filter.
 * @param array[]|string  $allowed_html           An array of allowed HTML elements and attributes,
 *                                                or a context name such as 'post'. See wp_kses_allowed_html()
 *                                                for the list of accepted context names.
 * @param string[]        $allowed_protocols      Array of allowed URL protocols.
 *
 * @return string Content with fixed HTML tags
 * @global array[]|string $pass_allowed_html      An array of allowed HTML elements and attributes,
 *                                                or a context name such as 'post'.
 * @global string[]       $pass_allowed_protocols Array of allowed URL protocols.
 *
 * @since 1.0.0
 *
 */
if (!function_exists('wp_kses_split')) {
    function wp_kses_split($string, $allowed_html, $allowed_protocols) {
        global $pass_allowed_html, $pass_allowed_protocols;

        $pass_allowed_html      = $allowed_html;
        $pass_allowed_protocols = $allowed_protocols;

        return preg_replace_callback('%(<!--.*?(-->|$))|(<[^>]*(>|$)|>)%', '_wp_kses_split_callback', $string);
    }
}

/**
 * Callback for `wp_kses_split()`.
 *
 * @param array           $match                  preg_replace regexp matches
 *
 * @return string
 * @global array[]|string $pass_allowed_html      An array of allowed HTML elements and attributes,
 *                                                or a context name such as 'post'.
 * @global string[]       $pass_allowed_protocols Array of allowed URL protocols.
 *
 * @since  3.1.0
 * @access private
 * @ignore
 *
 */
if (!function_exists('_wp_kses_split_callback')) {
    function _wp_kses_split_callback($match) {
        global $pass_allowed_html, $pass_allowed_protocols;

        return wp_kses_split2($match[0], $pass_allowed_html, $pass_allowed_protocols);
    }
}

/**
 * Callback for `wp_kses_split()` for fixing malformed HTML tags.
 *
 * This function does a lot of work. It rejects some very malformed things like
 * `<:::>`. It returns an empty string, if the element isn't allowed (look ma, no
 * `strip_tags()`!). Otherwise it splits the tag into an element and an attribute
 * list.
 *
 * After the tag is split into an element and an attribute list, it is run
 * through another filter which will remove illegal attributes and once that is
 * completed, will be returned.
 *
 * @access private
 *
 * @param string         $string            Content to filter.
 * @param array[]|string $allowed_html      An array of allowed HTML elements and attributes,
 *                                          or a context name such as 'post'. See wp_kses_allowed_html()
 *                                          for the list of accepted context names.
 * @param string[]       $allowed_protocols Array of allowed URL protocols.
 *
 * @return string Fixed HTML element
 * @ignore
 * @since  1.0.0
 *
 */
if (!function_exists('wp_kses_split2')) {
    function wp_kses_split2($string, $allowed_html, $allowed_protocols) {
        $string = wp_kses_stripslashes($string);

        // It matched a ">" character.
        if ('<' !== substr($string, 0, 1)) {
            return '&gt;';
        }

        // Allow HTML comments.
        if ('<!--' === substr($string, 0, 4)) {
            $string = str_replace(array(
                '<!--',
                '-->'
            ), '', $string);
            while (($newstring = wp_kses($string, $allowed_html, $allowed_protocols)) != $string) {
                $string = $newstring;
            }
            if ('' === $string) {
                return '';
            }
            // Prevent multiple dashes in comments.
            $string = preg_replace('/--+/', '-', $string);
            // Prevent three dashes closing a comment.
            $string = preg_replace('/-$/', '', $string);

            return "<!--{$string}-->";
        }

        // It's seriously malformed.
        if (!preg_match('%^<\s*(/\s*)?([a-zA-Z0-9-]+)([^>]*)>?$%', $string, $matches)) {
            return '';
        }

        $slash    = trim($matches[1]);
        $elem     = $matches[2];
        $attrlist = $matches[3];

        // They are using a not allowed HTML element.
        if (!isset($allowed_html[strtolower($elem)])) {
            return '';
        }

        // No attributes are allowed for closing elements.
        if ('' !== $slash) {
            return "</$elem>";
        }

        return wp_kses_attr($elem, $attrlist, $allowed_html, $allowed_protocols);
    }
}

/**
 * Strips slashes from in front of quotes.
 *
 * This function changes the character sequence `\"` to just `"`. It leaves all other
 * slashes alone. The quoting from `preg_replace(//e)` requires this.
 *
 * @param string $string String to strip slashes from.
 *
 * @return string Fixed string with quoted slashes.
 * @since 1.0.0
 *
 */
if (!function_exists('wp_kses_stripslashes')) {
    function wp_kses_stripslashes($string) {
        return preg_replace('%\\\\"%', '"', $string);
    }
}

/**
 * Removes all attributes, if none are allowed for this element.
 *
 * If some are allowed it calls `wp_kses_hair()` to split them further, and then
 * it builds up new HTML code from the data that `wp_kses_hair()` returns. It also
 * removes `<` and `>` characters, if there are any left. One more thing it does
 * is to check if the tag has a closing XHTML slash, and if it does, it puts one
 * in the returned code as well.
 *
 * An array of allowed values can be defined for attributes. If the attribute value
 * doesn't fall into the list, the attribute will be removed from the tag.
 *
 * Attributes can be marked as required. If a required attribute is not present,
 * KSES will remove all attributes from the tag. As KSES doesn't match opening and
 * closing tags, it's not possible to safely remove the tag itself, the safest
 * fallback is to strip all attributes from the tag, instead.
 *
 * @param string         $element           HTML element/tag.
 * @param string         $attr              HTML attributes from HTML element to closing HTML element tag.
 * @param array[]|string $allowed_html      An array of allowed HTML elements and attributes,
 *                                          or a context name such as 'post'. See wp_kses_allowed_html()
 *                                          for the list of accepted context names.
 * @param string[]       $allowed_protocols Array of allowed URL protocols.
 *
 * @return string Sanitized HTML element.
 * @since       5.9.0 Added support for an array of allowed values for attributes.
 *              Added support for required attributes.
 *
 * @since       1.0.0
 */
if (!function_exists('wp_kses_attr')) {
    function wp_kses_attr($element, $attr, $allowed_html, $allowed_protocols) {

        // Is there a closing XHTML slash at the end of the attributes?
        $xhtml_slash = '';
        if (preg_match('%\s*/\s*$%', $attr)) {
            $xhtml_slash = ' /';
        }

        // Are any attributes allowed at all for this element?
        $element_low = strtolower($element);
        if (empty($allowed_html[$element_low]) || true === $allowed_html[$element_low]) {
            return "<$element$xhtml_slash>";
        }

        // Split it.
        $attrarr = wp_kses_hair($attr, $allowed_protocols);

        // Check if there are attributes that are required.
        $required_attrs = array_filter($allowed_html[$element_low], function ($required_attr_limits) {
            return isset($required_attr_limits['required']) && true === $required_attr_limits['required'];
        });

        /*
         * If a required attribute check fails, we can return nothing for a self-closing tag,
         * but for a non-self-closing tag the best option is to return the element with attributes,
         * as KSES doesn't handle matching the relevant closing tag.
         */
        $stripped_tag = '';
        if (empty($xhtml_slash)) {
            $stripped_tag = "<$element>";
        }

        // Go through $attrarr, and save the allowed attributes for this element in $attr2.
        $attr2 = '';
        foreach ($attrarr as $arreach) {
            // Check if this attribute is required.
            $required = isset($required_attrs[strtolower($arreach['name'])]);

            if (wp_kses_attr_check($arreach['name'], $arreach['value'], $arreach['whole'], $arreach['vless'], $element, $allowed_html)) {
                $attr2 .= ' ' . $arreach['whole'];

                // If this was a required attribute, we can mark it as found.
                if ($required) {
                    unset($required_attrs[strtolower($arreach['name'])]);
                }
            } elseif ($required) {
                // This attribute was required, but didn't pass the check. The entire tag is not allowed.
                return $stripped_tag;
            }
        }

        // If some required attributes weren't set, the entire tag is not allowed.
        if (!empty($required_attrs)) {
            return $stripped_tag;
        }

        // Remove any "<" or ">" characters.
        $attr2 = preg_replace('/[<>]/', '', $attr2);

        return "<$element$attr2$xhtml_slash>";
    }
}

/**
 * Builds an attribute list from string containing attributes.
 *
 * This function does a lot of work. It parses an attribute list into an array
 * with attribute data, and tries to do the right thing even if it gets weird
 * input. It will add quotes around attribute values that don't have any quotes
 * or apostrophes around them, to make it easier to produce HTML code that will
 * conform to W3C's HTML specification. It will also remove bad URL protocols
 * from attribute values. It also reduces duplicate attributes by using the
 * attribute defined first (`foo='bar' foo='baz'` will result in `foo='bar'`).
 *
 * @param string   $attr              Attribute list from HTML element to closing HTML element tag.
 * @param string[] $allowed_protocols Array of allowed URL protocols.
 *
 * @return array[] Array of attribute information after parsing.
 * @since 1.0.0
 *
 */
if (!function_exists('wp_kses_hair')) {
    function wp_kses_hair($attr, $allowed_protocols) {
        $attrarr  = array();
        $mode     = 0;
        $attrname = '';
        $uris     = wp_kses_uri_attributes();

        // Loop through the whole attribute list.

        while (strlen($attr) != 0) {
            $working = 0; // Was the last operation successful?

            switch ($mode) {
                case 0:
                    if (preg_match('/^([_a-zA-Z][-_a-zA-Z0-9:.]*)/', $attr, $match)) {
                        $attrname = $match[1];
                        $working  = 1;
                        $mode     = 1;
                        $attr     = preg_replace('/^[_a-zA-Z][-_a-zA-Z0-9:.]*/', '', $attr);
                    }

                    break;

                case 1:
                    if (preg_match('/^\s*=\s*/', $attr)) { // Equals sign.
                        $working = 1;
                        $mode    = 2;
                        $attr    = preg_replace('/^\s*=\s*/', '', $attr);
                        break;
                    }

                    if (preg_match('/^\s+/', $attr)) { // Valueless.
                        $working = 1;
                        $mode    = 0;
                        if (false === array_key_exists($attrname, $attrarr)) {
                            $attrarr[$attrname] = array(
                                'name'  => $attrname,
                                'value' => '',
                                'whole' => $attrname,
                                'vless' => 'y',
                            );
                        }
                        $attr = preg_replace('/^\s+/', '', $attr);
                    }

                    break;

                case 2:
                    if (preg_match('%^"([^"]*)"(\s+|/?$)%', $attr, $match)) {
                        // "value"
                        $thisval = $match[1];
                        if (in_array(strtolower($attrname), $uris, true)) {
                            $thisval = wp_kses_bad_protocol($thisval, $allowed_protocols);
                        }

                        if (false === array_key_exists($attrname, $attrarr)) {
                            $attrarr[$attrname] = array(
                                'name'  => $attrname,
                                'value' => $thisval,
                                'whole' => "$attrname=\"$thisval\"",
                                'vless' => 'n',
                            );
                        }
                        $working = 1;
                        $mode    = 0;
                        $attr    = preg_replace('/^"[^"]*"(\s+|$)/', '', $attr);
                        break;
                    }

                    if (preg_match("%^'([^']*)'(\s+|/?$)%", $attr, $match)) {
                        // 'value'
                        $thisval = $match[1];
                        if (in_array(strtolower($attrname), $uris, true)) {
                            $thisval = wp_kses_bad_protocol($thisval, $allowed_protocols);
                        }

                        if (false === array_key_exists($attrname, $attrarr)) {
                            $attrarr[$attrname] = array(
                                'name'  => $attrname,
                                'value' => $thisval,
                                'whole' => "$attrname='$thisval'",
                                'vless' => 'n',
                            );
                        }
                        $working = 1;
                        $mode    = 0;
                        $attr    = preg_replace("/^'[^']*'(\s+|$)/", '', $attr);
                        break;
                    }

                    if (preg_match("%^([^\s\"']+)(\s+|/?$)%", $attr, $match)) {
                        // value
                        $thisval = $match[1];
                        if (in_array(strtolower($attrname), $uris, true)) {
                            $thisval = wp_kses_bad_protocol($thisval, $allowed_protocols);
                        }

                        if (false === array_key_exists($attrname, $attrarr)) {
                            $attrarr[$attrname] = array(
                                'name'  => $attrname,
                                'value' => $thisval,
                                'whole' => "$attrname=\"$thisval\"",
                                'vless' => 'n',
                            );
                        }
                        // We add quotes to conform to W3C's HTML spec.
                        $working = 1;
                        $mode    = 0;
                        $attr    = preg_replace("%^[^\s\"']+(\s+|$)%", '', $attr);
                    }

                    break;
            } // End switch.

            if (0 == $working) { // Not well-formed, remove and try again.
                $attr = wp_kses_html_error($attr);
                $mode = 0;
            }
        } // End while.

        if (1 == $mode && false === array_key_exists($attrname, $attrarr)) {
            // Special case, for when the attribute list ends with a valueless
            // attribute like "selected".
            $attrarr[$attrname] = array(
                'name'  => $attrname,
                'value' => '',
                'whole' => $attrname,
                'vless' => 'y',
            );
        }

        return $attrarr;
    }
}

/**
 * Determines whether an attribute is allowed.
 *
 * @param string $name         The attribute name. Passed by reference. Returns empty string when not allowed.
 * @param string $value        The attribute value. Passed by reference. Returns a filtered value.
 * @param string $whole        The `name=value` input. Passed by reference. Returns filtered input.
 * @param string $vless        Whether the attribute is valueless. Use 'y' or 'n'.
 * @param string $element      The name of the element to which this attribute belongs.
 * @param array  $allowed_html The full list of allowed elements and attributes.
 *
 * @return bool Whether or not the attribute is allowed.
 * @since 5.0.0 Added support for `data-*` wildcard attributes.
 *
 * @since 4.2.3
 */
if (!function_exists('wp_kses_attr_check')) {
    function wp_kses_attr_check(&$name, &$value, &$whole, $vless, $element, $allowed_html) {
        $name_low    = strtolower($name);
        $element_low = strtolower($element);

        if (!isset($allowed_html[$element_low])) {
            $name  = '';
            $value = '';
            $whole = '';

            return false;
        }

        $allowed_attr = $allowed_html[$element_low];

        if (!isset($allowed_attr[$name_low]) || '' === $allowed_attr[$name_low]) {
            /*
             * Allow `data-*` attributes.
             *
             * When specifying `$allowed_html`, the attribute name should be set as
             * `data-*` (not to be mixed with the HTML 4.0 `data` attribute, see
             * https://www.w3.org/TR/html40/struct/objects.html#adef-data).
             *
             * Note: the attribute name should only contain `A-Za-z0-9_-` chars,
             * double hyphens `--` are not accepted by WordPress.
             */
            if (strpos($name_low, 'data-') === 0 && !empty($allowed_attr['data-*']) && preg_match('/^data(?:-[a-z0-9_]+)+$/', $name_low, $match)) {
                /*
                 * Add the whole attribute name to the allowed attributes and set any restrictions
                 * for the `data-*` attribute values for the current element.
                 */
                $allowed_attr[$match[0]] = $allowed_attr['data-*'];
            } else {
                $name  = '';
                $value = '';
                $whole = '';

                return false;
            }
        }

        if ('style' === $name_low) {
            $new_value = safecss_filter_attr($value);

            if (empty($new_value)) {
                $name  = '';
                $value = '';
                $whole = '';

                return false;
            }

            $whole = str_replace($value, $new_value, $whole);
            $value = $new_value;
        }

        if (is_array($allowed_attr[$name_low])) {
            // There are some checks.
            foreach ($allowed_attr[$name_low] as $currkey => $currval) {
                if (!wp_kses_check_attr_val($value, $vless, $currkey, $currval)) {
                    $name  = '';
                    $value = '';
                    $whole = '';

                    return false;
                }
            }
        }

        return true;
    }
}

/**
 * Returns an array of HTML attribute names whose value contains a URL.
 *
 * This function returns a list of all HTML attributes that must contain
 * a URL according to the HTML specification.
 *
 * This list includes URI attributes both allowed and disallowed by KSES.
 *
 * @link  https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes
 *
 * @since 5.0.1
 *
 * @return string[] HTML attribute names whose value contains a URL.
 */
if (!function_exists('wp_kses_uri_attributes')) {
    function wp_kses_uri_attributes() {
        $uri_attributes = array(
            'action',
            'archive',
            'background',
            'cite',
            'classid',
            'codebase',
            'data',
            'formaction',
            'href',
            'icon',
            'longdesc',
            'manifest',
            'poster',
            'profile',
            'src',
            'usemap',
            'xmlns',
        );

        return $uri_attributes;
    }
}

/**
 * Sanitizes a string and removed disallowed URL protocols.
 *
 * This function removes all non-allowed protocols from the beginning of the
 * string. It ignores whitespace and the case of the letters, and it does
 * understand HTML entities. It does its work recursively, so it won't be
 * fooled by a string like `javascript:javascript:alert(57)`.
 *
 * @param string   $string            Content to filter bad protocols from.
 * @param string[] $allowed_protocols Array of allowed URL protocols.
 *
 * @return string Filtered content.
 * @since 1.0.0
 *
 */
if (!function_exists('wp_kses_bad_protocol')) {
    function wp_kses_bad_protocol($string, $allowed_protocols) {
        $string     = wp_kses_no_null($string);
        $iterations = 0;

        do {
            $original_string = $string;
            $string          = wp_kses_bad_protocol_once($string, $allowed_protocols);
        } while ($original_string != $string && ++$iterations < 6);

        if ($original_string != $string) {
            return '';
        }

        return $string;
    }
}

/**
 * Sanitizes content from bad protocols and other characters.
 *
 * This function searches for URL protocols at the beginning of the string, while
 * handling whitespace and HTML entities.
 *
 * @param string   $string            Content to check for bad protocols.
 * @param string[] $allowed_protocols Array of allowed URL protocols.
 * @param int      $count             Depth of call recursion to this function.
 *
 * @return string Sanitized content.
 * @since 1.0.0
 *
 */
if (!function_exists('wp_kses_bad_protocol_once')) {
    function wp_kses_bad_protocol_once($string, $allowed_protocols, $count = 1) {
        $string  = preg_replace('/(&#0*58(?![;0-9])|&#x0*3a(?![;a-f0-9]))/i', '$1;', $string);
        $string2 = preg_split('/:|&#0*58;|&#x0*3a;|&colon;/i', $string, 2);
        if (isset($string2[1]) && !preg_match('%/\?%', $string2[0])) {
            $string   = trim($string2[1]);
            $protocol = wp_kses_bad_protocol_once2($string2[0], $allowed_protocols);
            if ('feed:' === $protocol) {
                if ($count > 2) {
                    return '';
                }
                $string = wp_kses_bad_protocol_once($string, $allowed_protocols, ++$count);
                if (empty($string)) {
                    return $string;
                }
            }
            $string = $protocol . $string;
        }

        return $string;
    }
}

/**
 * Callback for `wp_kses_bad_protocol_once()` regular expression.
 *
 * This function processes URL protocols, checks to see if they're in the
 * list of allowed protocols or not, and returns different data depending
 * on the answer.
 *
 * @access private
 *
 * @param string   $string            URI scheme to check against the list of allowed protocols.
 * @param string[] $allowed_protocols Array of allowed URL protocols.
 *
 * @return string Sanitized content.
 * @since  1.0.0
 *
 * @ignore
 */
if (!function_exists('wp_kses_bad_protocol_once2')) {
    function wp_kses_bad_protocol_once2($string, $allowed_protocols) {
        $string2 = wp_kses_decode_entities($string);
        $string2 = preg_replace('/\s/', '', $string2);
        $string2 = wp_kses_no_null($string2);
        $string2 = strtolower($string2);

        $allowed = false;
        foreach ((array)$allowed_protocols as $one_protocol) {
            if (strtolower($one_protocol) == $string2) {
                $allowed = true;
                break;
            }
        }

        if ($allowed) {
            return "$string2:";
        } else {
            return '';
        }
    }
}

/**
 * Converts all numeric HTML entities to their named counterparts.
 *
 * This function decodes numeric HTML entities (`&#65;` and `&#x41;`).
 * It doesn't do anything with named entities like `&auml;`, but we don't
 * need them in the allowed URL protocols system anyway.
 *
 * @param string $string Content to change entities.
 *
 * @return string Content after decoded entities.
 * @since 1.0.0
 *
 */
if (!function_exists('wp_kses_decode_entities')) {
    function wp_kses_decode_entities($string) {
        $string = preg_replace_callback('/&#([0-9]+);/', '_wp_kses_decode_entities_chr', $string);
        $string = preg_replace_callback('/&#[Xx]([0-9A-Fa-f]+);/', '_wp_kses_decode_entities_chr_hexdec', $string);

        return $string;
    }
}

/**
 * Regex callback for `wp_kses_decode_entities()`.
 *
 * @param array $match preg match
 *
 * @return string
 * @since  2.9.0
 * @access private
 * @ignore
 *
 */
if (!function_exists('_wp_kses_decode_entities_chr')) {
    function _wp_kses_decode_entities_chr($match) {
        return chr($match[1]);
    }
}

/**
 * Regex callback for `wp_kses_decode_entities()`.
 *
 * @param array $match preg match
 *
 * @return string
 * @since  2.9.0
 * @access private
 * @ignore
 *
 */
if (!function_exists('_wp_kses_decode_entities_chr_hexdec')) {
    function _wp_kses_decode_entities_chr_hexdec($match) {
        return chr(hexdec($match[1]));
    }
}

/**
 * Handles parsing errors in `wp_kses_hair()`.
 *
 * The general plan is to remove everything to and including some whitespace,
 * but it deals with quotes and apostrophes as well.
 *
 * @param string $string
 *
 * @return string
 * @since 1.0.0
 *
 */
if (!function_exists('wp_kses_html_error')) {
    function wp_kses_html_error($string) {
        return preg_replace('/^("[^"]*("|$)|\'[^\']*(\'|$)|\S)*\s*/', '', $string);
    }
}

/**
 * Filters an inline style attribute and removes disallowed rules.
 *
 * @param string $css A string of CSS rules.
 *
 * @return string Filtered string of CSS rules.
 * @since       2.8.1
 * @since       4.4.0 Added support for `min-height`, `max-height`, `min-width`, and `max-width`.
 * @since       4.6.0 Added support for `list-style-type`.
 * @since       5.0.0 Added support for `background-image`.
 * @since       5.1.0 Added support for `text-transform`.
 * @since       5.2.0 Added support for `background-position` and `grid-template-columns`.
 * @since       5.3.0 Added support for `grid`, `flex` and `column` layout properties.
 *              Extend `background-*` support of individual properties.
 * @since       5.3.1 Added support for gradient backgrounds.
 * @since       5.7.1 Added support for `object-position`.
 * @since       5.8.0 Added support for `calc()` and `var()` values.
 *
 */
if (!function_exists('safecss_filter_attr')) {
    function safecss_filter_attr($css) {

        $css = wp_kses_no_null($css);
        $css = str_replace(array(
            "\n",
            "\r",
            "\t"
        ), '', $css);

        $allowed_protocols = wp_allowed_protocols();

        $css_array = explode(';', trim($css));

        /**
         * Filters the list of allowed CSS attributes.
         *
         * @param string[] $attr Array of allowed CSS attributes.
         *
         * @since 2.8.1
         *
         */
        $allowed_attr = array(
            'background',
            'background-color',
            'background-image',
            'background-position',
            'background-size',
            'background-attachment',
            'background-blend-mode',

            'border',
            'border-radius',
            'border-width',
            'border-color',
            'border-style',
            'border-right',
            'border-right-color',
            'border-right-style',
            'border-right-width',
            'border-bottom',
            'border-bottom-color',
            'border-bottom-left-radius',
            'border-bottom-right-radius',
            'border-bottom-style',
            'border-bottom-width',
            'border-bottom-right-radius',
            'border-bottom-left-radius',
            'border-left',
            'border-left-color',
            'border-left-style',
            'border-left-width',
            'border-top',
            'border-top-color',
            'border-top-left-radius',
            'border-top-right-radius',
            'border-top-style',
            'border-top-width',
            'border-top-left-radius',
            'border-top-right-radius',

            'border-spacing',
            'border-collapse',
            'caption-side',

            'columns',
            'column-count',
            'column-fill',
            'column-gap',
            'column-rule',
            'column-span',
            'column-width',

            'color',
            'filter',
            'font',
            'font-family',
            'font-size',
            'font-style',
            'font-variant',
            'font-weight',
            'letter-spacing',
            'line-height',
            'text-align',
            'text-decoration',
            'text-indent',
            'text-transform',

            'height',
            'min-height',
            'max-height',

            'width',
            'min-width',
            'max-width',

            'margin',
            'margin-right',
            'margin-bottom',
            'margin-left',
            'margin-top',

            'padding',
            'padding-right',
            'padding-bottom',
            'padding-left',
            'padding-top',

            'flex',
            'flex-basis',
            'flex-direction',
            'flex-flow',
            'flex-grow',
            'flex-shrink',

            'grid-template-columns',
            'grid-auto-columns',
            'grid-column-start',
            'grid-column-end',
            'grid-column-gap',
            'grid-template-rows',
            'grid-auto-rows',
            'grid-row-start',
            'grid-row-end',
            'grid-row-gap',
            'grid-gap',

            'justify-content',
            'justify-items',
            'justify-self',
            'align-content',
            'align-items',
            'align-self',

            'clear',
            'cursor',
            'direction',
            'float',
            'list-style-type',
            'object-position',
            'overflow',
            'vertical-align',
        );

        /*
         * CSS attributes that accept URL data types.
         *
         * This is in accordance to the CSS spec and unrelated to
         * the sub-set of supported attributes above.
         *
         * See: https://developer.mozilla.org/en-US/docs/Web/CSS/url
         */
        $css_url_data_types = array(
            'background',
            'background-image',

            'cursor',

            'list-style',
            'list-style-image',
        );

        /*
         * CSS attributes that accept gradient data types.
         *
         */
        $css_gradient_data_types = array(
            'background',
            'background-image',
        );

        if (empty($allowed_attr)) {
            return $css;
        }

        $css = '';
        foreach ($css_array as $css_item) {
            if ('' === $css_item) {
                continue;
            }

            $css_item        = trim($css_item);
            $css_test_string = $css_item;
            $found           = false;
            $url_attr        = false;
            $gradient_attr   = false;

            if (strpos($css_item, ':') === false) {
                $found = true;
            } else {
                $parts        = explode(':', $css_item, 2);
                $css_selector = trim($parts[0]);

                if (in_array($css_selector, $allowed_attr, true)) {
                    $found         = true;
                    $url_attr      = in_array($css_selector, $css_url_data_types, true);
                    $gradient_attr = in_array($css_selector, $css_gradient_data_types, true);
                }
            }

            if ($found && $url_attr) {
                // Simplified: matches the sequence `url(*)`.
                preg_match_all('/url\([^)]+\)/', $parts[1], $url_matches);

                foreach ($url_matches[0] as $url_match) {
                    // Clean up the URL from each of the matches above.
                    preg_match('/^url\(\s*([\'\"]?)(.*)(\g1)\s*\)$/', $url_match, $url_pieces);

                    if (empty($url_pieces[2])) {
                        $found = false;
                        break;
                    }

                    $url = trim($url_pieces[2]);

                    if (empty($url) || wp_kses_bad_protocol($url, $allowed_protocols) !== $url) {
                        $found = false;
                        break;
                    } else {
                        // Remove the whole `url(*)` bit that was matched above from the CSS.
                        $css_test_string = str_replace($url_match, '', $css_test_string);
                    }
                }
            }

            if ($found && $gradient_attr) {
                $css_value = trim($parts[1]);
                if (preg_match('/^(repeating-)?(linear|radial|conic)-gradient\(([^()]|rgb[a]?\([^()]*\))*\)$/', $css_value)) {
                    // Remove the whole `gradient` bit that was matched above from the CSS.
                    $css_test_string = str_replace($css_value, '', $css_test_string);
                }
            }

            if ($found) {
                // Allow CSS calc().
                $css_test_string = preg_replace('/calc\(((?:\([^()]*\)?|[^()])*)\)/', '', $css_test_string);
                // Allow CSS var().
                $css_test_string = preg_replace('/\(?var\(--[a-zA-Z0-9_-]*\)/', '', $css_test_string);

                // Check for any CSS containing \ ( & } = or comments,
                // except for url(), calc(), or var() usage checked above.
                $allow_css = !preg_match('%[\\\(&=}]|/\*%', $css_test_string);

                /**
                 * Filters the check for unsafe CSS in `safecss_filter_attr`.
                 *
                 * Enables developers to determine whether a section of CSS should be allowed or discarded.
                 * By default, the value will be false if the part contains \ ( & } = or comments.
                 * Return true to allow the CSS part to be included in the output.
                 *
                 * @param bool   $allow_css       Whether the CSS in the test string is considered safe.
                 * @param string $css_test_string The CSS string to test.
                 *
                 * @since 5.5.0
                 *
                 */

                // Only add the CSS part if it passes the regex check.
                if ($allow_css) {
                    if ('' !== $css) {
                        $css .= ';';
                    }

                    $css .= $css_item;
                }
            }
        }

        return $css;
    }
}

/**
 * Performs different checks for attribute values.
 *
 * The currently implemented checks are "maxlen", "minlen", "maxval", "minval",
 * and "valueless".
 *
 * @param string $value      Attribute value.
 * @param string $vless      Whether the attribute is valueless. Use 'y' or 'n'.
 * @param string $checkname  What $checkvalue is checking for.
 * @param mixed  $checkvalue What constraint the value should pass.
 *
 * @return bool Whether check passes.
 * @since 1.0.0
 *
 */
if (!function_exists('wp_kses_check_attr_val')) {
    function wp_kses_check_attr_val($value, $vless, $checkname, $checkvalue) {
        $ok = true;

        switch (strtolower($checkname)) {
            case 'maxlen':
                /*
                 * The maxlen check makes sure that the attribute value has a length not
                 * greater than the given value. This can be used to avoid Buffer Overflows
                 * in WWW clients and various Internet servers.
                 */

                if (strlen($value) > $checkvalue) {
                    $ok = false;
                }
                break;

            case 'minlen':
                /*
                 * The minlen check makes sure that the attribute value has a length not
                 * smaller than the given value.
                 */

                if (strlen($value) < $checkvalue) {
                    $ok = false;
                }
                break;

            case 'maxval':
                /*
                 * The maxval check does two things: it checks that the attribute value is
                 * an integer from 0 and up, without an excessive amount of zeroes or
                 * whitespace (to avoid Buffer Overflows). It also checks that the attribute
                 * value is not greater than the given value.
                 * This check can be used to avoid Denial of Service attacks.
                 */

                if (!preg_match('/^\s{0,6}[0-9]{1,6}\s{0,6}$/', $value)) {
                    $ok = false;
                }
                if ($value > $checkvalue) {
                    $ok = false;
                }
                break;

            case 'minval':
                /*
                 * The minval check makes sure that the attribute value is a positive integer,
                 * and that it is not smaller than the given value.
                 */

                if (!preg_match('/^\s{0,6}[0-9]{1,6}\s{0,6}$/', $value)) {
                    $ok = false;
                }
                if ($value < $checkvalue) {
                    $ok = false;
                }
                break;

            case 'valueless':
                /*
                 * The valueless check makes sure if the attribute has a value
                 * (like `<a href="blah">`) or not (`<option selected>`). If the given value
                 * is a "y" or a "Y", the attribute must not have a value.
                 * If the given value is an "n" or an "N", the attribute must have a value.
                 */

                if (strtolower($checkvalue) != $vless) {
                    $ok = false;
                }
                break;

            case 'values':
                /*
                 * The values check is used when you want to make sure that the attribute
                 * has one of the given values.
                 */

                if (false === array_search(strtolower($value), $checkvalue, true)) {
                    $ok = false;
                }
                break;

            case 'value_callback':
                /*
                 * The value_callback check is used when you want to make sure that the attribute
                 * value is accepted by the callback function.
                 */

                if (!call_user_func($checkvalue, $value)) {
                    $ok = false;
                }
                break;
        } // End switch.

        return $ok;
    }
}AdministratorComponent.php000064400000005433152416656040011776 0ustar00<?php


namespace Nextend\SmartSlider3\Platform\Joomla;


use Joomla\CMS\Access\Exception\NotAllowed;
use Joomla\CMS\Factory;
use Joomla\CMS\Plugin\PluginHelper;
use Joomla\CMS\Language\Text;
use Joomla\CMS\Uri\Uri;
use Nextend\Framework\PageFlow;
use Nextend\Framework\Request\Request;
use Nextend\SmartSlider3\Application\ApplicationSmartSlider3;
use Nextend\SmartSlider3\Install\Install;
use Nextend\SmartSlider3\Install\Tables;
use Nextend\SmartSlider3\Platform\SmartSlider3Platform;
use Nextend\SmartSlider3\Settings;
use Nextend\SmartSlider3\SmartSlider3Info;
use plgSystemSmartSlider3;

class AdministratorComponent {

    public function __construct() {

        $this->checkAcl();

        if (!Request::$GET->getInt('keepalive')) {

            /**
             * Required for the license activation to work.
             */
            Factory::getApplication()
                   ->setHeader('cross-origin-opener-policy', 'unsafe-none', true);

            $this->loadSystemPlugins();

            if (Settings::get('n2_ss3_version') != SmartSlider3Info::$completeVersion) {

                Install::install();
            } else if (Request::$REQUEST->getInt('repairss3')) {
                Install::install();

                Tables::repair();
                header('LOCATION: ' . SmartSlider3Platform::getAdminUrl());
                exit;
            }

            $applicationType = ApplicationSmartSlider3::getInstance()
                                                      ->getApplicationTypeAdmin();

            $isAjax = Request::$GET->getInt('nextendajax');

            $applicationType->processRequest('sliders', 'gettingstarted', $isAjax);

            ?>
            <script>
                _N2.r('$', function () {
                    var $ = _N2.$;
                    var __keepAlive = function () {
                        $.get('<?php echo esc_url(Uri::current() . '?option=com_smartslider3&keepalive=1');?>', function () {
                            setTimeout(__keepAlive, 300000);
                        });
                    };
                    setTimeout(__keepAlive, 300000);
                });
            </script>
            <?php
            PageFlow::markApplicationEnd();
        }
    }

    protected function checkAcl() {

        if (!Factory::getUser()
                     ->authorise('core.manage', 'com_smartslider3')) {
            throw new NotAllowed(Text::_('JERROR_ALERTNOAUTHOR'), 403);
        }
    }

    protected function loadSystemPlugins() {

        if (!class_exists('plgSystemSmartSlider3')) {

            $plugin = PluginHelper::getPlugin('system', 'smartslider3');
            new plgSystemSmartSlider3(JoomlaShim::getDispatcher(), (array)($plugin));
        }
    }
}compat.php000064400000000704152416656110006550 0ustar00<?php

use Nextend\SmartSlider3\Application\ApplicationSmartSlider3;

function nextend_smartslider3($sliderId, $usage = 'Used in PHP') {

    $applicationTypeFrontend = ApplicationSmartSlider3::getInstance()
                                                      ->getApplicationTypeFrontend();

    $applicationTypeFrontend->process('slider', 'display', false, array(
        'sliderID' => $sliderId,
        'usage'    => $usage
    ));
}ImageFallback.php000064400000007121152416656160007734 0ustar00<?php

namespace Nextend\SmartSlider3\Platform\Joomla;

use Joomla\CMS\Uri\Uri;
use Nextend\Framework\Filesystem\Filesystem;
use Nextend\Framework\Request\Request;

class ImageFallback {

    static public function fallback($imageVars, $textVars = array(), $root = '') {
        $root   = self::fixRoot($root);
        $return = '';

        foreach ($imageVars as $image) {
            if (!empty($image)) {
                if (strpos($image, '#') !== false) {
                    $imageHelper = explode('#', $image);
                    $realImage   = $imageHelper[0];
                } else {
                    $realImage = $image;
                }
                $return = self::getImage($realImage, $root);
                if (!empty($return)) {
                    break;
                }
            }
        }

        if ($return == '' && !empty($textVars)) {
            foreach ($textVars as $text) {
                $imageInText = self::findImage($text);

                if (!empty($imageInText)) {
                    $return = self::getImage($imageInText, $root);

                    if ($return != '$/') {
                        break;
                    } else {
                        $return = '';
                    }
                }
            }
        }

        return $return;
    }

    static public function fixRoot($root) {
        if (substr($root, 0, 5) != 'http:' && substr($root, 0, 6) != 'https:') {
            $root = self::siteURL();
        }

        return self::removeSlashes($root);
    }

    static public function getImage($image, $root) {
        $imageUrl = self::httpLink($image, $root);
        if (self::isExternal($imageUrl) || self::imageUrlExists($imageUrl)) {
            return $imageUrl;
        } else {
            return '';
        }
    }

    static public function findImage($s) {
        preg_match_all('/(<img.*?src=[\'"](.*?)[\'"][^>]*>)|(background(-image)??\s*?:.*?url\((["|\']?)?(.+?)(["|\']?)?\))/i', $s, $r);
        if (isset($r[2]) && !empty($r[2][0])) {
            $s = $r[2][0];
        } else if (isset($r[6]) && !empty($r[6][0])) {
            $s = trim($r[6][0], "'\" \t\n\r\0\x0B");
        } else {
            $s = '';
        }

        return $s;
    }

    static public function removeSlashes($text, $right = true) {
        if ($right) {
            return rtrim($text, '/\\');
        } else {
            return ltrim($text, '/\\');
        }
    }

    static public function siteURL() {
        return Uri::root(false);
    }

    static public function isExternal($url) {
        $url = str_replace(array(
            'http:',
            'https:',
            '//',
            '\\\\'
        ), '', $url);

        $domain = Request::$SERVER->getVar('HTTP_HOST');

        return !(substr($url, 0, strlen($domain)) === $domain);
    }

    static public function httpLink($image, $root) {
        if (substr($image, 0, 5) != 'http:' && substr($image, 0, 6) != 'https:' && substr($image, 0, 2) != '//' && substr($image, 0, 2) != '\\\\') {
            return $root . '/' . self::removeSlashes($image, false);
        } else {
            return $image;
        }
    }

    static public function imageUrlExists($imageUrl) {
        if (substr($imageUrl, 0, 2) == '//' || substr($imageUrl, 0, 2) == '\\\\') {
            $imageUrl = (strtolower(Request::$SERVER->getCmd('HTTPS', 'off')) != 'off' ? "https:" : "http:") . $imageUrl;
        }

        return Filesystem::existsFile(Filesystem::absoluteURLToPath(urldecode($imageUrl)));
    }
}Joomla3Assets.php000064400000025030152416656230007756 0ustar00<?php


namespace Nextend\SmartSlider3\Platform\Joomla;


use Joomla\CMS\Document\HtmlDocument;
use Joomla\CMS\Factory;

class Joomla3Assets {

    /**
     * @var HtmlDocument
     */
    private $document;

    private $original = array();
    private $updates = array();

    public function __construct() {

        $this->document = Factory::getDocument();

        $this->original['_styleSheets'] = $this->document->_styleSheets;
        $this->original['_style']       = $this->document->_style;

        $this->original['_scripts'] = $this->document->_scripts;
        $this->original['_script']  = $this->document->_script;

        $this->document->_style  = array();
        $this->document->_script = array();
    }

    public function process() {

        $this->updates['_styleSheets'] = array_diff_key($this->document->_styleSheets, $this->original['_styleSheets']);
        $this->updates['_style']       = $this->document->_style;

        $this->updates['_scripts'] = array_diff_key($this->document->_scripts, $this->original['_scripts']);
        $this->updates['_script']  = $this->document->_script;


        $this->document->_style  = $this->original['_style'];
        $this->document->_script = $this->original['_script'];
    }

    /**
     * Based on Joomla\CMS\Document\DocumentRendererHead
     *
     * @return string
     */
    public function renderHead() {

        if (get_class($this->document) === 'Joomla\CMS\Document\HtmlDocument') {
            $lnEnd        = $this->document->_getLineEnd();
            $tab          = $this->document->_getTab();
            $tagEnd       = ' >';
            $buffer       = '';
            $mediaVersion = $this->document->getMediaVersion();

            $defaultCssMimes = array('text/css');

            // Generate stylesheet links
            foreach ($this->updates['_styleSheets'] as $src => $attribs) {
                // Check if stylesheet uses IE conditional statements.
                $conditional = isset($attribs['options']) && isset($attribs['options']['conditional']) ? $attribs['options']['conditional'] : null;

                // Check if script uses media version.
                if (isset($attribs['options']['version']) && $attribs['options']['version'] && strpos($src, '?') === false && ($mediaVersion || $attribs['options']['version'] !== 'auto')) {
                    $src .= '?' . ($attribs['options']['version'] === 'auto' ? $mediaVersion : $attribs['options']['version']);
                }

                $buffer .= $tab;

                // This is for IE conditional statements support.
                if (!is_null($conditional)) {
                    $buffer .= '<!--[if ' . $conditional . ']>';
                }

                $buffer .= '<link href="' . $src . '" rel="stylesheet"';

                // Add script tag attributes.
                foreach ($attribs as $attrib => $value) {
                    // Don't add the 'options' attribute. This attribute is for internal use (version, conditional, etc).
                    if ($attrib === 'options') {
                        continue;
                    }

                    // Don't add type attribute if document is HTML5 and it's a default mime type. 'mime' is for B/C.
                    if (in_array($attrib, array(
                            'type',
                            'mime'
                        )) && $this->document->isHtml5() && in_array($value, $defaultCssMimes)) {
                        continue;
                    }

                    // Don't add type attribute if document is HTML5 and it's a default mime type. 'mime' is for B/C.
                    if ($attrib === 'mime') {
                        $attrib = 'type';
                    }

                    // Add attribute to script tag output.
                    $buffer .= ' ' . htmlspecialchars($attrib, ENT_COMPAT, 'UTF-8');

                    // Json encode value if it's an array.
                    $value = !is_scalar($value) ? json_encode($value) : $value;

                    $buffer .= '="' . htmlspecialchars($value, ENT_COMPAT, 'UTF-8') . '"';
                }

                $buffer .= $tagEnd;

                // This is for IE conditional statements support.
                if (!is_null($conditional)) {
                    $buffer .= '<![endif]-->';
                }

                $buffer .= $lnEnd;
            }

            // Generate stylesheet declarations
            foreach ($this->updates['_style'] as $type => $content) {
                $buffer .= $tab . '<style';

                if (!is_null($type) && (!$this->document->isHtml5() || !in_array($type, $defaultCssMimes))) {
                    $buffer .= ' type="' . $type . '"';
                }

                $buffer .= '>' . $lnEnd;

                // This is for full XHTML support.
                if ($this->document->_mime != 'text/html') {
                    $buffer .= $tab . $tab . '/*<![CDATA[*/' . $lnEnd;
                }

                $buffer .= $content . $lnEnd;

                // See above note
                if ($this->document->_mime != 'text/html') {
                    $buffer .= $tab . $tab . '/*]]>*/' . $lnEnd;
                }

                $buffer .= $tab . '</style>' . $lnEnd;
            }

            // Generate scripts options
            $scriptOptions = $this->document->getScriptOptions();

            if (!empty($scriptOptions)) {
                $buffer .= $tab . '<script type="application/json" class="joomla-script-options new">';

                $prettyPrint = (JDEBUG && defined('JSON_PRETTY_PRINT') ? JSON_PRETTY_PRINT : false);
                $jsonOptions = json_encode($scriptOptions, $prettyPrint);
                $jsonOptions = $jsonOptions ? $jsonOptions : '{}';

                $buffer .= $jsonOptions;
                $buffer .= '</script>' . $lnEnd;
            }

            $defaultJsMimes         = array(
                'text/javascript',
                'application/javascript',
                'text/x-javascript',
                'application/x-javascript'
            );
            $html5NoValueAttributes = array(
                'defer',
                'async'
            );

            foreach ($this->updates['_scripts'] as $src => $attribs) {
                // Check if script uses IE conditional statements.
                $conditional = isset($attribs['options']) && isset($attribs['options']['conditional']) ? $attribs['options']['conditional'] : null;

                // Check if script uses media version.
                if (isset($attribs['options']['version']) && $attribs['options']['version'] && strpos($src, '?') === false && ($mediaVersion || $attribs['options']['version'] !== 'auto')) {
                    $src .= '?' . ($attribs['options']['version'] === 'auto' ? $mediaVersion : $attribs['options']['version']);
                }

                $buffer .= $tab;

                // This is for IE conditional statements support.
                if (!is_null($conditional)) {
                    $buffer .= '<!--[if ' . $conditional . ']>';
                }

                $buffer .= '<script src="' . $src . '"';

                // Add script tag attributes.
                foreach ($attribs as $attrib => $value) {
                    // Don't add the 'options' attribute. This attribute is for internal use (version, conditional, etc).
                    if ($attrib === 'options') {
                        continue;
                    }

                    // Don't add type attribute if document is HTML5 and it's a default mime type. 'mime' is for B/C.
                    if (in_array($attrib, array(
                            'type',
                            'mime'
                        )) && $this->document->isHtml5() && in_array($value, $defaultJsMimes)) {
                        continue;
                    }

                    // B/C: If defer and async is false or empty don't render the attribute.
                    if (in_array($attrib, array(
                            'defer',
                            'async'
                        )) && !$value) {
                        continue;
                    }

                    // Don't add type attribute if document is HTML5 and it's a default mime type. 'mime' is for B/C.
                    if ($attrib === 'mime') {
                        $attrib = 'type';
                    } // B/C defer and async can be set to yes when using the old method.
                    else if (in_array($attrib, array(
                            'defer',
                            'async'
                        )) && $value === true) {
                        $value = $attrib;
                    }

                    // Add attribute to script tag output.
                    $buffer .= ' ' . htmlspecialchars($attrib, ENT_COMPAT, 'UTF-8');

                    if (!($this->document->isHtml5() && in_array($attrib, $html5NoValueAttributes))) {
                        // Json encode value if it's an array.
                        $value = !is_scalar($value) ? json_encode($value) : $value;

                        $buffer .= '="' . htmlspecialchars($value, ENT_COMPAT, 'UTF-8') . '"';
                    }
                }

                $buffer .= '></script>';

                // This is for IE conditional statements support.
                if (!is_null($conditional)) {
                    $buffer .= '<![endif]-->';
                }

                $buffer .= $lnEnd;
            }

            foreach ($this->updates['_script'] as $type => $content) {
                $buffer .= $tab . '<script';

                if (!is_null($type) && (!$this->document->isHtml5() || !in_array($type, $defaultJsMimes))) {
                    $buffer .= ' type="' . $type . '"';
                }

                $buffer .= '>' . $lnEnd;

                // This is for full XHTML support.
                if ($this->document->_mime != 'text/html') {
                    $buffer .= $tab . $tab . '//<![CDATA[' . $lnEnd;
                }

                $buffer .= $content . $lnEnd;

                // See above note
                if ($this->document->_mime != 'text/html') {
                    $buffer .= $tab . $tab . '//]]>' . $lnEnd;
                }

                $buffer .= $tab . '</script>' . $lnEnd;
            }

            return $buffer;
        } else {
            return null;
        }
    }
}JoomlaModule.php000064400000000775152416656350007672 0ustar00<?php


namespace Nextend\SmartSlider3\Platform\Joomla;


use Joomla\Registry\Registry;

class JoomlaModule {

    /**
     * JoomlaModule constructor.
     *
     * @param Registry $params
     */
    public function __construct($params) {

        $sliderId = intval($params->get('slider'));

        if (defined('LITESPEED_ESI_SUPPORT')) {
            nextend_smartslider3($sliderId);
        } else {
            echo 'smartslider3[' . esc_html($sliderId) . ']';
        }
    }
}JoomlaShim.php000064400000020572152416656430007341 0ustar00<?php

namespace Nextend\SmartSlider3\Platform\Joomla;

use Exception;
use JEventDispatcher;
use Joomla\CMS\Factory;
use Joomla\Event\Event;
use Joomla\CMS\Plugin\PluginHelper;
use Nextend\Framework\Pattern\SingletonTrait;
use Nextend\Security\Joomla\JoomlaSecurity;
use Nextend\SmartSlider3\Settings;
use ReflectionFunction;

class JoomlaShim {

    use SingletonTrait;

    public static $isJoomla4 = 0;

    protected function init() {
        self::$isJoomla4 = version_compare(JVERSION, '4', '>=') ? 1 : 0;

        JoomlaSecurity::getInstance();
    }

    public static function getDispatcher() {
        if (!self::$isJoomla4) {
            return JEventDispatcher::getInstance();
        }

        return Factory::getApplication()
                      ->getDispatcher();
    }

    private static function getExcludedContentPlugins() {
        static $excludedPlugins;
        if ($excludedPlugins === null) {

            $excludedPlugins   = explode('||', Settings::get('joomla-plugins-content-excluded', ''));
            $excludedPlugins[] = 'plgcontentemailcloak';
            $excludedPlugins[] = 'plgcontentdropeditor';
            $excludedPlugins[] = 'plgcontentshortcode_ultimate';
            $excludedPlugins[] = 'plgcontentarkcontent';
            $excludedPlugins[] = 'plgcontentosyoutube';
            $excludedPlugins[] = 'plgsystemt4';
            $excludedPlugins[] = 'plgcontentfields';
        }

        return $excludedPlugins;
    }

    public static function triggerOnContentPrepare($data) {
        static $contentPluginsEnabled, $pluginsToRun = array();

        PluginHelper::importPlugin('content');

        if (!self::$isJoomla4) {
            if ($contentPluginsEnabled === null) {
                $contentPluginsEnabled = intval(Settings::get('joomla-plugins-content-enabled', 1));

                if ($contentPluginsEnabled) {
                    $classNames = array();
                    foreach (PluginHelper::getPlugin('content') as $plugin) {
                        $classNames[] = strtolower('Plg' . $plugin->type . $plugin->name);
                    }

                    $classNames = array_diff($classNames, self::getExcludedContentPlugins());

                    $dispatcher = JEventDispatcher::getInstance();

                    $observers = $dispatcher->get('_observers');

                    foreach ($observers as $observer) {
                        if (is_object($observer)) {
                            $className = strtolower(get_class($observer));
                            if (in_array($className, $classNames)) {
                                $pluginsToRun[] = $observer;
                            } else if (method_exists($observer, 'onContentPrepare') && !in_array($className, self::getExcludedContentPlugins())) {
                                $pluginsToRun[] = $observer;
                            }
                        }
                    }
                }
            }

            if ($contentPluginsEnabled && !empty($pluginsToRun)) {
                foreach ($pluginsToRun as $observer) {
                    // Joomla removes it in every update
                    $data['event'] = 'oncontentprepare';
                    $observer->update($data);
                }
            }

            return true;
        }


        if ($contentPluginsEnabled === null) {
            $contentPluginsEnabled = intval(Settings::get('joomla-plugins-content-enabled', 1));
            if ($contentPluginsEnabled) {

                $classNames = array();
                foreach (PluginHelper::getPlugin('content') as $plugin) {
                    $classNames[] = strtolower('Plg' . $plugin->type . $plugin->name);
                }

                $classNames = array_diff($classNames, self::getExcludedContentPlugins());

                $dispatcher = Factory::getApplication()
                                     ->getDispatcher();

                $listeners = $dispatcher->getListeners('onContentPrepare');

                foreach ($listeners as $listener) {
                    if (is_array($listener)) {
                        if (is_callable($listener) && is_object($listener[0])) {

                            $className = strtolower(get_class($listener[0]));
                            if (in_array($className, $classNames)) {
                                $pluginsToRun[] = $listener;
                            }
                        }
                    } else {

                        $fn        = new ReflectionFunction($listener);
                        $fnClosure = $fn->getClosureThis();

                        if (is_object($fnClosure)) {
                            $className = strtolower(get_class($fnClosure));
                            if (in_array($className, $classNames)) {
                                $pluginsToRun[] = $listener;
                            }
                        }
                    }
                }
            }
        }

        if ($contentPluginsEnabled && !empty($pluginsToRun)) {
            $event = new Event('onContentPrepare', $data);
            foreach ($pluginsToRun as $callable) {

                try {
                    call_user_func($callable, $event);
                } catch (Exception $e) {
                }
            }
        }

        return true;
    }

    public static function getOnContentPreparePluginsList() {
        if (!self::$isJoomla4) {

            PluginHelper::importPlugin('content');

            $dispatcher = JEventDispatcher::getInstance();

            $classNames = array();
            foreach ($dispatcher->get('_observers') as $observer) {
                if ((is_object($observer) || (is_string($observer) && class_exists($observer))) && method_exists($observer, 'onContentPrepare')) {
                    $className              = strtolower(get_class($observer));
                    $classNames[$className] = $className;
                }
            }

            foreach (PluginHelper::getPlugin('content') as $plugin) {
                $className              = strtolower('Plg' . $plugin->type . $plugin->name);
                $classNames[$className] = ucfirst($plugin->name);
            }

            return $classNames;
        }

        PluginHelper::importPlugin('content');

        $dispatcher = Factory::getApplication()
                             ->getDispatcher();

        $classNames = array();
        foreach ($dispatcher->getListeners('onContentPrepare') as $listener) {

            if (is_array($listener)) {
                if (is_callable($listener) && is_object($listener[0])) {

                    $className              = strtolower(get_class($listener[0]));
                    $classNames[$className] = $className;
                }
            } else {
                $fn        = new ReflectionFunction($listener);
                $fnClosure = $fn->getClosureThis();

                if (is_object($fnClosure)) {
                    $className              = strtolower(get_class($fnClosure));
                    $classNames[$className] = $className;
                }
            }
        }

        foreach (PluginHelper::getPlugin('content') as $plugin) {
            $className              = strtolower('Plg' . $plugin->type . $plugin->name);
            $classNames[$className] = ucfirst($plugin->name);
        }

        return $classNames;
    }

    public static function triggerEvent($eventName, $args = array()) {
        if (!self::$isJoomla4) {
            $dispatcher = JEventDispatcher::getInstance();

            return $dispatcher->trigger('onInitN2Library', $args);
        }

        return Factory::getApplication()
                       ->triggerEvent($eventName, $args);
    }

    public static function loadComContentRoute() {
        if (!self::$isJoomla4) {
            require_once JPATH_ROOT . '/components/com_content/helpers/route.php';
        }
    }

    public static function mediaLibraryUrl() {
        if (!self::$isJoomla4) {
            return 'index.php?option=com_media&view=images&tmpl=component&asset=com_content&author=&fieldid=notused&folder=';
        }

        return 'index.php?option=com_media&tmpl=component&asset=86&author=584&fieldid={field-media-id}&path=local-0:/';
    }
}

JoomlaShim::getInstance();SmartSlider3PlatformJoomla.php000064400000001372152416656550012462 0ustar00<?php


namespace Nextend\SmartSlider3\Platform\Joomla;


use Joomla\CMS\Uri\Uri;
use Nextend\Framework\Sanitize;
use Nextend\SmartSlider3\Platform\AbstractSmartSlider3Platform;

class SmartSlider3PlatformJoomla extends AbstractSmartSlider3Platform {

    public function start() {

        require_once(dirname(__FILE__) . '/compat.php');

        $this->initSanitize();
    }


    public function getAdminUrl() {

        return Uri::root() . 'administrator/index.php?option=com_smartslider3';
    }

    public function getAdminAjaxUrl() {

        return Uri::root() . 'administrator/index.php?option=com_smartslider3&nextendajax=1';
    }

    private function initSanitize() {
        Sanitize::set_allowed_tags();
    }
}Module/Field/FieldEditSlider.php000064400000001337152416656670012547 0ustar00<?php


namespace Nextend\SmartSlider3\Platform\Joomla\Module\Field;


use Joomla\CMS\Form\FormField;
use Joomla\CMS\Uri\Uri;

jimport('joomla.form.formfield');

class FieldEditSlider extends FormField {

    protected $type = 'EditSlider';

    public function getInput() {
        $style = '<style>#jform_params_slider_chzn{width:100% !important;max-width:500px;}</style>';

        return $style . '<a href="#" onclick="window.open(\'' . Uri::root() . 'administrator/index.php?option=com_smartslider3&nextendcontroller=slider&nextendaction=edit&sliderid=\' + jQuery(\'#jform_params_slider\').val(), \'_blank\'); return false;" class="btn btn-small btn-success" target="_blank"> Edit selected slider</a>';
    }
}Plugin/PluginInstallerSmartSlider3.php000064400000002352152416656740014106 0ustar00<?php

namespace Nextend\SmartSlider3\Platform\Joomla\Plugin;

use Joomla\CMS\Factory;
use Joomla\CMS\Plugin\CMSPlugin;
use Nextend\SmartSlider3\Application\Model\ModelLicense;
use Nextend\SmartSlider3\SmartSlider3Info;

class PluginInstallerSmartSlider3 extends CMSPlugin {

    public function onInstallerBeforePackageDownload(&$url, &$headers) {

        if (in_array(parse_url($url, PHP_URL_HOST), array(
                'secure.nextendweb.com',
                'api.nextendweb.com'
            )) && strpos($url, 'smartslider3')) {

            $license  = ModelLicense::getInstance();
            $isActive = $license->isActive() == 'OK';

            if (!$isActive) {
                Factory::getApplication()
                        ->enqueueMessage('Update error: Smart Slider 3 Pro is not activated on your site!', 'error');

                $url = SmartSlider3Info::api(array(
                    'action' => 'joomla_fail'
                ), true);

                return false;
            }

            $url = SmartSlider3Info::api(array(
                'action'  => 'joomla_update',
                'channel' => SmartSlider3Info::$channel
            ), true);
        }

        return true;
    }
}Plugin/PluginSmartSlider3.php000064400000013130152416657010012213 0ustar00<?php


namespace Nextend\SmartSlider3\Platform\Joomla\Plugin;

use Artx;
use ArtxPage;
use EshopHelper;
use Joomla\CMS\Factory;
use Joomla\CMS\Application\SiteApplication;
use Joomla\CMS\Plugin\CMSPlugin;
use Nextend\Framework\Asset\AssetManager;
use Nextend\SmartSlider3\Platform\Joomla\Joomla3Assets;
use Nextend\SmartSlider3\Platform\Joomla\JoomlaShim;

jimport('joomla.plugin.plugin');

/**
 * Class PluginSmartSlider3
 *
 * Used in Joomla -> Plugin -> System -> Nextend2
 */
class PluginSmartSlider3 extends CMSPlugin {

    private $hadError = false;

    /*
    Artisteer jQuery fix
    */
    public function onAfterDispatch() {
        if (class_exists('Artx', true)) {
            Artx::load("Artx_Page");
            if (isset(ArtxPage::$inlineScripts)) {
                ArtxPage::$inlineScripts[] = '<script>if(typeof jQuery != "undefined") window.artxJQuery = jQuery;</script>';
            }
        }
    }

    private function isRenderAllowed() {
        static $isAllowed;

        if ($isAllowed === null) {
            /**
             * @var SiteApplication $application
             */
            $application = Factory::getApplication();
            if ($application->isClient('site')) {
                $request   = $application->input->request;
                $isAllowed = true;

                if (!Factory::getUser()->guest) {

                    if ($request->get('view') == 'form' && $request->get('layout') == 'edit' && $application->input->getInt('a_id') > 0) {
                        //Joomla frontend article editing
                        $isAllowed = false;

                    } else if ($request->get('option') == 'com_quix' && $request->get('layout') == 'edit' || $request->get('builder') == 'frontend') {
                        //Quix Visual Builder
                        $isAllowed = false;

                    } else if ($application->input->get('option') == 'com_sppagebuilder' && $application->input->get('layout') == 'edit') {
                        //SP Page Builder - @see SSDEV-3640
                        $isAllowed = false;
                    }
                }

                if ($request->get('type') == 'rss') {
                    //RSS feed
                    $isAllowed = false;
                }
            } else {
                $isAllowed = false;
            }
        }

        return $isAllowed;
    }

    private function displaySliders($output) {

        if (strpos($output, 'smartslider3[') !== false) {
            if (class_exists('\\EshopHelper', false) && EshopHelper::getConfigValue('rich_snippets') == '1') {
                $output = preg_replace_callback('/(<.*?>)?smartslider3\[([0-9]+)\]/', array(
                    self::class,
                    'cleanEshop'
                ), $output);
            }

            $output = preg_replace_callback('/smartslider3\[([0-9]+)\]/', array(
                self::class,
                'prepare'
            ), $output);
        }

        return $output;
    }

    private function onNextendBeforeCompileHead() {

        if ($this->isRenderAllowed()) {

            /**
             * @var SiteApplication $application
             */
            $application = Factory::getApplication();

            $body = $application->getBody();

            // Simple performance check to determine whether bot should process further
            if (strpos($body, 'smartslider3[') !== false) {


                $bodyParts = explode('</head>', $body);
                /**
                 * Last part is not the head
                 */
                $lastPart             = count($bodyParts) - 1;
                $bodyParts[$lastPart] = $this->displaySliders($bodyParts[$lastPart]);

                $application->setBody(implode('</head>', $bodyParts));
            }
        }
    }

    public function onAfterRender() {

        if (!JoomlaShim::$isJoomla4) {
            $joomla3Assets = new Joomla3Assets();

            $this->onNextendBeforeCompileHead();

            $joomla3Assets->process();
        } else {

            $this->onNextendBeforeCompileHead();
        }


        ob_start();
        if (class_exists('\\Nextend\\Framework\\Asset\\AssetManager', false)) {


            // PHPCS - Content already escaped
            echo AssetManager::getCSS(); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped

            // PHPCS - Content already escaped
            echo AssetManager::getJs(); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
        }
        $head = ob_get_clean();
        if (!empty($head)) {

            $application = Factory::getApplication();
            $body        = $application->getBody();

            $parts = preg_split('/<\/head>/', $body, 2);

            if (!JoomlaShim::$isJoomla4) {
                $head .= $joomla3Assets->renderHead();
            }

            $body = implode($head . '</head>', $parts);

            $application->setBody($body);
        }
    }

    public function onError() {
        $this->hadError = true;
    }

    public function onBeforeRespond() {
        if ($this->hadError) {
            $this->onAfterRender();
        }
    }

    public static function prepare($matches) {
        ob_start();
        nextend_smartslider3($matches[1]);

        return ob_get_clean();
    }

    public static function cleanEshop($matches) {
        if (strpos($matches[1], 'itemprop') !== false) {
            return $matches[1];
        }

        return $matches[0];
    }
}GeneratorJoomlaLoader.php000064400000000276152421750220011501 0ustar00<?php

namespace Nextend\SmartSlider3\Generator\Joomla;

use Nextend\SmartSlider3\Generator\AbstractGeneratorLoader;

class GeneratorJoomlaLoader extends AbstractGeneratorLoader {

}JoomlaContent/GeneratorGroupJoomlaContent.php000064400000001473152421750340015501 0ustar00<?php

namespace Nextend\SmartSlider3\Generator\Joomla\JoomlaContent;

use Nextend\SmartSlider3\Generator\AbstractGeneratorGroup;
use Nextend\SmartSlider3\Generator\Joomla\JoomlaContent\Sources\JoomlaContentArticle;
use Nextend\SmartSlider3\Generator\Joomla\JoomlaContent\Sources\JoomlaContentCategory;

class GeneratorGroupJoomlaContent extends AbstractGeneratorGroup {

    protected $name = 'joomlacontent';

    public function getLabel() {
        return n2_('Joomla articles');
    }

    public function getDescription() {
        return n2_('Creates slides from your Joomla articles or categories.');
    }

    protected function loadSources() {
        new JoomlaContentArticle($this, 'article', n2_('Article'));
        new JoomlaContentCategory($this, 'category', n2_('Category'));
    }

}JoomlaContent/Elements/JoomlaContentAccessLevels.php000064400000001721152421750470016666 0ustar00<?php

namespace Nextend\SmartSlider3\Generator\Joomla\JoomlaContent\Elements;

use Joomla\CMS\Factory;
use Nextend\Framework\Form\Element\Select;


class JoomlaContentAccessLevels extends Select {

    public function __construct($insertAt, $name = '', $label = '', $default = '', $parameters = array()) {
        parent::__construct($insertAt, $name, $label, $default, $parameters);

        $db = Factory::getDBO();

        $query = 'SELECT
                    m.id, 
                    m.title AS name, 
                    m.title, 
                    m.ordering
                FROM #__viewlevels m
                ORDER BY m.ordering';


        $db->setQuery($query);
        $menuItems = $db->loadObjectList();

        $this->options['0'] = n2_('All');

        if (count($menuItems)) {
            foreach ($menuItems as $option) {
                $this->options[$option->id] = $option->name;
            }
        }
    }

}
JoomlaContent/Elements/JoomlaContentCategories.php000064400000003243152421750540016376 0ustar00<?php

namespace Nextend\SmartSlider3\Generator\Joomla\JoomlaContent\Elements;

use Joomla\CMS\Factory;
use Joomla\CMS\HTML\HTMLHelper;
use Nextend\Framework\Form\Element\Select;


class JoomlaContentCategories extends Select {

    public function __construct($insertAt, $name = '', $label = '', $default = '', $parameters = array()) {
        parent::__construct($insertAt, $name, $label, $default, $parameters);

        $db = Factory::getDBO();

        $query = 'SELECT
                    id, 
                    title AS name, 
                    title, 
                    parent_id AS parent, 
                    parent_id
                FROM #__categories
                WHERE published = 1 AND extension = "com_content"
                ORDER BY lft';


        $db->setQuery($query);
        $menuItems = $db->loadObjectList();
        $children  = array();
        if ($menuItems) {
            foreach ($menuItems as $v) {
                $pt   = $v->parent_id;
                $list = isset($children[$pt]) ? $children[$pt] : array();
                array_push($list, $v);
                $children[$pt] = $list;
            }
        }

        $this->options[0] = n2_('All');

        jimport('joomla.html.html.menu');
        $options = HTMLHelper::_('menu.treerecurse', 1, '', array(), $children, 9999, 0, 0);
        if (count($options)) {
            foreach ($options as $option) {
                $this->options[$option->id] = $option->treename;
            }
        }
        if ($this->getValue() == '') {
            reset($this->options);
            $this->setValue(key($this->options));
        }

    }

}
JoomlaContent/Elements/JoomlaContentTags.php000064400000001530152421750660015207 0ustar00<?php

namespace Nextend\SmartSlider3\Generator\Joomla\JoomlaContent\Elements;

use Joomla\CMS\Factory;
use Nextend\Framework\Form\Element\Select;


class JoomlaContentTags extends Select {

    public function __construct($insertAt, $name = '', $label = '', $default = '', $parameters = array()) {
        parent::__construct($insertAt, $name, $label, $default, $parameters);

        $db = Factory::getDBO();

        $query = 'SELECT id, title FROM #__tags WHERE published = 1 ORDER BY id';

        $db->setQuery($query);
        $menuItems = $db->loadObjectList();

        $this->options['0'] = n2_('All');

        if (count($menuItems)) {
            array_shift($menuItems);
            foreach ($menuItems as $option) {
                $this->options[$option->id] = $option->title;
            }
        }
    }

}
JoomlaContent/Sources/JoomlaContentArticle.php000064400000051614152421751000015540 0ustar00<?php

namespace Nextend\SmartSlider3\Generator\Joomla\JoomlaContent\Sources;

use Joomla\Component\Content\Site\Helper\RouteHelper;
use DateTime;
use DateTimeZone;
use ContentHelperRoute;
use Joomla\CMS\Factory;
use Joomla\CMS\Plugin\PluginHelper;
use Nextend\Framework\Database\Database;
use Nextend\Framework\Form\Container\ContainerTable;
use Nextend\Framework\Form\Element\MixedField\GeneratorOrder;
use Nextend\Framework\Form\Element\OnOff;
use Nextend\Framework\Form\Element\Select;
use Nextend\Framework\Form\Element\Select\Filter;
use Nextend\Framework\Form\Element\Text;
use Nextend\Framework\Form\Element\Text\Number;
use Nextend\Framework\Form\Element\Textarea;
use Nextend\Framework\Parser\Common;
use Nextend\Framework\ResourceTranslator\ResourceTranslator;
use Nextend\Framework\Url\Url;
use Nextend\SmartSlider3\Generator\AbstractGenerator;
use Nextend\SmartSlider3\Generator\Joomla\JoomlaContent\Elements\JoomlaContentAccessLevels;
use Nextend\SmartSlider3\Generator\Joomla\JoomlaContent\Elements\JoomlaContentCategories;
use Nextend\SmartSlider3\Generator\Joomla\JoomlaContent\Elements\JoomlaContentTags;
use Nextend\SmartSlider3\Platform\Joomla\ImageFallback;
use Nextend\SmartSlider3\Platform\Joomla\JoomlaShim;
use Nextend\SmartSlider3\Slider\Slider;
use stdClass;


JoomlaShim::loadComContentRoute();


class JoomlaContentArticle extends AbstractGenerator {

    protected $layout = 'article';

    public function getDescription() {
        return n2_('Creates slides from your Joomla articles in the selected categories.');
    }

    public function renderFields($container) {
        parent::renderFields($container);

        $filterGroup = new ContainerTable($container, 'filter', n2_('Filter'));

        $source = $filterGroup->createRow('source-row');
        new JoomlaContentCategories($source, 'sourcecategories', n2_('Category'), 0, array(
            'isMultiple' => true
        ));
        new JoomlaContentTags($source, 'sourcetags', n2_('Tags'), 0, array(
            'isMultiple' => true
        ));
        new JoomlaContentAccessLevels($source, 'sourceaccesslevels', n2_('Access level'), 0, array(
            'isMultiple' => true
        ));

        $limit = $filterGroup->createRow('limit-row');

        new Filter($limit, 'sourcefeatured', n2_('Featured'), 0);
        new Number($limit, 'sourceuserid', n2_('User ID'), '', array(
            'tipLabel'       => n2_('Created by'),
            'tipDescription' => n2_('The ID number of the article\'s author. Only one number is accepted.'),
        ));
        new Text($limit, 'sourcearticleids', n2_('Included article IDs'), '', array(
            'tipLabel'       => n2_('Included article IDs'),
            'tipDescription' => n2_('Write down article ID numbers separated by commas, to include them in the result. For example: 1,12,25'),
        ));
        new Text($limit, 'sourcearticleidsexcluded', n2_('Excluded article IDs'), '', array(
            'tipLabel'       => n2_('Excluded article IDs'),
            'tipDescription' => n2_('Write down article ID numbers separated by commas, to exclude them from the result. For example: 2,14,27'),
        ));
        new Text($limit, 'sourcelanguage', n2_('Language'), '*', array(
            'tipLabel'       => n2_('Language'),
            'tipDescription' => n2_('The language code of your articles. Multiple language codes should be separated by commas, for example: en-GB,hu-HU,es-ES'),
            'tipLink'        => 'https://smartslider.helpscoutdocs.com/article/1879-language-filters'
        ));

        $variables = $filterGroup->createRow('variables-row');

        new OnOff($variables, 'sourcefields', n2_('Fields'), 0, array(
            'tipLabel'       => n2_('Extra variables'),
            'tipDescription' => n2_('Turn on these options to generate more variables for the slides.'),
            'tipLink'        => 'https://smartslider.helpscoutdocs.com/article/1864-joomla-articles-generator#fields'
        ));
        new OnOff($variables, 'sourcetagvariables', n2_('Tags'), 0, array(
            'tipLabel'       => n2_('Extra variables'),
            'tipDescription' => n2_('Turn on these options to generate more variables for the slides.'),
            'tipLink'        => 'https://smartslider.helpscoutdocs.com/article/1864-joomla-articles-generator#tags-19'
        ));
        new Select($variables, 'removeshortcodes', n2_('Remove shortcodes'), '0', array(
            'isMultiple'     => true,
            'size'           => 5,
            'options'        => array(
                '0' => n2_('All'),
                '1' => '{shortcode}example{/shortcode}',
                '2' => '{shortcode}',
                '3' => '[shortcode]example[/shortcode]',
                '4' => '[shortcode]'
            ),
            'tipLabel'       => n2_('Remove shortcodes'),
            'tipDescription' => n2_('Remove shortcodes from article description with the following patterns.')
        ));

        $date = $filterGroup->createRow('date-row');
        new Text($date, 'sourcedateformat', n2_('Date format'), 'm-d-Y');
        new Text($date, 'sourcetimeformat', n2_('Time format'), 'G:i');
        new Textarea($date, 'sourcetranslatedate', n2_('Translate date and time'), 'January->January||February->February||March->March', array(
            'width'  => 300,
            'height' => 100

        ));

        $orderGroup = new ContainerTable($container, 'order-group', n2_('Order'));
        $order      = $orderGroup->createRow('order-row');
        new GeneratorOrder($order, 'joomlaorder', 'con.created|*|desc', array(
            'options' => array(
                ''                 => n2_('None'),
                'con.title'        => n2_('Title'),
                'cat_title'        => n2_('Category'),
                'created_by_alias' => n2_('User name'),
                'con.featured'     => n2_('Featured'),
                'con.ordering'     => n2_('Ordering'),
                'con.hits'         => n2_('Hits'),
                'con.created'      => n2_('Creation time'),
                'con.modified'     => n2_('Modification time'),
                'con.publish_up'   => n2_('Publish time'),
                'cf.ordering'      => n2_('Featured article ordering')
            )
        ));
    }

    public function datify($date, $format) {
        if (empty($date) || $date == '0000-00-00 00:00:00') {
            return '';
        } else {
            $config   = Factory::getConfig();
            $timezone = new DateTimeZone($config->get('offset'));
            $offset   = $timezone->getOffset(new DateTime);

            $result = date($format, strtotime($date) + $offset);

            return $result;
        }
    }

    private function translate($from, $translate) {
        if (!empty($translate) && !empty($from)) {
            foreach ($translate as $key => $value) {
                $from = str_replace($key, $value, $from);
            }
        }

        return $from;
    }

    private function removeShortcodes($content) {
        $selection = $this->data->get('removeshortcodes', 1);
        if ($selection !== '') {
            $shortcodes = explode('||', $selection);

            if (in_array(0, $shortcodes) || in_array(1, $shortcodes)) {
                $content = preg_replace('/{[^{}]*?}[^{}]*?{\/.*?}/', '', $content);
            }
            if (in_array(0, $shortcodes) || in_array(2, $shortcodes)) {
                $content = preg_replace('/{.*?}/', '', $content);
            }
            if (in_array(0, $shortcodes) || in_array(3, $shortcodes)) {
                $content = preg_replace('/\[[^\[\]]*?][^\[\]]*?\[\/.*?]/', '', $content);
            }
            if (in_array(0, $shortcodes) || in_array(4, $shortcodes)) {
                $content = preg_replace('/\[.*?]/', '', $content);
            }
        }

        return $content;
    }

    protected function _getData($count, $startIndex) {
        $categories = array_map('intval', explode('||', $this->data->get('sourcecategories', '')));
        $tags       = array_map('intval', explode('||', $this->data->get('sourcetags', '0')));

        $query = 'SELECT ';
        $query .= 'con.id, ';
        $query .= 'con.title, ';
        $query .= 'con.alias, ';
        $query .= 'con.introtext, ';
        $query .= 'con.fulltext, ';
        $query .= 'con.created, ';
        $query .= 'con.catid, ';
        $query .= 'cat.title AS cat_title, ';
        $query .= 'cat.alias AS cat_alias, ';
        $query .= 'con.created_by, con.state, con.metadata, ';
        $query .= 'con.created_by_alias AS con_created_by_alias, ';
        $query .= 'usr.name AS created_by_alias, ';
        $query .= 'con.images, ';
        $query .= 'con.publish_up, ';
        $query .= 'con.publish_down, ';
        $query .= 'con.urls, ';
        $query .= 'con.attribs ';

        $query .= 'FROM #__content AS con ';

        $query .= 'LEFT JOIN #__users AS usr ON usr.id = con.created_by ';

        $query .= 'LEFT JOIN #__categories AS cat ON cat.id = con.catid ';

        $query .= 'LEFT JOIN #__content_frontpage AS cf ON cf.content_id = con.id ';

        $jNow  = Factory::getDate();
        $now   = $jNow->toSql();
        $where = array(
            'con.state = 1 ',
            "(con.publish_up IS NULL OR con.publish_up = '0000-00-00 00:00:00' OR con.publish_up < '" . $now . "') AND (con.publish_down IS NULL OR con.publish_down = '0000-00-00 00:00:00' OR con.publish_down > '" . $now . "') "
        );

        if (!in_array(0, $categories)) {
            $where[] = 'con.catid IN (' . implode(',', $categories) . ') ';
        }

        if (!in_array(0, $tags)) {
            $where[] = 'con.id IN (SELECT content_item_id FROM #__contentitem_tag_map WHERE type_alias = \'com_content.article\' AND tag_id IN (' . implode(',', $tags) . ')) ';
        }

        $sourceUserID = intval($this->data->get('sourceuserid', ''));
        if ($sourceUserID) {
            $where[] = 'con.created_by = ' . $sourceUserID . ' ';
        }

        switch ($this->data->get('sourcefeatured', 0)) {
            case 1:
                $where[] = 'con.featured = 1 ';
                break;
            case -1:
                $where[] = 'con.featured = 0 ';
                break;
        }
        $language = explode(",", $this->data->get('sourcelanguage', '*'));
        if (!empty($language[0]) && $language[0] != '*') {
            $where[] = 'con.language IN (' . implode(",", Database::quote($language)) . ') ';
        }

        $articleIds = $this->data->get('sourcearticleids', '');
        if (!empty($articleIds)) {
            $where[] = 'con.id IN (' . preg_replace("/[^0-9,]/", "", $articleIds) . ') ';
        }

        $articleIdsExcluded = $this->data->get('sourcearticleidsexcluded', '');
        if (!empty($articleIdsExcluded)) {
            $where[] = 'con.id NOT IN (' . preg_replace("/[^0-9,]/", "", $articleIdsExcluded) . ') ';
        }

        $accessLevels = explode('||', $this->data->get('sourceaccesslevels', '*'));
        if (!in_array(0, $accessLevels)) {
            $where[] = 'con.access IN (' . implode(",", $accessLevels) . ')';
        }

        if (count($where) > 0) {
            $query .= 'WHERE ' . implode(' AND ', $where) . ' ';
        }

        $order = Common::parse($this->data->get('joomlaorder', 'con.created|*|desc'));
        if ($order[0]) {
            $query .= 'ORDER BY ' . $order[0] . ' ' . $order[1] . ' ';
        }

        $query .= 'LIMIT ' . $startIndex . ', ' . $count;

        $result = Database::queryAll($query);

        if (empty($result)) {
            return null;
        }

        $sourceTranslate = $this->data->get('sourcetranslatedate', '');
        $translateValue  = explode('||', $sourceTranslate);
        $translate       = array();
        if ($sourceTranslate != 'January->January||February->February||March->March' && !empty($translateValue)) {
            foreach ($translateValue as $tv) {
                $translateArray = explode('->', $tv);
                if (!empty($translateArray) && count($translateArray) == 2) {
                    $translate[$translateArray[0]] = $translateArray[1];
                }
            }
        }

        PluginHelper::importPlugin('content');
        $uri = Url::getBaseUri();

        $data    = array();
        $idArray = array();
        for ($i = 0; $i < count($result); $i++) {
            $idArray[$i] = $result[$i]['id'];
            $r           = array(
                'title' => $result[$i]['title']
            );

            $article       = new stdClass();
            $article->text = $this->removeShortcodes(Slider::removeShortcode($result[$i]['introtext']));
            $_p            = array();

            JoomlaShim::triggerOnContentPrepare(array(
                'com_smartslider3',
                &$article,
                &$_p,
                0
            ));
            if (!empty($article->text)) {
                $r['description'] = $article->text;
            }

            $article->text = $result[$i]['fulltext'];
            $_p            = array();
            JoomlaShim::triggerOnContentPrepare(array(
                'com_smartslider3',
                &$article,
                &$_p,
                0
            ));
            if (!empty($article->text)) {
                $result[$i]['fulltext'] = $article->text;
                if (!isset($r['description'])) {
                    $r['description'] = $result[$i]['fulltext'];
                } else {
                    $r['fulltext'] = $result[$i]['fulltext'];
                }
            }

            $images = (array)json_decode($result[$i]['images'], true);

            $r['image'] = $r['thumbnail'] = ImageFallback::fallback(array(
                @$images['image_intro'],
                @$images['image_fulltext']
            ), array(
                @$r['description']
            ));

            $r += array(
                'url'               => JoomlaShim::$isJoomla4 ? RouteHelper::getArticleRoute($result[$i]['id'] . ':' . $result[$i]['alias'], $result[$i]['catid'] . ':' . $result[$i]['cat_alias']) : ContentHelperRoute::getArticleRoute($result[$i]['id'] . ':' . $result[$i]['alias'], $result[$i]['catid'] . ':' . $result[$i]['cat_alias']),
                'url_label'         => n2_('View article'),
                'category_list_url' => 'index.php?option=com_content&view=category&id=' . $result[$i]['catid'],
                'category_blog_url' => 'index.php?option=com_content&view=category&layout=blog&id=' . $result[$i]['catid'],
                'fulltext_image'    => ImageFallback::fallback(array(@$images['image_fulltext'])),
                'category_title'    => $result[$i]['cat_title'],
                'created_by'        => $result[$i]['created_by_alias'],
                'con_created_by'    => $result[$i]['con_created_by_alias'],
                'id'                => $result[$i]['id'],
                'created_date'      => $this->translate($this->datify($result[$i]['created'], $this->data->get('sourcedateformat', 'm-d-Y')), $translate),
                'created_time'      => $this->translate($this->datify($result[$i]['created'], $this->data->get('sourcetimeformat', 'G:i')), $translate),
                'publish_up_date'   => $this->translate($this->datify($result[$i]['publish_up'], $this->data->get('sourcedateformat', 'm-d-Y')), $translate),
                'publish_up_time'   => $this->translate($this->datify($result[$i]['publish_up'], $this->data->get('sourcetimeformat', 'G:i')), $translate),
                'publish_down_date' => $this->translate($this->datify($result[$i]['publish_down'], $this->data->get('sourcedateformat', 'm-d-Y')), $translate),
                'publish_down_time' => $this->translate($this->datify($result[$i]['publish_down'], $this->data->get('sourcetimeformat', 'G:i')), $translate),
            );

            if (!empty($images)) {
                foreach ($images as $name => $value) {
                    if (!empty($value)) {
                        $image = ImageFallback::fallback(array($value));
                        if (!empty($image)) {
                            $r[$name] = $image;
                        } else {
                            $r[$name] = $value;
                        }
                    }
                }
            }

            $urls = json_decode($result[$i]['urls'], true);
            if (!empty($urls['urla'])) {
                $r['urla']     = $urls['urla'];
                $r['urlatext'] = $urls['urlatext'];
            }
            if (!empty($urls['urlb'])) {
                $r['urlb']     = $urls['urlb'];
                $r['urlbtext'] = $urls['urlbtext'];
            }
            if (!empty($urls['urlc'])) {
                $r['urlc']     = $urls['urlc'];
                $r['urlctext'] = $urls['urlctext'];
            }

            $metadata = json_decode($result[$i]['metadata']);
            foreach ($metadata as $metakey => $metavalue) {
                $r[$metakey] = $metavalue;
            }

            $attribs = (array)json_decode($result[$i]['attribs'], true);
            foreach ($attribs as $attrib => $value) {
                if (!empty($value) && is_string($value)) {
                    $r[$attrib] = $value;
                }
            }

            if (isset($r['helix_ultimate_image'])) {
                $r['spfeatured_image'] = $r['helix_ultimate_image'] = '$/' . $r['helix_ultimate_image'];
            }

            if (isset($r['helix_ultimate_gallery'])) {
                $gallery = (array)json_decode($r['helix_ultimate_gallery'], true);
                for ($j = 0; $j < count($gallery["helix_ultimate_gallery_images"]); $j++) {
                    $r['helix_ultimate_gallery_images_' . $j] = $r['spgallery_' . $j] = '$/' . $gallery["helix_ultimate_gallery_images"][$j];
                }

            }

            $data[] = $r;
        }

        if (!empty($idArray)) {
            if ($this->data->get('sourcetagvariables', 0)) {
                $query  = 'SELECT t.title, c.content_item_id  FROM #__tags AS t
				  LEFT JOIN #__contentitem_tag_map AS c ON t.id = c.tag_id
				  WHERE t.id IN (SELECT tag_id FROM #__contentitem_tag_map WHERE type_alias = \'com_content.article\' AND content_item_id IN (' . implode(',', $idArray) . '))';
                $result = Database::queryAll($query);

                if (!empty($result)) {
                    $tags     = array();
                    $articles = array();
                    foreach ($result as $r) {
                        $tags[$r['content_item_id']][] = $r['title'];
                        $articles[]                    = $r['content_item_id'];

                    }
                    for ($i = 0; $i < count($data); $i++) {
                        if (in_array($data[$i]['id'], $articles)) {
                            $j = 1;
                            foreach ($tags[$data[$i]['id']] as $tag) {
                                $data[$i]['tag' . $j] = $tag;
                                $j++;
                            }
                        }
                    }
                }
            }

            if ($this->data->get('sourcefields', 0)) {
                $query  = "SELECT fv.value, fv.item_id, f.name, f.type FROM #__fields_values AS fv LEFT JOIN #__fields AS f ON fv.field_id = f.id WHERE fv.item_id IN (" . implode(',', $idArray) . ")";
                $result = Database::queryAll($query);
                if (!empty($result)) {
                    $AllResult = array();
                    foreach ($result as $r) {
                        if ($r['type'] == 'media') {
                            $valueParts = json_decode($r['value']);
                            if (isset($valueParts->imagefile)) {
                                $r['value']                                         = ImageFallback::fallback(array($valueParts->imagefile));
                                $AllResult[$r['item_id']][$r['name'] . '_alt_text'] = $valueParts->alt_text;
                            } else {
                                $r['value'] = ResourceTranslator::urlToResource($uri . "/" . $r["value"]);
                            }
                        }

                        $AllResult[$r['item_id']][$r['name']] = $r['value'];
                    }

                    for ($i = 0; $i < count($data); $i++) {
                        if (isset($AllResult[$data[$i]['id']])) {
                            foreach ($AllResult[$data[$i]['id']] as $key => $value) {
                                $key            = preg_replace('/[^a-zA-Z0-9_\x7f-\xff]*/', '', $key);
                                $data[$i][$key] = $value;
                            }
                        }
                    }
                }
            }
        }

        return $data;
    }

}JoomlaContent/Sources/JoomlaContentCategory.php000064400000014036152421751200015731 0ustar00<?php

namespace Nextend\SmartSlider3\Generator\Joomla\JoomlaContent\Sources;

use Joomla\CMS\Plugin\PluginHelper;
use Nextend\Framework\Database\Database;
use Nextend\Framework\Form\Container\ContainerTable;
use Nextend\Framework\Form\Element\MixedField\GeneratorOrder;
use Nextend\Framework\Form\Element\Text;
use Nextend\Framework\Parser\Common;
use Nextend\SmartSlider3\Generator\AbstractGenerator;
use Nextend\SmartSlider3\Generator\Joomla\JoomlaContent\Elements\JoomlaContentCategories;
use Nextend\SmartSlider3\Generator\Joomla\JoomlaContent\Elements\JoomlaContentTags;
use Nextend\SmartSlider3\Platform\Joomla\ImageFallback;
use Nextend\SmartSlider3\Platform\Joomla\JoomlaShim;
use Nextend\SmartSlider3\Slider\Slider;
use stdClass;


class JoomlaContentCategory extends AbstractGenerator {

    protected $layout = 'article';

    public function getDescription() {
        return n2_('Creates slides from your Joomla categories. (Not the articles inside them.)');
    }

    public function renderFields($container) {
        parent::renderFields($container);

        $filterGroup = new ContainerTable($container, 'filter', n2_('Filter'));

        $source = $filterGroup->createRow('source-row');
        new JoomlaContentCategories($source, 'sourcecategory', n2_('Parent category'), 0);
        new JoomlaContentTags($source, 'sourcetags', n2_('Tags'), 0, array(
            'isMultiple' => true
        ));

        $languageRow = $filterGroup->createRow('language-row');
        new Text($languageRow, 'sourcelanguage', n2_('Language'), '*');

        $orderGroup = new ContainerTable($container, 'order-group', n2_('Order'));
        $order      = $orderGroup->createRow('order-row');
        new GeneratorOrder($order, 'joomlaorder', 'cat.created_time|*|desc', array(
            'options' => array(
                ''                  => n2_('None'),
                'cat.title'         => n2_('Title'),
                'cat.lft'           => n2_('Ordering'),
                'cat.created_time'  => n2_('Creation time'),
                'cat.modified_time' => n2_('Modification time'),
                'cat.hits'          => n2_('Hits')
            )
        ));
    }

    protected function _getData($count, $startIndex) {

        $category = $this->data->get('sourcecategory', '');
        $tags     = array_map('intval', explode('||', $this->data->get('sourcetags', '0')));

        $query = 'SELECT ';
        $query .= 'cat.id, ';
        $query .= 'cat.title, ';
        $query .= 'cat.alias, ';
        $query .= 'cat.description, ';
        $query .= 'cat.params, ';
        $query .= 'cat_parent.id AS parent_id, ';
        $query .= 'cat_parent.title AS parent_title ';

        $query .= 'FROM #__categories AS cat ';

        $query .= 'LEFT JOIN #__categories AS cat_parent ON cat_parent.id = cat.parent_id ';


        $where = array(
            'cat.published = 1 ',
            'cat.extension = \'com_content\' '
        );

        if ($category != 0) {
            $where[] = 'cat.parent_id = ' . $category . ' ';
        }

        if (!in_array(0, $tags)) {
            $where[] = 'cat.id IN (SELECT content_item_id FROM #__contentitem_tag_map WHERE type_alias = \'com_content.category\'  AND tag_id IN (' . implode(',', $tags) . ')) ';
        }

        $language = $this->data->get('sourcelanguage', '*');
        if ($language) {
            $where[] = 'cat.language = ' . Database::quote($language) . ' ';
        }

        if (count($where) > 0) {
            $query .= 'WHERE ' . implode(' AND ', $where) . ' ';
        }

        $order = Common::parse($this->data->get('joomlaorder', 'cat.created_time|*|desc'));
        if ($order[0]) {
            $query .= 'ORDER BY ' . $order[0] . ' ' . $order[1] . ' ';
        }

        $query .= 'LIMIT ' . $startIndex . ', ' . $count . ' ';

        $result = Database::queryAll($query);

        PluginHelper::importPlugin('content');

        $data = array();
        for ($i = 0; $i < count($result); $i++) {
            $r = array(
                'title' => $result[$i]['title']
            );

            $article       = new stdClass();
            $article->text = Slider::removeShortcode($result[$i]['description']);
            $_p            = array();
            JoomlaShim::triggerOnContentPrepare(array(
                'com_smartslider3',
                &$article,
                &$_p,
                0
            ));
            if (!empty($article->text)) {
                $r['description'] = $article->text;
            } else {
                $r['description'] = '';
            }
            $params = (array)json_decode($result[$i]['params'], true);

            $r['image'] = $r['thumbnail'] = ImageFallback::fallback(array(@$params['image']), array($r['description']));

            $r += array(
                'url'       => 'index.php?option=com_content&view=category&id=' . $result[$i]['id'],
                'url_label' => n2_('View category'),
                'url_blog'  => 'index.php?option=com_content&view=category&layout=blog&id=' . $result[$i]['id']
            );

            if ($result[$i]['parent_title'] != 'ROOT') {
                $r += array(
                    'parent_title'    => $result[$i]['parent_title'],
                    'parent_url'      => 'index.php?option=com_content&view=category&id=' . $result[$i]['parent_id'],
                    'parent_url_blog' => 'index.php?option=com_content&view=category&layout=blog&id=' . $result[$i]['parent_id']
                );
            } else {
                $r += array(
                    'parent_title'    => '',
                    'parent_url'      => '',
                    'parent_url_blog' => ''
                );
            }

            $r += array(
                'alias'     => $result[$i]['alias'],
                'id'        => $result[$i]['id'],
                'parent_id' => $result[$i]['parent_id']
            );

            $data[] = $r;
        }

        return $data;
    }

}
InstallJoomla.php000064400000000206152423740050010025 0ustar00<?php

namespace Nextend\SmartSlider3\Install\Joomla;

class InstallJoomla {

    public static function install() {

    }
}JoomlaConflict.php000064400000001453152431102220010153 0ustar00<?php


namespace Nextend\SmartSlider3\Conflict\Joomla;


use Nextend\SmartSlider3\Conflict\Conflict;
use Nextend\Framework\Settings;

class JoomlaConflict extends Conflict {

    protected function __construct() {
        parent::__construct();

        $this->testPluginJCHOptimize();
    }

    /**
     * JCH Optimize
     * @url https://extensions.joomla.org/extension/jch-optimize/
     */
    private function testPluginJCHOptimize() {
        if (defined('JCH_VERSION') && Settings::get('async-non-primary-css', 0)) {
            $this->displayConflict('JCH Optimize', n2_('JCH Optimize could have a conflict with Smart Slider\'s Global settings -> Framework settings -> Async Non-Primary CSS. If your Google fonts are not loading, turn this option off.'));
        }
    }

}Session/LICENSE000064400000042630152431555720007212 0ustar00GNU GENERAL PUBLIC LICENSE
				Version 2, June 1991

 Copyright (C) 1989, 1991 Free Software Foundation, Inc.
 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 Everyone is permitted to copy and distribute verbatim copies
 of this license document, but changing it is not allowed.

				Preamble

  The licenses for most software are designed to take away your
freedom to share and change it.  By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users.  This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it.  (Some other Free Software Foundation software is covered by
the GNU Library General Public License instead.)  You can apply it to
your programs, too.

  When we speak of free software, we are referring to freedom, not
price.  Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.

  To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.

  For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have.  You must make sure that they, too, receive or can get the
source code.  And you must show them these terms so they know their
rights.

  We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.

  Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software.  If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.

  Finally, any free program is threatened constantly by software
patents.  We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary.  To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.

  The precise terms and conditions for copying, distribution and
modification follow.

			GNU GENERAL PUBLIC LICENSE
   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION

  0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License.  The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language.  (Hereinafter, translation is included without limitation in
the term "modification".)  Each licensee is addressed as "you".

Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope.  The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.

  1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.

You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.

  2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:

	a) You must cause the modified files to carry prominent notices
	stating that you changed the files and the date of any change.

	b) You must cause any work that you distribute or publish, that in
	whole or in part contains or is derived from the Program or any
	part thereof, to be licensed as a whole at no charge to all third
	parties under the terms of this License.

	c) If the modified program normally reads commands interactively
	when run, you must cause it, when started running for such
	interactive use in the most ordinary way, to print or display an
	announcement including an appropriate copyright notice and a
	notice that there is no warranty (or else, saying that you provide
	a warranty) and that users may redistribute the program under
	these conditions, and telling the user how to view a copy of this
	License.  (Exception: if the Program itself is interactive but
	does not normally print such an announcement, your work based on
	the Program is not required to print an announcement.)

These requirements apply to the modified work as a whole.  If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works.  But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.

Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.

In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.

  3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:

	a) Accompany it with the complete corresponding machine-readable
	source code, which must be distributed under the terms of Sections
	1 and 2 above on a medium customarily used for software interchange; or,

	b) Accompany it with a written offer, valid for at least three
	years, to give any third party, for a charge no more than your
	cost of physically performing source distribution, a complete
	machine-readable copy of the corresponding source code, to be
	distributed under the terms of Sections 1 and 2 above on a medium
	customarily used for software interchange; or,

	c) Accompany it with the information you received as to the offer
	to distribute corresponding source code.  (This alternative is
	allowed only for noncommercial distribution and only if you
	received the program in object code or executable form with such
	an offer, in accord with Subsection b above.)

The source code for a work means the preferred form of the work for
making modifications to it.  For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable.  However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.

If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.

  4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License.  Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.

  5. You are not required to accept this License, since you have not
signed it.  However, nothing else grants you permission to modify or
distribute the Program or its derivative works.  These actions are
prohibited by law if you do not accept this License.  Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.

  6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions.  You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.

  7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License.  If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all.  For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.

If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.

It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices.  Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.

This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.

  8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded.  In such case, this License incorporates
the limitation as if written in the body of this License.

  9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time.  Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.

Each version is given a distinguishing version number.  If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation.  If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.

  10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission.  For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this.  Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.

				NO WARRANTY

  11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.

  12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.

			 END OF TERMS AND CONDITIONS

		How to Apply These Terms to Your New Programs

  If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.

  To do so, attach the following notices to the program.  It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.

	<one line to give the program's name and a brief idea of what it does.>
	Copyright (C) <year>  <name of author>

	This program is free software; you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation; either version 2 of the License, or
	(at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with this program; if not, write to the Free Software
	Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA


Also add information on how to contact you by electronic and paper mail.

If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:

	Gnomovision version 69, Copyright (C) year name of author
	Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
	This is free software, and you are welcome to redistribute it
	under certain conditions; type `show c' for details.

The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License.  Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.

You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary.  Here is a sample; alter the names:

  Yoyodyne, Inc., hereby disclaims all copyright interest in the program
  `Gnomovision' (which makes passes at compilers) written by James Hacker.

  <signature of Ty Coon>, 1 April 1989
  Ty Coon, President of Vice

This General Public License does not permit incorporating your program into
proprietary programs.  If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library.  If this is what you want to do, use the GNU Library General
Public License instead of this License.
Session/Storage.php000064400000010270152431556110010307 0ustar00<?php
/**
 * Part of the Joomla Framework Session Package
 *
 * @copyright  Copyright (C) 2005 - 2020 Open Source Matters, Inc. All rights reserved.
 * @license    GNU General Public License version 2 or later; see LICENSE
 */

namespace Joomla\Session;

use Joomla\Filter\InputFilter;

/**
 * Custom session storage handler for PHP
 *
 * @link        https://www.php.net/manual/en/function.session-set-save-handler.php
 * @since       1.0
 * @deprecated  2.0  The Storage class chain will be removed.
 */
abstract class Storage
{
	/**
	 * @var    Storage[]  Storage instances container.
	 * @since  1.0
	 * @deprecated  2.0
	 */
	protected static $instances = array();

	/**
	 * Constructor
	 *
	 * @param   array  $options  Optional parameters.
	 *
	 * @since   1.0
	 * @deprecated  2.0
	 */
	public function __construct($options = array())
	{
		$this->register($options);
	}

	/**
	 * Returns a session storage handler object, only creating it if it doesn't already exist.
	 *
	 * @param   string  $name     The session store to instantiate
	 * @param   array   $options  Array of options
	 *
	 * @return  Storage
	 *
	 * @since   1.0
	 * @deprecated  2.0
	 */
	public static function getInstance($name = 'none', $options = array())
	{
		$filter = new InputFilter;
		$name   = strtolower($filter->clean($name, 'word'));

		if (empty(self::$instances[$name]))
		{
			$class = '\\Joomla\\Session\\Storage\\' . ucfirst($name);

			if (!class_exists($class))
			{
				$path = __DIR__ . '/storage/' . $name . '.php';

				if (file_exists($path))
				{
					require_once $path;
				}
				else
				{
					// No attempt to die gracefully here, as it tries to close the non-existing session
					exit('Unable to load session storage class: ' . $name);
				}
			}

			self::$instances[$name] = new $class($options);
		}

		return self::$instances[$name];
	}

	/**
	 * Register the functions of this class with PHP's session handler
	 *
	 * @return  void
	 *
	 * @since   1.0
	 * @deprecated  2.0
	 */
	public function register()
	{
		if (!headers_sent())
		{
			session_set_save_handler(
				array($this, 'open'),
				array($this, 'close'),
				array($this, 'read'),
				array($this, 'write'),
				array($this, 'destroy'),
				array($this, 'gc')
			);
		}
	}

	/**
	 * Open the SessionHandler backend.
	 *
	 * @param   string  $savePath     The path to the session object.
	 * @param   string  $sessionName  The name of the session.
	 *
	 * @return  boolean  True on success, false otherwise.
	 *
	 * @since   1.0
	 * @deprecated  2.0
	 */
	public function open($savePath, $sessionName)
	{
		return true;
	}

	/**
	 * Close the SessionHandler backend.
	 *
	 * @return  boolean  True on success, false otherwise.
	 *
	 * @since   1.0
	 * @deprecated  2.0
	 */
	public function close()
	{
		return true;
	}

	/**
	 * Read the data for a particular session identifier from the
	 * SessionHandler backend.
	 *
	 * @param   string  $id  The session identifier.
	 *
	 * @return  string  The session data.
	 *
	 * @since   1.0
	 * @deprecated  2.0
	 */
	public function read($id)
	{
		return '';
	}

	/**
	 * Write session data to the SessionHandler backend.
	 *
	 * @param   string  $id           The session identifier.
	 * @param   string  $sessionData  The session data.
	 *
	 * @return  boolean  True on success, false otherwise.
	 *
	 * @since   1.0
	 * @deprecated  2.0
	 */
	public function write($id, $sessionData)
	{
		return true;
	}

	/**
	 * Destroy the data for a particular session identifier in the
	 * SessionHandler backend.
	 *
	 * @param   string  $id  The session identifier.
	 *
	 * @return  boolean  True on success, false otherwise.
	 *
	 * @since   1.0
	 * @deprecated  2.0
	 */
	public function destroy($id)
	{
		return true;
	}

	/**
	 * Garbage collect stale sessions from the SessionHandler backend.
	 *
	 * @param   integer  $maxlifetime  The maximum age of a session.
	 *
	 * @return  boolean  True on success, false otherwise.
	 *
	 * @since   1.0
	 * @deprecated  2.0
	 */
	public function gc($maxlifetime = null)
	{
		return true;
	}

	/**
	 * Test to see if the SessionHandler is available.
	 *
	 * @return  boolean  True on success, false otherwise.
	 *
	 * @since   1.0
	 * @deprecated  2.0
	 */
	public static function isSupported()
	{
		return true;
	}
}
Session/Session.php000064400000056072152431556160010345 0ustar00<?php
/**
 * Part of the Joomla Framework Session Package
 *
 * @copyright  Copyright (C) 2005 - 2020 Open Source Matters, Inc. All rights reserved.
 * @license    GNU General Public License version 2 or later; see LICENSE
 */

namespace Joomla\Session;

use Joomla\Event\DispatcherInterface;
use Joomla\Input\Input;

/**
 * Class for managing HTTP sessions
 *
 * Provides access to session-state values as well as session-level
 * settings and lifetime management methods.
 * Based on the standard PHP session handling mechanism it provides
 * more advanced features such as expire timeouts.
 *
 * @since  1.0
 */
class Session implements \IteratorAggregate
{
	/**
	 * Internal state.
	 * One of 'inactive'|'active'|'expired'|'destroyed'|'error'
	 *
	 * @var    string
	 * @see    getState()
	 * @since  1.0
	 */
	protected $state = 'inactive';

	/**
	 * Maximum age of unused session in minutes
	 *
	 * @var    string
	 * @since  1.0
	 */
	protected $expire = 15;

	/**
	 * The session store object.
	 *
	 * @var    Storage
	 * @since  1.0
	 */
	protected $store;

	/**
	 * Security policy.
	 * List of checks that will be done.
	 *
	 * Default values:
	 * - fix_browser
	 * - fix_adress
	 *
	 * @var    array
	 * @since  1.0
	 */
	protected $security = array('fix_browser');

	/**
	 * Force cookies to be SSL only
	 * Default  false
	 *
	 * @var    boolean
	 * @since  1.0
	 */
	protected $force_ssl = false;

	/**
	 * The domain to use when setting cookies.
	 *
	 * @var    mixed
	 * @since  1.0
	 * @deprecated  2.0
	 */
	protected $cookie_domain;

	/**
	 * The path to use when setting cookies.
	 *
	 * @var    mixed
	 * @since  1.0
	 * @deprecated  2.0
	 */
	protected $cookie_path;

	/**
	 * The configuration of the HttpOnly cookie.
	 *
	 * @var    mixed
	 * @since  1.5.0
	 * @deprecated  2.0
	 */
	protected $cookie_httponly = true;

	/**
	 * The configuration of the SameSite cookie.
	 *
	 * @var    mixed
	 * @since  1.5.0
	 * @deprecated  2.0
	 */
	protected $cookie_samesite;

	/**
	 * Session instances container.
	 *
	 * @var    Session
	 * @since  1.0
	 * @deprecated  2.0
	 */
	protected static $instance;

	/**
	 * The type of storage for the session.
	 *
	 * @var    string
	 * @since  1.0
	 * @deprecated  2.0
	 */
	protected $storeName;

	/**
	 * Holds the Input object
	 *
	 * @var    Input
	 * @since  1.0
	 */
	private $input;

	/**
	 * Holds the Dispatcher object
	 *
	 * @var    DispatcherInterface
	 * @since  1.0
	 */
	private $dispatcher;

	/**
	 * Constructor
	 *
	 * @param   string  $store    The type of storage for the session.
	 * @param   array   $options  Optional parameters
	 *
	 * @since   1.0
	 */
	public function __construct($store = 'none', array $options = array())
	{
		// Need to destroy any existing sessions started with session.auto_start
		if (session_id())
		{
			session_unset();
			session_destroy();
		}

		// Disable transparent sid support
		ini_set('session.use_trans_sid', '0');

		// Only allow the session ID to come from cookies and nothing else.
		ini_set('session.use_only_cookies', '1');

		// Create handler
		$this->store = Storage::getInstance($store, $options);

		$this->storeName = $store;

		// Set options
		$this->_setOptions($options);

		$this->_setCookieParams();

		$this->setState('inactive');
	}

	/**
	 * Magic method to get read-only access to properties.
	 *
	 * @param   string  $name  Name of property to retrieve
	 *
	 * @return  mixed   The value of the property
	 *
	 * @since   1.0
	 * @deprecated  2.0  Use get methods for non-deprecated properties
	 */
	public function __get($name)
	{
		if ($name === 'storeName' || $name === 'state' || $name === 'expire')
		{
			return $this->$name;
		}
	}

	/**
	 * Returns the global Session object, only creating it
	 * if it doesn't already exist.
	 *
	 * @param   string  $handler  The type of session handler.
	 * @param   array   $options  An array of configuration options (for new sessions only).
	 *
	 * @return  Session  The Session object.
	 *
	 * @since   1.0
	 * @deprecated  2.0  A singleton object store will no longer be supported
	 */
	public static function getInstance($handler, array $options = array())
	{
		if (!\is_object(self::$instance))
		{
			self::$instance = new self($handler, $options);
		}

		return self::$instance;
	}

	/**
	 * Get current state of session
	 *
	 * @return  string  The session state
	 *
	 * @since   1.0
	 */
	public function getState()
	{
		return $this->state;
	}

	/**
	 * Get expiration time in minutes
	 *
	 * @return  integer  The session expiration time in minutes
	 *
	 * @since   1.0
	 */
	public function getExpire()
	{
		return $this->expire;
	}

	/**
	 * Get a session token, if a token isn't set yet one will be generated.
	 *
	 * Tokens are used to secure forms from spamming attacks. Once a token
	 * has been generated the system will check the post request to see if
	 * it is present, if not it will invalidate the session.
	 *
	 * @param   boolean  $forceNew  If true, force a new token to be created
	 *
	 * @return  string  The session token
	 *
	 * @since   1.0
	 */
	public function getToken($forceNew = false)
	{
		$token = $this->get('session.token');

		// Create a token
		if ($token === null || $forceNew)
		{
			$token = $this->_createToken();
			$this->set('session.token', $token);
		}

		return $token;
	}

	/**
	 * Method to determine if a token exists in the session. If not the
	 * session will be set to expired
	 *
	 * @param   string   $tCheck       Hashed token to be verified
	 * @param   boolean  $forceExpire  If true, expires the session
	 *
	 * @return  boolean
	 *
	 * @since   1.0
	 */
	public function hasToken($tCheck, $forceExpire = true)
	{
		// Check if a token exists in the session
		$tStored = $this->get('session.token');

		// Check token
		if (($tStored !== $tCheck))
		{
			if ($forceExpire)
			{
				$this->setState('expired');
			}

			return false;
		}

		return true;
	}

	/**
	 * Retrieve an external iterator.
	 *
	 * @return  \ArrayIterator  Return an ArrayIterator of $_SESSION.
	 *
	 * @since   1.0
	 */
	public function getIterator()
	{
		return new \ArrayIterator($_SESSION);
	}

	/**
	 * Get session name
	 *
	 * @return  string  The session name
	 *
	 * @since   1.0
	 */
	public function getName()
	{
		if ($this->getState() === 'destroyed')
		{
			// @codingStandardsIgnoreLine
			return;
		}

		return session_name();
	}

	/**
	 * Get session id
	 *
	 * @return  string  The session name
	 *
	 * @since   1.0
	 */
	public function getId()
	{
		if ($this->getState() === 'destroyed')
		{
			// @codingStandardsIgnoreLine
			return;
		}

		return session_id();
	}

	/**
	 * Get the session handlers
	 *
	 * @return  array  An array of available session handlers
	 *
	 * @since   1.0
	 * @deprecated  2.0  The Storage class chain will be removed
	 */
	public static function getStores()
	{
		$connectors = array();

		// Get an iterator and loop trough the driver classes.
		$iterator = new \DirectoryIterator(__DIR__ . '/Storage');

		foreach ($iterator as $file)
		{
			$fileName = $file->getFilename();

			// Only load for php files.
			if (!$file->isFile() || $file->getExtension() != 'php')
			{
				continue;
			}

			// Derive the class name from the type.
			$class = str_ireplace('.php', '', '\\Joomla\\Session\\Storage\\' . ucfirst(trim($fileName)));

			// If the class doesn't exist we have nothing left to do but look at the next type. We did our best.
			if (!class_exists($class))
			{
				continue;
			}

			// Sweet!  Our class exists, so now we just need to know if it passes its test method.
			if ($class::isSupported())
			{
				// Connector names should not have file extensions.
				$connectors[] = str_ireplace('.php', '', $fileName);
			}
		}

		return $connectors;
	}

	/**
	 * Shorthand to check if the session is active
	 *
	 * @return  boolean
	 *
	 * @since   1.0
	 */
	public function isActive()
	{
		return (bool) ($this->getState() == 'active');
	}

	/**
	 * Check whether this session is currently created
	 *
	 * @return  boolean  True on success.
	 *
	 * @since   1.0
	 */
	public function isNew()
	{
		$counter = $this->get('session.counter');

		return (bool) ($counter === 1);
	}

	/**
	 * Check whether this session is currently created
	 *
	 * @param   Input                $input       Input object for the session to use.
	 * @param   DispatcherInterface  $dispatcher  Dispatcher object for the session to use.
	 *
	 * @return  void
	 *
	 * @since   1.0
	 * @deprecated  2.0  In 2.0 the DispatcherInterface should be injected via the object constructor
	 */
	public function initialise(Input $input, DispatcherInterface $dispatcher = null)
	{
		$this->input      = $input;
		$this->dispatcher = $dispatcher;
	}

	/**
	 * Get data from the session store
	 *
	 * @param   string  $name       Name of a variable
	 * @param   mixed   $default    Default value of a variable if not set
	 * @param   string  $namespace  Namespace to use, default to 'default' {@deprecated 2.0 Namespace support will be removed.}
	 *
	 * @return  mixed  Value of a variable
	 *
	 * @since   1.0
	 */
	public function get($name, $default = null, $namespace = 'default')
	{
		// Add prefix to namespace to avoid collisions
		$namespace = '__' . $namespace;

		if ($this->getState() !== 'active' && $this->getState() !== 'expired')
		{
			return;
		}

		if (isset($_SESSION[$namespace][$name]))
		{
			return $_SESSION[$namespace][$name];
		}

		return $default;
	}

	/**
	 * Set data into the session store.
	 *
	 * @param   string  $name       Name of a variable.
	 * @param   mixed   $value      Value of a variable.
	 * @param   string  $namespace  Namespace to use, default to 'default' {@deprecated 2.0 Namespace support will be removed.}
	 *
	 * @return  mixed  Old value of a variable.
	 *
	 * @since   1.0
	 */
	public function set($name, $value = null, $namespace = 'default')
	{
		// Add prefix to namespace to avoid collisions
		$namespace = '__' . $namespace;

		if ($this->getState() !== 'active')
		{
			return;
		}

		$old = isset($_SESSION[$namespace][$name]) ? $_SESSION[$namespace][$name] : null;

		if ($value === null)
		{
			unset($_SESSION[$namespace][$name]);
		}
		else
		{
			$_SESSION[$namespace][$name] = $value;
		}

		return $old;
	}

	/**
	 * Check whether data exists in the session store
	 *
	 * @param   string  $name       Name of variable
	 * @param   string  $namespace  Namespace to use, default to 'default' {@deprecated 2.0 Namespace support will be removed.}
	 *
	 * @return  boolean  True if the variable exists
	 *
	 * @since   1.0
	 */
	public function has($name, $namespace = 'default')
	{
		// Add prefix to namespace to avoid collisions.
		$namespace = '__' . $namespace;

		if ($this->getState() !== 'active')
		{
			// @codingStandardsIgnoreLine
			return;
		}

		return isset($_SESSION[$namespace][$name]);
	}

	/**
	 * Unset data from the session store
	 *
	 * @param   string  $name       Name of variable
	 * @param   string  $namespace  Namespace to use, default to 'default' {@deprecated 2.0 Namespace support will be removed.}
	 *
	 * @return  mixed   The value from session or NULL if not set
	 *
	 * @since   1.0
	 */
	public function clear($name, $namespace = 'default')
	{
		// Add prefix to namespace to avoid collisions
		$namespace = '__' . $namespace;

		if ($this->getState() !== 'active')
		{
			// @TODO :: generated error here
			return;
		}

		$value = null;

		if (isset($_SESSION[$namespace][$name]))
		{
			$value = $_SESSION[$namespace][$name];
			unset($_SESSION[$namespace][$name]);
		}

		return $value;
	}

	/**
	 * Start a session.
	 *
	 * @return  void
	 *
	 * @since   1.0
	 */
	public function start()
	{
		if ($this->getState() === 'active')
		{
			return;
		}

		$this->_start();

		$this->setState('active');

		// Initialise the session
		$this->_setCounter();
		$this->_setTimers();

		// Perform security checks
		$this->_validate();

		if ($this->dispatcher instanceof DispatcherInterface)
		{
			$this->dispatcher->triggerEvent('onAfterSessionStart');
		}
	}

	/**
	 * Start a session.
	 *
	 * Creates a session (or resumes the current one based on the state of the session)
	 *
	 * @return  boolean  true on success
	 *
	 * @since   1.0
	 * @deprecated  2.0
	 */
	protected function _start()
	{
		// Start session if not started
		if ($this->getState() === 'restart')
		{
			session_regenerate_id(true);
		}
		else
		{
			$session_name = session_name();

			// Get the Joomla\Input\Cookie object
			$cookie = $this->input->cookie;

			if ($cookie->get($session_name) === null)
			{
				$session_clean = $this->input->get($session_name, false, 'string');

				if ($session_clean)
				{
					session_id($session_clean);
					$cookie->set($session_name, '', array('expires' => 1));
				}
			}
		}

		/**
		 * Write and Close handlers are called after destructing objects since PHP 5.0.5.
		 * Thus destructors can use sessions but session handler can't use objects.
		 * So we are moving session closure before destructing objects.
		 *
		 * Replace with session_register_shutdown() when dropping compatibility with PHP 5.3
		 */
		register_shutdown_function('session_write_close');

		session_cache_limiter('none');
		session_start();

		return true;
	}

	/**
	 * Frees all session variables and destroys all data registered to a session
	 *
	 * This method resets the $_SESSION variable and destroys all of the data associated
	 * with the current session in its storage (file or DB). It forces new session to be
	 * started after this method is called. It does not unset the session cookie.
	 *
	 * @return  boolean  True on success
	 *
	 * @see     session_destroy()
	 * @see     session_unset()
	 * @since   1.0
	 */
	public function destroy()
	{
		// Session was already destroyed
		if ($this->getState() === 'destroyed')
		{
			return true;
		}

		/*
		 * In order to kill the session altogether, such as to log the user out, the session id
		 * must also be unset. If a cookie is used to propagate the session id (default behavior),
		 * then the session cookie must be deleted.
		 */
		$cookie = session_get_cookie_params();

		$cookieOptions = array(
			'expires'  => 1,
			'path'     => $cookie['path'],
			'domain'   => $cookie['domain'],
			'secure'   => $cookie['secure'],
			'httponly' => true,
		);

		if (isset($cookie['samesite']))
		{
			$cookieOptions['samesite'] = $cookie['samesite'];
		}

		$this->input->cookie->set($this->getName(), '', $cookieOptions);

		session_unset();
		session_destroy();

		$this->setState('destroyed');

		return true;
	}

	/**
	 * Restart an expired or locked session.
	 *
	 * @return  boolean  True on success
	 *
	 * @see     destroy
	 * @since   1.0
	 */
	public function restart()
	{
		$this->destroy();

		if ($this->getState() !== 'destroyed')
		{
			// @TODO :: generated error here
			return false;
		}

		// Re-register the session handler after a session has been destroyed, to avoid PHP bug
		$this->store->register();

		$this->setState('restart');

		// Regenerate session id
		session_regenerate_id(true);
		$this->_start();
		$this->setState('active');

		$this->_validate();
		$this->_setCounter();

		return true;
	}

	/**
	 * Create a new session and copy variables from the old one
	 *
	 * @return  boolean $result true on success
	 *
	 * @since   1.0
	 */
	public function fork()
	{
		if ($this->getState() !== 'active')
		{
			// @TODO :: generated error here
			return false;
		}

		// Keep session config
		$cookie = session_get_cookie_params();

		// Kill session
		session_destroy();

		// Re-register the session store after a session has been destroyed, to avoid PHP bug
		$this->store->register();

		// Restore config
		if (version_compare(PHP_VERSION, '7.3', '>='))
		{
			session_set_cookie_params($cookie);
		}
		else
		{
			session_set_cookie_params($cookie['lifetime'], $cookie['path'], $cookie['domain'], $cookie['secure'], $cookie['httponly']);
		}

		// Restart session with new id
		session_regenerate_id(true);
		session_start();

		return true;
	}

	/**
	 * Writes session data and ends session
	 *
	 * Session data is usually stored after your script terminated without the need
	 * to call JSession::close(), but as session data is locked to prevent concurrent
	 * writes only one script may operate on a session at any time. When using
	 * framesets together with sessions you will experience the frames loading one
	 * by one due to this locking. You can reduce the time needed to load all the
	 * frames by ending the session as soon as all changes to session variables are
	 * done.
	 *
	 * @return  void
	 *
	 * @see     session_write_close()
	 * @since   1.0
	 */
	public function close()
	{
		session_write_close();
	}

	/**
	 * Set the session expiration
	 *
	 * @param   integer  $expire  Maximum age of unused session in minutes
	 *
	 * @return  $this
	 *
	 * @since   1.3.0
	 */
	protected function setExpire($expire)
	{
		$this->expire = $expire;

		return $this;
	}

	/**
	 * Set the session state
	 *
	 * @param   string  $state  Internal state
	 *
	 * @return  $this
	 *
	 * @since   1.3.0
	 */
	protected function setState($state)
	{
		$this->state = $state;

		return $this;
	}

	/**
	 * Set session cookie parameters
	 *
	 * @return  void
	 *
	 * @since   1.0
	 * @deprecated  2.0
	 */
	protected function _setCookieParams()
	{
		$cookie = session_get_cookie_params();

		if ($this->force_ssl)
		{
			$cookie['secure'] = true;
		}

		if ($this->cookie_domain)
		{
			$cookie['domain'] = $this->cookie_domain;
		}

		if ($this->cookie_path)
		{
			$cookie['path'] = $this->cookie_path;
		}

		$cookie['httponly'] = $this->cookie_httponly;

		if ($this->cookie_samesite)
		{
			$cookie['samesite'] = $this->cookie_samesite;
		}

		if (version_compare(PHP_VERSION, '7.3', '>='))
		{
			session_set_cookie_params($cookie);
		}
		else
		{
			session_set_cookie_params($cookie['lifetime'], $cookie['path'], $cookie['domain'], $cookie['secure'], $cookie['httponly']);
		}
	}

	/**
	 * Create a token-string
	 *
	 * @param   integer  $length  Length of string {@deprecated As of 2.0 the session token will be a fixed length}
	 *
	 * @return  string  Generated token
	 *
	 * @since   1.0
	 * @deprecated  2.0  Use createToken instead
	 */
	protected function _createToken($length = 32)
	{
		return $this->createToken($length);
	}

	/**
	 * Create a token-string
	 *
	 * @param   integer  $length  Length of string {@deprecated As of 2.0 the session token will be a fixed length}
	 *
	 * @return  string  Generated token
	 *
	 * @since   1.3.1
	 */
	protected function createToken($length = 32)
	{
		return bin2hex(random_bytes($length));
	}

	/**
	 * Set counter of session usage
	 *
	 * @return  boolean  True on success
	 *
	 * @since   1.0
	 * @deprecated  2.0  Use setCounter instead
	 */
	protected function _setCounter()
	{
		return $this->setCounter();
	}

	/**
	 * Set counter of session usage
	 *
	 * @return  boolean  True on success
	 *
	 * @since   1.3.0
	 */
	protected function setCounter()
	{
		$counter = $this->get('session.counter', 0);
		++$counter;

		$this->set('session.counter', $counter);

		return true;
	}

	/**
	 * Set the session timers
	 *
	 * @return  boolean  True on success
	 *
	 * @since   1.0
	 * @deprecated  2.0  Use setTimers instead
	 */
	protected function _setTimers()
	{
		return $this->setTimers();
	}

	/**
	 * Set the session timers
	 *
	 * @return  boolean  True on success
	 *
	 * @since   1.3.0
	 */
	protected function setTimers()
	{
		if (!$this->has('session.timer.start'))
		{
			$start = time();

			$this->set('session.timer.start', $start);
			$this->set('session.timer.last', $start);
			$this->set('session.timer.now', $start);
		}

		$this->set('session.timer.last', $this->get('session.timer.now'));
		$this->set('session.timer.now', time());

		return true;
	}

	/**
	 * Set additional session options
	 *
	 * @param   array  $options  List of parameter
	 *
	 * @return  boolean  True on success
	 *
	 * @since   1.0
	 * @deprecated  2.0  Use setOptions instead
	 */
	protected function _setOptions(array $options)
	{
		return $this->setOptions($options);
	}

	/**
	 * Set additional session options
	 *
	 * @param   array  $options  List of parameter
	 *
	 * @return  boolean  True on success
	 *
	 * @since   1.3.0
	 */
	protected function setOptions(array $options)
	{
		// Set name
		if (isset($options['name']))
		{
			session_name(md5($options['name']));
		}

		// Set id
		if (isset($options['id']))
		{
			session_id($options['id']);
		}

		// Set expire time
		if (isset($options['expire']))
		{
			$this->setExpire($options['expire']);
		}

		// Get security options
		if (isset($options['security']))
		{
			$this->security = explode(',', $options['security']);
		}

		if (isset($options['force_ssl']))
		{
			$this->force_ssl = (bool) $options['force_ssl'];
		}

		if (isset($options['cookie_domain']))
		{
			$this->cookie_domain = $options['cookie_domain'];
		}

		if (isset($options['cookie_path']))
		{
			$this->cookie_path = $options['cookie_path'];
		}

		if (isset($options['cookie_httponly']))
		{
			$this->cookie_httponly = (bool) $options['cookie_httponly'];
		}

		if (isset($options['cookie_samesite']))
		{
			$this->cookie_samesite = $options['cookie_samesite'];
		}

		// Sync the session maxlifetime
		if (!headers_sent())
		{
			ini_set('session.gc_maxlifetime', $this->getExpire());
		}

		return true;
	}

	/**
	 * Do some checks for security reason
	 *
	 * - timeout check (expire)
	 * - ip-fixiation
	 * - browser-fixiation
	 *
	 * If one check failed, session data has to be cleaned.
	 *
	 * @param   boolean  $restart  Reactivate session
	 *
	 * @return  boolean  True on success
	 *
	 * @link    http://shiflett.org/articles/the-truth-about-sessions
	 * @since   1.0
	 * @deprecated  2.0  Use validate instead
	 */
	protected function _validate($restart = false)
	{
		return $this->validate($restart);
	}

	/**
	 * Do some checks for security reason
	 *
	 * - timeout check (expire)
	 * - ip-fixiation
	 * - browser-fixiation
	 *
	 * If one check failed, session data has to be cleaned.
	 *
	 * @param   boolean  $restart  Reactivate session
	 *
	 * @return  boolean  True on success
	 *
	 * @link    http://shiflett.org/articles/the-truth-about-sessions
	 * @since   1.3.0
	 */
	protected function validate($restart = false)
	{
		// Allow to restart a session
		if ($restart)
		{
			$this->setState('active');

			$this->set('session.client.address', null);
			$this->set('session.client.forwarded', null);
			$this->set('session.token', null);
		}

		// Check if session has expired
		if ($this->getExpire())
		{
			$curTime = $this->get('session.timer.now', 0);
			$maxTime = $this->get('session.timer.last', 0) + $this->getExpire();

			// Empty session variables
			if ($maxTime < $curTime)
			{
				$this->setState('expired');

				return false;
			}
		}

		$remoteAddr = $this->input->server->getString('REMOTE_ADDR', '');

		// Check for client address
		if (\in_array('fix_adress', $this->security) && !empty($remoteAddr) && filter_var($remoteAddr, FILTER_VALIDATE_IP) !== false)
		{
			$ip = $this->get('session.client.address');

			if ($ip === null)
			{
				$this->set('session.client.address', $remoteAddr);
			}
			elseif ($remoteAddr !== $ip)
			{
				$this->setState('error');

				return false;
			}
		}

		$xForwardedFor = $this->input->server->getString('HTTP_X_FORWARDED_FOR', '');

		// Record proxy forwarded for in the session in case we need it later
		if (!empty($xForwardedFor) && filter_var($xForwardedFor, FILTER_VALIDATE_IP) !== false)
		{
			$this->set('session.client.forwarded', $xForwardedFor);
		}

		return true;
	}
}
Session/Storage/None.php000064400000001331152431556430011211 0ustar00<?php
/**
 * Part of the Joomla Framework Session Package
 *
 * @copyright  Copyright (C) 2005 - 2020 Open Source Matters, Inc. All rights reserved.
 * @license    GNU General Public License version 2 or later; see LICENSE
 */

namespace Joomla\Session\Storage;

use Joomla\Session\Storage;

/**
 * Default PHP configured session handler for Joomla!
 *
 * @link        https://www.php.net/manual/en/function.session-set-save-handler.php
 * @since       1.0
 * @deprecated  2.0  The Storage class chain will be removed
 */
class None extends Storage
{
	/**
	 * Register the functions of this class with PHP's session handler
	 *
	 * @return  void
	 *
	 * @since   1.0
	 * @deprecated  2.0
	 */
	public function register()
	{
	}
}
Session/Storage/Apc.php000064400000004326152431556500011022 0ustar00<?php
/**
 * Part of the Joomla Framework Session Package
 *
 * @copyright  Copyright (C) 2005 - 2020 Open Source Matters, Inc. All rights reserved.
 * @license    GNU General Public License version 2 or later; see LICENSE
 */

namespace Joomla\Session\Storage;

use Joomla\Session\Storage;

/**
 * APC session storage handler for PHP
 *
 * @link        https://www.php.net/manual/en/function.session-set-save-handler.php
 * @since       1.0
 * @deprecated  2.0  The Storage class chain will be removed.
 */
class Apc extends Storage
{
	/**
	 * Constructor
	 *
	 * @param   array  $options  Optional parameters
	 *
	 * @since   1.0
	 * @throws  \RuntimeException
	 * @deprecated  2.0
	 */
	public function __construct($options = array())
	{
		if (!self::isSupported())
		{
			throw new \RuntimeException('APC Extension is not available', 404);
		}

		parent::__construct($options);
	}

	/**
	 * Read the data for a particular session identifier from the
	 * SessionHandler backend.
	 *
	 * @param   string  $id  The session identifier.
	 *
	 * @return  string  The session data.
	 *
	 * @since   1.0
	 * @deprecated  2.0
	 */
	public function read($id)
	{
		$sess_id = 'sess_' . $id;

		return (string) apc_fetch($sess_id);
	}

	/**
	 * Write session data to the SessionHandler backend.
	 *
	 * @param   string  $id           The session identifier.
	 * @param   string  $sessionData  The session data.
	 *
	 * @return  boolean  True on success, false otherwise.
	 *
	 * @since   1.0
	 * @deprecated  2.0
	 */
	public function write($id, $sessionData)
	{
		$sess_id = 'sess_' . $id;

		return apc_store($sess_id, $sessionData, ini_get('session.gc_maxlifetime'));
	}

	/**
	 * Destroy the data for a particular session identifier in the SessionHandler backend.
	 *
	 * @param   string  $id  The session identifier.
	 *
	 * @return  boolean  True on success, false otherwise.
	 *
	 * @since   1.0
	 * @deprecated  2.0
	 */
	public function destroy($id)
	{
		$sess_id = 'sess_' . $id;

		return apc_delete($sess_id);
	}

	/**
	 * Test to see if the SessionHandler is available.
	 *
	 * @return boolean  True on success, false otherwise.
	 *
	 * @since   1.0
	 * @deprecated  2.0
	 */
	public static function isSupported()
	{
		return \extension_loaded('apc');
	}
}
Session/Storage/Wincache.php000064400000002605152431556550012043 0ustar00<?php
/**
 * Part of the Joomla Framework Session Package
 *
 * @copyright  Copyright (C) 2005 - 2020 Open Source Matters, Inc. All rights reserved.
 * @license    GNU General Public License version 2 or later; see LICENSE
 */

namespace Joomla\Session\Storage;

use Joomla\Session\Storage;

/**
 * WINCACHE session storage handler for PHP
 *
 * @since       1.0
 * @deprecated  2.0  The Storage class chain will be removed
 */
class Wincache extends Storage
{
	/**
	 * Constructor
	 *
	 * @param   array  $options  Optional parameters.
	 *
	 * @since   1.0
	 * @throws  \RuntimeException
	 * @deprecated  2.0
	 */
	public function __construct($options = array())
	{
		if (!self::isSupported())
		{
			throw new \RuntimeException('Wincache Extension is not available', 404);
		}

		parent::__construct($options);
	}

	/**
	 * Register the functions of this class with PHP's session handler
	 *
	 * @return  void
	 *
	 * @since   1.0
	 * @deprecated  2.0
	 */
	public function register()
	{
		if (!headers_sent())
		{
			ini_set('session.save_handler', 'wincache');
		}
	}

	/**
	 * Test to see if the SessionHandler is available.
	 *
	 * @return  boolean  True on success, false otherwise.
	 *
	 * @since   1.0
	 * @deprecated  2.0
	 */
	public static function isSupported()
	{
		return \extension_loaded('wincache') && \function_exists('wincache_ucache_get') && !strcmp(ini_get('wincache.ucenabled'), '1');
	}
}
Session/Storage/Memcached.php000064400000004147152431556620012171 0ustar00<?php
/**
 * Part of the Joomla Framework Session Package
 *
 * @copyright  Copyright (C) 2005 - 2020 Open Source Matters, Inc. All rights reserved.
 * @license    GNU General Public License version 2 or later; see LICENSE
 */

namespace Joomla\Session\Storage;

use Joomla\Session\Storage;

/**
 * Memcached session storage handler for PHP
 *
 * @since       1.0
 * @deprecated  2.0  The Storage class chain will be removed
 */
class Memcached extends Storage
{
	/**
	 * Container for server data
	 *
	 * @var    array
	 * @since  1.0
	 * @deprecated  2.0
	 */
	protected $_servers = array();

	/**
	 * Constructor
	 *
	 * @param   array  $options  Optional parameters.
	 *
	 * @since   1.0
	 * @throws  \RuntimeException
	 * @deprecated  2.0
	 */
	public function __construct($options = array())
	{
		if (!self::isSupported())
		{
			throw new \RuntimeException('Memcached Extension is not available', 404);
		}

		// This will be an array of loveliness
		// @todo: multiple servers
		$this->_servers = array(
			array(
				'host' => isset($options['memcache_server_host']) ? $options['memcache_server_host'] : 'localhost',
				'port' => isset($options['memcache_server_port']) ? $options['memcache_server_port'] : 11211,
			),
		);

		// Only construct parent AFTER host and port are sent, otherwise when register is called this will fail.
		parent::__construct($options);
	}

	/**
	 * Register the functions of this class with PHP's session handler
	 *
	 * @return  void
	 *
	 * @since   1.0
	 * @deprecated  2.0
	 */
	public function register()
	{
		if (!headers_sent())
		{
			ini_set('session.save_path', $this->_servers[0]['host'] . ':' . $this->_servers[0]['port']);
			ini_set('session.save_handler', 'memcached');
		}
	}

	/**
	 * Test to see if the SessionHandler is available.
	 *
	 * @return  boolean  True on success, false otherwise.
	 *
	 * @since   1.0
	 * @deprecated  2.0
	 */
	public static function isSupported()
	{
		/*
		 * GAE and HHVM have both had instances where Memcached the class was defined but no extension was loaded.
		 * If the class is there, we can assume it works.
		 */
		return class_exists('Memcached');
	}
}
Session/Storage/Xcache.php000064400000004415152431556670011521 0ustar00<?php
/**
 * Part of the Joomla Framework Session Package
 *
 * @copyright  Copyright (C) 2005 - 2020 Open Source Matters, Inc. All rights reserved.
 * @license    GNU General Public License version 2 or later; see LICENSE
 */

namespace Joomla\Session\Storage;

use Joomla\Session\Storage;

/**
 * XCache session storage handler
 *
 * @since       1.0
 * @deprecated  2.0  The Storage class chain will be removed
 */
class Xcache extends Storage
{
	/**
	 * Constructor
	 *
	 * @param   array  $options  Optional parameters.
	 *
	 * @since   1.0
	 * @throws  \RuntimeException
	 * @deprecated  2.0
	 */
	public function __construct($options = array())
	{
		if (!self::isSupported())
		{
			throw new \RuntimeException('XCache Extension is not available', 404);
		}

		parent::__construct($options);
	}

	/**
	 * Read the data for a particular session identifier from the SessionHandler backend.
	 *
	 * @param   string  $id  The session identifier.
	 *
	 * @return  string  The session data.
	 *
	 * @since   1.0
	 * @deprecated  2.0
	 */
	public function read($id)
	{
		$sess_id = 'sess_' . $id;

		// Check if id exists
		if (!xcache_isset($sess_id))
		{
			return '';
		}

		return (string) xcache_get($sess_id);
	}

	/**
	 * Write session data to the SessionHandler backend.
	 *
	 * @param   string  $id           The session identifier.
	 * @param   string  $sessionData  The session data.
	 *
	 * @return  boolean  True on success, false otherwise.
	 *
	 * @since   1.0
	 * @deprecated  2.0
	 */
	public function write($id, $sessionData)
	{
		$sess_id = 'sess_' . $id;

		return xcache_set($sess_id, $sessionData, ini_get('session.gc_maxlifetime'));
	}

	/**
	 * Destroy the data for a particular session identifier in the SessionHandler backend.
	 *
	 * @param   string  $id  The session identifier.
	 *
	 * @return  boolean  True on success, false otherwise.
	 *
	 * @since   1.0
	 * @deprecated  2.0
	 */
	public function destroy($id)
	{
		$sess_id = 'sess_' . $id;

		if (!xcache_isset($sess_id))
		{
			return true;
		}

		return xcache_unset($sess_id);
	}

	/**
	 * Test to see if the SessionHandler is available.
	 *
	 * @return  boolean  True on success, false otherwise.
	 *
	 * @since   1.0
	 * @deprecated  2.0
	 */
	public static function isSupported()
	{
		return \extension_loaded('xcache');
	}
}
Session/Storage/Memcache.php000064400000003554152431556740012031 0ustar00<?php
/**
 * Part of the Joomla Framework Session Package
 *
 * @copyright  Copyright (C) 2005 - 2020 Open Source Matters, Inc. All rights reserved.
 * @license    GNU General Public License version 2 or later; see LICENSE
 */

namespace Joomla\Session\Storage;

use Joomla\Session\Storage;

/**
 * Memcache session storage handler for PHP
 *
 * @since       1.0
 * @deprecated  2.0  The Storage class chain will be removed
 */
class Memcache extends Storage
{
	/**
	 * Container for server data
	 *
	 * @var    array
	 * @since  1.0
	 * @deprecated  2.0
	 */
	protected $_servers = array();

	/**
	 * Constructor
	 *
	 * @param   array  $options  Optional parameters.
	 *
	 * @since   1.0
	 * @throws  \RuntimeException
	 * @deprecated  2.0
	 */
	public function __construct($options = array())
	{
		if (!self::isSupported())
		{
			throw new \RuntimeException('Memcache Extension is not available', 404);
		}

		// This will be an array of loveliness
		// @todo: multiple servers
		$this->_servers = array(
			array(
				'host' => isset($options['memcache_server_host']) ? $options['memcache_server_host'] : 'localhost',
				'port' => isset($options['memcache_server_port']) ? $options['memcache_server_port'] : 11211,
			),
		);

		parent::__construct($options);
	}

	/**
	 * Register the functions of this class with PHP's session handler
	 *
	 * @return  void
	 *
	 * @since   1.0
	 * @deprecated  2.0
	 */
	public function register()
	{
		if (!headers_sent())
		{
			ini_set('session.save_path', $this->_servers[0]['host'] . ':' . $this->_servers[0]['port']);
			ini_set('session.save_handler', 'memcache');
		}
	}

	/**
	 * Test to see if the SessionHandler is available.
	 *
	 * @return  boolean  True on success, false otherwise.
	 *
	 * @since   1.0
	 * @deprecated  2.0
	 */
	public static function isSupported()
	{
		return \extension_loaded('memcache') && class_exists('Memcache');
	}
}
Session/Storage/Database.php000064400000010500152431556740012020 0ustar00<?php
/**
 * Part of the Joomla Framework Session Package
 *
 * @copyright  Copyright (C) 2005 - 2020 Open Source Matters, Inc. All rights reserved.
 * @license    GNU General Public License version 2 or later; see LICENSE
 */

namespace Joomla\Session\Storage;

use Joomla\Database\DatabaseDriver;
use Joomla\Session\Storage;

/**
 * Database session storage handler for PHP
 *
 * @link        https://www.php.net/manual/en/function.session-set-save-handler.php
 * @since       1.0
 * @deprecated  2.0  The Storage class chain will be removed
 */
class Database extends Storage
{
	/**
	 * The DatabaseDriver to use when querying.
	 *
	 * @var    DatabaseDriver
	 * @since  1.0
	 * @deprecated  2.0
	 */
	protected $db;

	/**
	 * Constructor
	 *
	 * @param   array  $options  Optional parameters. A `dbo` options is required.
	 *
	 * @since   1.0
	 * @throws  \RuntimeException
	 * @deprecated  2.0
	 */
	public function __construct($options = array())
	{
		if (isset($options['db']) && ($options['db'] instanceof DatabaseDriver))
		{
			parent::__construct($options);
			$this->db = $options['db'];
		}
		else
		{
			throw new \RuntimeException(
				sprintf('The %s storage engine requires a `db` option that is an instance of Joomla\\Database\\DatabaseDriver.', __CLASS__)
			);
		}
	}

	/**
	 * Read the data for a particular session identifier from the SessionHandler backend.
	 *
	 * @param   string  $id  The session identifier.
	 *
	 * @return  string  The session data.
	 *
	 * @since   1.0
	 * @deprecated  2.0
	 */
	public function read($id)
	{
		try
		{
			// Get the session data from the database table.
			$query = $this->db->getQuery(true);
			$query->select($this->db->quoteName('data'))
				->from($this->db->quoteName('#__session'))
				->where($this->db->quoteName('session_id') . ' = ' . $this->db->quote($id));

			$this->db->setQuery($query);

			return (string) $this->db->loadResult();
		}
		catch (\Exception $e)
		{
			return false;
		}
	}

	/**
	 * Write session data to the SessionHandler backend.
	 *
	 * @param   string  $id    The session identifier.
	 * @param   string  $data  The session data.
	 *
	 * @return  boolean  True on success, false otherwise.
	 *
	 * @since   1.0
	 * @deprecated  2.0
	 */
	public function write($id, $data)
	{
		try
		{
			$query = $this->db->getQuery(true);
			$query->update($this->db->quoteName('#__session'))
				->set($this->db->quoteName('data') . ' = ' . $this->db->quote($data))
				->set($this->db->quoteName('time') . ' = ' . $this->db->quote((int) time()))
				->where($this->db->quoteName('session_id') . ' = ' . $this->db->quote($id));

			// Try to update the session data in the database table.
			$this->db->setQuery($query);

			if (!$this->db->execute())
			{
				return false;
			}

			// Since $this->db->execute did not throw an exception the query was successful.
			// Either the data changed, or the data was identical. In either case we are done.

			return true;
		}
		catch (\Exception $e)
		{
			return false;
		}
	}

	/**
	 * Destroy the data for a particular session identifier in the SessionHandler backend.
	 *
	 * @param   string  $id  The session identifier.
	 *
	 * @return  boolean  True on success, false otherwise.
	 *
	 * @since   1.0
	 * @deprecated  2.0
	 */
	public function destroy($id)
	{
		try
		{
			$query = $this->db->getQuery(true);
			$query->delete($this->db->quoteName('#__session'))
				->where($this->db->quoteName('session_id') . ' = ' . $this->db->quote($id));

			// Remove a session from the database.
			$this->db->setQuery($query);

			return (boolean) $this->db->execute();
		}
		catch (\Exception $e)
		{
			return false;
		}
	}

	/**
	 * Garbage collect stale sessions from the SessionHandler backend.
	 *
	 * @param   integer  $lifetime  The maximum age of a session.
	 *
	 * @return  boolean  True on success, false otherwise.
	 *
	 * @since   1.0
	 * @deprecated  2.0
	 */
	public function gc($lifetime = 1440)
	{
		// Determine the timestamp threshold with which to purge old sessions.
		$past = time() - $lifetime;

		try
		{
			$query = $this->db->getQuery(true);
			$query->delete($this->db->quoteName('#__session'))
				->where($this->db->quoteName('time') . ' < ' . $this->db->quote((int) $past));

			// Remove expired sessions from the database.
			$this->db->setQuery($query);

			return (boolean) $this->db->execute();
		}
		catch (\Exception $e)
		{
			return false;
		}
	}
}
Session/Storage/Apcu.php000064400000004201152431557010011174 0ustar00<?php
/**
 * Part of the Joomla Framework Session Package
 *
 * @copyright  Copyright (C) 2005 - 2020 Open Source Matters, Inc. All rights reserved.
 * @license    GNU General Public License version 2 or later; see LICENSE
 */

namespace Joomla\Session\Storage;

use Joomla\Session\Storage;

/**
 * APCU session storage handler for PHP
 *
 * @link        https://www.php.net/manual/en/function.session-set-save-handler.php
 * @since       1.4.0
 * @deprecated  2.0  The Storage class chain will be removed.
 */
class Apcu extends Storage
{
	/**
	 * Constructor
	 *
	 * @param   array  $options  Optional parameters
	 *
	 * @since   1.4.0
	 * @throws  \RuntimeException
	 */
	public function __construct($options = array())
	{
		if (!self::isSupported())
		{
			throw new \RuntimeException('APCU Extension is not available', 404);
		}

		parent::__construct($options);
	}

	/**
	 * Read the data for a particular session identifier from the
	 * SessionHandler backend.
	 *
	 * @param   string  $id  The session identifier.
	 *
	 * @return  string  The session data.
	 *
	 * @since   1.4.0
	 */
	public function read($id)
	{
		$sess_id = 'sess_' . $id;

		return (string) apcu_fetch($sess_id);
	}

	/**
	 * Write session data to the SessionHandler backend.
	 *
	 * @param   string  $id           The session identifier.
	 * @param   string  $sessionData  The session data.
	 *
	 * @return  boolean  True on success, false otherwise.
	 *
	 * @since   1.4.0
	 */
	public function write($id, $sessionData)
	{
		$sess_id = 'sess_' . $id;

		return apcu_store($sess_id, $sessionData, ini_get('session.gc_maxlifetime'));
	}

	/**
	 * Destroy the data for a particular session identifier in the SessionHandler backend.
	 *
	 * @param   string  $id  The session identifier.
	 *
	 * @return  boolean  True on success, false otherwise.
	 *
	 * @since   1.4.0
	 */
	public function destroy($id)
	{
		$sess_id = 'sess_' . $id;

		return apcu_delete($sess_id);
	}

	/**
	 * Test to see if the SessionHandler is available.
	 *
	 * @return  boolean  True on success, false otherwise.
	 *
	 * @since   1.4.0
	 */
	public static function isSupported()
	{
		return \extension_loaded('apcu');
	}
}