File manager - Edit - /home/capoccitel/www/wp-admin/vendor.tar
Back
brumann/polyfill-unserialize/LICENSE 0000705 00000002063 15242100017 0013364 0 ustar 00 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. brumann/polyfill-unserialize/composer.json 0000705 00000001144 15242100017 0015100 0 ustar 00 { "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" } } brumann/polyfill-unserialize/src/DisallowedClassesSubstitutor.php 0000705 00000012233 15242100017 0021554 0 ustar 00 <?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) ); } } brumann/polyfill-unserialize/src/Unserialize.php 0000705 00000002254 15242100017 0016153 0 ustar 00 <?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()); } } phpmailer/phpmailer/class.phpmailer.php 0000705 00000443574 15242100017 0014313 0 ustar 00 <?php /** * PHPMailer - PHP email creation and transport class. * PHP Version 5 * @package PHPMailer * @link https://github.com/PHPMailer/PHPMailer/ The PHPMailer GitHub project * @author Marcus Bointon (Synchro/coolbru) <phpmailer@synchromedia.co.uk> * @author Jim Jagielski (jimjag) <jimjag@gmail.com> * @author Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net> * @author Brent R. Matzelle (original founder) * @copyright 2012 - 2014 Marcus Bointon * @copyright 2010 - 2012 Jim Jagielski * @copyright 2004 - 2009 Andy Prevost * @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License * @note This program is distributed in the hope that it will be useful - WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. */ /** * PHPMailer - PHP email creation and transport class. * @package PHPMailer * @author Marcus Bointon (Synchro/coolbru) <phpmailer@synchromedia.co.uk> * @author Jim Jagielski (jimjag) <jimjag@gmail.com> * @author Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net> * @author Brent R. Matzelle (original founder) */ class PHPMailer { /** * The PHPMailer Version number. * @var string */ public $Version = '5.2.28+joomla2'; /** * Email priority. * Options: null (default), 1 = High, 3 = Normal, 5 = low. * When null, the header is not set at all. * @var integer */ public $Priority = null; /** * The character set of the message. * @var string */ public $CharSet = 'iso-8859-1'; /** * The MIME Content-type of the message. * @var string */ public $ContentType = 'text/plain'; /** * The message encoding. * Options: "8bit", "7bit", "binary", "base64", and "quoted-printable". * @var string */ public $Encoding = '8bit'; /** * Holds the most recent mailer error message. * @var string */ public $ErrorInfo = ''; /** * The From email address for the message. * @var string */ public $From = 'root@localhost'; /** * The From name of the message. * @var string */ public $FromName = 'Root User'; /** * The Sender email (Return-Path) of the message. * If not empty, will be sent via -f to sendmail or as 'MAIL FROM' in smtp mode. * @var string */ public $Sender = ''; /** * The Return-Path of the message. * If empty, it will be set to either From or Sender. * @var string * @deprecated Email senders should never set a return-path header; * it's the receiver's job (RFC5321 section 4.4), so this no longer does anything. * @link https://tools.ietf.org/html/rfc5321#section-4.4 RFC5321 reference */ public $ReturnPath = ''; /** * The Subject of the message. * @var string */ public $Subject = ''; /** * An HTML or plain text message body. * If HTML then call isHTML(true). * @var string */ public $Body = ''; /** * The plain-text message body. * This body can be read by mail clients that do not have HTML email * capability such as mutt & Eudora. * Clients that can read HTML will view the normal Body. * @var string */ public $AltBody = ''; /** * An iCal message part body. * Only supported in simple alt or alt_inline message types * To generate iCal events, use the bundled extras/EasyPeasyICS.php class or iCalcreator * @link http://sprain.ch/blog/downloads/php-class-easypeasyics-create-ical-files-with-php/ * @link http://kigkonsult.se/iCalcreator/ * @var string */ public $Ical = ''; /** * The complete compiled MIME message body. * @access protected * @var string */ protected $MIMEBody = ''; /** * The complete compiled MIME message headers. * @var string * @access protected */ protected $MIMEHeader = ''; /** * Extra headers that createHeader() doesn't fold in. * @var string * @access protected */ protected $mailHeader = ''; /** * Word-wrap the message body to this number of chars. * Set to 0 to not wrap. A useful value here is 78, for RFC2822 section 2.1.1 compliance. * @var integer */ public $WordWrap = 0; /** * Which method to use to send mail. * Options: "mail", "sendmail", or "smtp". * @var string */ public $Mailer = 'mail'; /** * The path to the sendmail program. * @var string */ public $Sendmail = '/usr/sbin/sendmail'; /** * Whether mail() uses a fully sendmail-compatible MTA. * One which supports sendmail's "-oi -f" options. * @var boolean */ public $UseSendmailOptions = true; /** * Path to PHPMailer plugins. * Useful if the SMTP class is not in the PHP include path. * @var string * @deprecated Should not be needed now there is an autoloader. */ public $PluginDir = ''; /** * The email address that a reading confirmation should be sent to, also known as read receipt. * @var string */ public $ConfirmReadingTo = ''; /** * The hostname to use in the Message-ID header and as default HELO string. * If empty, PHPMailer attempts to find one with, in order, * $_SERVER['SERVER_NAME'], gethostname(), php_uname('n'), or the value * 'localhost.localdomain'. * @var string */ public $Hostname = ''; /** * An ID to be used in the Message-ID header. * If empty, a unique id will be generated. * You can set your own, but it must be in the format "<id@domain>", * as defined in RFC5322 section 3.6.4 or it will be ignored. * @see https://tools.ietf.org/html/rfc5322#section-3.6.4 * @var string */ public $MessageID = ''; /** * The message Date to be used in the Date header. * If empty, the current date will be added. * @var string */ public $MessageDate = ''; /** * SMTP hosts. * Either a single hostname or multiple semicolon-delimited hostnames. * You can also specify a different port * for each host by using this format: [hostname:port] * (e.g. "smtp1.example.com:25;smtp2.example.com"). * You can also specify encryption type, for example: * (e.g. "tls://smtp1.example.com:587;ssl://smtp2.example.com:465"). * Hosts will be tried in order. * @var string */ public $Host = 'localhost'; /** * The default SMTP server port. * @var integer * @TODO Why is this needed when the SMTP class takes care of it? */ public $Port = 25; /** * The SMTP HELO of the message. * Default is $Hostname. If $Hostname is empty, PHPMailer attempts to find * one with the same method described above for $Hostname. * @var string * @see PHPMailer::$Hostname */ public $Helo = ''; /** * What kind of encryption to use on the SMTP connection. * Options: '', 'ssl' or 'tls' * @var string */ public $SMTPSecure = ''; /** * Whether to enable TLS encryption automatically if a server supports it, * even if `SMTPSecure` is not set to 'tls'. * Be aware that in PHP >= 5.6 this requires that the server's certificates are valid. * @var boolean */ public $SMTPAutoTLS = true; /** * Whether to use SMTP authentication. * Uses the Username and Password properties. * @var boolean * @see PHPMailer::$Username * @see PHPMailer::$Password */ public $SMTPAuth = false; /** * Options array passed to stream_context_create when connecting via SMTP. * @var array */ public $SMTPOptions = array(); /** * SMTP username. * @var string */ public $Username = ''; /** * SMTP password. * @var string */ public $Password = ''; /** * SMTP auth type. * Options are CRAM-MD5, LOGIN, PLAIN, NTLM, XOAUTH2, attempted in that order if not specified * @var string */ public $AuthType = ''; /** * SMTP realm. * Used for NTLM auth * @var string */ public $Realm = ''; /** * SMTP workstation. * Used for NTLM auth * @var string */ public $Workstation = ''; /** * The SMTP server timeout in seconds. * Default of 5 minutes (300sec) is from RFC2821 section 4.5.3.2 * @var integer */ public $Timeout = 300; /** * SMTP class debug output mode. * Debug output level. * Options: * * `0` No output * * `1` Commands * * `2` Data and commands * * `3` As 2 plus connection status * * `4` Low-level data output * @var integer * @see SMTP::$do_debug */ public $SMTPDebug = 0; /** * How to handle debug output. * Options: * * `echo` Output plain-text as-is, appropriate for CLI * * `html` Output escaped, line breaks converted to `<br>`, appropriate for browser output * * `error_log` Output to error log as configured in php.ini * * Alternatively, you can provide a callable expecting two params: a message string and the debug level: * <code> * $mail->Debugoutput = function($str, $level) {echo "debug level $level; message: $str";}; * </code> * @var string|callable * @see SMTP::$Debugoutput */ public $Debugoutput = 'echo'; /** * Whether to keep SMTP connection open after each message. * If this is set to true then to close the connection * requires an explicit call to smtpClose(). * @var boolean */ public $SMTPKeepAlive = false; /** * Whether to split multiple to addresses into multiple messages * or send them all in one message. * Only supported in `mail` and `sendmail` transports, not in SMTP. * @var boolean */ public $SingleTo = false; /** * Storage for addresses when SingleTo is enabled. * @var array * @TODO This should really not be public */ public $SingleToArray = array(); /** * Whether to generate VERP addresses on send. * Only applicable when sending via SMTP. * @link https://en.wikipedia.org/wiki/Variable_envelope_return_path * @link http://www.postfix.org/VERP_README.html Postfix VERP info * @var boolean */ public $do_verp = false; /** * Whether to allow sending messages with an empty body. * @var boolean */ public $AllowEmpty = false; /** * The default line ending. * @note The default remains "\n". We force CRLF where we know * it must be used via self::CRLF. * @var string */ public $LE = "\n"; /** * DKIM selector. * @var string */ public $DKIM_selector = ''; /** * DKIM Identity. * Usually the email address used as the source of the email. * @var string */ public $DKIM_identity = ''; /** * DKIM passphrase. * Used if your key is encrypted. * @var string */ public $DKIM_passphrase = ''; /** * DKIM signing domain name. * @example 'example.com' * @var string */ public $DKIM_domain = ''; /** * DKIM private key file path. * @var string */ public $DKIM_private = ''; /** * DKIM private key string. * If set, takes precedence over `$DKIM_private`. * @var string */ public $DKIM_private_string = ''; /** * Callback Action function name. * * The function that handles the result of the send email action. * It is called out by send() for each email sent. * * Value can be any php callable: http://www.php.net/is_callable * * Parameters: * boolean $result result of the send action * array $to email addresses of the recipients * array $cc cc email addresses * array $bcc bcc email addresses * string $subject the subject * string $body the email body * string $from email address of sender * @var string */ public $action_function = ''; /** * What to put in the X-Mailer header. * Options: An empty string for PHPMailer default, whitespace for none, or a string to use * @var string */ public $XMailer = ''; /** * Which validator to use by default when validating email addresses. * May be a callable to inject your own validator, but there are several built-in validators. * @see PHPMailer::validateAddress() * @var string|callable * @static */ public static $validator = 'auto'; /** * An instance of the SMTP sender class. * @var SMTP * @access protected */ protected $smtp = null; /** * The array of 'to' names and addresses. * @var array * @access protected */ protected $to = array(); /** * The array of 'cc' names and addresses. * @var array * @access protected */ protected $cc = array(); /** * The array of 'bcc' names and addresses. * @var array * @access protected */ protected $bcc = array(); /** * The array of reply-to names and addresses. * @var array * @access protected */ protected $ReplyTo = array(); /** * An array of all kinds of addresses. * Includes all of $to, $cc, $bcc * @var array * @access protected * @see PHPMailer::$to @see PHPMailer::$cc @see PHPMailer::$bcc */ protected $all_recipients = array(); /** * An array of names and addresses queued for validation. * In send(), valid and non duplicate entries are moved to $all_recipients * and one of $to, $cc, or $bcc. * This array is used only for addresses with IDN. * @var array * @access protected * @see PHPMailer::$to @see PHPMailer::$cc @see PHPMailer::$bcc * @see PHPMailer::$all_recipients */ protected $RecipientsQueue = array(); /** * An array of reply-to names and addresses queued for validation. * In send(), valid and non duplicate entries are moved to $ReplyTo. * This array is used only for addresses with IDN. * @var array * @access protected * @see PHPMailer::$ReplyTo */ protected $ReplyToQueue = array(); /** * The array of attachments. * @var array * @access protected */ protected $attachment = array(); /** * The array of custom headers. * @var array * @access protected */ protected $CustomHeader = array(); /** * The most recent Message-ID (including angular brackets). * @var string * @access protected */ protected $lastMessageID = ''; /** * The message's MIME type. * @var string * @access protected */ protected $message_type = ''; /** * The array of MIME boundary strings. * @var array * @access protected */ protected $boundary = array(); /** * The array of available languages. * @var array * @access protected */ protected $language = array(); /** * The number of errors encountered. * @var integer * @access protected */ protected $error_count = 0; /** * The S/MIME certificate file path. * @var string * @access protected */ protected $sign_cert_file = ''; /** * The S/MIME key file path. * @var string * @access protected */ protected $sign_key_file = ''; /** * The optional S/MIME extra certificates ("CA Chain") file path. * @var string * @access protected */ protected $sign_extracerts_file = ''; /** * The S/MIME password for the key. * Used only if the key is encrypted. * @var string * @access protected */ protected $sign_key_pass = ''; /** * Whether to throw exceptions for errors. * @var boolean * @access protected */ protected $exceptions = false; /** * Unique ID used for message ID and boundaries. * @var string * @access protected */ protected $uniqueid = ''; /** * Error severity: message only, continue processing. */ const STOP_MESSAGE = 0; /** * Error severity: message, likely ok to continue processing. */ const STOP_CONTINUE = 1; /** * Error severity: message, plus full stop, critical error reached. */ const STOP_CRITICAL = 2; /** * SMTP RFC standard line ending. */ const CRLF = "\r\n"; /** * The maximum line length allowed by RFC 2822 section 2.1.1 * @var integer */ const MAX_LINE_LENGTH = 998; /** * Constructor. * @param boolean $exceptions Should we throw external exceptions? */ public function __construct($exceptions = null) { if ($exceptions !== null) { $this->exceptions = (boolean)$exceptions; } //Pick an appropriate debug output format automatically $this->Debugoutput = (strpos(PHP_SAPI, 'cli') !== false ? 'echo' : 'html'); } /** * Destructor. */ public function __destruct() { //Close any open SMTP connection nicely $this->smtpClose(); } /** * Call mail() in a safe_mode-aware fashion. * Also, unless sendmail_path points to sendmail (or something that * claims to be sendmail), don't pass params (not a perfect fix, * but it will do) * @param string $to To * @param string $subject Subject * @param string $body Message Body * @param string $header Additional Header(s) * @param string $params Params * @access private * @return boolean */ private function mailPassthru($to, $subject, $body, $header, $params) { // Joomla Backported concept from https://github.com/PHPMailer/PHPMailer/pull/2188 if (PHP_VERSION_ID >= 80000 || stripos(PHP_OS, 'WIN') === 0) { $header = str_replace("\n", self::CRLF, $header); } //Check overloading of mail function to avoid double-encoding if (ini_get('mbstring.func_overload') & 1) { $subject = $this->secureHeader($subject); } else { $subject = $this->encodeHeader($this->secureHeader($subject)); } //Can't use additional_parameters in safe_mode, calling mail() with null params breaks //@link http://php.net/manual/en/function.mail.php if (ini_get('safe_mode') or !$this->UseSendmailOptions or is_null($params)) { $result = @mail($to, $subject, $body, $header); } else { $result = @mail($to, $subject, $body, $header, $params); } return $result; } /** * Output debugging info via user-defined method. * Only generates output if SMTP debug output is enabled (@see SMTP::$do_debug). * @see PHPMailer::$Debugoutput * @see PHPMailer::$SMTPDebug * @param string $str */ protected function edebug($str) { if ($this->SMTPDebug <= 0) { return; } //Avoid clash with built-in function names if (!in_array($this->Debugoutput, array('error_log', 'html', 'echo')) and is_callable($this->Debugoutput)) { call_user_func($this->Debugoutput, $str, $this->SMTPDebug); return; } switch ($this->Debugoutput) { case 'error_log': //Don't output, just log error_log($str); break; case 'html': //Cleans up output a bit for a better looking, HTML-safe output echo htmlentities( preg_replace('/[\r\n]+/', '', $str), ENT_QUOTES, 'UTF-8' ) . "<br>\n"; break; case 'echo': default: //Normalize line breaks $str = preg_replace('/\r\n?/ms', "\n", $str); echo gmdate('Y-m-d H:i:s') . "\t" . str_replace( "\n", "\n \t ", trim($str) ) . "\n"; } } /** * Sets message type to HTML or plain. * @param boolean $isHtml True for HTML mode. * @return void */ public function isHTML($isHtml = true) { if ($isHtml) { $this->ContentType = 'text/html'; } else { $this->ContentType = 'text/plain'; } } /** * Send messages using SMTP. * @return void */ public function isSMTP() { $this->Mailer = 'smtp'; } /** * Send messages using PHP's mail() function. * @return void */ public function isMail() { $this->Mailer = 'mail'; } /** * Send messages using $Sendmail. * @return void */ public function isSendmail() { $ini_sendmail_path = ini_get('sendmail_path'); if (!stristr($ini_sendmail_path, 'sendmail')) { $this->Sendmail = '/usr/sbin/sendmail'; } else { $this->Sendmail = $ini_sendmail_path; } $this->Mailer = 'sendmail'; } /** * Send messages using qmail. * @return void */ public function isQmail() { $ini_sendmail_path = ini_get('sendmail_path'); if (!stristr($ini_sendmail_path, 'qmail')) { $this->Sendmail = '/var/qmail/bin/qmail-inject'; } else { $this->Sendmail = $ini_sendmail_path; } $this->Mailer = 'qmail'; } /** * Add a "To" address. * @param string $address The email address to send to * @param string $name * @return boolean true on success, false if address already used or invalid in some way */ public function addAddress($address, $name = '') { return $this->addOrEnqueueAnAddress('to', $address, $name); } /** * Add a "CC" address. * @note: This function works with the SMTP mailer on win32, not with the "mail" mailer. * @param string $address The email address to send to * @param string $name * @return boolean true on success, false if address already used or invalid in some way */ public function addCC($address, $name = '') { return $this->addOrEnqueueAnAddress('cc', $address, $name); } /** * Add a "BCC" address. * @note: This function works with the SMTP mailer on win32, not with the "mail" mailer. * @param string $address The email address to send to * @param string $name * @return boolean true on success, false if address already used or invalid in some way */ public function addBCC($address, $name = '') { return $this->addOrEnqueueAnAddress('bcc', $address, $name); } /** * Add a "Reply-To" address. * @param string $address The email address to reply to * @param string $name * @return boolean true on success, false if address already used or invalid in some way */ public function addReplyTo($address, $name = '') { return $this->addOrEnqueueAnAddress('Reply-To', $address, $name); } /** * Add an address to one of the recipient arrays or to the ReplyTo array. Because PHPMailer * can't validate addresses with an IDN without knowing the PHPMailer::$CharSet (that can still * be modified after calling this function), addition of such addresses is delayed until send(). * Addresses that have been added already return false, but do not throw exceptions. * @param string $kind One of 'to', 'cc', 'bcc', or 'ReplyTo' * @param string $address The email address to send, resp. to reply to * @param string $name * @throws phpmailerException * @return boolean true on success, false if address already used or invalid in some way * @access protected */ protected function addOrEnqueueAnAddress($kind, $address, $name) { $address = trim($address); $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim if (($pos = strrpos($address, '@')) === false) { // At-sign is misssing. $error_message = $this->lang('invalid_address') . " (addAnAddress $kind): $address"; $this->setError($error_message); $this->edebug($error_message); if ($this->exceptions) { throw new phpmailerException($error_message); } return false; } $params = array($kind, $address, $name); // Enqueue addresses with IDN until we know the PHPMailer::$CharSet. if ($this->has8bitChars(substr($address, ++$pos)) and $this->idnSupported()) { if ($kind != 'Reply-To') { if (!array_key_exists($address, $this->RecipientsQueue)) { $this->RecipientsQueue[$address] = $params; return true; } } else { if (!array_key_exists($address, $this->ReplyToQueue)) { $this->ReplyToQueue[$address] = $params; return true; } } return false; } // Immediately add standard addresses without IDN. return call_user_func_array(array($this, 'addAnAddress'), $params); } /** * Add an address to one of the recipient arrays or to the ReplyTo array. * Addresses that have been added already return false, but do not throw exceptions. * @param string $kind One of 'to', 'cc', 'bcc', or 'ReplyTo' * @param string $address The email address to send, resp. to reply to * @param string $name * @throws phpmailerException * @return boolean true on success, false if address already used or invalid in some way * @access protected */ protected function addAnAddress($kind, $address, $name = '') { if (!in_array($kind, array('to', 'cc', 'bcc', 'Reply-To'))) { $error_message = $this->lang('Invalid recipient kind: ') . $kind; $this->setError($error_message); $this->edebug($error_message); if ($this->exceptions) { throw new phpmailerException($error_message); } return false; } if (!$this->validateAddress($address)) { $error_message = $this->lang('invalid_address') . " (addAnAddress $kind): $address"; $this->setError($error_message); $this->edebug($error_message); if ($this->exceptions) { throw new phpmailerException($error_message); } return false; } if ($kind != 'Reply-To') { if (!array_key_exists(strtolower($address), $this->all_recipients)) { array_push($this->$kind, array($address, $name)); $this->all_recipients[strtolower($address)] = true; return true; } } else { if (!array_key_exists(strtolower($address), $this->ReplyTo)) { $this->ReplyTo[strtolower($address)] = array($address, $name); return true; } } return false; } /** * Parse and validate a string containing one or more RFC822-style comma-separated email addresses * of the form "display name <address>" into an array of name/address pairs. * Uses the imap_rfc822_parse_adrlist function if the IMAP extension is available. * Note that quotes in the name part are removed. * @param string $addrstr The address list string * @param bool $useimap Whether to use the IMAP extension to parse the list * @return array * @link http://www.andrew.cmu.edu/user/agreen1/testing/mrbs/web/Mail/RFC822.php A more careful implementation */ public function parseAddresses($addrstr, $useimap = true) { $addresses = array(); if ($useimap and function_exists('imap_rfc822_parse_adrlist')) { //Use this built-in parser if it's available $list = imap_rfc822_parse_adrlist($addrstr, ''); foreach ($list as $address) { if ($address->host != '.SYNTAX-ERROR.') { if ($this->validateAddress($address->mailbox . '@' . $address->host)) { $addresses[] = array( 'name' => (property_exists($address, 'personal') ? $address->personal : ''), 'address' => $address->mailbox . '@' . $address->host ); } } } } else { //Use this simpler parser $list = explode(',', $addrstr); foreach ($list as $address) { $address = trim($address); //Is there a separate name part? if (strpos($address, '<') === false) { //No separate name, just use the whole thing if ($this->validateAddress($address)) { $addresses[] = array( 'name' => '', 'address' => $address ); } } else { list($name, $email) = explode('<', $address); $email = trim(str_replace('>', '', $email)); if ($this->validateAddress($email)) { $addresses[] = array( 'name' => trim(str_replace(array('"', "'"), '', $name)), 'address' => $email ); } } } } return $addresses; } /** * Set the From and FromName properties. * @param string $address * @param string $name * @param boolean $auto Whether to also set the Sender address, defaults to true * @throws phpmailerException * @return boolean */ public function setFrom($address, $name = '', $auto = true) { $address = trim($address); $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim // Don't validate now addresses with IDN. Will be done in send(). if (($pos = strrpos($address, '@')) === false or (!$this->has8bitChars(substr($address, ++$pos)) or !$this->idnSupported()) and !$this->validateAddress($address)) { $error_message = $this->lang('invalid_address') . " (setFrom) $address"; $this->setError($error_message); $this->edebug($error_message); if ($this->exceptions) { throw new phpmailerException($error_message); } return false; } $this->From = $address; $this->FromName = $name; if ($auto) { if (empty($this->Sender)) { $this->Sender = $address; } } return true; } /** * Return the Message-ID header of the last email. * Technically this is the value from the last time the headers were created, * but it's also the message ID of the last sent message except in * pathological cases. * @return string */ public function getLastMessageID() { return $this->lastMessageID; } /** * Check that a string looks like an email address. * @param string $address The email address to check * @param string|callable $patternselect A selector for the validation pattern to use : * * `auto` Pick best pattern automatically; * * `pcre8` Use the squiloople.com pattern, requires PCRE > 8.0, PHP >= 5.3.2, 5.2.14; * * `pcre` Use old PCRE implementation; * * `php` Use PHP built-in FILTER_VALIDATE_EMAIL; * * `html5` Use the pattern given by the HTML5 spec for 'email' type form input elements. * * `noregex` Don't use a regex: super fast, really dumb. * Alternatively you may pass in a callable to inject your own validator, for example: * PHPMailer::validateAddress('user@example.com', function($address) { * return (strpos($address, '@') !== false); * }); * You can also set the PHPMailer::$validator static to a callable, allowing built-in methods to use your validator. * @return boolean * @static * @access public */ public static function validateAddress($address, $patternselect = null) { if (is_null($patternselect)) { $patternselect = self::$validator; } //Don't allow strings as callables, see CVE-2021-3603 if (is_callable($patternselect) && !is_string($patternselect)) { return call_user_func($patternselect, $address); } //Reject line breaks in addresses; it's valid RFC5322, but not RFC5321 if (strpos($address, "\n") !== false or strpos($address, "\r") !== false) { return false; } if (!$patternselect or $patternselect == 'auto') { //Check this constant first so it works when extension_loaded() is disabled by safe mode //Constant was added in PHP 5.2.4 if (defined('PCRE_VERSION')) { //This pattern can get stuck in a recursive loop in PCRE <= 8.0.2 if (version_compare(PCRE_VERSION, '8.0.3') >= 0) { $patternselect = 'pcre8'; } else { $patternselect = 'pcre'; } } elseif (function_exists('extension_loaded') and extension_loaded('pcre')) { //Fall back to older PCRE $patternselect = 'pcre'; } else { //Filter_var appeared in PHP 5.2.0 and does not require the PCRE extension if (version_compare(PHP_VERSION, '5.2.0') >= 0) { $patternselect = 'php'; } else { $patternselect = 'noregex'; } } } switch ($patternselect) { case 'pcre8': /** * Uses the same RFC5322 regex on which FILTER_VALIDATE_EMAIL is based, but allows dotless domains. * @link http://squiloople.com/2009/12/20/email-address-validation/ * @copyright 2009-2010 Michael Rushton * Feel free to use and redistribute this code. But please keep this copyright notice. */ return (boolean)preg_match( '/^(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){255,})(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){65,}@)' . '((?>(?>(?>((?>(?>(?>\x0D\x0A)?[\t ])+|(?>[\t ]*\x0D\x0A)?[\t ]+)?)(\((?>(?2)' . '(?>[\x01-\x08\x0B\x0C\x0E-\'*-\[\]-\x7F]|\\\[\x00-\x7F]|(?3)))*(?2)\)))+(?2))|(?2))?)' . '([!#-\'*+\/-9=?^-~-]+|"(?>(?2)(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\x7F]))*' . '(?2)")(?>(?1)\.(?1)(?4))*(?1)@(?!(?1)[a-z0-9-]{64,})(?1)(?>([a-z0-9](?>[a-z0-9-]*[a-z0-9])?)' . '(?>(?1)\.(?!(?1)[a-z0-9-]{64,})(?1)(?5)){0,126}|\[(?:(?>IPv6:(?>([a-f0-9]{1,4})(?>:(?6)){7}' . '|(?!(?:.*[a-f0-9][:\]]){8,})((?6)(?>:(?6)){0,6})?::(?7)?))|(?>(?>IPv6:(?>(?6)(?>:(?6)){5}:' . '|(?!(?:.*[a-f0-9]:){6,})(?8)?::(?>((?6)(?>:(?6)){0,4}):)?))?(25[0-5]|2[0-4][0-9]|1[0-9]{2}' . '|[1-9]?[0-9])(?>\.(?9)){3}))\])(?1)$/isD', $address ); case 'pcre': //An older regex that doesn't need a recent PCRE return (boolean)preg_match( '/^(?!(?>"?(?>\\\[ -~]|[^"])"?){255,})(?!(?>"?(?>\\\[ -~]|[^"])"?){65,}@)(?>' . '[!#-\'*+\/-9=?^-~-]+|"(?>(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\xFF]))*")' . '(?>\.(?>[!#-\'*+\/-9=?^-~-]+|"(?>(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\xFF]))*"))*' . '@(?>(?![a-z0-9-]{64,})(?>[a-z0-9](?>[a-z0-9-]*[a-z0-9])?)(?>\.(?![a-z0-9-]{64,})' . '(?>[a-z0-9](?>[a-z0-9-]*[a-z0-9])?)){0,126}|\[(?:(?>IPv6:(?>(?>[a-f0-9]{1,4})(?>:' . '[a-f0-9]{1,4}){7}|(?!(?:.*[a-f0-9][:\]]){8,})(?>[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,6})?' . '::(?>[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,6})?))|(?>(?>IPv6:(?>[a-f0-9]{1,4}(?>:' . '[a-f0-9]{1,4}){5}:|(?!(?:.*[a-f0-9]:){6,})(?>[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,4})?' . '::(?>(?:[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,4}):)?))?(?>25[0-5]|2[0-4][0-9]|1[0-9]{2}' . '|[1-9]?[0-9])(?>\.(?>25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}))\])$/isD', $address ); case 'html5': /** * This is the pattern used in the HTML5 spec for validation of 'email' type form input elements. * @link http://www.whatwg.org/specs/web-apps/current-work/#e-mail-state-(type=email) */ return (boolean)preg_match( '/^[a-zA-Z0-9.!#$%&\'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}' . '[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/sD', $address ); case 'noregex': //No PCRE! Do something _very_ approximate! //Check the address is 3 chars or longer and contains an @ that's not the first or last char return (strlen($address) >= 3 and strpos($address, '@') >= 1 and strpos($address, '@') != strlen($address) - 1); case 'php': default: return (boolean)filter_var($address, FILTER_VALIDATE_EMAIL); } } /** * Tells whether IDNs (Internationalized Domain Names) are supported or not. This requires the * "intl" and "mbstring" PHP extensions. * @return bool "true" if required functions for IDN support are present */ public function idnSupported() { // @TODO: Write our own "idn_to_ascii" function for PHP <= 5.2. return function_exists('idn_to_ascii') and function_exists('mb_convert_encoding'); } /** * Converts IDN in given email address to its ASCII form, also known as punycode, if possible. * Important: Address must be passed in same encoding as currently set in PHPMailer::$CharSet. * This function silently returns unmodified address if: * - No conversion is necessary (i.e. domain name is not an IDN, or is already in ASCII form) * - Conversion to punycode is impossible (e.g. required PHP functions are not available) * or fails for any reason (e.g. domain has characters not allowed in an IDN) * @see PHPMailer::$CharSet * @param string $address The email address to convert * @return string The encoded address in ASCII form */ public function punyencodeAddress($address) { // Verify we have required functions, CharSet, and at-sign. if ($this->idnSupported() and !empty($this->CharSet) and ($pos = strrpos($address, '@')) !== false) { $domain = substr($address, ++$pos); // Verify CharSet string is a valid one, and domain properly encoded in this CharSet. if ($this->has8bitChars($domain) and @mb_check_encoding($domain, $this->CharSet)) { $domain = mb_convert_encoding($domain, 'UTF-8', $this->CharSet); if (($punycode = defined('INTL_IDNA_VARIANT_UTS46') ? idn_to_ascii($domain, 0, INTL_IDNA_VARIANT_UTS46) : idn_to_ascii($domain)) !== false) { return substr($address, 0, $pos) . $punycode; } } } return $address; } /** * Create a message and send it. * Uses the sending method specified by $Mailer. * @throws phpmailerException * @return boolean false on error - See the ErrorInfo property for details of the error. */ public function send() { try { if (!$this->preSend()) { return false; } return $this->postSend(); } catch (phpmailerException $exc) { $this->mailHeader = ''; $this->setError($exc->getMessage()); if ($this->exceptions) { throw $exc; } return false; } } /** * Prepare a message for sending. * @throws phpmailerException * @return boolean */ public function preSend() { try { $this->error_count = 0; // Reset errors $this->mailHeader = ''; // Dequeue recipient and Reply-To addresses with IDN foreach (array_merge($this->RecipientsQueue, $this->ReplyToQueue) as $params) { $params[1] = $this->punyencodeAddress($params[1]); call_user_func_array(array($this, 'addAnAddress'), $params); } if ((count($this->to) + count($this->cc) + count($this->bcc)) < 1) { throw new phpmailerException($this->lang('provide_address'), self::STOP_CRITICAL); } // Validate From, Sender, and ConfirmReadingTo addresses foreach (array('From', 'Sender', 'ConfirmReadingTo') as $address_kind) { $this->$address_kind = trim($this->$address_kind); if (empty($this->$address_kind)) { continue; } $this->$address_kind = $this->punyencodeAddress($this->$address_kind); if (!$this->validateAddress($this->$address_kind)) { $error_message = $this->lang('invalid_address') . ' (punyEncode) ' . $this->$address_kind; $this->setError($error_message); $this->edebug($error_message); if ($this->exceptions) { throw new phpmailerException($error_message); } return false; } } // Set whether the message is multipart/alternative if ($this->alternativeExists()) { $this->ContentType = 'multipart/alternative'; } $this->setMessageType(); // Refuse to send an empty message unless we are specifically allowing it if (!$this->AllowEmpty and empty($this->Body)) { throw new phpmailerException($this->lang('empty_message'), self::STOP_CRITICAL); } // Create body before headers in case body makes changes to headers (e.g. altering transfer encoding) $this->MIMEHeader = ''; $this->MIMEBody = $this->createBody(); // createBody may have added some headers, so retain them $tempheaders = $this->MIMEHeader; $this->MIMEHeader = $this->createHeader(); $this->MIMEHeader .= $tempheaders; // To capture the complete message when using mail(), create // an extra header list which createHeader() doesn't fold in if ($this->Mailer == 'mail') { if (count($this->to) > 0) { $this->mailHeader .= $this->addrAppend('To', $this->to); } else { $this->mailHeader .= $this->headerLine('To', 'undisclosed-recipients:;'); } $this->mailHeader .= $this->headerLine( 'Subject', $this->encodeHeader($this->secureHeader(trim($this->Subject))) ); } // Sign with DKIM if enabled if (!empty($this->DKIM_domain) and !empty($this->DKIM_selector) and (!empty($this->DKIM_private_string) or (!empty($this->DKIM_private) and self::isPermittedPath($this->DKIM_private) and file_exists($this->DKIM_private) ) ) ) { $header_dkim = $this->DKIM_Add( $this->MIMEHeader . $this->mailHeader, $this->encodeHeader($this->secureHeader($this->Subject)), $this->MIMEBody ); $this->MIMEHeader = rtrim($this->MIMEHeader, "\r\n ") . self::CRLF . str_replace("\r\n", "\n", $header_dkim) . self::CRLF; } return true; } catch (phpmailerException $exc) { $this->setError($exc->getMessage()); if ($this->exceptions) { throw $exc; } return false; } } /** * Actually send a message. * Send the email via the selected mechanism * @throws phpmailerException * @return boolean */ public function postSend() { try { // Choose the mailer and send through it switch ($this->Mailer) { case 'sendmail': case 'qmail': return $this->sendmailSend($this->MIMEHeader, $this->MIMEBody); case 'smtp': return $this->smtpSend($this->MIMEHeader, $this->MIMEBody); case 'mail': return $this->mailSend($this->MIMEHeader, $this->MIMEBody); default: $sendMethod = $this->Mailer.'Send'; if (method_exists($this, $sendMethod)) { return $this->$sendMethod($this->MIMEHeader, $this->MIMEBody); } return $this->mailSend($this->MIMEHeader, $this->MIMEBody); } } catch (phpmailerException $exc) { $this->setError($exc->getMessage()); $this->edebug($exc->getMessage()); if ($this->exceptions) { throw $exc; } } return false; } /** * Send mail using the $Sendmail program. * @param string $header The message headers * @param string $body The message body * @see PHPMailer::$Sendmail * @throws phpmailerException * @access protected * @return boolean */ protected function sendmailSend($header, $body) { // CVE-2016-10033, CVE-2016-10045: Don't pass -f if characters will be escaped. if (!empty($this->Sender) and self::isShellSafe($this->Sender)) { if ($this->Mailer == 'qmail') { $sendmailFmt = '%s -f%s'; } else { $sendmailFmt = '%s -oi -f%s -t'; } } else { if ($this->Mailer == 'qmail') { $sendmailFmt = '%s'; } else { $sendmailFmt = '%s -oi -t'; } } // TODO: If possible, this should be changed to escapeshellarg. Needs thorough testing. $sendmail = sprintf($sendmailFmt, escapeshellcmd($this->Sendmail), $this->Sender); if ($this->SingleTo) { foreach ($this->SingleToArray as $toAddr) { if (!@$mail = popen($sendmail, 'w')) { throw new phpmailerException($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL); } fputs($mail, 'To: ' . $toAddr . "\n"); fputs($mail, $header); fputs($mail, $body); $result = pclose($mail); $this->doCallback( ($result == 0), array($toAddr), $this->cc, $this->bcc, $this->Subject, $body, $this->From ); if ($result != 0) { throw new phpmailerException($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL); } } } else { if (!@$mail = popen($sendmail, 'w')) { throw new phpmailerException($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL); } fputs($mail, $header); fputs($mail, $body); $result = pclose($mail); $this->doCallback( ($result == 0), $this->to, $this->cc, $this->bcc, $this->Subject, $body, $this->From ); if ($result != 0) { throw new phpmailerException($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL); } } return true; } /** * Fix CVE-2016-10033 and CVE-2016-10045 by disallowing potentially unsafe shell characters. * * Note that escapeshellarg and escapeshellcmd are inadequate for our purposes, especially on Windows. * @param string $string The string to be validated * @see https://github.com/PHPMailer/PHPMailer/issues/924 CVE-2016-10045 bug report * @access protected * @return boolean */ protected static function isShellSafe($string) { // Future-proof if (escapeshellcmd($string) !== $string or !in_array(escapeshellarg($string), array("'$string'", "\"$string\"")) ) { return false; } $length = strlen($string); for ($i = 0; $i < $length; $i++) { $c = $string[$i]; // All other characters have a special meaning in at least one common shell, including = and +. // Full stop (.) has a special meaning in cmd.exe, but its impact should be negligible here. // Note that this does permit non-Latin alphanumeric characters based on the current locale. if (!ctype_alnum($c) && strpos('@_-.', $c) === false) { return false; } } return true; } /** * Check whether a file path is of a permitted type. * Used to reject URLs and phar files from functions that access local file paths, * such as addAttachment. * @param string $path A relative or absolute path to a file. * @return bool */ protected static function isPermittedPath($path) { return !preg_match('#^[a-z]+://#i', $path); } /** * Send mail using the PHP mail() function. * @param string $header The message headers * @param string $body The message body * @link http://www.php.net/manual/en/book.mail.php * @throws phpmailerException * @access protected * @return boolean */ protected function mailSend($header, $body) { $toArr = array(); foreach ($this->to as $toaddr) { $toArr[] = $this->addrFormat($toaddr); } $to = implode(', ', $toArr); $params = null; //This sets the SMTP envelope sender which gets turned into a return-path header by the receiver if (!empty($this->Sender) and $this->validateAddress($this->Sender)) { // CVE-2016-10033, CVE-2016-10045: Don't pass -f if characters will be escaped. if (self::isShellSafe($this->Sender)) { $params = sprintf('-f%s', $this->Sender); } } if (!empty($this->Sender) and !ini_get('safe_mode') and $this->validateAddress($this->Sender)) { $old_from = ini_get('sendmail_from'); ini_set('sendmail_from', $this->Sender); } $result = false; if ($this->SingleTo and count($toArr) > 1) { foreach ($toArr as $toAddr) { $result = $this->mailPassthru($toAddr, $this->Subject, $body, $header, $params); $this->doCallback($result, array($toAddr), $this->cc, $this->bcc, $this->Subject, $body, $this->From); } } else { $result = $this->mailPassthru($to, $this->Subject, $body, $header, $params); $this->doCallback($result, $this->to, $this->cc, $this->bcc, $this->Subject, $body, $this->From); } if (isset($old_from)) { ini_set('sendmail_from', $old_from); } if (!$result) { throw new phpmailerException($this->lang('instantiate'), self::STOP_CRITICAL); } return true; } /** * Get an instance to use for SMTP operations. * Override this function to load your own SMTP implementation * @return SMTP */ public function getSMTPInstance() { if (!is_object($this->smtp)) { $this->smtp = new SMTP; } return $this->smtp; } /** * Send mail via SMTP. * Returns false if there is a bad MAIL FROM, RCPT, or DATA input. * Uses the PHPMailerSMTP class by default. * @see PHPMailer::getSMTPInstance() to use a different class. * @param string $header The message headers * @param string $body The message body * @throws phpmailerException * @uses SMTP * @access protected * @return boolean */ protected function smtpSend($header, $body) { $bad_rcpt = array(); if (!$this->smtpConnect($this->SMTPOptions)) { throw new phpmailerException($this->lang('smtp_connect_failed'), self::STOP_CRITICAL); } if (!empty($this->Sender) and $this->validateAddress($this->Sender)) { $smtp_from = $this->Sender; } else { $smtp_from = $this->From; } if (!$this->smtp->mail($smtp_from)) { $this->setError($this->lang('from_failed') . $smtp_from . ' : ' . implode(',', $this->smtp->getError())); throw new phpmailerException($this->ErrorInfo, self::STOP_CRITICAL); } // Attempt to send to all recipients foreach (array($this->to, $this->cc, $this->bcc) as $togroup) { foreach ($togroup as $to) { if (!$this->smtp->recipient($to[0])) { $error = $this->smtp->getError(); $bad_rcpt[] = array('to' => $to[0], 'error' => $error['detail']); $isSent = false; } else { $isSent = true; } $this->doCallback($isSent, array($to[0]), array(), array(), $this->Subject, $body, $this->From); } } // Only send the DATA command if we have viable recipients if ((count($this->all_recipients) > count($bad_rcpt)) and !$this->smtp->data($header . $body)) { throw new phpmailerException($this->lang('data_not_accepted'), self::STOP_CRITICAL); } if ($this->SMTPKeepAlive) { $this->smtp->reset(); } else { $this->smtp->quit(); $this->smtp->close(); } //Create error message for any bad addresses if (count($bad_rcpt) > 0) { $errstr = ''; foreach ($bad_rcpt as $bad) { $errstr .= $bad['to'] . ': ' . $bad['error']; } throw new phpmailerException( $this->lang('recipients_failed') . $errstr, self::STOP_CONTINUE ); } return true; } /** * Initiate a connection to an SMTP server. * Returns false if the operation failed. * @param array $options An array of options compatible with stream_context_create() * @uses SMTP * @access public * @throws phpmailerException * @return boolean */ public function smtpConnect($options = null) { if (is_null($this->smtp)) { $this->smtp = $this->getSMTPInstance(); } //If no options are provided, use whatever is set in the instance if (is_null($options)) { $options = $this->SMTPOptions; } // Already connected? if ($this->smtp->connected()) { return true; } $this->smtp->setTimeout($this->Timeout); $this->smtp->setDebugLevel($this->SMTPDebug); $this->smtp->setDebugOutput($this->Debugoutput); $this->smtp->setVerp($this->do_verp); $hosts = explode(';', $this->Host); $lastexception = null; foreach ($hosts as $hostentry) { $hostinfo = array(); if (!preg_match( '/^((ssl|tls):\/\/)*([a-zA-Z0-9\.-]*|\[[a-fA-F0-9:]+\]):?([0-9]*)$/', trim($hostentry), $hostinfo )) { // Not a valid host entry $this->edebug('Ignoring invalid host: ' . $hostentry); continue; } // $hostinfo[2]: optional ssl or tls prefix // $hostinfo[3]: the hostname // $hostinfo[4]: optional port number // The host string prefix can temporarily override the current setting for SMTPSecure // If it's not specified, the default value is used $prefix = ''; $secure = $this->SMTPSecure; $tls = ($this->SMTPSecure == 'tls'); if ('ssl' == $hostinfo[2] or ('' == $hostinfo[2] and 'ssl' == $this->SMTPSecure)) { $prefix = 'ssl://'; $tls = false; // Can't have SSL and TLS at the same time $secure = 'ssl'; } elseif ($hostinfo[2] == 'tls') { $tls = true; // tls doesn't use a prefix $secure = 'tls'; } //Do we need the OpenSSL extension? $sslext = defined('OPENSSL_ALGO_SHA1'); if ('tls' === $secure or 'ssl' === $secure) { //Check for an OpenSSL constant rather than using extension_loaded, which is sometimes disabled if (!$sslext) { throw new phpmailerException($this->lang('extension_missing').'openssl', self::STOP_CRITICAL); } } $host = $hostinfo[3]; $port = $this->Port; $tport = (integer)$hostinfo[4]; if ($tport > 0 and $tport < 65536) { $port = $tport; } if ($this->smtp->connect($prefix . $host, $port, $this->Timeout, $options)) { try { if ($this->Helo) { $hello = $this->Helo; } else { $hello = $this->serverHostname(); } $this->smtp->hello($hello); //Automatically enable TLS encryption if: // * it's not disabled // * we have openssl extension // * we are not already using SSL // * the server offers STARTTLS if ($this->SMTPAutoTLS and $sslext and $secure != 'ssl' and $this->smtp->getServerExt('STARTTLS')) { $tls = true; } if ($tls) { if (!$this->smtp->startTLS()) { throw new phpmailerException($this->lang('connect_host')); } // We must resend EHLO after TLS negotiation $this->smtp->hello($hello); } if ($this->SMTPAuth) { if (!$this->smtp->authenticate( $this->Username, $this->Password, $this->AuthType, $this->Realm, $this->Workstation ) ) { throw new phpmailerException($this->lang('authenticate')); } } return true; } catch (phpmailerException $exc) { $lastexception = $exc; $this->edebug($exc->getMessage()); // We must have connected, but then failed TLS or Auth, so close connection nicely $this->smtp->quit(); } } } // If we get here, all connection attempts have failed, so close connection hard $this->smtp->close(); // As we've caught all exceptions, just report whatever the last one was if ($this->exceptions and !is_null($lastexception)) { throw $lastexception; } return false; } /** * Close the active SMTP session if one exists. * @return void */ public function smtpClose() { if (is_a($this->smtp, 'SMTP')) { if ($this->smtp->connected()) { $this->smtp->quit(); $this->smtp->close(); } } } /** * Set the language for error messages. * Returns false if it cannot load the language file. * The default language is English. * @param string $langcode ISO 639-1 2-character language code (e.g. French is "fr") * @param string $lang_path Path to the language file directory, with trailing separator (slash) * @return boolean * @access public */ public function setLanguage($langcode = 'en', $lang_path = '') { // Backwards compatibility for renamed language codes $renamed_langcodes = array( 'br' => 'pt_br', 'cz' => 'cs', 'dk' => 'da', 'no' => 'nb', 'se' => 'sv', 'sr' => 'rs' ); if (isset($renamed_langcodes[$langcode])) { $langcode = $renamed_langcodes[$langcode]; } // Define full set of translatable strings in English $PHPMAILER_LANG = array( 'authenticate' => 'SMTP Error: Could not authenticate.', 'connect_host' => 'SMTP Error: Could not connect to SMTP host.', 'data_not_accepted' => 'SMTP Error: data not accepted.', 'empty_message' => 'Message body empty', 'encoding' => 'Unknown encoding: ', 'execute' => 'Could not execute: ', 'file_access' => 'Could not access file: ', 'file_open' => 'File Error: Could not open file: ', 'from_failed' => 'The following From address failed: ', 'instantiate' => 'Could not instantiate mail function.', 'invalid_address' => 'Invalid address: ', 'mailer_not_supported' => ' mailer is not supported.', 'provide_address' => 'You must provide at least one recipient email address.', 'recipients_failed' => 'SMTP Error: The following recipients failed: ', 'signing' => 'Signing Error: ', 'smtp_connect_failed' => 'SMTP connect() failed.', 'smtp_error' => 'SMTP server error: ', 'variable_set' => 'Cannot set or reset variable: ', 'extension_missing' => 'Extension missing: ' ); if (empty($lang_path)) { // Calculate an absolute path so it can work if CWD is not here $lang_path = dirname(__FILE__). DIRECTORY_SEPARATOR . 'language'. DIRECTORY_SEPARATOR; } //Validate $langcode if (!preg_match('/^[a-z]{2}(?:_[a-zA-Z]{2})?$/', $langcode)) { $langcode = 'en'; } $foundlang = true; $lang_file = $lang_path . 'phpmailer.lang-' . $langcode . '.php'; // There is no English translation file if ($langcode != 'en') { // Make sure language file path is readable if (!self::isPermittedPath($lang_file) or !is_readable($lang_file)) { $foundlang = false; } else { //$foundlang = include $lang_file; $lines = file($lang_file); foreach ($lines as $line) { //Translation file lines look like this: //$PHPMAILER_LANG['authenticate'] = 'SMTP-Fehler: Authentifizierung fehlgeschlagen.'; //These files are parsed as text and not PHP so as to avoid the possibility of code injection //See https://blog.stevenlevithan.com/archives/match-quoted-string $matches = array(); if ( preg_match( '/^\$PHPMAILER_LANG\[\'([a-z\d_]+)\'\]\s*=\s*(["\'])(.+)*?\2;/', $line, $matches ) && //Ignore unknown translation keys array_key_exists($matches[1], $PHPMAILER_LANG) ) { //Overwrite language-specific strings so we'll never have missing translation keys. $PHPMAILER_LANG[$matches[1]] = (string)$matches[3]; } } } } $this->language = $PHPMAILER_LANG; return (boolean)$foundlang; // Returns false if language not found } /** * Get the array of strings for the current language. * @return array */ public function getTranslations() { return $this->language; } /** * Create recipient headers. * @access public * @param string $type * @param array $addr An array of recipient, * where each recipient is a 2-element indexed array with element 0 containing an address * and element 1 containing a name, like: * array(array('joe@example.com', 'Joe User'), array('zoe@example.com', 'Zoe User')) * @return string */ public function addrAppend($type, $addr) { $addresses = array(); foreach ($addr as $address) { $addresses[] = $this->addrFormat($address); } return $type . ': ' . implode(', ', $addresses) . $this->LE; } /** * Format an address for use in a message header. * @access public * @param array $addr A 2-element indexed array, element 0 containing an address, element 1 containing a name * like array('joe@example.com', 'Joe User') * @return string */ public function addrFormat($addr) { if (empty($addr[1])) { // No name provided return $this->secureHeader($addr[0]); } else { return $this->encodeHeader($this->secureHeader($addr[1]), 'phrase') . ' <' . $this->secureHeader( $addr[0] ) . '>'; } } /** * Word-wrap message. * For use with mailers that do not automatically perform wrapping * and for quoted-printable encoded messages. * Original written by philippe. * @param string $message The message to wrap * @param integer $length The line length to wrap to * @param boolean $qp_mode Whether to run in Quoted-Printable mode * @access public * @return string */ public function wrapText($message, $length, $qp_mode = false) { if ($qp_mode) { $soft_break = sprintf(' =%s', $this->LE); } else { $soft_break = $this->LE; } // If utf-8 encoding is used, we will need to make sure we don't // split multibyte characters when we wrap $is_utf8 = (strtolower($this->CharSet) == 'utf-8'); $lelen = strlen($this->LE); $crlflen = strlen(self::CRLF); $message = $this->fixEOL($message); //Remove a trailing line break if (substr($message, -$lelen) == $this->LE) { $message = substr($message, 0, -$lelen); } //Split message into lines $lines = explode($this->LE, $message); //Message will be rebuilt in here $message = ''; foreach ($lines as $line) { $words = explode(' ', $line); $buf = ''; $firstword = true; foreach ($words as $word) { if ($qp_mode and (strlen($word) > $length)) { $space_left = $length - strlen($buf) - $crlflen; if (!$firstword) { if ($space_left > 20) { $len = $space_left; if ($is_utf8) { $len = $this->utf8CharBoundary($word, $len); } elseif (substr($word, $len - 1, 1) == '=') { $len--; } elseif (substr($word, $len - 2, 1) == '=') { $len -= 2; } $part = substr($word, 0, $len); $word = substr($word, $len); $buf .= ' ' . $part; $message .= $buf . sprintf('=%s', self::CRLF); } else { $message .= $buf . $soft_break; } $buf = ''; } while (strlen($word) > 0) { if ($length <= 0) { break; } $len = $length; if ($is_utf8) { $len = $this->utf8CharBoundary($word, $len); } elseif (substr($word, $len - 1, 1) == '=') { $len--; } elseif (substr($word, $len - 2, 1) == '=') { $len -= 2; } $part = substr($word, 0, $len); $word = substr($word, $len); if (strlen($word) > 0) { $message .= $part . sprintf('=%s', self::CRLF); } else { $buf = $part; } } } else { $buf_o = $buf; if (!$firstword) { $buf .= ' '; } $buf .= $word; if (strlen($buf) > $length and $buf_o != '') { $message .= $buf_o . $soft_break; $buf = $word; } } $firstword = false; } $message .= $buf . self::CRLF; } return $message; } /** * Find the last character boundary prior to $maxLength in a utf-8 * quoted-printable encoded string. * Original written by Colin Brown. * @access public * @param string $encodedText utf-8 QP text * @param integer $maxLength Find the last character boundary prior to this length * @return integer */ public function utf8CharBoundary($encodedText, $maxLength) { $foundSplitPos = false; $lookBack = 3; while (!$foundSplitPos) { $lastChunk = substr($encodedText, $maxLength - $lookBack, $lookBack); $encodedCharPos = strpos($lastChunk, '='); if (false !== $encodedCharPos) { // Found start of encoded character byte within $lookBack block. // Check the encoded byte value (the 2 chars after the '=') $hex = substr($encodedText, $maxLength - $lookBack + $encodedCharPos + 1, 2); $dec = hexdec($hex); if ($dec < 128) { // Single byte character. // If the encoded char was found at pos 0, it will fit // otherwise reduce maxLength to start of the encoded char if ($encodedCharPos > 0) { $maxLength = $maxLength - ($lookBack - $encodedCharPos); } $foundSplitPos = true; } elseif ($dec >= 192) { // First byte of a multi byte character // Reduce maxLength to split at start of character $maxLength = $maxLength - ($lookBack - $encodedCharPos); $foundSplitPos = true; } elseif ($dec < 192) { // Middle byte of a multi byte character, look further back $lookBack += 3; } } else { // No encoded character found $foundSplitPos = true; } } return $maxLength; } /** * Apply word wrapping to the message body. * Wraps the message body to the number of chars set in the WordWrap property. * You should only do this to plain-text bodies as wrapping HTML tags may break them. * This is called automatically by createBody(), so you don't need to call it yourself. * @access public * @return void */ public function setWordWrap() { if ($this->WordWrap < 1) { return; } switch ($this->message_type) { case 'alt': case 'alt_inline': case 'alt_attach': case 'alt_inline_attach': $this->AltBody = $this->wrapText($this->AltBody, $this->WordWrap); break; default: $this->Body = $this->wrapText($this->Body, $this->WordWrap); break; } } /** * Assemble message headers. * @access public * @return string The assembled headers */ public function createHeader() { $result = ''; $result .= $this->headerLine('Date', $this->MessageDate == '' ? self::rfcDate() : $this->MessageDate); // To be created automatically by mail() if ($this->SingleTo) { if ($this->Mailer != 'mail') { foreach ($this->to as $toaddr) { $this->SingleToArray[] = $this->addrFormat($toaddr); } } } else { if (count($this->to) > 0) { if ($this->Mailer != 'mail') { $result .= $this->addrAppend('To', $this->to); } } elseif (count($this->cc) == 0) { $result .= $this->headerLine('To', 'undisclosed-recipients:;'); } } $result .= $this->addrAppend('From', array(array(trim($this->From), $this->FromName))); // sendmail and mail() extract Cc from the header before sending if (count($this->cc) > 0) { $result .= $this->addrAppend('Cc', $this->cc); } // sendmail and mail() extract Bcc from the header before sending if (( $this->Mailer == 'sendmail' or $this->Mailer == 'qmail' or $this->Mailer == 'mail' ) and count($this->bcc) > 0 ) { $result .= $this->addrAppend('Bcc', $this->bcc); } if (count($this->ReplyTo) > 0) { $result .= $this->addrAppend('Reply-To', $this->ReplyTo); } // mail() sets the subject itself if ($this->Mailer != 'mail') { $result .= $this->headerLine('Subject', $this->encodeHeader($this->secureHeader($this->Subject))); } // Only allow a custom message ID if it conforms to RFC 5322 section 3.6.4 // https://tools.ietf.org/html/rfc5322#section-3.6.4 if ('' != $this->MessageID and preg_match('/^<.*@.*>$/', $this->MessageID)) { $this->lastMessageID = $this->MessageID; } else { $this->lastMessageID = sprintf('<%s@%s>', $this->uniqueid, $this->serverHostname()); } $result .= $this->headerLine('Message-ID', $this->lastMessageID); if (!is_null($this->Priority)) { $result .= $this->headerLine('X-Priority', $this->Priority); } if ($this->XMailer == '') { $result .= $this->headerLine( 'X-Mailer', 'PHPMailer ' . $this->Version . ' (https://github.com/PHPMailer/PHPMailer)' ); } else { $myXmailer = trim($this->XMailer); if ($myXmailer) { $result .= $this->headerLine('X-Mailer', $myXmailer); } } if ($this->ConfirmReadingTo != '') { $result .= $this->headerLine('Disposition-Notification-To', '<' . $this->ConfirmReadingTo . '>'); } // Add custom headers foreach ($this->CustomHeader as $header) { $result .= $this->headerLine( trim($header[0]), $this->encodeHeader(trim($header[1])) ); } if (!$this->sign_key_file) { $result .= $this->headerLine('MIME-Version', '1.0'); $result .= $this->getMailMIME(); } return $result; } /** * Get the message MIME type headers. * @access public * @return string */ public function getMailMIME() { $result = ''; $ismultipart = true; switch ($this->message_type) { case 'inline': $result .= $this->headerLine('Content-Type', 'multipart/related;'); $result .= $this->textLine("\tboundary=\"" . $this->boundary[1] . '"'); break; case 'attach': case 'inline_attach': case 'alt_attach': case 'alt_inline_attach': $result .= $this->headerLine('Content-Type', 'multipart/mixed;'); $result .= $this->textLine("\tboundary=\"" . $this->boundary[1] . '"'); break; case 'alt': case 'alt_inline': $result .= $this->headerLine('Content-Type', 'multipart/alternative;'); $result .= $this->textLine("\tboundary=\"" . $this->boundary[1] . '"'); break; default: // Catches case 'plain': and case '': $result .= $this->textLine('Content-Type: ' . $this->ContentType . '; charset=' . $this->CharSet); $ismultipart = false; break; } // RFC1341 part 5 says 7bit is assumed if not specified if ($this->Encoding != '7bit') { // RFC 2045 section 6.4 says multipart MIME parts may only use 7bit, 8bit or binary CTE if ($ismultipart) { if ($this->Encoding == '8bit') { $result .= $this->headerLine('Content-Transfer-Encoding', '8bit'); } // The only remaining alternatives are quoted-printable and base64, which are both 7bit compatible } else { $result .= $this->headerLine('Content-Transfer-Encoding', $this->Encoding); } } if ($this->Mailer != 'mail') { $result .= $this->LE; } return $result; } /** * Returns the whole MIME message. * Includes complete headers and body. * Only valid post preSend(). * @see PHPMailer::preSend() * @access public * @return string */ public function getSentMIMEMessage() { return rtrim($this->MIMEHeader . $this->mailHeader, "\n\r") . self::CRLF . self::CRLF . $this->MIMEBody; } /** * Create unique ID * @return string */ protected function generateId() { return md5(uniqid(time())); } /** * Assemble the message body. * Returns an empty string on failure. * @access public * @throws phpmailerException * @return string The assembled message body */ public function createBody() { $body = ''; //Create unique IDs and preset boundaries $this->uniqueid = $this->generateId(); $this->boundary[1] = 'b1_' . $this->uniqueid; $this->boundary[2] = 'b2_' . $this->uniqueid; $this->boundary[3] = 'b3_' . $this->uniqueid; if ($this->sign_key_file) { $body .= $this->getMailMIME() . $this->LE; } $this->setWordWrap(); $bodyEncoding = $this->Encoding; $bodyCharSet = $this->CharSet; //Can we do a 7-bit downgrade? if ($bodyEncoding == '8bit' and !$this->has8bitChars($this->Body)) { $bodyEncoding = '7bit'; //All ISO 8859, Windows codepage and UTF-8 charsets are ascii compatible up to 7-bit $bodyCharSet = 'us-ascii'; } //If lines are too long, and we're not already using an encoding that will shorten them, //change to quoted-printable transfer encoding for the body part only if ('base64' != $this->Encoding and self::hasLineLongerThanMax($this->Body)) { $bodyEncoding = 'quoted-printable'; } $altBodyEncoding = $this->Encoding; $altBodyCharSet = $this->CharSet; //Can we do a 7-bit downgrade? if ($altBodyEncoding == '8bit' and !$this->has8bitChars($this->AltBody)) { $altBodyEncoding = '7bit'; //All ISO 8859, Windows codepage and UTF-8 charsets are ascii compatible up to 7-bit $altBodyCharSet = 'us-ascii'; } //If lines are too long, and we're not already using an encoding that will shorten them, //change to quoted-printable transfer encoding for the alt body part only if ('base64' != $altBodyEncoding and self::hasLineLongerThanMax($this->AltBody)) { $altBodyEncoding = 'quoted-printable'; } //Use this as a preamble in all multipart message types $mimepre = "This is a multi-part message in MIME format." . $this->LE . $this->LE; switch ($this->message_type) { case 'inline': $body .= $mimepre; $body .= $this->getBoundary($this->boundary[1], $bodyCharSet, '', $bodyEncoding); $body .= $this->encodeString($this->Body, $bodyEncoding); $body .= $this->LE . $this->LE; $body .= $this->attachAll('inline', $this->boundary[1]); break; case 'attach': $body .= $mimepre; $body .= $this->getBoundary($this->boundary[1], $bodyCharSet, '', $bodyEncoding); $body .= $this->encodeString($this->Body, $bodyEncoding); $body .= $this->LE . $this->LE; $body .= $this->attachAll('attachment', $this->boundary[1]); break; case 'inline_attach': $body .= $mimepre; $body .= $this->textLine('--' . $this->boundary[1]); $body .= $this->headerLine('Content-Type', 'multipart/related;'); $body .= $this->textLine("\tboundary=\"" . $this->boundary[2] . '"'); $body .= $this->LE; $body .= $this->getBoundary($this->boundary[2], $bodyCharSet, '', $bodyEncoding); $body .= $this->encodeString($this->Body, $bodyEncoding); $body .= $this->LE . $this->LE; $body .= $this->attachAll('inline', $this->boundary[2]); $body .= $this->LE; $body .= $this->attachAll('attachment', $this->boundary[1]); break; case 'alt': $body .= $mimepre; $body .= $this->getBoundary($this->boundary[1], $altBodyCharSet, 'text/plain', $altBodyEncoding); $body .= $this->encodeString($this->AltBody, $altBodyEncoding); $body .= $this->LE . $this->LE; $body .= $this->getBoundary($this->boundary[1], $bodyCharSet, 'text/html', $bodyEncoding); $body .= $this->encodeString($this->Body, $bodyEncoding); $body .= $this->LE . $this->LE; if (!empty($this->Ical)) { $body .= $this->getBoundary($this->boundary[1], '', 'text/calendar; method=REQUEST', ''); $body .= $this->encodeString($this->Ical, $this->Encoding); $body .= $this->LE . $this->LE; } $body .= $this->endBoundary($this->boundary[1]); break; case 'alt_inline': $body .= $mimepre; $body .= $this->getBoundary($this->boundary[1], $altBodyCharSet, 'text/plain', $altBodyEncoding); $body .= $this->encodeString($this->AltBody, $altBodyEncoding); $body .= $this->LE . $this->LE; $body .= $this->textLine('--' . $this->boundary[1]); $body .= $this->headerLine('Content-Type', 'multipart/related;'); $body .= $this->textLine("\tboundary=\"" . $this->boundary[2] . '"'); $body .= $this->LE; $body .= $this->getBoundary($this->boundary[2], $bodyCharSet, 'text/html', $bodyEncoding); $body .= $this->encodeString($this->Body, $bodyEncoding); $body .= $this->LE . $this->LE; $body .= $this->attachAll('inline', $this->boundary[2]); $body .= $this->LE; $body .= $this->endBoundary($this->boundary[1]); break; case 'alt_attach': $body .= $mimepre; $body .= $this->textLine('--' . $this->boundary[1]); $body .= $this->headerLine('Content-Type', 'multipart/alternative;'); $body .= $this->textLine("\tboundary=\"" . $this->boundary[2] . '"'); $body .= $this->LE; $body .= $this->getBoundary($this->boundary[2], $altBodyCharSet, 'text/plain', $altBodyEncoding); $body .= $this->encodeString($this->AltBody, $altBodyEncoding); $body .= $this->LE . $this->LE; $body .= $this->getBoundary($this->boundary[2], $bodyCharSet, 'text/html', $bodyEncoding); $body .= $this->encodeString($this->Body, $bodyEncoding); $body .= $this->LE . $this->LE; $body .= $this->endBoundary($this->boundary[2]); $body .= $this->LE; $body .= $this->attachAll('attachment', $this->boundary[1]); break; case 'alt_inline_attach': $body .= $mimepre; $body .= $this->textLine('--' . $this->boundary[1]); $body .= $this->headerLine('Content-Type', 'multipart/alternative;'); $body .= $this->textLine("\tboundary=\"" . $this->boundary[2] . '"'); $body .= $this->LE; $body .= $this->getBoundary($this->boundary[2], $altBodyCharSet, 'text/plain', $altBodyEncoding); $body .= $this->encodeString($this->AltBody, $altBodyEncoding); $body .= $this->LE . $this->LE; $body .= $this->textLine('--' . $this->boundary[2]); $body .= $this->headerLine('Content-Type', 'multipart/related;'); $body .= $this->textLine("\tboundary=\"" . $this->boundary[3] . '"'); $body .= $this->LE; $body .= $this->getBoundary($this->boundary[3], $bodyCharSet, 'text/html', $bodyEncoding); $body .= $this->encodeString($this->Body, $bodyEncoding); $body .= $this->LE . $this->LE; $body .= $this->attachAll('inline', $this->boundary[3]); $body .= $this->LE; $body .= $this->endBoundary($this->boundary[2]); $body .= $this->LE; $body .= $this->attachAll('attachment', $this->boundary[1]); break; default: // Catch case 'plain' and case '', applies to simple `text/plain` and `text/html` body content types //Reset the `Encoding` property in case we changed it for line length reasons $this->Encoding = $bodyEncoding; $body .= $this->encodeString($this->Body, $this->Encoding); break; } if ($this->isError()) { $body = ''; } elseif ($this->sign_key_file) { try { if (!defined('PKCS7_TEXT')) { throw new phpmailerException($this->lang('extension_missing') . 'openssl'); } // @TODO would be nice to use php://temp streams here, but need to wrap for PHP < 5.1 $file = tempnam(sys_get_temp_dir(), 'mail'); if (false === file_put_contents($file, $body)) { throw new phpmailerException($this->lang('signing') . ' Could not write temp file'); } $signed = tempnam(sys_get_temp_dir(), 'signed'); //Workaround for PHP bug https://bugs.php.net/bug.php?id=69197 if (empty($this->sign_extracerts_file)) { $sign = @openssl_pkcs7_sign( $file, $signed, 'file://' . realpath($this->sign_cert_file), array('file://' . realpath($this->sign_key_file), $this->sign_key_pass), null ); } else { $sign = @openssl_pkcs7_sign( $file, $signed, 'file://' . realpath($this->sign_cert_file), array('file://' . realpath($this->sign_key_file), $this->sign_key_pass), null, PKCS7_DETACHED, $this->sign_extracerts_file ); } if ($sign) { @unlink($file); $body = file_get_contents($signed); @unlink($signed); //The message returned by openssl contains both headers and body, so need to split them up $parts = explode("\n\n", $body, 2); $this->MIMEHeader .= $parts[0] . $this->LE . $this->LE; $body = $parts[1]; } else { @unlink($file); @unlink($signed); throw new phpmailerException($this->lang('signing') . openssl_error_string()); } } catch (phpmailerException $exc) { $body = ''; if ($this->exceptions) { throw $exc; } } } return $body; } /** * Return the start of a message boundary. * @access protected * @param string $boundary * @param string $charSet * @param string $contentType * @param string $encoding * @return string */ protected function getBoundary($boundary, $charSet, $contentType, $encoding) { $result = ''; if ($charSet == '') { $charSet = $this->CharSet; } if ($contentType == '') { $contentType = $this->ContentType; } if ($encoding == '') { $encoding = $this->Encoding; } $result .= $this->textLine('--' . $boundary); $result .= sprintf('Content-Type: %s; charset=%s', $contentType, $charSet); $result .= $this->LE; // RFC1341 part 5 says 7bit is assumed if not specified if ($encoding != '7bit') { $result .= $this->headerLine('Content-Transfer-Encoding', $encoding); } $result .= $this->LE; return $result; } /** * Return the end of a message boundary. * @access protected * @param string $boundary * @return string */ protected function endBoundary($boundary) { return $this->LE . '--' . $boundary . '--' . $this->LE; } /** * Set the message type. * PHPMailer only supports some preset message types, not arbitrary MIME structures. * @access protected * @return void */ protected function setMessageType() { $type = array(); if ($this->alternativeExists()) { $type[] = 'alt'; } if ($this->inlineImageExists()) { $type[] = 'inline'; } if ($this->attachmentExists()) { $type[] = 'attach'; } $this->message_type = implode('_', $type); if ($this->message_type == '') { //The 'plain' message_type refers to the message having a single body element, not that it is plain-text $this->message_type = 'plain'; } } /** * Format a header line. * @access public * @param string $name * @param string $value * @return string */ public function headerLine($name, $value) { return $name . ': ' . $value . $this->LE; } /** * Return a formatted mail line. * @access public * @param string $value * @return string */ public function textLine($value) { return $value . $this->LE; } /** * Add an attachment from a path on the filesystem. * Never use a user-supplied path to a file! * Returns false if the file could not be found or read. * Explicitly *does not* support passing URLs; PHPMailer is not an HTTP client. * If you need to do that, fetch the resource yourself and pass it in via a local file or string. * @param string $path Path to the attachment. * @param string $name Overrides the attachment name. * @param string $encoding File encoding (see $Encoding). * @param string $type File extension (MIME) type. * @param string $disposition Disposition to use * @throws phpmailerException * @return boolean */ public function addAttachment($path, $name = '', $encoding = 'base64', $type = '', $disposition = 'attachment') { try { if (!self::isPermittedPath($path) or !@is_file($path)) { throw new phpmailerException($this->lang('file_access') . $path, self::STOP_CONTINUE); } // If a MIME type is not specified, try to work it out from the file name if ($type == '') { $type = self::filenameToType($path); } $filename = basename($path); if ($name == '') { $name = $filename; } $this->attachment[] = array( 0 => $path, 1 => $filename, 2 => $name, 3 => $encoding, 4 => $type, 5 => false, // isStringAttachment 6 => $disposition, 7 => 0 ); } catch (phpmailerException $exc) { $this->setError($exc->getMessage()); $this->edebug($exc->getMessage()); if ($this->exceptions) { throw $exc; } return false; } return true; } /** * Return the array of attachments. * @return array */ public function getAttachments() { return $this->attachment; } /** * Attach all file, string, and binary attachments to the message. * Returns an empty string on failure. * @access protected * @param string $disposition_type * @param string $boundary * @return string */ protected function attachAll($disposition_type, $boundary) { // Return text of body $mime = array(); $cidUniq = array(); $incl = array(); // Add all attachments foreach ($this->attachment as $attachment) { // Check if it is a valid disposition_filter if ($attachment[6] == $disposition_type) { // Check for string attachment $string = ''; $path = ''; $bString = $attachment[5]; if ($bString) { $string = $attachment[0]; } else { $path = $attachment[0]; } $inclhash = md5(serialize($attachment)); if (in_array($inclhash, $incl)) { continue; } $incl[] = $inclhash; $name = $attachment[2]; $encoding = $attachment[3]; $type = $attachment[4]; $disposition = $attachment[6]; $cid = $attachment[7]; if ($disposition == 'inline' && array_key_exists($cid, $cidUniq)) { continue; } $cidUniq[$cid] = true; $mime[] = sprintf('--%s%s', $boundary, $this->LE); //Only include a filename property if we have one if (!empty($name)) { $mime[] = sprintf( 'Content-Type: %s; name=%s%s', $type, $this->quotedString($this->encodeHeader($this->secureHeader($name))), $this->LE ); } else { $mime[] = sprintf( 'Content-Type: %s%s', $type, $this->LE ); } // RFC1341 part 5 says 7bit is assumed if not specified if ($encoding != '7bit') { $mime[] = sprintf('Content-Transfer-Encoding: %s%s', $encoding, $this->LE); } if ($disposition == 'inline') { $mime[] = sprintf('Content-ID: <%s>%s', $cid, $this->LE); } // Allow for bypassing the Content-Disposition header if (!(empty($disposition))) { $encoded_name = $this->encodeHeader($this->secureHeader($name)); if (!empty($encoded_name)) { $mime[] = sprintf( 'Content-Disposition: %s; filename=%s%s', $disposition, $this->quotedString($encoded_name), $this->LE . $this->LE ); } else { $mime[] = sprintf( 'Content-Disposition: %s%s', $disposition, $this->LE . $this->LE ); } } else { $mime[] = $this->LE; } // Encode as string attachment if ($bString) { $mime[] = $this->encodeString($string, $encoding); if ($this->isError()) { return ''; } $mime[] = $this->LE . $this->LE; } else { $mime[] = $this->encodeFile($path, $encoding); if ($this->isError()) { return ''; } $mime[] = $this->LE . $this->LE; } } } $mime[] = sprintf('--%s--%s', $boundary, $this->LE); return implode('', $mime); } /** * Encode a file attachment in requested format. * Returns an empty string on failure. * @param string $path The full path to the file * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable' * @throws phpmailerException * @access protected * @return string */ protected function encodeFile($path, $encoding = 'base64') { try { if (!self::isPermittedPath($path) or !file_exists($path)) { throw new phpmailerException($this->lang('file_open') . $path, self::STOP_CONTINUE); } $magic_quotes = false; if( version_compare(PHP_VERSION, '7.4.0', '<') ) { $magic_quotes = get_magic_quotes_runtime(); } if ($magic_quotes) { if (version_compare(PHP_VERSION, '5.3.0', '<')) { set_magic_quotes_runtime(false); } else { //Doesn't exist in PHP 5.4, but we don't need to check because //get_magic_quotes_runtime always returns false in 5.4+ //so it will never get here ini_set('magic_quotes_runtime', false); } } $file_buffer = file_get_contents($path); $file_buffer = $this->encodeString($file_buffer, $encoding); if ($magic_quotes) { if (version_compare(PHP_VERSION, '5.3.0', '<')) { set_magic_quotes_runtime($magic_quotes); } else { ini_set('magic_quotes_runtime', $magic_quotes); } } return $file_buffer; } catch (Exception $exc) { $this->setError($exc->getMessage()); return ''; } } /** * Encode a string in requested format. * Returns an empty string on failure. * @param string $str The text to encode * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable' * @access public * @return string */ public function encodeString($str, $encoding = 'base64') { $encoded = ''; switch (strtolower($encoding)) { case 'base64': $encoded = chunk_split(base64_encode($str), 76, $this->LE); break; case '7bit': case '8bit': $encoded = $this->fixEOL($str); // Make sure it ends with a line break if (substr($encoded, -(strlen($this->LE))) != $this->LE) { $encoded .= $this->LE; } break; case 'binary': $encoded = $str; break; case 'quoted-printable': $encoded = $this->encodeQP($str); break; default: $this->setError($this->lang('encoding') . $encoding); break; } return $encoded; } /** * Encode a header string optimally. * Picks shortest of Q, B, quoted-printable or none. * @access public * @param string $str * @param string $position * @return string */ public function encodeHeader($str, $position = 'text') { $matchcount = 0; switch (strtolower($position)) { case 'phrase': if (!preg_match('/[\200-\377]/', $str)) { // Can't use addslashes as we don't know the value of magic_quotes_sybase $encoded = addcslashes($str, "\0..\37\177\\\""); if (($str == $encoded) && !preg_match('/[^A-Za-z0-9!#$%&\'*+\/=?^_`{|}~ -]/', $str)) { return ($encoded); } else { return ("\"$encoded\""); } } $matchcount = preg_match_all('/[^\040\041\043-\133\135-\176]/', $str, $matches); break; /** @noinspection PhpMissingBreakStatementInspection */ case 'comment': $matchcount = preg_match_all('/[()"]/', $str, $matches); // Intentional fall-through case 'text': default: $matchcount += preg_match_all('/[\000-\010\013\014\016-\037\177-\377]/', $str, $matches); break; } //There are no chars that need encoding if ($matchcount == 0) { return ($str); } $maxlen = 75 - 7 - strlen($this->CharSet); // Try to select the encoding which should produce the shortest output if ($matchcount > strlen($str) / 3) { // More than a third of the content will need encoding, so B encoding will be most efficient $encoding = 'B'; if (function_exists('mb_strlen') && $this->hasMultiBytes($str)) { // Use a custom function which correctly encodes and wraps long // multibyte strings without breaking lines within a character $encoded = $this->base64EncodeWrapMB($str, "\n"); } else { $encoded = base64_encode($str); $maxlen -= $maxlen % 4; $encoded = trim(chunk_split($encoded, $maxlen, "\n")); } } else { $encoding = 'Q'; $encoded = $this->encodeQ($str, $position); $encoded = $this->wrapText($encoded, $maxlen, true); $encoded = str_replace('=' . self::CRLF, "\n", trim($encoded)); } $encoded = preg_replace('/^(.*)$/m', ' =?' . $this->CharSet . "?$encoding?\\1?=", $encoded); $encoded = trim(str_replace("\n", $this->LE, $encoded)); return $encoded; } /** * Check if a string contains multi-byte characters. * @access public * @param string $str multi-byte text to wrap encode * @return boolean */ public function hasMultiBytes($str) { if (function_exists('mb_strlen')) { return (strlen($str) > mb_strlen($str, $this->CharSet)); } else { // Assume no multibytes (we can't handle without mbstring functions anyway) return false; } } /** * Does a string contain any 8-bit chars (in any charset)? * @param string $text * @return boolean */ public function has8bitChars($text) { return (boolean)preg_match('/[\x80-\xFF]/', $text); } /** * Encode and wrap long multibyte strings for mail headers * without breaking lines within a character. * Adapted from a function by paravoid * @link http://www.php.net/manual/en/function.mb-encode-mimeheader.php#60283 * @access public * @param string $str multi-byte text to wrap encode * @param string $linebreak string to use as linefeed/end-of-line * @return string */ public function base64EncodeWrapMB($str, $linebreak = null) { $start = '=?' . $this->CharSet . '?B?'; $end = '?='; $encoded = ''; if ($linebreak === null) { $linebreak = $this->LE; } $mb_length = mb_strlen($str, $this->CharSet); // Each line must have length <= 75, including $start and $end $length = 75 - strlen($start) - strlen($end); // Average multi-byte ratio $ratio = $mb_length / strlen($str); // Base64 has a 4:3 ratio $avgLength = floor($length * $ratio * .75); for ($i = 0; $i < $mb_length; $i += $offset) { $lookBack = 0; do { $offset = $avgLength - $lookBack; $chunk = mb_substr($str, $i, $offset, $this->CharSet); $chunk = base64_encode($chunk); $lookBack++; } while (strlen($chunk) > $length); $encoded .= $chunk . $linebreak; } // Chomp the last linefeed $encoded = substr($encoded, 0, -strlen($linebreak)); return $encoded; } /** * Encode a string in quoted-printable format. * According to RFC2045 section 6.7. * @access public * @param string $string The text to encode * @param integer $line_max Number of chars allowed on a line before wrapping * @return string * @link http://www.php.net/manual/en/function.quoted-printable-decode.php#89417 Adapted from this comment */ public function encodeQP($string, $line_max = 76) { // Use native function if it's available (>= PHP5.3) if (function_exists('quoted_printable_encode')) { return quoted_printable_encode($string); } // Fall back to a pure PHP implementation $string = str_replace( array('%20', '%0D%0A.', '%0D%0A', '%'), array(' ', "\r\n=2E", "\r\n", '='), rawurlencode($string) ); return preg_replace('/[^\r\n]{' . ($line_max - 3) . '}[^=\r\n]{2}/', "$0=\r\n", $string); } /** * Backward compatibility wrapper for an old QP encoding function that was removed. * @see PHPMailer::encodeQP() * @access public * @param string $string * @param integer $line_max * @param boolean $space_conv * @return string * @deprecated Use encodeQP instead. */ public function encodeQPphp( $string, $line_max = 76, /** @noinspection PhpUnusedParameterInspection */ $space_conv = false ) { return $this->encodeQP($string, $line_max); } /** * Encode a string using Q encoding. * @link http://tools.ietf.org/html/rfc2047 * @param string $str the text to encode * @param string $position Where the text is going to be used, see the RFC for what that means * @access public * @return string */ public function encodeQ($str, $position = 'text') { // There should not be any EOL in the string $pattern = ''; $encoded = str_replace(array("\r", "\n"), '', $str); switch (strtolower($position)) { case 'phrase': // RFC 2047 section 5.3 $pattern = '^A-Za-z0-9!*+\/ -'; break; /** @noinspection PhpMissingBreakStatementInspection */ case 'comment': // RFC 2047 section 5.2 $pattern = '\(\)"'; // intentional fall-through // for this reason we build the $pattern without including delimiters and [] case 'text': default: // RFC 2047 section 5.1 // Replace every high ascii, control, =, ? and _ characters $pattern = '\000-\011\013\014\016-\037\075\077\137\177-\377' . $pattern; break; } $matches = array(); if (preg_match_all("/[{$pattern}]/", $encoded, $matches)) { // If the string contains an '=', make sure it's the first thing we replace // so as to avoid double-encoding $eqkey = array_search('=', $matches[0]); if (false !== $eqkey) { unset($matches[0][$eqkey]); array_unshift($matches[0], '='); } foreach (array_unique($matches[0]) as $char) { $encoded = str_replace($char, '=' . sprintf('%02X', ord($char)), $encoded); } } // Replace every spaces to _ (more readable than =20) return str_replace(' ', '_', $encoded); } /** * Add a string or binary attachment (non-filesystem). * This method can be used to attach ascii or binary data, * such as a BLOB record from a database. * @param string $string String attachment data. * @param string $filename Name of the attachment. * @param string $encoding File encoding (see $Encoding). * @param string $type File extension (MIME) type. * @param string $disposition Disposition to use * @return void */ public function addStringAttachment( $string, $filename, $encoding = 'base64', $type = '', $disposition = 'attachment' ) { // If a MIME type is not specified, try to work it out from the file name if ($type == '') { $type = self::filenameToType($filename); } // Append to $attachment array $this->attachment[] = array( 0 => $string, 1 => $filename, 2 => basename($filename), 3 => $encoding, 4 => $type, 5 => true, // isStringAttachment 6 => $disposition, 7 => 0 ); } /** * Add an embedded (inline) attachment from a file. * This can include images, sounds, and just about any other document type. * These differ from 'regular' attachments in that they are intended to be * displayed inline with the message, not just attached for download. * This is used in HTML messages that embed the images * the HTML refers to using the $cid value. * Never use a user-supplied path to a file! * @param string $path Path to the attachment. * @param string $cid Content ID of the attachment; Use this to reference * the content when using an embedded image in HTML. * @param string $name Overrides the attachment name. * @param string $encoding File encoding (see $Encoding). * @param string $type File MIME type. * @param string $disposition Disposition to use * @return boolean True on successfully adding an attachment */ public function addEmbeddedImage($path, $cid, $name = '', $encoding = 'base64', $type = '', $disposition = 'inline') { if (!self::isPermittedPath($path) or !@is_file($path)) { $this->setError($this->lang('file_access') . $path); return false; } // If a MIME type is not specified, try to work it out from the file name if ($type == '') { $type = self::filenameToType($path); } $filename = basename($path); if ($name == '') { $name = $filename; } // Append to $attachment array $this->attachment[] = array( 0 => $path, 1 => $filename, 2 => $name, 3 => $encoding, 4 => $type, 5 => false, // isStringAttachment 6 => $disposition, 7 => $cid ); return true; } /** * Add an embedded stringified attachment. * This can include images, sounds, and just about any other document type. * Be sure to set the $type to an image type for images: * JPEG images use 'image/jpeg', GIF uses 'image/gif', PNG uses 'image/png'. * @param string $string The attachment binary data. * @param string $cid Content ID of the attachment; Use this to reference * the content when using an embedded image in HTML. * @param string $name * @param string $encoding File encoding (see $Encoding). * @param string $type MIME type. * @param string $disposition Disposition to use * @return boolean True on successfully adding an attachment */ public function addStringEmbeddedImage( $string, $cid, $name = '', $encoding = 'base64', $type = '', $disposition = 'inline' ) { // If a MIME type is not specified, try to work it out from the name if ($type == '' and !empty($name)) { $type = self::filenameToType($name); } // Append to $attachment array $this->attachment[] = array( 0 => $string, 1 => $name, 2 => $name, 3 => $encoding, 4 => $type, 5 => true, // isStringAttachment 6 => $disposition, 7 => $cid ); return true; } /** * Check if an inline attachment is present. * @access public * @return boolean */ public function inlineImageExists() { foreach ($this->attachment as $attachment) { if ($attachment[6] == 'inline') { return true; } } return false; } /** * Check if an attachment (non-inline) is present. * @return boolean */ public function attachmentExists() { foreach ($this->attachment as $attachment) { if ($attachment[6] == 'attachment') { return true; } } return false; } /** * Check if this message has an alternative body set. * @return boolean */ public function alternativeExists() { return !empty($this->AltBody); } /** * Clear queued addresses of given kind. * @access protected * @param string $kind 'to', 'cc', or 'bcc' * @return void */ public function clearQueuedAddresses($kind) { $RecipientsQueue = $this->RecipientsQueue; foreach ($RecipientsQueue as $address => $params) { if ($params[0] == $kind) { unset($this->RecipientsQueue[$address]); } } } /** * Clear all To recipients. * @return void */ public function clearAddresses() { foreach ($this->to as $to) { unset($this->all_recipients[strtolower($to[0])]); } $this->to = array(); $this->clearQueuedAddresses('to'); } /** * Clear all CC recipients. * @return void */ public function clearCCs() { foreach ($this->cc as $cc) { unset($this->all_recipients[strtolower($cc[0])]); } $this->cc = array(); $this->clearQueuedAddresses('cc'); } /** * Clear all BCC recipients. * @return void */ public function clearBCCs() { foreach ($this->bcc as $bcc) { unset($this->all_recipients[strtolower($bcc[0])]); } $this->bcc = array(); $this->clearQueuedAddresses('bcc'); } /** * Clear all ReplyTo recipients. * @return void */ public function clearReplyTos() { $this->ReplyTo = array(); $this->ReplyToQueue = array(); } /** * Clear all recipient types. * @return void */ public function clearAllRecipients() { $this->to = array(); $this->cc = array(); $this->bcc = array(); $this->all_recipients = array(); $this->RecipientsQueue = array(); } /** * Clear all filesystem, string, and binary attachments. * @return void */ public function clearAttachments() { $this->attachment = array(); } /** * Clear all custom headers. * @return void */ public function clearCustomHeaders() { $this->CustomHeader = array(); } /** * Add an error message to the error container. * @access protected * @param string $msg * @return void */ protected function setError($msg) { $this->error_count++; if ($this->Mailer == 'smtp' and !is_null($this->smtp)) { $lasterror = $this->smtp->getError(); if (!empty($lasterror['error'])) { $msg .= $this->lang('smtp_error') . $lasterror['error']; if (!empty($lasterror['detail'])) { $msg .= ' Detail: '. $lasterror['detail']; } if (!empty($lasterror['smtp_code'])) { $msg .= ' SMTP code: ' . $lasterror['smtp_code']; } if (!empty($lasterror['smtp_code_ex'])) { $msg .= ' Additional SMTP info: ' . $lasterror['smtp_code_ex']; } } } $this->ErrorInfo = $msg; } /** * Return an RFC 822 formatted date. * @access public * @return string * @static */ public static function rfcDate() { // Set the time zone to whatever the default is to avoid 500 errors // Will default to UTC if it's not set properly in php.ini date_default_timezone_set(@date_default_timezone_get()); return date('D, j M Y H:i:s O'); } /** * Get the server hostname. * Returns 'localhost.localdomain' if unknown. * @access protected * @return string */ protected function serverHostname() { $result = 'localhost.localdomain'; if (!empty($this->Hostname)) { $result = $this->Hostname; } elseif (isset($_SERVER) and array_key_exists('SERVER_NAME', $_SERVER) and !empty($_SERVER['SERVER_NAME'])) { $result = $_SERVER['SERVER_NAME']; } elseif (function_exists('gethostname') && gethostname() !== false) { $result = gethostname(); } elseif (php_uname('n') !== false) { $result = php_uname('n'); } return $result; } /** * Get an error message in the current language. * @access protected * @param string $key * @return string */ protected function lang($key) { if (count($this->language) < 1) { $this->setLanguage('en'); // set the default language } if (array_key_exists($key, $this->language)) { if ($key == 'smtp_connect_failed') { //Include a link to troubleshooting docs on SMTP connection failure //this is by far the biggest cause of support questions //but it's usually not PHPMailer's fault. return $this->language[$key] . ' https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting'; } return $this->language[$key]; } else { //Return the key as a fallback return $key; } } /** * Check if an error occurred. * @access public * @return boolean True if an error did occur. */ public function isError() { return ($this->error_count > 0); } /** * Ensure consistent line endings in a string. * Changes every end of line from CRLF, CR or LF to $this->LE. * @access public * @param string $str String to fixEOL * @return string */ public function fixEOL($str) { // Normalise to \n $nstr = str_replace(array("\r\n", "\r"), "\n", $str); // Now convert LE as needed if ($this->LE !== "\n") { $nstr = str_replace("\n", $this->LE, $nstr); } return $nstr; } /** * Add a custom header. * $name value can be overloaded to contain * both header name and value (name:value) * @access public * @param string $name Custom header name * @param string $value Header value * @return void */ public function addCustomHeader($name, $value = null) { if ($value === null) { // Value passed in as name:value $this->CustomHeader[] = explode(':', $name, 2); } else { $this->CustomHeader[] = array($name, $value); } } /** * Returns all custom headers. * @return array */ public function getCustomHeaders() { return $this->CustomHeader; } /** * Create a message body from an HTML string. * Automatically inlines images and creates a plain-text version by converting the HTML, * overwriting any existing values in Body and AltBody. * Do not source $message content from user input! * $basedir is prepended when handling relative URLs, e.g. <img src="/images/a.png"> and must not be empty * will look for an image file in $basedir/images/a.png and convert it to inline. * If you don't provide a $basedir, relative paths will be left untouched (and thus probably break in email) * If you don't want to apply these transformations to your HTML, just set Body and AltBody directly. * @access public * @param string $message HTML message string * @param string $basedir Absolute path to a base directory to prepend to relative paths to images * @param boolean|callable $advanced Whether to use the internal HTML to text converter * or your own custom converter @see PHPMailer::html2text() * @return string $message The transformed message Body */ public function msgHTML($message, $basedir = '', $advanced = false) { preg_match_all('/(src|background)=["\'](.*)["\']/Ui', $message, $images); if (array_key_exists(2, $images)) { if (strlen($basedir) > 1 && substr($basedir, -1) != '/') { // Ensure $basedir has a trailing / $basedir .= '/'; } foreach ($images[2] as $imgindex => $url) { // Convert data URIs into embedded images if (preg_match('#^data:(image[^;,]*)(;base64)?,#', $url, $match)) { $data = substr($url, strpos($url, ',')); if ($match[2]) { $data = base64_decode($data); } else { $data = rawurldecode($data); } $cid = md5($url) . '@phpmailer.0'; // RFC2392 S 2 if ($this->addStringEmbeddedImage($data, $cid, 'embed' . $imgindex, 'base64', $match[1])) { $message = str_replace( $images[0][$imgindex], $images[1][$imgindex] . '="cid:' . $cid . '"', $message ); } continue; } if ( // Only process relative URLs if a basedir is provided (i.e. no absolute local paths) !empty($basedir) // Ignore URLs containing parent dir traversal (..) && (strpos($url, '..') === false) // Do not change urls that are already inline images && substr($url, 0, 4) !== 'cid:' // Do not change absolute URLs, including anonymous protocol && !preg_match('#^[a-z][a-z0-9+.-]*:?//#i', $url) ) { $filename = basename($url); $directory = dirname($url); if ($directory == '.') { $directory = ''; } $cid = md5($url) . '@phpmailer.0'; // RFC2392 S 2 if (strlen($directory) > 1 && substr($directory, -1) != '/') { $directory .= '/'; } if ($this->addEmbeddedImage( $basedir . $directory . $filename, $cid, $filename, 'base64', self::_mime_types((string)self::mb_pathinfo($filename, PATHINFO_EXTENSION)) ) ) { $message = preg_replace( '/' . $images[1][$imgindex] . '=["\']' . preg_quote($url, '/') . '["\']/Ui', $images[1][$imgindex] . '="cid:' . $cid . '"', $message ); } } } } $this->isHTML(true); // Convert all message body line breaks to CRLF, makes quoted-printable encoding work much better $this->Body = $this->normalizeBreaks($message); $this->AltBody = $this->normalizeBreaks($this->html2text($message, $advanced)); if (!$this->alternativeExists()) { $this->AltBody = 'To view this email message, open it in a program that understands HTML!' . self::CRLF . self::CRLF; } return $this->Body; } /** * Convert an HTML string into plain text. * This is used by msgHTML(). * Note - older versions of this function used a bundled advanced converter * which was been removed for license reasons in #232. * Example usage: * <code> * // Use default conversion * $plain = $mail->html2text($html); * // Use your own custom converter * $plain = $mail->html2text($html, function($html) { * $converter = new MyHtml2text($html); * return $converter->get_text(); * }); * </code> * @param string $html The HTML text to convert * @param boolean|callable $advanced Any boolean value to use the internal converter, * or provide your own callable for custom conversion. * @return string */ public function html2text($html, $advanced = false) { if (is_callable($advanced)) { return call_user_func($advanced, $html); } return html_entity_decode( trim(strip_tags(preg_replace('/<(head|title|style|script)[^>]*>.*?<\/\\1>/si', '', $html))), ENT_QUOTES, $this->CharSet ); } /** * Get the MIME type for a file extension. * @param string $ext File extension * @access public * @return string MIME type of file. * @static */ public static function _mime_types($ext = '') { $mimes = array( 'xl' => 'application/excel', 'js' => 'application/javascript', 'hqx' => 'application/mac-binhex40', 'cpt' => 'application/mac-compactpro', 'bin' => 'application/macbinary', 'doc' => 'application/msword', 'word' => 'application/msword', 'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'xltx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.template', 'potx' => 'application/vnd.openxmlformats-officedocument.presentationml.template', 'ppsx' => 'application/vnd.openxmlformats-officedocument.presentationml.slideshow', 'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation', 'sldx' => 'application/vnd.openxmlformats-officedocument.presentationml.slide', 'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'dotx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.template', 'xlam' => 'application/vnd.ms-excel.addin.macroEnabled.12', 'xlsb' => 'application/vnd.ms-excel.sheet.binary.macroEnabled.12', 'class' => 'application/octet-stream', 'dll' => 'application/octet-stream', 'dms' => 'application/octet-stream', 'exe' => 'application/octet-stream', 'lha' => 'application/octet-stream', 'lzh' => 'application/octet-stream', 'psd' => 'application/octet-stream', 'sea' => 'application/octet-stream', 'so' => 'application/octet-stream', 'oda' => 'application/oda', 'pdf' => 'application/pdf', 'ai' => 'application/postscript', 'eps' => 'application/postscript', 'ps' => 'application/postscript', 'smi' => 'application/smil', 'smil' => 'application/smil', 'mif' => 'application/vnd.mif', 'xls' => 'application/vnd.ms-excel', 'ppt' => 'application/vnd.ms-powerpoint', 'wbxml' => 'application/vnd.wap.wbxml', 'wmlc' => 'application/vnd.wap.wmlc', 'dcr' => 'application/x-director', 'dir' => 'application/x-director', 'dxr' => 'application/x-director', 'dvi' => 'application/x-dvi', 'gtar' => 'application/x-gtar', 'php3' => 'application/x-httpd-php', 'php4' => 'application/x-httpd-php', 'php' => 'application/x-httpd-php', 'phtml' => 'application/x-httpd-php', 'phps' => 'application/x-httpd-php-source', 'swf' => 'application/x-shockwave-flash', 'sit' => 'application/x-stuffit', 'tar' => 'application/x-tar', 'tgz' => 'application/x-tar', 'xht' => 'application/xhtml+xml', 'xhtml' => 'application/xhtml+xml', 'zip' => 'application/zip', 'mid' => 'audio/midi', 'midi' => 'audio/midi', 'mp2' => 'audio/mpeg', 'mp3' => 'audio/mpeg', 'mpga' => 'audio/mpeg', 'aif' => 'audio/x-aiff', 'aifc' => 'audio/x-aiff', 'aiff' => 'audio/x-aiff', 'ram' => 'audio/x-pn-realaudio', 'rm' => 'audio/x-pn-realaudio', 'rpm' => 'audio/x-pn-realaudio-plugin', 'ra' => 'audio/x-realaudio', 'wav' => 'audio/x-wav', 'bmp' => 'image/bmp', 'gif' => 'image/gif', 'jpeg' => 'image/jpeg', 'jpe' => 'image/jpeg', 'jpg' => 'image/jpeg', 'png' => 'image/png', 'tiff' => 'image/tiff', 'tif' => 'image/tiff', 'eml' => 'message/rfc822', 'css' => 'text/css', 'html' => 'text/html', 'htm' => 'text/html', 'shtml' => 'text/html', 'log' => 'text/plain', 'text' => 'text/plain', 'txt' => 'text/plain', 'rtx' => 'text/richtext', 'rtf' => 'text/rtf', 'vcf' => 'text/vcard', 'vcard' => 'text/vcard', 'xml' => 'text/xml', 'xsl' => 'text/xml', 'mpeg' => 'video/mpeg', 'mpe' => 'video/mpeg', 'mpg' => 'video/mpeg', 'mov' => 'video/quicktime', 'qt' => 'video/quicktime', 'rv' => 'video/vnd.rn-realvideo', 'avi' => 'video/x-msvideo', 'movie' => 'video/x-sgi-movie' ); if (array_key_exists(strtolower($ext), $mimes)) { return $mimes[strtolower($ext)]; } return 'application/octet-stream'; } /** * Map a file name to a MIME type. * Defaults to 'application/octet-stream', i.e.. arbitrary binary data. * @param string $filename A file name or full path, does not need to exist as a file * @return string * @static */ public static function filenameToType($filename) { // In case the path is a URL, strip any query string before getting extension $qpos = strpos($filename, '?'); if (false !== $qpos) { $filename = substr($filename, 0, $qpos); } $pathinfo = self::mb_pathinfo($filename); return self::_mime_types($pathinfo['extension']); } /** * Multi-byte-safe pathinfo replacement. * Drop-in replacement for pathinfo(), but multibyte-safe, cross-platform-safe, old-version-safe. * Works similarly to the one in PHP >= 5.2.0 * @link http://www.php.net/manual/en/function.pathinfo.php#107461 * @param string $path A filename or path, does not need to exist as a file * @param integer|string $options Either a PATHINFO_* constant, * or a string name to return only the specified piece, allows 'filename' to work on PHP < 5.2 * @return string|array * @static */ public static function mb_pathinfo($path, $options = null) { $ret = array('dirname' => '', 'basename' => '', 'extension' => '', 'filename' => ''); $pathinfo = array(); if (preg_match('%^(.*?)[\\\\/]*(([^/\\\\]*?)(\.([^\.\\\\/]+?)|))[\\\\/\.]*$%im', $path, $pathinfo)) { if (array_key_exists(1, $pathinfo)) { $ret['dirname'] = $pathinfo[1]; } if (array_key_exists(2, $pathinfo)) { $ret['basename'] = $pathinfo[2]; } if (array_key_exists(5, $pathinfo)) { $ret['extension'] = $pathinfo[5]; } if (array_key_exists(3, $pathinfo)) { $ret['filename'] = $pathinfo[3]; } } switch ($options) { case PATHINFO_DIRNAME: case 'dirname': return $ret['dirname']; case PATHINFO_BASENAME: case 'basename': return $ret['basename']; case PATHINFO_EXTENSION: case 'extension': return $ret['extension']; case PATHINFO_FILENAME: case 'filename': return $ret['filename']; default: return $ret; } } /** * Set or reset instance properties. * You should avoid this function - it's more verbose, less efficient, more error-prone and * harder to debug than setting properties directly. * Usage Example: * `$mail->set('SMTPSecure', 'tls');` * is the same as: * `$mail->SMTPSecure = 'tls';` * @access public * @param string $name The property name to set * @param mixed $value The value to set the property to * @return boolean * @TODO Should this not be using the __set() magic function? */ public function set($name, $value = '') { if (property_exists($this, $name)) { $this->$name = $value; return true; } else { $this->setError($this->lang('variable_set') . $name); return false; } } /** * Strip newlines to prevent header injection. * @access public * @param string $str * @return string */ public function secureHeader($str) { return trim(str_replace(array("\r", "\n"), '', $str)); } /** * Normalize line breaks in a string. * Converts UNIX LF, Mac CR and Windows CRLF line breaks into a single line break format. * Defaults to CRLF (for message bodies) and preserves consecutive breaks. * @param string $text * @param string $breaktype What kind of line break to use, defaults to CRLF * @return string * @access public * @static */ public static function normalizeBreaks($text, $breaktype = "\r\n") { return preg_replace('/(\r\n|\r|\n)/ms', $breaktype, $text); } /** * Set the public and private key files and password for S/MIME signing. * @access public * @param string $cert_filename * @param string $key_filename * @param string $key_pass Password for private key * @param string $extracerts_filename Optional path to chain certificate */ public function sign($cert_filename, $key_filename, $key_pass, $extracerts_filename = '') { $this->sign_cert_file = $cert_filename; $this->sign_key_file = $key_filename; $this->sign_key_pass = $key_pass; $this->sign_extracerts_file = $extracerts_filename; } /** * Quoted-Printable-encode a DKIM header. * @access public * @param string $txt * @return string */ public function DKIM_QP($txt) { $line = ''; for ($i = 0; $i < strlen($txt); $i++) { $ord = ord($txt[$i]); if (((0x21 <= $ord) && ($ord <= 0x3A)) || $ord == 0x3C || ((0x3E <= $ord) && ($ord <= 0x7E))) { $line .= $txt[$i]; } else { $line .= '=' . sprintf('%02X', $ord); } } return $line; } /** * Generate a DKIM signature. * @access public * @param string $signHeader * @throws phpmailerException * @return string The DKIM signature value */ public function DKIM_Sign($signHeader) { if (!defined('PKCS7_TEXT')) { if ($this->exceptions) { throw new phpmailerException($this->lang('extension_missing') . 'openssl'); } return ''; } $privKeyStr = !empty($this->DKIM_private_string) ? $this->DKIM_private_string : file_get_contents($this->DKIM_private); if ('' != $this->DKIM_passphrase) { $privKey = openssl_pkey_get_private($privKeyStr, $this->DKIM_passphrase); } else { $privKey = openssl_pkey_get_private($privKeyStr); } //Workaround for missing digest algorithms in old PHP & OpenSSL versions //@link http://stackoverflow.com/a/11117338/333340 if (version_compare(PHP_VERSION, '5.3.0') >= 0 and in_array('sha256WithRSAEncryption', openssl_get_md_methods(true))) { if (openssl_sign($signHeader, $signature, $privKey, 'sha256WithRSAEncryption')) { openssl_pkey_free($privKey); return base64_encode($signature); } } else { $pinfo = openssl_pkey_get_details($privKey); $hash = hash('sha256', $signHeader); //'Magic' constant for SHA256 from RFC3447 //@link https://tools.ietf.org/html/rfc3447#page-43 $t = '3031300d060960864801650304020105000420' . $hash; $pslen = $pinfo['bits'] / 8 - (strlen($t) / 2 + 3); $eb = pack('H*', '0001' . str_repeat('FF', $pslen) . '00' . $t); if (openssl_private_encrypt($eb, $signature, $privKey, OPENSSL_NO_PADDING)) { openssl_pkey_free($privKey); return base64_encode($signature); } } openssl_pkey_free($privKey); return ''; } /** * Generate a DKIM canonicalization header. * @access public * @param string $signHeader Header * @return string */ public function DKIM_HeaderC($signHeader) { $signHeader = preg_replace('/\r\n\s+/', ' ', $signHeader); $lines = explode("\r\n", $signHeader); foreach ($lines as $key => $line) { list($heading, $value) = explode(':', $line, 2); $heading = strtolower($heading); $value = preg_replace('/\s{2,}/', ' ', $value); // Compress useless spaces $lines[$key] = $heading . ':' . trim($value); // Don't forget to remove WSP around the value } $signHeader = implode("\r\n", $lines); return $signHeader; } /** * Generate a DKIM canonicalization body. * @access public * @param string $body Message Body * @return string */ public function DKIM_BodyC($body) { if ($body == '') { return "\r\n"; } // stabilize line endings $body = str_replace("\r\n", "\n", $body); $body = str_replace("\n", "\r\n", $body); // END stabilize line endings while (substr($body, strlen($body) - 4, 4) == "\r\n\r\n") { $body = substr($body, 0, strlen($body) - 2); } return $body; } /** * Create the DKIM header and body in a new message header. * @access public * @param string $headers_line Header lines * @param string $subject Subject * @param string $body Body * @return string */ public function DKIM_Add($headers_line, $subject, $body) { $DKIMsignatureType = 'rsa-sha256'; // Signature & hash algorithms $DKIMcanonicalization = 'relaxed/simple'; // Canonicalization of header/body $DKIMquery = 'dns/txt'; // Query method $DKIMtime = time(); // Signature Timestamp = seconds since 00:00:00 - Jan 1, 1970 (UTC time zone) $subject_header = "Subject: $subject"; $headers = explode($this->LE, $headers_line); $from_header = ''; $to_header = ''; $date_header = ''; $current = ''; foreach ($headers as $header) { if (strpos($header, 'From:') === 0) { $from_header = $header; $current = 'from_header'; } elseif (strpos($header, 'To:') === 0) { $to_header = $header; $current = 'to_header'; } elseif (strpos($header, 'Date:') === 0) { $date_header = $header; $current = 'date_header'; } else { if (!empty($$current) && strpos($header, ' =?') === 0) { $$current .= $header; } else { $current = ''; } } } $from = str_replace('|', '=7C', $this->DKIM_QP($from_header)); $to = str_replace('|', '=7C', $this->DKIM_QP($to_header)); $date = str_replace('|', '=7C', $this->DKIM_QP($date_header)); $subject = str_replace( '|', '=7C', $this->DKIM_QP($subject_header) ); // Copied header fields (dkim-quoted-printable) $body = $this->DKIM_BodyC($body); $DKIMlen = strlen($body); // Length of body $DKIMb64 = base64_encode(pack('H*', hash('sha256', $body))); // Base64 of packed binary SHA-256 hash of body if ('' == $this->DKIM_identity) { $ident = ''; } else { $ident = ' i=' . $this->DKIM_identity . ';'; } $dkimhdrs = 'DKIM-Signature: v=1; a=' . $DKIMsignatureType . '; q=' . $DKIMquery . '; l=' . $DKIMlen . '; s=' . $this->DKIM_selector . ";\r\n" . "\tt=" . $DKIMtime . '; c=' . $DKIMcanonicalization . ";\r\n" . "\th=From:To:Date:Subject;\r\n" . "\td=" . $this->DKIM_domain . ';' . $ident . "\r\n" . "\tz=$from\r\n" . "\t|$to\r\n" . "\t|$date\r\n" . "\t|$subject;\r\n" . "\tbh=" . $DKIMb64 . ";\r\n" . "\tb="; $toSign = $this->DKIM_HeaderC( $from_header . "\r\n" . $to_header . "\r\n" . $date_header . "\r\n" . $subject_header . "\r\n" . $dkimhdrs ); $signed = $this->DKIM_Sign($toSign); return $dkimhdrs . $signed . "\r\n"; } /** * Detect if a string contains a line longer than the maximum line length allowed. * @param string $str * @return boolean * @static */ public static function hasLineLongerThanMax($str) { //+2 to include CRLF line break for a 1000 total return (boolean)preg_match('/^(.{'.(self::MAX_LINE_LENGTH + 2).',})/m', $str); } /** * If a string contains any "special" characters, double-quote the name, * and escape any double quotes with a backslash. * * @param string $str * * @return string * * @see RFC822 3.4.1 */ public function quotedString($str) { if (preg_match('/[ ()<>@,;:"\/\[\]?=]/', $str)) { //If the string contains any of these chars, it must be double-quoted //and any double quotes must be escaped with a backslash return '"' . str_replace('"', '\\"', $str) . '"'; } //Return the string untouched, it doesn't need quoting return $str; } /** * Allows for public read access to 'to' property. * @note: Before the send() call, queued addresses (i.e. with IDN) are not yet included. * @access public * @return array */ public function getToAddresses() { return $this->to; } /** * Allows for public read access to 'cc' property. * @note: Before the send() call, queued addresses (i.e. with IDN) are not yet included. * @access public * @return array */ public function getCcAddresses() { return $this->cc; } /** * Allows for public read access to 'bcc' property. * @note: Before the send() call, queued addresses (i.e. with IDN) are not yet included. * @access public * @return array */ public function getBccAddresses() { return $this->bcc; } /** * Allows for public read access to 'ReplyTo' property. * @note: Before the send() call, queued addresses (i.e. with IDN) are not yet included. * @access public * @return array */ public function getReplyToAddresses() { return $this->ReplyTo; } /** * Allows for public read access to 'all_recipients' property. * @note: Before the send() call, queued addresses (i.e. with IDN) are not yet included. * @access public * @return array */ public function getAllRecipientAddresses() { return $this->all_recipients; } /** * Perform a callback. * @param boolean $isSent * @param array $to * @param array $cc * @param array $bcc * @param string $subject * @param string $body * @param string $from */ protected function doCallback($isSent, $to, $cc, $bcc, $subject, $body, $from) { if (!empty($this->action_function) && is_callable($this->action_function)) { $params = array($isSent, $to, $cc, $bcc, $subject, $body, $from); call_user_func_array($this->action_function, $params); } } } /** * PHPMailer exception handler * @package PHPMailer */ class phpmailerException extends Exception { /** * Prettify error message output * @return string */ public function errorMessage() { $errorMsg = '<strong>' . htmlspecialchars($this->getMessage()) . "</strong><br />\n"; return $errorMsg; } } phpmailer/phpmailer/VERSION 0000705 00000000016 15242100017 0011541 0 ustar 00 5.2.28+joomla1 phpmailer/phpmailer/class.smtp.php 0000705 00000124747 15242100017 0013313 0 ustar 00 <?php /** * PHPMailer RFC821 SMTP email transport class. * PHP Version 5 * @package PHPMailer * @link https://github.com/PHPMailer/PHPMailer/ The PHPMailer GitHub project * @author Marcus Bointon (Synchro/coolbru) <phpmailer@synchromedia.co.uk> * @author Jim Jagielski (jimjag) <jimjag@gmail.com> * @author Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net> * @author Brent R. Matzelle (original founder) * @copyright 2014 Marcus Bointon * @copyright 2010 - 2012 Jim Jagielski * @copyright 2004 - 2009 Andy Prevost * @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License * @note This program is distributed in the hope that it will be useful - WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. */ /** * PHPMailer RFC821 SMTP email transport class. * Implements RFC 821 SMTP commands and provides some utility methods for sending mail to an SMTP server. * @package PHPMailer * @author Chris Ryan * @author Marcus Bointon <phpmailer@synchromedia.co.uk> */ class SMTP { /** * The PHPMailer SMTP version number. * @var string */ const VERSION = '5.2.28'; /** * SMTP line break constant. * @var string */ const CRLF = "\r\n"; /** * The SMTP port to use if one is not specified. * @var integer */ const DEFAULT_SMTP_PORT = 25; /** * The maximum line length allowed by RFC 2822 section 2.1.1 * @var integer */ const MAX_LINE_LENGTH = 998; /** * Debug level for no output */ const DEBUG_OFF = 0; /** * Debug level to show client -> server messages */ const DEBUG_CLIENT = 1; /** * Debug level to show client -> server and server -> client messages */ const DEBUG_SERVER = 2; /** * Debug level to show connection status, client -> server and server -> client messages */ const DEBUG_CONNECTION = 3; /** * Debug level to show all messages */ const DEBUG_LOWLEVEL = 4; /** * The PHPMailer SMTP Version number. * @var string * @deprecated Use the `VERSION` constant instead * @see SMTP::VERSION */ public $Version = '5.2.28'; /** * SMTP server port number. * @var integer * @deprecated This is only ever used as a default value, so use the `DEFAULT_SMTP_PORT` constant instead * @see SMTP::DEFAULT_SMTP_PORT */ public $SMTP_PORT = 25; /** * SMTP reply line ending. * @var string * @deprecated Use the `CRLF` constant instead * @see SMTP::CRLF */ public $CRLF = "\r\n"; /** * Debug output level. * Options: * * self::DEBUG_OFF (`0`) No debug output, default * * self::DEBUG_CLIENT (`1`) Client commands * * self::DEBUG_SERVER (`2`) Client commands and server responses * * self::DEBUG_CONNECTION (`3`) As DEBUG_SERVER plus connection status * * self::DEBUG_LOWLEVEL (`4`) Low-level data output, all messages * @var integer */ public $do_debug = self::DEBUG_OFF; /** * How to handle debug output. * Options: * * `echo` Output plain-text as-is, appropriate for CLI * * `html` Output escaped, line breaks converted to `<br>`, appropriate for browser output * * `error_log` Output to error log as configured in php.ini * * Alternatively, you can provide a callable expecting two params: a message string and the debug level: * <code> * $smtp->Debugoutput = function($str, $level) {echo "debug level $level; message: $str";}; * </code> * @var string|callable */ public $Debugoutput = 'echo'; /** * Whether to use VERP. * @link http://en.wikipedia.org/wiki/Variable_envelope_return_path * @link http://www.postfix.org/VERP_README.html Info on VERP * @var boolean */ public $do_verp = false; /** * The timeout value for connection, in seconds. * Default of 5 minutes (300sec) is from RFC2821 section 4.5.3.2 * This needs to be quite high to function correctly with hosts using greetdelay as an anti-spam measure. * @link http://tools.ietf.org/html/rfc2821#section-4.5.3.2 * @var integer */ public $Timeout = 300; /** * How long to wait for commands to complete, in seconds. * Default of 5 minutes (300sec) is from RFC2821 section 4.5.3.2 * @var integer */ public $Timelimit = 300; /** * @var array Patterns to extract an SMTP transaction id from reply to a DATA command. * The first capture group in each regex will be used as the ID. */ protected $smtp_transaction_id_patterns = array( 'exim' => '/[0-9]{3} OK id=(.*)/', 'sendmail' => '/[0-9]{3} 2.0.0 (.*) Message/', 'postfix' => '/[0-9]{3} 2.0.0 Ok: queued as (.*)/' ); /** * @var string The last transaction ID issued in response to a DATA command, * if one was detected */ protected $last_smtp_transaction_id; /** * The socket for the server connection. * @var resource */ protected $smtp_conn; /** * Error information, if any, for the last SMTP command. * @var array */ protected $error = array( 'error' => '', 'detail' => '', 'smtp_code' => '', 'smtp_code_ex' => '' ); /** * The reply the server sent to us for HELO. * If null, no HELO string has yet been received. * @var string|null */ protected $helo_rply = null; /** * The set of SMTP extensions sent in reply to EHLO command. * Indexes of the array are extension names. * Value at index 'HELO' or 'EHLO' (according to command that was sent) * represents the server name. In case of HELO it is the only element of the array. * Other values can be boolean TRUE or an array containing extension options. * If null, no HELO/EHLO string has yet been received. * @var array|null */ protected $server_caps = null; /** * The most recent reply received from the server. * @var string */ protected $last_reply = ''; /** * Output debugging info via a user-selected method. * @see SMTP::$Debugoutput * @see SMTP::$do_debug * @param string $str Debug string to output * @param integer $level The debug level of this message; see DEBUG_* constants * @return void */ protected function edebug($str, $level = 0) { if ($level > $this->do_debug) { return; } //Avoid clash with built-in function names if (!in_array($this->Debugoutput, array('error_log', 'html', 'echo')) and is_callable($this->Debugoutput)) { call_user_func($this->Debugoutput, $str, $level); return; } switch ($this->Debugoutput) { case 'error_log': //Don't output, just log error_log($str); break; case 'html': //Cleans up output a bit for a better looking, HTML-safe output echo gmdate('Y-m-d H:i:s') . ' ' . htmlentities( preg_replace('/[\r\n]+/', '', $str), ENT_QUOTES, 'UTF-8' ) . "<br>\n"; break; case 'echo': default: //Normalize line breaks $str = preg_replace('/(\r\n|\r|\n)/ms', "\n", $str); echo gmdate('Y-m-d H:i:s') . "\t" . str_replace( "\n", "\n \t ", trim($str) ) . "\n"; } } /** * Connect to an SMTP server. * @param string $host SMTP server IP or host name * @param integer $port The port number to connect to * @param integer $timeout How long to wait for the connection to open * @param array $options An array of options for stream_context_create() * @access public * @return boolean */ public function connect($host, $port = null, $timeout = 30, $options = array()) { static $streamok; //This is enabled by default since 5.0.0 but some providers disable it //Check this once and cache the result if (is_null($streamok)) { $streamok = function_exists('stream_socket_client'); } // Clear errors to avoid confusion $this->setError(''); // Make sure we are __not__ connected if ($this->connected()) { // Already connected, generate error $this->setError('Already connected to a server'); return false; } if (empty($port)) { $port = self::DEFAULT_SMTP_PORT; } // Connect to the SMTP server $this->edebug( "Connection: opening to $host:$port, timeout=$timeout, options=" . var_export($options, true), self::DEBUG_CONNECTION ); $errno = 0; $errstr = ''; if ($streamok) { $socket_context = stream_context_create($options); set_error_handler(array($this, 'errorHandler')); $this->smtp_conn = stream_socket_client( $host . ":" . $port, $errno, $errstr, $timeout, STREAM_CLIENT_CONNECT, $socket_context ); restore_error_handler(); } else { //Fall back to fsockopen which should work in more places, but is missing some features $this->edebug( "Connection: stream_socket_client not available, falling back to fsockopen", self::DEBUG_CONNECTION ); set_error_handler(array($this, 'errorHandler')); $this->smtp_conn = fsockopen( $host, $port, $errno, $errstr, $timeout ); restore_error_handler(); } // Verify we connected properly if (!is_resource($this->smtp_conn)) { $this->setError( 'Failed to connect to server', $errno, $errstr ); $this->edebug( 'SMTP ERROR: ' . $this->error['error'] . ": $errstr ($errno)", self::DEBUG_CLIENT ); return false; } $this->edebug('Connection: opened', self::DEBUG_CONNECTION); // SMTP server can take longer to respond, give longer timeout for first read // Windows does not have support for this timeout function if (substr(PHP_OS, 0, 3) != 'WIN') { $max = ini_get('max_execution_time'); // Don't bother if unlimited if ($max != 0 && $timeout > $max) { @set_time_limit($timeout); } stream_set_timeout($this->smtp_conn, $timeout, 0); } // Get any announcement $announce = $this->get_lines(); $this->edebug('SERVER -> CLIENT: ' . $announce, self::DEBUG_SERVER); return true; } /** * Initiate a TLS (encrypted) session. * @access public * @return boolean */ public function startTLS() { if (!$this->sendCommand('STARTTLS', 'STARTTLS', 220)) { return false; } //Allow the best TLS version(s) we can $crypto_method = STREAM_CRYPTO_METHOD_TLS_CLIENT; //PHP 5.6.7 dropped inclusion of TLS 1.1 and 1.2 in STREAM_CRYPTO_METHOD_TLS_CLIENT //so add them back in manually if we can if (defined('STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT')) { $crypto_method |= STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT; $crypto_method |= STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT; } // Begin encrypted connection set_error_handler(array($this, 'errorHandler')); $crypto_ok = stream_socket_enable_crypto( $this->smtp_conn, true, $crypto_method ); restore_error_handler(); return $crypto_ok; } /** * Perform SMTP authentication. * Must be run after hello(). * @see hello() * @param string $username The user name * @param string $password The password * @param string $authtype The auth type (PLAIN, LOGIN, NTLM, CRAM-MD5, XOAUTH2) * @param string $realm The auth realm for NTLM * @param string $workstation The auth workstation for NTLM * @param null|OAuth $OAuth An optional OAuth instance (@see PHPMailerOAuth) * @return bool True if successfully authenticated.* @access public */ public function authenticate( $username, $password, $authtype = null, $realm = '', $workstation = '', $OAuth = null ) { if (!$this->server_caps) { $this->setError('Authentication is not allowed before HELO/EHLO'); return false; } if (array_key_exists('EHLO', $this->server_caps)) { // SMTP extensions are available; try to find a proper authentication method if (!array_key_exists('AUTH', $this->server_caps)) { $this->setError('Authentication is not allowed at this stage'); // 'at this stage' means that auth may be allowed after the stage changes // e.g. after STARTTLS return false; } self::edebug('Auth method requested: ' . ($authtype ? $authtype : 'UNKNOWN'), self::DEBUG_LOWLEVEL); self::edebug( 'Auth methods available on the server: ' . implode(',', $this->server_caps['AUTH']), self::DEBUG_LOWLEVEL ); if (empty($authtype)) { foreach (array('CRAM-MD5', 'LOGIN', 'PLAIN', 'NTLM', 'XOAUTH2') as $method) { if (in_array($method, $this->server_caps['AUTH'])) { $authtype = $method; break; } } if (empty($authtype)) { $this->setError('No supported authentication methods found'); return false; } self::edebug('Auth method selected: ' . $authtype, self::DEBUG_LOWLEVEL); } if (!in_array($authtype, $this->server_caps['AUTH'])) { $this->setError("The requested authentication method \"$authtype\" is not supported by the server"); return false; } } elseif (empty($authtype)) { $authtype = 'LOGIN'; } switch ($authtype) { case 'PLAIN': // Start authentication if (!$this->sendCommand('AUTH', 'AUTH PLAIN', 334)) { return false; } // Send encoded username and password if (!$this->sendCommand( 'User & Password', base64_encode("\0" . $username . "\0" . $password), 235 ) ) { return false; } break; case 'LOGIN': // Start authentication if (!$this->sendCommand('AUTH', 'AUTH LOGIN', 334)) { return false; } if (!$this->sendCommand("Username", base64_encode($username), 334)) { return false; } if (!$this->sendCommand("Password", base64_encode($password), 235)) { return false; } break; case 'XOAUTH2': //If the OAuth Instance is not set. Can be a case when PHPMailer is used //instead of PHPMailerOAuth if (is_null($OAuth)) { return false; } $oauth = $OAuth->getOauth64(); // Start authentication if (!$this->sendCommand('AUTH', 'AUTH XOAUTH2 ' . $oauth, 235)) { return false; } break; case 'NTLM': /* * ntlm_sasl_client.php * Bundled with Permission * * How to telnet in windows: * http://technet.microsoft.com/en-us/library/aa995718%28EXCHG.65%29.aspx * PROTOCOL Docs http://curl.haxx.se/rfc/ntlm.html#ntlmSmtpAuthentication */ require_once 'extras/ntlm_sasl_client.php'; $temp = new stdClass; $ntlm_client = new ntlm_sasl_client_class; //Check that functions are available if (!$ntlm_client->initialize($temp)) { $this->setError($temp->error); $this->edebug( 'You need to enable some modules in your php.ini file: ' . $this->error['error'], self::DEBUG_CLIENT ); return false; } //msg1 $msg1 = $ntlm_client->typeMsg1($realm, $workstation); //msg1 if (!$this->sendCommand( 'AUTH NTLM', 'AUTH NTLM ' . base64_encode($msg1), 334 ) ) { return false; } //Though 0 based, there is a white space after the 3 digit number //msg2 $challenge = substr($this->last_reply, 3); $challenge = base64_decode($challenge); $ntlm_res = $ntlm_client->NTLMResponse( substr($challenge, 24, 8), $password ); //msg3 $msg3 = $ntlm_client->typeMsg3( $ntlm_res, $username, $realm, $workstation ); // send encoded username return $this->sendCommand('Username', base64_encode($msg3), 235); case 'CRAM-MD5': // Start authentication if (!$this->sendCommand('AUTH CRAM-MD5', 'AUTH CRAM-MD5', 334)) { return false; } // Get the challenge $challenge = base64_decode(substr($this->last_reply, 4)); // Build the response $response = $username . ' ' . $this->hmac($challenge, $password); // send encoded credentials return $this->sendCommand('Username', base64_encode($response), 235); default: $this->setError("Authentication method \"$authtype\" is not supported"); return false; } return true; } /** * Calculate an MD5 HMAC hash. * Works like hash_hmac('md5', $data, $key) * in case that function is not available * @param string $data The data to hash * @param string $key The key to hash with * @access protected * @return string */ protected function hmac($data, $key) { if (function_exists('hash_hmac')) { return hash_hmac('md5', $data, $key); } // The following borrowed from // http://php.net/manual/en/function.mhash.php#27225 // RFC 2104 HMAC implementation for php. // Creates an md5 HMAC. // Eliminates the need to install mhash to compute a HMAC // by Lance Rushing $bytelen = 64; // byte length for md5 if (strlen($key) > $bytelen) { $key = pack('H*', md5($key)); } $key = str_pad($key, $bytelen, chr(0x00)); $ipad = str_pad('', $bytelen, chr(0x36)); $opad = str_pad('', $bytelen, chr(0x5c)); $k_ipad = $key ^ $ipad; $k_opad = $key ^ $opad; return md5($k_opad . pack('H*', md5($k_ipad . $data))); } /** * Check connection state. * @access public * @return boolean True if connected. */ public function connected() { if (is_resource($this->smtp_conn)) { $sock_status = stream_get_meta_data($this->smtp_conn); if ($sock_status['eof']) { // The socket is valid but we are not connected $this->edebug( 'SMTP NOTICE: EOF caught while checking if connected', self::DEBUG_CLIENT ); $this->close(); return false; } return true; // everything looks good } return false; } /** * Close the socket and clean up the state of the class. * Don't use this function without first trying to use QUIT. * @see quit() * @access public * @return void */ public function close() { $this->setError(''); $this->server_caps = null; $this->helo_rply = null; if (is_resource($this->smtp_conn)) { // close the connection and cleanup fclose($this->smtp_conn); $this->smtp_conn = null; //Makes for cleaner serialization $this->edebug('Connection: closed', self::DEBUG_CONNECTION); } } /** * Send an SMTP DATA command. * Issues a data command and sends the msg_data to the server, * finializing the mail transaction. $msg_data is the message * that is to be send with the headers. Each header needs to be * on a single line followed by a <CRLF> with the message headers * and the message body being separated by and additional <CRLF>. * Implements rfc 821: DATA <CRLF> * @param string $msg_data Message data to send * @access public * @return boolean */ public function data($msg_data) { //This will use the standard timelimit if (!$this->sendCommand('DATA', 'DATA', 354)) { return false; } /* The server is ready to accept data! * According to rfc821 we should not send more than 1000 characters on a single line (including the CRLF) * so we will break the data up into lines by \r and/or \n then if needed we will break each of those into * smaller lines to fit within the limit. * We will also look for lines that start with a '.' and prepend an additional '.'. * NOTE: this does not count towards line-length limit. */ // Normalize line breaks before exploding $lines = explode("\n", str_replace(array("\r\n", "\r"), "\n", $msg_data)); /* To distinguish between a complete RFC822 message and a plain message body, we check if the first field * of the first line (':' separated) does not contain a space then it _should_ be a header and we will * process all lines before a blank line as headers. */ $field = substr($lines[0], 0, strpos($lines[0], ':')); $in_headers = false; if (!empty($field) && strpos($field, ' ') === false) { $in_headers = true; } foreach ($lines as $line) { $lines_out = array(); if ($in_headers and $line == '') { $in_headers = false; } //Break this line up into several smaller lines if it's too long //Micro-optimisation: isset($str[$len]) is faster than (strlen($str) > $len), while (isset($line[self::MAX_LINE_LENGTH])) { //Working backwards, try to find a space within the last MAX_LINE_LENGTH chars of the line to break on //so as to avoid breaking in the middle of a word $pos = strrpos(substr($line, 0, self::MAX_LINE_LENGTH), ' '); //Deliberately matches both false and 0 if (!$pos) { //No nice break found, add a hard break $pos = self::MAX_LINE_LENGTH - 1; $lines_out[] = substr($line, 0, $pos); $line = substr($line, $pos); } else { //Break at the found point $lines_out[] = substr($line, 0, $pos); //Move along by the amount we dealt with $line = substr($line, $pos + 1); } //If processing headers add a LWSP-char to the front of new line RFC822 section 3.1.1 if ($in_headers) { $line = "\t" . $line; } } $lines_out[] = $line; //Send the lines to the server foreach ($lines_out as $line_out) { //RFC2821 section 4.5.2 if (!empty($line_out) and $line_out[0] == '.') { $line_out = '.' . $line_out; } $this->client_send($line_out . self::CRLF); } } //Message data has been sent, complete the command //Increase timelimit for end of DATA command $savetimelimit = $this->Timelimit; $this->Timelimit = $this->Timelimit * 2; $result = $this->sendCommand('DATA END', '.', 250); $this->recordLastTransactionID(); //Restore timelimit $this->Timelimit = $savetimelimit; return $result; } /** * Send an SMTP HELO or EHLO command. * Used to identify the sending server to the receiving server. * This makes sure that client and server are in a known state. * Implements RFC 821: HELO <SP> <domain> <CRLF> * and RFC 2821 EHLO. * @param string $host The host name or IP to connect to * @access public * @return boolean */ public function hello($host = '') { //Try extended hello first (RFC 2821) return (boolean)($this->sendHello('EHLO', $host) or $this->sendHello('HELO', $host)); } /** * Send an SMTP HELO or EHLO command. * Low-level implementation used by hello() * @see hello() * @param string $hello The HELO string * @param string $host The hostname to say we are * @access protected * @return boolean */ protected function sendHello($hello, $host) { $noerror = $this->sendCommand($hello, $hello . ' ' . $host, 250); $this->helo_rply = $this->last_reply; if ($noerror) { $this->parseHelloFields($hello); } else { $this->server_caps = null; } return $noerror; } /** * Parse a reply to HELO/EHLO command to discover server extensions. * In case of HELO, the only parameter that can be discovered is a server name. * @access protected * @param string $type - 'HELO' or 'EHLO' */ protected function parseHelloFields($type) { $this->server_caps = array(); $lines = explode("\n", $this->helo_rply); foreach ($lines as $n => $s) { //First 4 chars contain response code followed by - or space $s = trim(substr($s, 4)); if (empty($s)) { continue; } $fields = explode(' ', $s); if (!empty($fields)) { if (!$n) { $name = $type; $fields = $fields[0]; } else { $name = array_shift($fields); switch ($name) { case 'SIZE': $fields = ($fields ? $fields[0] : 0); break; case 'AUTH': if (!is_array($fields)) { $fields = array(); } break; default: $fields = true; } } $this->server_caps[$name] = $fields; } } } /** * Send an SMTP MAIL command. * Starts a mail transaction from the email address specified in * $from. Returns true if successful or false otherwise. If True * the mail transaction is started and then one or more recipient * commands may be called followed by a data command. * Implements rfc 821: MAIL <SP> FROM:<reverse-path> <CRLF> * @param string $from Source address of this message * @access public * @return boolean */ public function mail($from) { $useVerp = ($this->do_verp ? ' XVERP' : ''); return $this->sendCommand( 'MAIL FROM', 'MAIL FROM:<' . $from . '>' . $useVerp, 250 ); } /** * Send an SMTP QUIT command. * Closes the socket if there is no error or the $close_on_error argument is true. * Implements from rfc 821: QUIT <CRLF> * @param boolean $close_on_error Should the connection close if an error occurs? * @access public * @return boolean */ public function quit($close_on_error = true) { $noerror = $this->sendCommand('QUIT', 'QUIT', 221); $err = $this->error; //Save any error if ($noerror or $close_on_error) { $this->close(); $this->error = $err; //Restore any error from the quit command } return $noerror; } /** * Send an SMTP RCPT command. * Sets the TO argument to $toaddr. * Returns true if the recipient was accepted false if it was rejected. * Implements from rfc 821: RCPT <SP> TO:<forward-path> <CRLF> * @param string $address The address the message is being sent to * @access public * @return boolean */ public function recipient($address) { return $this->sendCommand( 'RCPT TO', 'RCPT TO:<' . $address . '>', array(250, 251) ); } /** * Send an SMTP RSET command. * Abort any transaction that is currently in progress. * Implements rfc 821: RSET <CRLF> * @access public * @return boolean True on success. */ public function reset() { return $this->sendCommand('RSET', 'RSET', 250); } /** * Send a command to an SMTP server and check its return code. * @param string $command The command name - not sent to the server * @param string $commandstring The actual command to send * @param integer|array $expect One or more expected integer success codes * @access protected * @return boolean True on success. */ protected function sendCommand($command, $commandstring, $expect) { if (!$this->connected()) { $this->setError("Called $command without being connected"); return false; } //Reject line breaks in all commands if (strpos($commandstring, "\n") !== false or strpos($commandstring, "\r") !== false) { $this->setError("Command '$command' contained line breaks"); return false; } $this->client_send($commandstring . self::CRLF); $this->last_reply = $this->get_lines(); // Fetch SMTP code and possible error code explanation $matches = array(); if (preg_match("/^([0-9]{3})[ -](?:([0-9]\\.[0-9]\\.[0-9]) )?/", $this->last_reply, $matches)) { $code = $matches[1]; $code_ex = (count($matches) > 2 ? $matches[2] : null); // Cut off error code from each response line $detail = preg_replace( "/{$code}[ -]" . ($code_ex ? str_replace('.', '\\.', $code_ex) . ' ' : '') . "/m", '', $this->last_reply ); } else { // Fall back to simple parsing if regex fails $code = substr($this->last_reply, 0, 3); $code_ex = null; $detail = substr($this->last_reply, 4); } $this->edebug('SERVER -> CLIENT: ' . $this->last_reply, self::DEBUG_SERVER); if (!in_array($code, (array)$expect)) { $this->setError( "$command command failed", $detail, $code, $code_ex ); $this->edebug( 'SMTP ERROR: ' . $this->error['error'] . ': ' . $this->last_reply, self::DEBUG_CLIENT ); return false; } $this->setError(''); return true; } /** * Send an SMTP SAML command. * Starts a mail transaction from the email address specified in $from. * Returns true if successful or false otherwise. If True * the mail transaction is started and then one or more recipient * commands may be called followed by a data command. This command * will send the message to the users terminal if they are logged * in and send them an email. * Implements rfc 821: SAML <SP> FROM:<reverse-path> <CRLF> * @param string $from The address the message is from * @access public * @return boolean */ public function sendAndMail($from) { return $this->sendCommand('SAML', "SAML FROM:$from", 250); } /** * Send an SMTP VRFY command. * @param string $name The name to verify * @access public * @return boolean */ public function verify($name) { return $this->sendCommand('VRFY', "VRFY $name", array(250, 251)); } /** * Send an SMTP NOOP command. * Used to keep keep-alives alive, doesn't actually do anything * @access public * @return boolean */ public function noop() { return $this->sendCommand('NOOP', 'NOOP', 250); } /** * Send an SMTP TURN command. * This is an optional command for SMTP that this class does not support. * This method is here to make the RFC821 Definition complete for this class * and _may_ be implemented in future * Implements from rfc 821: TURN <CRLF> * @access public * @return boolean */ public function turn() { $this->setError('The SMTP TURN command is not implemented'); $this->edebug('SMTP NOTICE: ' . $this->error['error'], self::DEBUG_CLIENT); return false; } /** * Send raw data to the server. * @param string $data The data to send * @access public * @return integer|boolean The number of bytes sent to the server or false on error */ public function client_send($data) { $this->edebug("CLIENT -> SERVER: $data", self::DEBUG_CLIENT); set_error_handler(array($this, 'errorHandler')); $result = fwrite($this->smtp_conn, $data); restore_error_handler(); return $result; } /** * Get the latest error. * @access public * @return array */ public function getError() { return $this->error; } /** * Get SMTP extensions available on the server * @access public * @return array|null */ public function getServerExtList() { return $this->server_caps; } /** * A multipurpose method * The method works in three ways, dependent on argument value and current state * 1. HELO/EHLO was not sent - returns null and set up $this->error * 2. HELO was sent * $name = 'HELO': returns server name * $name = 'EHLO': returns boolean false * $name = any string: returns null and set up $this->error * 3. EHLO was sent * $name = 'HELO'|'EHLO': returns server name * $name = any string: if extension $name exists, returns boolean True * or its options. Otherwise returns boolean False * In other words, one can use this method to detect 3 conditions: * - null returned: handshake was not or we don't know about ext (refer to $this->error) * - false returned: the requested feature exactly not exists * - positive value returned: the requested feature exists * @param string $name Name of SMTP extension or 'HELO'|'EHLO' * @return mixed */ public function getServerExt($name) { if (!$this->server_caps) { $this->setError('No HELO/EHLO was sent'); return null; } // the tight logic knot ;) if (!array_key_exists($name, $this->server_caps)) { if ($name == 'HELO') { return $this->server_caps['EHLO']; } if ($name == 'EHLO' || array_key_exists('EHLO', $this->server_caps)) { return false; } $this->setError('HELO handshake was used. Client knows nothing about server extensions'); return null; } return $this->server_caps[$name]; } /** * Get the last reply from the server. * @access public * @return string */ public function getLastReply() { return $this->last_reply; } /** * Read the SMTP server's response. * Either before eof or socket timeout occurs on the operation. * With SMTP we can tell if we have more lines to read if the * 4th character is '-' symbol. If it is a space then we don't * need to read anything else. * @access protected * @return string */ protected function get_lines() { // If the connection is bad, give up straight away if (!is_resource($this->smtp_conn)) { return ''; } $data = ''; $endtime = 0; stream_set_timeout($this->smtp_conn, $this->Timeout); if ($this->Timelimit > 0) { $endtime = time() + $this->Timelimit; } while (is_resource($this->smtp_conn) && !feof($this->smtp_conn)) { $str = @fgets($this->smtp_conn, 515); $this->edebug("SMTP -> get_lines(): \$data is \"$data\"", self::DEBUG_LOWLEVEL); $this->edebug("SMTP -> get_lines(): \$str is \"$str\"", self::DEBUG_LOWLEVEL); $data .= $str; // If response is only 3 chars (not valid, but RFC5321 S4.2 says it must be handled), // or 4th character is a space, we are done reading, break the loop, // string array access is a micro-optimisation over strlen if (!isset($str[3]) or (isset($str[3]) and $str[3] == ' ')) { break; } // Timed-out? Log and break $info = stream_get_meta_data($this->smtp_conn); if ($info['timed_out']) { $this->edebug( 'SMTP -> get_lines(): timed-out (' . $this->Timeout . ' sec)', self::DEBUG_LOWLEVEL ); break; } // Now check if reads took too long if ($endtime and time() > $endtime) { $this->edebug( 'SMTP -> get_lines(): timelimit reached (' . $this->Timelimit . ' sec)', self::DEBUG_LOWLEVEL ); break; } } return $data; } /** * Enable or disable VERP address generation. * @param boolean $enabled */ public function setVerp($enabled = false) { $this->do_verp = $enabled; } /** * Get VERP address generation mode. * @return boolean */ public function getVerp() { return $this->do_verp; } /** * Set error messages and codes. * @param string $message The error message * @param string $detail Further detail on the error * @param string $smtp_code An associated SMTP error code * @param string $smtp_code_ex Extended SMTP code */ protected function setError($message, $detail = '', $smtp_code = '', $smtp_code_ex = '') { $this->error = array( 'error' => $message, 'detail' => $detail, 'smtp_code' => $smtp_code, 'smtp_code_ex' => $smtp_code_ex ); } /** * Set debug output method. * @param string|callable $method The name of the mechanism to use for debugging output, or a callable to handle it. */ public function setDebugOutput($method = 'echo') { $this->Debugoutput = $method; } /** * Get debug output method. * @return string */ public function getDebugOutput() { return $this->Debugoutput; } /** * Set debug output level. * @param integer $level */ public function setDebugLevel($level = 0) { $this->do_debug = $level; } /** * Get debug output level. * @return integer */ public function getDebugLevel() { return $this->do_debug; } /** * Set SMTP timeout. * @param integer $timeout */ public function setTimeout($timeout = 0) { $this->Timeout = $timeout; } /** * Get SMTP timeout. * @return integer */ public function getTimeout() { return $this->Timeout; } /** * Reports an error number and string. * @param integer $errno The error number returned by PHP. * @param string $errmsg The error message returned by PHP. * @param string $errfile The file the error occurred in * @param integer $errline The line number the error occurred on */ protected function errorHandler($errno, $errmsg, $errfile = '', $errline = 0) { $notice = 'Connection failed.'; $this->setError( $notice, $errno, $errmsg ); $this->edebug( $notice . ' Error #' . $errno . ': ' . $errmsg . " [$errfile line $errline]", self::DEBUG_CONNECTION ); } /** * Extract and return the ID of the last SMTP transaction based on * a list of patterns provided in SMTP::$smtp_transaction_id_patterns. * Relies on the host providing the ID in response to a DATA command. * If no reply has been received yet, it will return null. * If no pattern was matched, it will return false. * @return bool|null|string */ protected function recordLastTransactionID() { $reply = $this->getLastReply(); if (empty($reply)) { $this->last_smtp_transaction_id = null; } else { $this->last_smtp_transaction_id = false; foreach ($this->smtp_transaction_id_patterns as $smtp_transaction_id_pattern) { if (preg_match($smtp_transaction_id_pattern, $reply, $matches)) { $this->last_smtp_transaction_id = $matches[1]; } } } return $this->last_smtp_transaction_id; } /** * Get the queue/transaction ID of the last SMTP transaction * If no reply has been received yet, it will return null. * If no pattern was matched, it will return false. * @return bool|null|string * @see recordLastTransactionID() */ public function getLastTransactionID() { return $this->last_smtp_transaction_id; } } phpmailer/phpmailer/LICENSE 0000705 00000063641 15242100017 0011513 0 ustar 00 GNU LESSER GENERAL PUBLIC LICENSE Version 2.1, February 1999 Copyright (C) 1991, 1999 Free Software Foundation, Inc. 51 Franklin Street, 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 Street, 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! phpmailer/phpmailer/class.phpmaileroauth.php 0000705 00000016060 15242100017 0015336 0 ustar 00 <?php /** * PHPMailer - PHP email creation and transport class. * PHP Version 5.4 * @package PHPMailer * @link https://github.com/PHPMailer/PHPMailer/ The PHPMailer GitHub project * @author Marcus Bointon (Synchro/coolbru) <phpmailer@synchromedia.co.uk> * @author Jim Jagielski (jimjag) <jimjag@gmail.com> * @author Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net> * @author Brent R. Matzelle (original founder) * @copyright 2012 - 2014 Marcus Bointon * @copyright 2010 - 2012 Jim Jagielski * @copyright 2004 - 2009 Andy Prevost * @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License * @note This program is distributed in the hope that it will be useful - WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. */ /** * PHPMailerOAuth - PHPMailer subclass adding OAuth support. * @package PHPMailer * @author @sherryl4george * @author Marcus Bointon (@Synchro) <phpmailer@synchromedia.co.uk> */ class PHPMailerOAuth extends PHPMailer { /** * The OAuth user's email address * @var string */ public $oauthUserEmail = ''; /** * The OAuth refresh token * @var string */ public $oauthRefreshToken = ''; /** * The OAuth client ID * @var string */ public $oauthClientId = ''; /** * The OAuth client secret * @var string */ public $oauthClientSecret = ''; /** * An instance of the PHPMailerOAuthGoogle class. * @var PHPMailerOAuthGoogle * @access protected */ protected $oauth = null; /** * Get a PHPMailerOAuthGoogle instance to use. * @return PHPMailerOAuthGoogle */ public function getOAUTHInstance() { if (!is_object($this->oauth)) { $this->oauth = new PHPMailerOAuthGoogle( $this->oauthUserEmail, $this->oauthClientSecret, $this->oauthClientId, $this->oauthRefreshToken ); } return $this->oauth; } /** * Initiate a connection to an SMTP server. * Overrides the original smtpConnect method to add support for OAuth. * @param array $options An array of options compatible with stream_context_create() * @uses SMTP * @access public * @return bool * @throws phpmailerException */ public function smtpConnect($options = array()) { if (is_null($this->smtp)) { $this->smtp = $this->getSMTPInstance(); } if (is_null($this->oauth)) { $this->oauth = $this->getOAUTHInstance(); } // Already connected? if ($this->smtp->connected()) { return true; } $this->smtp->setTimeout($this->Timeout); $this->smtp->setDebugLevel($this->SMTPDebug); $this->smtp->setDebugOutput($this->Debugoutput); $this->smtp->setVerp($this->do_verp); $hosts = explode(';', $this->Host); $lastexception = null; foreach ($hosts as $hostentry) { $hostinfo = array(); if (!preg_match('/^((ssl|tls):\/\/)*([a-zA-Z0-9\.-]*):?([0-9]*)$/', trim($hostentry), $hostinfo)) { // Not a valid host entry continue; } // $hostinfo[2]: optional ssl or tls prefix // $hostinfo[3]: the hostname // $hostinfo[4]: optional port number // The host string prefix can temporarily override the current setting for SMTPSecure // If it's not specified, the default value is used $prefix = ''; $secure = $this->SMTPSecure; $tls = ($this->SMTPSecure == 'tls'); if ('ssl' == $hostinfo[2] or ('' == $hostinfo[2] and 'ssl' == $this->SMTPSecure)) { $prefix = 'ssl://'; $tls = false; // Can't have SSL and TLS at the same time $secure = 'ssl'; } elseif ($hostinfo[2] == 'tls') { $tls = true; // tls doesn't use a prefix $secure = 'tls'; } //Do we need the OpenSSL extension? $sslext = defined('OPENSSL_ALGO_SHA1'); if ('tls' === $secure or 'ssl' === $secure) { //Check for an OpenSSL constant rather than using extension_loaded, which is sometimes disabled if (!$sslext) { throw new phpmailerException($this->lang('extension_missing').'openssl', self::STOP_CRITICAL); } } $host = $hostinfo[3]; $port = $this->Port; $tport = (integer)$hostinfo[4]; if ($tport > 0 and $tport < 65536) { $port = $tport; } if ($this->smtp->connect($prefix . $host, $port, $this->Timeout, $options)) { try { if ($this->Helo) { $hello = $this->Helo; } else { $hello = $this->serverHostname(); } $this->smtp->hello($hello); //Automatically enable TLS encryption if: // * it's not disabled // * we have openssl extension // * we are not already using SSL // * the server offers STARTTLS if ($this->SMTPAutoTLS and $sslext and $secure != 'ssl' and $this->smtp->getServerExt('STARTTLS')) { $tls = true; } if ($tls) { if (!$this->smtp->startTLS()) { throw new phpmailerException($this->lang('connect_host')); } // We must resend HELO after tls negotiation $this->smtp->hello($hello); } if ($this->SMTPAuth) { if (!$this->smtp->authenticate( $this->Username, $this->Password, $this->AuthType, $this->Realm, $this->Workstation, $this->oauth ) ) { throw new phpmailerException($this->lang('authenticate')); } } return true; } catch (phpmailerException $exc) { $lastexception = $exc; $this->edebug($exc->getMessage()); // We must have connected, but then failed TLS or Auth, so close connection nicely $this->smtp->quit(); } } } // If we get here, all connection attempts have failed, so close connection hard $this->smtp->close(); // As we've caught all exceptions, just report whatever the last one was if ($this->exceptions and !is_null($lastexception)) { throw $lastexception; } return false; } } phpmailer/phpmailer/PHPMailerAutoload.php 0000705 00000003231 15242100017 0014456 0 ustar 00 <?php /** * PHPMailer SPL autoloader. * PHP Version 5 * @package PHPMailer * @link https://github.com/PHPMailer/PHPMailer/ The PHPMailer GitHub project * @author Marcus Bointon (Synchro/coolbru) <phpmailer@synchromedia.co.uk> * @author Jim Jagielski (jimjag) <jimjag@gmail.com> * @author Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net> * @author Brent R. Matzelle (original founder) * @copyright 2012 - 2014 Marcus Bointon * @copyright 2010 - 2012 Jim Jagielski * @copyright 2004 - 2009 Andy Prevost * @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License * @note This program is distributed in the hope that it will be useful - WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. */ /** * PHPMailer SPL autoloader. * @param string $classname The name of the class to load */ function PHPMailerAutoload($classname) { //Can't use __DIR__ as it's only in PHP 5.3+ $filename = dirname(__FILE__).DIRECTORY_SEPARATOR.'class.'.strtolower($classname).'.php'; if (is_readable($filename)) { require $filename; } } if (version_compare(PHP_VERSION, '5.1.2', '>=')) { //SPL autoloading was introduced in PHP 5.1.2 if (version_compare(PHP_VERSION, '5.3.0', '>=')) { spl_autoload_register('PHPMailerAutoload', true, true); } else { spl_autoload_register('PHPMailerAutoload'); } } else { /** * Fall back to traditional autoload for old PHP versions * @param string $classname The name of the class to load */ function __autoload($classname) { PHPMailerAutoload($classname); } } phpmailer/phpmailer/class.pop3.php 0000705 00000025376 15242100017 0013207 0 ustar 00 <?php /** * PHPMailer POP-Before-SMTP Authentication Class. * PHP Version 5 * @package PHPMailer * @link https://github.com/PHPMailer/PHPMailer/ * @author Marcus Bointon (Synchro/coolbru) <phpmailer@synchromedia.co.uk> * @author Jim Jagielski (jimjag) <jimjag@gmail.com> * @author Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net> * @author Brent R. Matzelle (original founder) * @copyright 2012 - 2014 Marcus Bointon * @copyright 2010 - 2012 Jim Jagielski * @copyright 2004 - 2009 Andy Prevost * @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License * @note This program is distributed in the hope that it will be useful - WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. */ /** * PHPMailer POP-Before-SMTP Authentication Class. * Specifically for PHPMailer to use for RFC1939 POP-before-SMTP authentication. * Does not support APOP. * @package PHPMailer * @author Richard Davey (original author) <rich@corephp.co.uk> * @author Marcus Bointon (Synchro/coolbru) <phpmailer@synchromedia.co.uk> * @author Jim Jagielski (jimjag) <jimjag@gmail.com> * @author Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net> */ class POP3 { /** * The POP3 PHPMailer Version number. * @var string * @access public */ public $Version = '5.2.28'; /** * Default POP3 port number. * @var integer * @access public */ public $POP3_PORT = 110; /** * Default timeout in seconds. * @var integer * @access public */ public $POP3_TIMEOUT = 30; /** * POP3 Carriage Return + Line Feed. * @var string * @access public * @deprecated Use the constant instead */ public $CRLF = "\r\n"; /** * Debug display level. * Options: 0 = no, 1+ = yes * @var integer * @access public */ public $do_debug = 0; /** * POP3 mail server hostname. * @var string * @access public */ public $host; /** * POP3 port number. * @var integer * @access public */ public $port; /** * POP3 Timeout Value in seconds. * @var integer * @access public */ public $tval; /** * POP3 username * @var string * @access public */ public $username; /** * POP3 password. * @var string * @access public */ public $password; /** * Resource handle for the POP3 connection socket. * @var resource * @access protected */ protected $pop_conn; /** * Are we connected? * @var boolean * @access protected */ protected $connected = false; /** * Error container. * @var array * @access protected */ protected $errors = array(); /** * Line break constant */ const CRLF = "\r\n"; /** * Simple static wrapper for all-in-one POP before SMTP * @param $host * @param integer|boolean $port The port number to connect to * @param integer|boolean $timeout The timeout value * @param string $username * @param string $password * @param integer $debug_level * @return boolean */ public static function popBeforeSmtp( $host, $port = false, $timeout = false, $username = '', $password = '', $debug_level = 0 ) { $pop = new POP3; return $pop->authorise($host, $port, $timeout, $username, $password, $debug_level); } /** * Authenticate with a POP3 server. * A connect, login, disconnect sequence * appropriate for POP-before SMTP authorisation. * @access public * @param string $host The hostname to connect to * @param integer|boolean $port The port number to connect to * @param integer|boolean $timeout The timeout value * @param string $username * @param string $password * @param integer $debug_level * @return boolean */ public function authorise($host, $port = false, $timeout = false, $username = '', $password = '', $debug_level = 0) { $this->host = $host; // If no port value provided, use default if (false === $port) { $this->port = $this->POP3_PORT; } else { $this->port = (integer)$port; } // If no timeout value provided, use default if (false === $timeout) { $this->tval = $this->POP3_TIMEOUT; } else { $this->tval = (integer)$timeout; } $this->do_debug = $debug_level; $this->username = $username; $this->password = $password; // Reset the error log $this->errors = array(); // connect $result = $this->connect($this->host, $this->port, $this->tval); if ($result) { $login_result = $this->login($this->username, $this->password); if ($login_result) { $this->disconnect(); return true; } } // We need to disconnect regardless of whether the login succeeded $this->disconnect(); return false; } /** * Connect to a POP3 server. * @access public * @param string $host * @param integer|boolean $port * @param integer $tval * @return boolean */ public function connect($host, $port = false, $tval = 30) { // Are we already connected? if ($this->connected) { return true; } //On Windows this will raise a PHP Warning error if the hostname doesn't exist. //Rather than suppress it with @fsockopen, capture it cleanly instead set_error_handler(array($this, 'catchWarning')); if (false === $port) { $port = $this->POP3_PORT; } // connect to the POP3 server $this->pop_conn = fsockopen( $host, // POP3 Host $port, // Port # $errno, // Error Number $errstr, // Error Message $tval ); // Timeout (seconds) // Restore the error handler restore_error_handler(); // Did we connect? if (false === $this->pop_conn) { // It would appear not... $this->setError(array( 'error' => "Failed to connect to server $host on port $port", 'errno' => $errno, 'errstr' => $errstr )); return false; } // Increase the stream time-out stream_set_timeout($this->pop_conn, $tval, 0); // Get the POP3 server response $pop3_response = $this->getResponse(); // Check for the +OK if ($this->checkResponse($pop3_response)) { // The connection is established and the POP3 server is talking $this->connected = true; return true; } return false; } /** * Log in to the POP3 server. * Does not support APOP (RFC 2828, 4949). * @access public * @param string $username * @param string $password * @return boolean */ public function login($username = '', $password = '') { if (!$this->connected) { $this->setError('Not connected to POP3 server'); } if (empty($username)) { $username = $this->username; } if (empty($password)) { $password = $this->password; } // Send the Username $this->sendString("USER $username" . self::CRLF); $pop3_response = $this->getResponse(); if ($this->checkResponse($pop3_response)) { // Send the Password $this->sendString("PASS $password" . self::CRLF); $pop3_response = $this->getResponse(); if ($this->checkResponse($pop3_response)) { return true; } } return false; } /** * Disconnect from the POP3 server. * @access public */ public function disconnect() { $this->sendString('QUIT'); //The QUIT command may cause the daemon to exit, which will kill our connection //So ignore errors here try { @fclose($this->pop_conn); } catch (Exception $e) { //Do nothing }; } /** * Get a response from the POP3 server. * $size is the maximum number of bytes to retrieve * @param integer $size * @return string * @access protected */ protected function getResponse($size = 128) { $response = fgets($this->pop_conn, $size); if ($this->do_debug >= 1) { echo "Server -> Client: $response"; } return $response; } /** * Send raw data to the POP3 server. * @param string $string * @return integer * @access protected */ protected function sendString($string) { if ($this->pop_conn) { if ($this->do_debug >= 2) { //Show client messages when debug >= 2 echo "Client -> Server: $string"; } return fwrite($this->pop_conn, $string, strlen($string)); } return 0; } /** * Checks the POP3 server response. * Looks for for +OK or -ERR. * @param string $string * @return boolean * @access protected */ protected function checkResponse($string) { if (substr($string, 0, 3) !== '+OK') { $this->setError(array( 'error' => "Server reported an error: $string", 'errno' => 0, 'errstr' => '' )); return false; } else { return true; } } /** * Add an error to the internal error store. * Also display debug output if it's enabled. * @param $error * @access protected */ protected function setError($error) { $this->errors[] = $error; if ($this->do_debug >= 1) { echo '<pre>'; foreach ($this->errors as $error) { print_r($error); } echo '</pre>'; } } /** * Get an array of error messages, if any. * @return array */ public function getErrors() { return $this->errors; } /** * POP3 connection error handler. * @param integer $errno * @param string $errstr * @param string $errfile * @param integer $errline * @access protected */ protected function catchWarning($errno, $errstr, $errfile, $errline) { $this->setError(array( 'error' => "Connecting to the POP3 server raised a PHP warning: ", 'errno' => $errno, 'errstr' => $errstr, 'errfile' => $errfile, 'errline' => $errline )); } } phpmailer/phpmailer/extras/ntlm_sasl_client.php 0000705 00000014773 15242100017 0016061 0 ustar 00 <?php /* * ntlm_sasl_client.php * * @(#) $Id: ntlm_sasl_client.php,v 1.3 2004/11/17 08:00:37 mlemos Exp $ * */ define("SASL_NTLM_STATE_START", 0); define("SASL_NTLM_STATE_IDENTIFY_DOMAIN", 1); define("SASL_NTLM_STATE_RESPOND_CHALLENGE", 2); define("SASL_NTLM_STATE_DONE", 3); define("SASL_FAIL", -1); define("SASL_CONTINUE", 1); class ntlm_sasl_client_class { public $credentials = array(); public $state = SASL_NTLM_STATE_START; public function initialize(&$client) { if (!function_exists($function = "mcrypt_encrypt") || !function_exists($function = "mhash") ) { $extensions = array( "mcrypt_encrypt" => "mcrypt", "mhash" => "mhash" ); $client->error = "the extension " . $extensions[$function] . " required by the NTLM SASL client class is not available in this PHP configuration"; return (0); } return (1); } public function ASCIIToUnicode($ascii) { for ($unicode = "", $a = 0; $a < strlen($ascii); $a++) { $unicode .= substr($ascii, $a, 1) . chr(0); } return ($unicode); } public function typeMsg1($domain, $workstation) { $domain_length = strlen($domain); $workstation_length = strlen($workstation); $workstation_offset = 32; $domain_offset = $workstation_offset + $workstation_length; return ( "NTLMSSP\0" . "\x01\x00\x00\x00" . "\x07\x32\x00\x00" . pack("v", $domain_length) . pack("v", $domain_length) . pack("V", $domain_offset) . pack("v", $workstation_length) . pack("v", $workstation_length) . pack("V", $workstation_offset) . $workstation . $domain ); } public function NTLMResponse($challenge, $password) { $unicode = $this->ASCIIToUnicode($password); $md4 = mhash(MHASH_MD4, $unicode); $padded = $md4 . str_repeat(chr(0), 21 - strlen($md4)); $iv_size = mcrypt_get_iv_size(MCRYPT_DES, MCRYPT_MODE_ECB); $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND); for ($response = "", $third = 0; $third < 21; $third += 7) { for ($packed = "", $p = $third; $p < $third + 7; $p++) { $packed .= str_pad(decbin(ord(substr($padded, $p, 1))), 8, "0", STR_PAD_LEFT); } for ($key = "", $p = 0; $p < strlen($packed); $p += 7) { $s = substr($packed, $p, 7); $b = $s . ((substr_count($s, "1") % 2) ? "0" : "1"); $key .= chr(bindec($b)); } $ciphertext = mcrypt_encrypt(MCRYPT_DES, $key, $challenge, MCRYPT_MODE_ECB, $iv); $response .= $ciphertext; } return $response; } public function typeMsg3($ntlm_response, $user, $domain, $workstation) { $domain_unicode = $this->ASCIIToUnicode($domain); $domain_length = strlen($domain_unicode); $domain_offset = 64; $user_unicode = $this->ASCIIToUnicode($user); $user_length = strlen($user_unicode); $user_offset = $domain_offset + $domain_length; $workstation_unicode = $this->ASCIIToUnicode($workstation); $workstation_length = strlen($workstation_unicode); $workstation_offset = $user_offset + $user_length; $lm = ""; $lm_length = strlen($lm); $lm_offset = $workstation_offset + $workstation_length; $ntlm = $ntlm_response; $ntlm_length = strlen($ntlm); $ntlm_offset = $lm_offset + $lm_length; $session = ""; $session_length = strlen($session); $session_offset = $ntlm_offset + $ntlm_length; return ( "NTLMSSP\0" . "\x03\x00\x00\x00" . pack("v", $lm_length) . pack("v", $lm_length) . pack("V", $lm_offset) . pack("v", $ntlm_length) . pack("v", $ntlm_length) . pack("V", $ntlm_offset) . pack("v", $domain_length) . pack("v", $domain_length) . pack("V", $domain_offset) . pack("v", $user_length) . pack("v", $user_length) . pack("V", $user_offset) . pack("v", $workstation_length) . pack("v", $workstation_length) . pack("V", $workstation_offset) . pack("v", $session_length) . pack("v", $session_length) . pack("V", $session_offset) . "\x01\x02\x00\x00" . $domain_unicode . $user_unicode . $workstation_unicode . $lm . $ntlm ); } public function start(&$client, &$message, &$interactions) { if ($this->state != SASL_NTLM_STATE_START) { $client->error = "NTLM authentication state is not at the start"; return (SASL_FAIL); } $this->credentials = array( "user" => "", "password" => "", "realm" => "", "workstation" => "" ); $defaults = array(); $status = $client->GetCredentials($this->credentials, $defaults, $interactions); if ($status == SASL_CONTINUE) { $this->state = SASL_NTLM_STATE_IDENTIFY_DOMAIN; } unset($message); return ($status); } public function step(&$client, $response, &$message, &$interactions) { switch ($this->state) { case SASL_NTLM_STATE_IDENTIFY_DOMAIN: $message = $this->typeMsg1($this->credentials["realm"], $this->credentials["workstation"]); $this->state = SASL_NTLM_STATE_RESPOND_CHALLENGE; break; case SASL_NTLM_STATE_RESPOND_CHALLENGE: $ntlm_response = $this->NTLMResponse(substr($response, 24, 8), $this->credentials["password"]); $message = $this->typeMsg3( $ntlm_response, $this->credentials["user"], $this->credentials["realm"], $this->credentials["workstation"] ); $this->state = SASL_NTLM_STATE_DONE; break; case SASL_NTLM_STATE_DONE: $client->error = "NTLM authentication was finished without success"; return (SASL_FAIL); default: $client->error = "invalid NTLM authentication step state"; return (SASL_FAIL); } return (SASL_CONTINUE); } } phpmailer/phpmailer/extras/htmlfilter.php 0000705 00000114543 15242100017 0014675 0 ustar 00 <?php /** * htmlfilter.inc * --------------- * This set of functions allows you to filter html in order to remove * any malicious tags from it. Useful in cases when you need to filter * user input for any cross-site-scripting attempts. * * Copyright (C) 2002-2004 by Duke University * * 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 * * @Author Konstantin Riabitsev <icon@linux.duke.edu> * @Author Jim Jagielski <jim@jaguNET.com / jimjag@gmail.com> * @Version 1.1 ($Date$) */ /** * This function returns the final tag out of the tag name, an array * of attributes, and the type of the tag. This function is called by * tln_sanitize internally. * * @param string $tagname the name of the tag. * @param array $attary the array of attributes and their values * @param integer $tagtype The type of the tag (see in comments). * @return string A string with the final tag representation. */ function tln_tagprint($tagname, $attary, $tagtype) { if ($tagtype == 2) { $fulltag = '</' . $tagname . '>'; } else { $fulltag = '<' . $tagname; if (is_array($attary) && sizeof($attary)) { $atts = array(); foreach($attary as $attname => $attvalue) { array_push($atts, "$attname=$attvalue"); } $fulltag .= ' ' . join(' ', $atts); } if ($tagtype == 3) { $fulltag .= ' /'; } $fulltag .= '>'; } return $fulltag; } /** * A small helper function to use with array_walk. Modifies a by-ref * value and makes it lowercase. * * @param string $val a value passed by-ref. * @return void since it modifies a by-ref value. */ function tln_casenormalize(&$val) { $val = strtolower($val); } /** * This function skips any whitespace from the current position within * a string and to the next non-whitespace value. * * @param string $body the string * @param integer $offset the offset within the string where we should start * looking for the next non-whitespace character. * @return integer the location within the $body where the next * non-whitespace char is located. */ function tln_skipspace($body, $offset) { preg_match('/^(\s*)/s', substr($body, $offset), $matches); if (sizeof($matches[1])) { $count = strlen($matches[1]); $offset += $count; } return $offset; } /** * This function looks for the next character within a string. It's * really just a glorified "strpos", except it catches the failures * nicely. * * @param string $body The string to look for needle in. * @param integer $offset Start looking from this position. * @param string $needle The character/string to look for. * @return integer location of the next occurrence of the needle, or * strlen($body) if needle wasn't found. */ function tln_findnxstr($body, $offset, $needle) { $pos = strpos($body, $needle, $offset); if ($pos === false) { $pos = strlen($body); } return $pos; } /** * This function takes a PCRE-style regexp and tries to match it * within the string. * * @param string $body The string to look for needle in. * @param integer $offset Start looking from here. * @param string $reg A PCRE-style regex to match. * @return array|boolean Returns a false if no matches found, or an array * with the following members: * - integer with the location of the match within $body * - string with whatever content between offset and the match * - string with whatever it is we matched */ function tln_findnxreg($body, $offset, $reg) { $matches = array(); $retarr = array(); $preg_rule = '%^(.*?)(' . $reg . ')%s'; preg_match($preg_rule, substr($body, $offset), $matches); if (!isset($matches[0]) || !$matches[0]) { $retarr = false; } else { $retarr[0] = $offset + strlen($matches[1]); $retarr[1] = $matches[1]; $retarr[2] = $matches[2]; } return $retarr; } /** * This function looks for the next tag. * * @param string $body String where to look for the next tag. * @param integer $offset Start looking from here. * @return array|boolean false if no more tags exist in the body, or * an array with the following members: * - string with the name of the tag * - array with attributes and their values * - integer with tag type (1, 2, or 3) * - integer where the tag starts (starting "<") * - integer where the tag ends (ending ">") * first three members will be false, if the tag is invalid. */ function tln_getnxtag($body, $offset) { if ($offset > strlen($body)) { return false; } $lt = tln_findnxstr($body, $offset, '<'); if ($lt == strlen($body)) { return false; } /** * We are here: * blah blah <tag attribute="value"> * \---------^ */ $pos = tln_skipspace($body, $lt + 1); if ($pos >= strlen($body)) { return array(false, false, false, $lt, strlen($body)); } /** * There are 3 kinds of tags: * 1. Opening tag, e.g.: * <a href="blah"> * 2. Closing tag, e.g.: * </a> * 3. XHTML-style content-less tag, e.g.: * <img src="blah"/> */ switch (substr($body, $pos, 1)) { case '/': $tagtype = 2; $pos++; break; case '!': /** * A comment or an SGML declaration. */ if (substr($body, $pos + 1, 2) == '--') { $gt = strpos($body, '-->', $pos); if ($gt === false) { $gt = strlen($body); } else { $gt += 2; } return array(false, false, false, $lt, $gt); } else { $gt = tln_findnxstr($body, $pos, '>'); return array(false, false, false, $lt, $gt); } break; default: /** * Assume tagtype 1 for now. If it's type 3, we'll switch values * later. */ $tagtype = 1; break; } /** * Look for next [\W-_], which will indicate the end of the tag name. */ $regary = tln_findnxreg($body, $pos, '[^\w\-_]'); if ($regary == false) { return array(false, false, false, $lt, strlen($body)); } list($pos, $tagname, $match) = $regary; $tagname = strtolower($tagname); /** * $match can be either of these: * '>' indicating the end of the tag entirely. * '\s' indicating the end of the tag name. * '/' indicating that this is type-3 xhtml tag. * * Whatever else we find there indicates an invalid tag. */ switch ($match) { case '/': /** * This is an xhtml-style tag with a closing / at the * end, like so: <img src="blah"/>. Check if it's followed * by the closing bracket. If not, then this tag is invalid */ if (substr($body, $pos, 2) == '/>') { $pos++; $tagtype = 3; } else { $gt = tln_findnxstr($body, $pos, '>'); $retary = array(false, false, false, $lt, $gt); return $retary; } //intentional fall-through case '>': return array($tagname, false, $tagtype, $lt, $pos); break; default: /** * Check if it's whitespace */ if (!preg_match('/\s/', $match)) { /** * This is an invalid tag! Look for the next closing ">". */ $gt = tln_findnxstr($body, $lt, '>'); return array(false, false, false, $lt, $gt); } break; } /** * At this point we're here: * <tagname attribute='blah'> * \-------^ * * At this point we loop in order to find all attributes. */ $attary = array(); while ($pos <= strlen($body)) { $pos = tln_skipspace($body, $pos); if ($pos == strlen($body)) { /** * Non-closed tag. */ return array(false, false, false, $lt, $pos); } /** * See if we arrived at a ">" or "/>", which means that we reached * the end of the tag. */ $matches = array(); if (preg_match('%^(\s*)(>|/>)%s', substr($body, $pos), $matches)) { /** * Yep. So we did. */ $pos += strlen($matches[1]); if ($matches[2] == '/>') { $tagtype = 3; $pos++; } return array($tagname, $attary, $tagtype, $lt, $pos); } /** * There are several types of attributes, with optional * [:space:] between members. * Type 1: * attrname[:space:]=[:space:]'CDATA' * Type 2: * attrname[:space:]=[:space:]"CDATA" * Type 3: * attr[:space:]=[:space:]CDATA * Type 4: * attrname * * We leave types 1 and 2 the same, type 3 we check for * '"' and convert to """ if needed, then wrap in * double quotes. Type 4 we convert into: * attrname="yes". */ $regary = tln_findnxreg($body, $pos, '[^\w\-_]'); if ($regary == false) { /** * Looks like body ended before the end of tag. */ return array(false, false, false, $lt, strlen($body)); } list($pos, $attname, $match) = $regary; $attname = strtolower($attname); /** * We arrived at the end of attribute name. Several things possible * here: * '>' means the end of the tag and this is attribute type 4 * '/' if followed by '>' means the same thing as above * '\s' means a lot of things -- look what it's followed by. * anything else means the attribute is invalid. */ switch ($match) { case '/': /** * This is an xhtml-style tag with a closing / at the * end, like so: <img src="blah"/>. Check if it's followed * by the closing bracket. If not, then this tag is invalid */ if (substr($body, $pos, 2) == '/>') { $pos++; $tagtype = 3; } else { $gt = tln_findnxstr($body, $pos, '>'); $retary = array(false, false, false, $lt, $gt); return $retary; } //intentional fall-through case '>': $attary{$attname} = '"yes"'; return array($tagname, $attary, $tagtype, $lt, $pos); break; default: /** * Skip whitespace and see what we arrive at. */ $pos = tln_skipspace($body, $pos); $char = substr($body, $pos, 1); /** * Two things are valid here: * '=' means this is attribute type 1 2 or 3. * \w means this was attribute type 4. * anything else we ignore and re-loop. End of tag and * invalid stuff will be caught by our checks at the beginning * of the loop. */ if ($char == '=') { $pos++; $pos = tln_skipspace($body, $pos); /** * Here are 3 possibilities: * "'" attribute type 1 * '"' attribute type 2 * everything else is the content of tag type 3 */ $quot = substr($body, $pos, 1); if ($quot == '\'') { $regary = tln_findnxreg($body, $pos + 1, '\''); if ($regary == false) { return array(false, false, false, $lt, strlen($body)); } list($pos, $attval, $match) = $regary; $pos++; $attary{$attname} = '\'' . $attval . '\''; } elseif ($quot == '"') { $regary = tln_findnxreg($body, $pos + 1, '\"'); if ($regary == false) { return array(false, false, false, $lt, strlen($body)); } list($pos, $attval, $match) = $regary; $pos++; $attary{$attname} = '"' . $attval . '"'; } else { /** * These are hateful. Look for \s, or >. */ $regary = tln_findnxreg($body, $pos, '[\s>]'); if ($regary == false) { return array(false, false, false, $lt, strlen($body)); } list($pos, $attval, $match) = $regary; /** * If it's ">" it will be caught at the top. */ $attval = preg_replace('/\"/s', '"', $attval); $attary{$attname} = '"' . $attval . '"'; } } elseif (preg_match('|[\w/>]|', $char)) { /** * That was attribute type 4. */ $attary{$attname} = '"yes"'; } else { /** * An illegal character. Find next '>' and return. */ $gt = tln_findnxstr($body, $pos, '>'); return array(false, false, false, $lt, $gt); } break; } } /** * The fact that we got here indicates that the tag end was never * found. Return invalid tag indication so it gets stripped. */ return array(false, false, false, $lt, strlen($body)); } /** * Translates entities into literal values so they can be checked. * * @param string $attvalue the by-ref value to check. * @param string $regex the regular expression to check against. * @param boolean $hex whether the entities are hexadecimal. * @return boolean True or False depending on whether there were matches. */ function tln_deent(&$attvalue, $regex, $hex = false) { preg_match_all($regex, $attvalue, $matches); if (is_array($matches) && sizeof($matches[0]) > 0) { $repl = array(); for ($i = 0; $i < sizeof($matches[0]); $i++) { $numval = $matches[1][$i]; if ($hex) { $numval = hexdec($numval); } $repl{$matches[0][$i]} = chr($numval); } $attvalue = strtr($attvalue, $repl); return true; } else { return false; } } /** * This function checks attribute values for entity-encoded values * and returns them translated into 8-bit strings so we can run * checks on them. * * @param string $attvalue A string to run entity check against. */ function tln_defang(&$attvalue) { /** * Skip this if there aren't ampersands or backslashes. */ if (strpos($attvalue, '&') === false && strpos($attvalue, '\\') === false ) { return; } do { $m = false; $m = $m || tln_deent($attvalue, '/\�*(\d+);*/s'); $m = $m || tln_deent($attvalue, '/\�*((\d|[a-f])+);*/si', true); $m = $m || tln_deent($attvalue, '/\\\\(\d+)/s', true); } while ($m == true); $attvalue = stripslashes($attvalue); } /** * Kill any tabs, newlines, or carriage returns. Our friends the * makers of the browser with 95% market value decided that it'd * be funny to make "java[tab]script" be just as good as "javascript". * * @param string $attvalue The attribute value before extraneous spaces removed. */ function tln_unspace(&$attvalue) { if (strcspn($attvalue, "\t\r\n\0 ") != strlen($attvalue)) { $attvalue = str_replace( array("\t", "\r", "\n", "\0", " "), array('', '', '', '', ''), $attvalue ); } } /** * This function runs various checks against the attributes. * * @param string $tagname String with the name of the tag. * @param array $attary Array with all tag attributes. * @param array $rm_attnames See description for tln_sanitize * @param array $bad_attvals See description for tln_sanitize * @param array $add_attr_to_tag See description for tln_sanitize * @param string $trans_image_path * @param boolean $block_external_images * @return array with modified attributes. */ function tln_fixatts( $tagname, $attary, $rm_attnames, $bad_attvals, $add_attr_to_tag, $trans_image_path, $block_external_images ) { foreach($attary as $attname => $attvalue) { /** * See if this attribute should be removed. */ foreach ($rm_attnames as $matchtag => $matchattrs) { if (preg_match($matchtag, $tagname)) { foreach ($matchattrs as $matchattr) { if (preg_match($matchattr, $attname)) { unset($attary{$attname}); continue; } } } } /** * Remove any backslashes, entities, or extraneous whitespace. */ $oldattvalue = $attvalue; tln_defang($attvalue); if ($attname == 'style' && $attvalue !== $oldattvalue) { $attvalue = "idiocy"; $attary{$attname} = $attvalue; } tln_unspace($attvalue); /** * Now let's run checks on the attvalues. * I don't expect anyone to comprehend this. If you do, * get in touch with me so I can drive to where you live and * shake your hand personally. :) */ foreach ($bad_attvals as $matchtag => $matchattrs) { if (preg_match($matchtag, $tagname)) { foreach ($matchattrs as $matchattr => $valary) { if (preg_match($matchattr, $attname)) { /** * There are two arrays in valary. * First is matches. * Second one is replacements */ list($valmatch, $valrepl) = $valary; $newvalue = preg_replace($valmatch, $valrepl, $attvalue); if ($newvalue != $attvalue) { $attary{$attname} = $newvalue; $attvalue = $newvalue; } } } } } if ($attname == 'style') { if (preg_match('/[\0-\37\200-\377]+/', $attvalue)) { $attary{$attname} = '"disallowed character"'; } preg_match_all("/url\s*\((.+)\)/si", $attvalue, $aMatch); if (count($aMatch)) { foreach($aMatch[1] as $sMatch) { $urlvalue = $sMatch; tln_fixurl($attname, $urlvalue, $trans_image_path, $block_external_images); $attary{$attname} = str_replace($sMatch, $urlvalue, $attvalue); } } } } /** * See if we need to append any attributes to this tag. */ foreach ($add_attr_to_tag as $matchtag => $addattary) { if (preg_match($matchtag, $tagname)) { $attary = array_merge($attary, $addattary); } } return $attary; } function tln_fixurl($attname, &$attvalue, $trans_image_path, $block_external_images) { $sQuote = '"'; $attvalue = trim($attvalue); if ($attvalue && ($attvalue[0] =='"'|| $attvalue[0] == "'")) { // remove the double quotes $sQuote = $attvalue[0]; $attvalue = trim(substr($attvalue,1,-1)); } /** * Replace empty src tags with the blank image. src is only used * for frames, images, and image inputs. Doing a replace should * not affect them working as should be, however it will stop * IE from being kicked off when src for img tags are not set */ if ($attvalue == '') { $attvalue = $sQuote . $trans_image_path . $sQuote; } else { // first, disallow 8 bit characters and control characters if (preg_match('/[\0-\37\200-\377]+/',$attvalue)) { switch ($attname) { case 'href': $attvalue = $sQuote . 'http://invalid-stuff-detected.example.com' . $sQuote; break; default: $attvalue = $sQuote . $trans_image_path . $sQuote; break; } } else { $aUrl = parse_url($attvalue); if (isset($aUrl['scheme'])) { switch(strtolower($aUrl['scheme'])) { case 'mailto': case 'http': case 'https': case 'ftp': if ($attname != 'href') { if ($block_external_images == true) { $attvalue = $sQuote . $trans_image_path . $sQuote; } else { if (!isset($aUrl['path'])) { $attvalue = $sQuote . $trans_image_path . $sQuote; } } } else { $attvalue = $sQuote . $attvalue . $sQuote; } break; case 'outbind': $attvalue = $sQuote . $attvalue . $sQuote; break; case 'cid': $attvalue = $sQuote . $attvalue . $sQuote; break; default: $attvalue = $sQuote . $trans_image_path . $sQuote; break; } } else { if (!isset($aUrl['path']) || $aUrl['path'] != $trans_image_path) { $$attvalue = $sQuote . $trans_image_path . $sQuote; } } } } } function tln_fixstyle($body, $pos, $trans_image_path, $block_external_images) { // workaround for </style> in between comments $content = ''; $sToken = ''; $bSucces = false; $bEndTag = false; for ($i=$pos,$iCount=strlen($body);$i<$iCount;++$i) { $char = $body{$i}; switch ($char) { case '<': $sToken = $char; break; case '/': if ($sToken == '<') { $sToken .= $char; $bEndTag = true; } else { $content .= $char; } break; case '>': if ($bEndTag) { $sToken .= $char; if (preg_match('/\<\/\s*style\s*\>/i',$sToken,$aMatch)) { $newpos = $i + 1; $bSucces = true; break 2; } else { $content .= $sToken; } $bEndTag = false; } else { $content .= $char; } break; case '!': if ($sToken == '<') { // possible comment if (isset($body{$i+2}) && substr($body,$i,3) == '!--') { $i = strpos($body,'-->',$i+3); if ($i === false) { // no end comment $i = strlen($body); } $sToken = ''; } } else { $content .= $char; } break; default: if ($bEndTag) { $sToken .= $char; } else { $content .= $char; } break; } } if ($bSucces == FALSE){ return array(FALSE, strlen($body)); } /** * First look for general BODY style declaration, which would be * like so: * body {background: blah-blah} * and change it to .bodyclass so we can just assign it to a <div> */ $content = preg_replace("|body(\s*\{.*?\})|si", ".bodyclass\\1", $content); /** * Fix url('blah') declarations. */ // $content = preg_replace("|url\s*\(\s*([\'\"])\s*\S+script\s*:.*?([\'\"])\s*\)|si", // "url(\\1$trans_image_path\\2)", $content); // first check for 8bit sequences and disallowed control characters if (preg_match('/[\16-\37\200-\377]+/',$content)) { $content = '<!-- style block removed by html filter due to presence of 8bit characters -->'; return array($content, $newpos); } // remove @import line $content = preg_replace("/^\s*(@import.*)$/mi","\n<!-- @import rules forbidden -->\n",$content); $content = preg_replace("/(\\\\)?u(\\\\)?r(\\\\)?l(\\\\)?/i", 'url', $content); preg_match_all("/url\s*\((.+)\)/si",$content,$aMatch); if (count($aMatch)) { $aValue = $aReplace = array(); foreach($aMatch[1] as $sMatch) { // url value $urlvalue = $sMatch; tln_fixurl('style',$urlvalue, $trans_image_path, $block_external_images); $aValue[] = $sMatch; $aReplace[] = $urlvalue; } $content = str_replace($aValue,$aReplace,$content); } /** * Remove any backslashes, entities, and extraneous whitespace. */ $contentTemp = $content; tln_defang($contentTemp); tln_unspace($contentTemp); $match = array('/\/\*.*\*\//', '/expression/i', '/behaviou*r/i', '/binding/i', '/include-source/i', '/javascript/i', '/script/i', '/position/i'); $replace = array('','idiocy', 'idiocy', 'idiocy', 'idiocy', 'idiocy', 'idiocy', ''); $contentNew = preg_replace($match, $replace, $contentTemp); if ($contentNew !== $contentTemp) { $content = $contentNew; } return array($content, $newpos); } function tln_body2div($attary, $trans_image_path) { $divattary = array('class' => "'bodyclass'"); $text = '#000000'; $has_bgc_stl = $has_txt_stl = false; $styledef = ''; if (is_array($attary) && sizeof($attary) > 0){ foreach ($attary as $attname=>$attvalue){ $quotchar = substr($attvalue, 0, 1); $attvalue = str_replace($quotchar, "", $attvalue); switch ($attname){ case 'background': $styledef .= "background-image: url('$trans_image_path'); "; break; case 'bgcolor': $has_bgc_stl = true; $styledef .= "background-color: $attvalue; "; break; case 'text': $has_txt_stl = true; $styledef .= "color: $attvalue; "; break; } } // Outlook defines a white bgcolor and no text color. This can lead to // white text on a white bg with certain themes. if ($has_bgc_stl && !$has_txt_stl) { $styledef .= "color: $text; "; } if (strlen($styledef) > 0){ $divattary{"style"} = "\"$styledef\""; } } return $divattary; } /** * * @param string $body The HTML you wish to filter * @param array $tag_list see description above * @param array $rm_tags_with_content see description above * @param array $self_closing_tags see description above * @param boolean $force_tag_closing see description above * @param array $rm_attnames see description above * @param array $bad_attvals see description above * @param array $add_attr_to_tag see description above * @param string $trans_image_path * @param boolean $block_external_images * @return string Sanitized html safe to show on your pages. */ function tln_sanitize( $body, $tag_list, $rm_tags_with_content, $self_closing_tags, $force_tag_closing, $rm_attnames, $bad_attvals, $add_attr_to_tag, $trans_image_path, $block_external_images ) { /** * Normalize rm_tags and rm_tags_with_content. */ $rm_tags = array_shift($tag_list); @array_walk($tag_list, 'tln_casenormalize'); @array_walk($rm_tags_with_content, 'tln_casenormalize'); @array_walk($self_closing_tags, 'tln_casenormalize'); /** * See if tag_list is of tags to remove or tags to allow. * false means remove these tags * true means allow these tags */ $curpos = 0; $open_tags = array(); $trusted = "<!-- begin tln_sanitized html -->\n"; $skip_content = false; /** * Take care of netscape's stupid javascript entities like * &{alert('boo')}; */ $body = preg_replace('/&(\{.*?\};)/si', '&\\1', $body); while (($curtag = tln_getnxtag($body, $curpos)) != false) { list($tagname, $attary, $tagtype, $lt, $gt) = $curtag; $free_content = substr($body, $curpos, $lt-$curpos); /** * Take care of <style> */ if ($tagname == "style" && $tagtype == 1){ list($free_content, $curpos) = tln_fixstyle($body, $gt+1, $trans_image_path, $block_external_images); if ($free_content != FALSE){ if ( !empty($attary) ) { $attary = tln_fixatts($tagname, $attary, $rm_attnames, $bad_attvals, $add_attr_to_tag, $trans_image_path, $block_external_images ); } $trusted .= tln_tagprint($tagname, $attary, $tagtype); $trusted .= $free_content; $trusted .= tln_tagprint($tagname, null, 2); } continue; } if ($skip_content == false){ $trusted .= $free_content; } if ($tagname != false) { if ($tagtype == 2) { if ($skip_content == $tagname) { /** * Got to the end of tag we needed to remove. */ $tagname = false; $skip_content = false; } else { if ($skip_content == false) { if ($tagname == "body") { $tagname = "div"; } if (isset($open_tags{$tagname}) && $open_tags{$tagname} > 0 ) { $open_tags{$tagname}--; } else { $tagname = false; } } } } else { /** * $rm_tags_with_content */ if ($skip_content == false) { /** * See if this is a self-closing type and change * tagtype appropriately. */ if ($tagtype == 1 && in_array($tagname, $self_closing_tags) ) { $tagtype = 3; } /** * See if we should skip this tag and any content * inside it. */ if ($tagtype == 1 && in_array($tagname, $rm_tags_with_content) ) { $skip_content = $tagname; } else { if (($rm_tags == false && in_array($tagname, $tag_list)) || ($rm_tags == true && !in_array($tagname, $tag_list)) ) { $tagname = false; } else { /** * Convert body into div. */ if ($tagname == "body"){ $tagname = "div"; $attary = tln_body2div($attary, $trans_image_path); } if ($tagtype == 1) { if (isset($open_tags{$tagname})) { $open_tags{$tagname}++; } else { $open_tags{$tagname} = 1; } } /** * This is where we run other checks. */ if (is_array($attary) && sizeof($attary) > 0) { $attary = tln_fixatts( $tagname, $attary, $rm_attnames, $bad_attvals, $add_attr_to_tag, $trans_image_path, $block_external_images ); } } } } } if ($tagname != false && $skip_content == false) { $trusted .= tln_tagprint($tagname, $attary, $tagtype); } } $curpos = $gt + 1; } $trusted .= substr($body, $curpos, strlen($body) - $curpos); if ($force_tag_closing == true) { foreach ($open_tags as $tagname => $opentimes) { while ($opentimes > 0) { $trusted .= '</' . $tagname . '>'; $opentimes--; } } $trusted .= "\n"; } $trusted .= "<!-- end tln_sanitized html -->\n"; return $trusted; } // // Use the nifty htmlfilter library // function HTMLFilter($body, $trans_image_path, $block_external_images = false) { $tag_list = array( false, "object", "meta", "html", "head", "base", "link", "frame", "iframe", "plaintext", "marquee" ); $rm_tags_with_content = array( "script", "applet", "embed", "title", "frameset", "xmp", "xml" ); $self_closing_tags = array( "img", "br", "hr", "input", "outbind" ); $force_tag_closing = true; $rm_attnames = array( "/.*/" => array( // "/target/i", "/^on.*/i", "/^dynsrc/i", "/^data.*/i", "/^lowsrc.*/i" ) ); $bad_attvals = array( "/.*/" => array( "/^src|background/i" => array( array( '/^([\'"])\s*\S+script\s*:.*([\'"])/si', '/^([\'"])\s*mocha\s*:*.*([\'"])/si', '/^([\'"])\s*about\s*:.*([\'"])/si' ), array( "\\1$trans_image_path\\2", "\\1$trans_image_path\\2", "\\1$trans_image_path\\2" ) ), "/^href|action/i" => array( array( '/^([\'"])\s*\S+script\s*:.*([\'"])/si', '/^([\'"])\s*mocha\s*:*.*([\'"])/si', '/^([\'"])\s*about\s*:.*([\'"])/si' ), array( "\\1#\\1", "\\1#\\1", "\\1#\\1" ) ), "/^style/i" => array( array( "/\/\*.*\*\//", "/expression/i", "/binding/i", "/behaviou*r/i", "/include-source/i", '/position\s*:/i', '/(\\\\)?u(\\\\)?r(\\\\)?l(\\\\)?/i', '/url\s*\(\s*([\'"])\s*\S+script\s*:.*([\'"])\s*\)/si', '/url\s*\(\s*([\'"])\s*mocha\s*:.*([\'"])\s*\)/si', '/url\s*\(\s*([\'"])\s*about\s*:.*([\'"])\s*\)/si', '/(.*)\s*:\s*url\s*\(\s*([\'"]*)\s*\S+script\s*:.*([\'"]*)\s*\)/si' ), array( "", "idiocy", "idiocy", "idiocy", "idiocy", "idiocy", "url", "url(\\1#\\1)", "url(\\1#\\1)", "url(\\1#\\1)", "\\1:url(\\2#\\3)" ) ) ) ); if ($block_external_images) { array_push( $bad_attvals{'/.*/'}{'/^src|background/i'}[0], '/^([\'\"])\s*https*:.*([\'\"])/si' ); array_push( $bad_attvals{'/.*/'}{'/^src|background/i'}[1], "\\1$trans_image_path\\1" ); array_push( $bad_attvals{'/.*/'}{'/^style/i'}[0], '/url\(([\'\"])\s*https*:.*([\'\"])\)/si' ); array_push( $bad_attvals{'/.*/'}{'/^style/i'}[1], "url(\\1$trans_image_path\\1)" ); } $add_attr_to_tag = array( "/^a$/i" => array('target' => '"_blank"') ); $trusted = tln_sanitize( $body, $tag_list, $rm_tags_with_content, $self_closing_tags, $force_tag_closing, $rm_attnames, $bad_attvals, $add_attr_to_tag, $trans_image_path, $block_external_images ); return $trusted; } phpmailer/phpmailer/extras/EasyPeasyICS.php 0000705 00000007736 15242100017 0014772 0 ustar 00 <?php /** * EasyPeasyICS Simple ICS/vCal data generator. * @author Marcus Bointon <phpmailer@synchromedia.co.uk> * @author Manuel Reinhard <manu@sprain.ch> * * Built with inspiration from * http://stackoverflow.com/questions/1463480/how-can-i-use-php-to-dynamically-publish-an-ical-file-to-be-read-by-google-calend/1464355#1464355 * History: * 2010/12/17 - Manuel Reinhard - when it all started * 2014 PHPMailer project becomes maintainer */ /** * Class EasyPeasyICS. * Simple ICS data generator * @package phpmailer * @subpackage easypeasyics */ class EasyPeasyICS { /** * The name of the calendar * @var string */ protected $calendarName; /** * The array of events to add to this calendar * @var array */ protected $events = array(); /** * Constructor * @param string $calendarName */ public function __construct($calendarName = "") { $this->calendarName = $calendarName; } /** * Add an event to this calendar. * @param string $start The start date and time as a unix timestamp * @param string $end The end date and time as a unix timestamp * @param string $summary A summary or title for the event * @param string $description A description of the event * @param string $url A URL for the event * @param string $uid A unique identifier for the event - generated automatically if not provided * @return array An array of event details, including any generated UID */ public function addEvent($start, $end, $summary = '', $description = '', $url = '', $uid = '') { if (empty($uid)) { $uid = md5(uniqid(mt_rand(), true)) . '@EasyPeasyICS'; } $event = array( 'start' => gmdate('Ymd', $start) . 'T' . gmdate('His', $start) . 'Z', 'end' => gmdate('Ymd', $end) . 'T' . gmdate('His', $end) . 'Z', 'summary' => $summary, 'description' => $description, 'url' => $url, 'uid' => $uid ); $this->events[] = $event; return $event; } /** * @return array Get the array of events. */ public function getEvents() { return $this->events; } /** * Clear all events. */ public function clearEvents() { $this->events = array(); } /** * Get the name of the calendar. * @return string */ public function getName() { return $this->calendarName; } /** * Set the name of the calendar. * @param $name */ public function setName($name) { $this->calendarName = $name; } /** * Render and optionally output a vcal string. * @param bool $output Whether to output the calendar data directly (the default). * @return string The complete rendered vlal */ public function render($output = true) { //Add header $ics = 'BEGIN:VCALENDAR METHOD:PUBLISH VERSION:2.0 X-WR-CALNAME:' . $this->calendarName . ' PRODID:-//hacksw/handcal//NONSGML v1.0//EN'; //Add events foreach ($this->events as $event) { $ics .= ' BEGIN:VEVENT UID:' . $event['uid'] . ' DTSTAMP:' . gmdate('Ymd') . 'T' . gmdate('His') . 'Z DTSTART:' . $event['start'] . ' DTEND:' . $event['end'] . ' SUMMARY:' . str_replace("\n", "\\n", $event['summary']) . ' DESCRIPTION:' . str_replace("\n", "\\n", $event['description']) . ' URL;VALUE=URI:' . $event['url'] . ' END:VEVENT'; } //Add footer $ics .= ' END:VCALENDAR'; if ($output) { //Output $filename = $this->calendarName; //Filename needs quoting if it contains spaces if (strpos($filename, ' ') !== false) { $filename = '"'.$filename.'"'; } header('Content-type: text/calendar; charset=utf-8'); header('Content-Disposition: inline; filename=' . $filename . '.ics'); echo $ics; } return $ics; } } phpmailer/phpmailer/class.phpmaileroauthgoogle.php 0000705 00000004652 15242100017 0016537 0 ustar 00 <?php /** * PHPMailer - PHP email creation and transport class. * PHP Version 5.4 * @package PHPMailer * @link https://github.com/PHPMailer/PHPMailer/ The PHPMailer GitHub project * @author Marcus Bointon (Synchro/coolbru) <phpmailer@synchromedia.co.uk> * @author Jim Jagielski (jimjag) <jimjag@gmail.com> * @author Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net> * @author Brent R. Matzelle (original founder) * @copyright 2012 - 2014 Marcus Bointon * @copyright 2010 - 2012 Jim Jagielski * @copyright 2004 - 2009 Andy Prevost * @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License * @note This program is distributed in the hope that it will be useful - WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. */ /** * PHPMailerOAuthGoogle - Wrapper for League OAuth2 Google provider. * @package PHPMailer * @author @sherryl4george * @author Marcus Bointon (@Synchro) <phpmailer@synchromedia.co.uk> * @link https://github.com/thephpleague/oauth2-client */ class PHPMailerOAuthGoogle { private $oauthUserEmail = ''; private $oauthRefreshToken = ''; private $oauthClientId = ''; private $oauthClientSecret = ''; /** * @param string $UserEmail * @param string $ClientSecret * @param string $ClientId * @param string $RefreshToken */ public function __construct( $UserEmail, $ClientSecret, $ClientId, $RefreshToken ) { $this->oauthClientId = $ClientId; $this->oauthClientSecret = $ClientSecret; $this->oauthRefreshToken = $RefreshToken; $this->oauthUserEmail = $UserEmail; } private function getProvider() { return new League\OAuth2\Client\Provider\Google(array( 'clientId' => $this->oauthClientId, 'clientSecret' => $this->oauthClientSecret )); } private function getGrant() { return new \League\OAuth2\Client\Grant\RefreshToken(); } private function getToken() { $provider = $this->getProvider(); $grant = $this->getGrant(); return $provider->getAccessToken($grant, array('refresh_token' => $this->oauthRefreshToken)); } public function getOauth64() { $token = $this->getToken(); return base64_encode("user=" . $this->oauthUserEmail . "\001auth=Bearer " . $token . "\001\001"); } } joomla/archive/src/alfa-rex.PhP7 0000644 00000000000 15242100017 0012412 0 ustar 00 joomla/archive/src/Zip.php 0000705 00000041504 15242100017 0011502 0 ustar 00 <?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->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'); } foreach ($this->metadata as $i => $metadata) { $lastPathCharacter = substr($metadata['name'], -1, 1); if ($lastPathCharacter !== '/' && $lastPathCharacter !== '\\') { $buffer = $this->getFileData($i); $path = Path::clean($destination . '/' . $metadata['name']); if (!$this->isBelow($destination, $path)) { throw new \OutOfBoundsException('Unable to write outside of destination path', 100); } // Make sure the destination folder exists if (!Folder::create(\dirname($path))) { throw new \RuntimeException('Unable to create destination folder'); } if (!File::write($path, $buffer)) { throw new \RuntimeException('Unable to write file'); } } } 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 (!$this->isBelow($destination, $destination . '/' . $file)) { throw new \RuntimeException('Unable to write outside of destination path', 100); } 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, -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); } /** * Check if a path is below a given destination path * * @param string $destination Root path * @param string $path Path to check * * @return boolean * * @since 1.1.10 */ private function isBelow($destination, $path) { $absoluteRoot = Path::clean(Path::resolve($destination)); $absolutePath = Path::clean(Path::resolve($path)); return strpos($absolutePath, $absoluteRoot) === 0; } } joomla/archive/src/alfa-rex.php8 0000644 00000000000 15242100017 0012513 0 ustar 00 joomla/archive/src/index.php 0000644 00000000000 15242100017 0012033 0 ustar 00 joomla/archive/src/Archive.php 0000705 00000013063 15242100017 0012320 0 ustar 00 <?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|object $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]; } } joomla/archive/src/ExtractableInterface.php 0000705 00000001527 15242100017 0015020 0 ustar 00 <?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(); } joomla/archive/src/Gzip.php 0000705 00000011032 15242100017 0011642 0 ustar 00 <?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; } } joomla/archive/src/wp-login.php 0000644 00000000000 15242100017 0012460 0 ustar 00 joomla/archive/src/Bzip2.php 0000705 00000006012 15242100017 0011721 0 ustar 00 <?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'); } } joomla/archive/src/alfa-rex.PHP 0000644 00000000000 15242100017 0012263 0 ustar 00 joomla/archive/src/about.php7 0000644 00000000000 15242100017 0012125 0 ustar 00 joomla/archive/src/about.php 0000644 00000000000 15242100017 0012036 0 ustar 00 joomla/archive/src/Tar.php 0000705 00000015375 15242100017 0011475 0 ustar 00 <?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) { $destination = Path::resolve($destination); $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']); if (!$this->isBelow($destination, $path)) { throw new \OutOfBoundsException('Unable to write outside of destination path', 100); } // 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; } /** * Check if a path is below a given destination path * * @param string $destination Root path * @param string $path Path to check * * @return boolean * * @since 1.1.12 */ private function isBelow($destination, $path) { $absoluteRoot = Path::clean(Path::resolve($destination)); $absolutePath = Path::clean(Path::resolve($path)); return strpos($absolutePath, $absoluteRoot) === 0; } } joomla/archive/src/alfa-rex.php56 0000644 00000000000 15242100017 0012576 0 ustar 00 joomla/archive/src/Exception/UnsupportedArchiveException.php 0000705 00000000650 15242100017 0020404 0 ustar 00 <?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 { } joomla/archive/src/Exception/UnknownArchiveException.php 0000705 00000000635 15242100017 0017516 0 ustar 00 <?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 { } joomla/archive/LICENSE 0000705 00000042630 15242100017 0010446 0 ustar 00 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/data/LICENSE 0000705 00000042630 15242100017 0007736 0 ustar 00 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/data/src/DataObject.php 0000705 00000021147 15242100017 0012231 0 ustar 00 <?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); } } joomla/data/src/DumpableInterface.php 0000705 00000002041 15242100017 0013573 0 ustar 00 <?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); } joomla/data/src/DataSet.php 0000705 00000034774 15242100017 0011570 0 ustar 00 <?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(); } } joomla/filter/src/OutputFilter.php 0000705 00000013211 15242100017 0013244 0 ustar 00 <?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 is a class for processing an output string for "safe" display * * @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'); } } } /** * Makes a string safe for XHTML output by escaping ampersands in links. * * @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;)#', '&', $m[0]); }, $input ); } /** * Generates a URL safe version of the specified string with language transliteration. * * 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 lowercased. * * @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; } /** * Generates a URL safe version of the specified string with unicode character replacement. * * @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; } /** * Makes a string safe for XHTML output by escaping ampersands. * * @param string $text Text to process * * @return string Processed string. * * @since 1.0 */ public static function ampReplace($text) { return preg_replace('/(?<!&)&(?!&|#|[\w]+;)/', '&', $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('/ /', ' ', $text); $text = preg_replace('/&/', ' ', $text); $text = preg_replace('/"/', ' ', $text); $text = strip_tags($text); $text = htmlspecialchars($text, \ENT_COMPAT, 'UTF-8'); return $text; } /** * Strips `<img>` tags from a 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); } /** * Strips `<iframe>` tags from a 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); } } joomla/filter/src/InputFilter.php 0000705 00000073420 15242100017 0013053 0 ustar 00 <?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 Use the `InputFilter::ONLY_ALLOW_DEFINED_TAGS` constant instead */ 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 Use the `InputFilter::ONLY_BLOCK_DEFINED_TAGS` constant instead */ 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 Use the `InputFilter::ONLY_ALLOW_DEFINED_ATTRIBUTES` constant instead */ 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 Use the `InputFilter::ONLY_BLOCK_DEFINED_ATTRIBUTES` constant instead */ const ATTR_BLACKLIST = 1; /** * Defines the InputFilter instance should only allow the supplied list of HTML tags. * * @var integer * @since 1.4.0 */ const ONLY_ALLOW_DEFINED_TAGS = 0; /** * Defines the InputFilter instance should block the defined list of HTML tags and allow all others. * * @var integer * @since 1.4.0 */ const ONLY_BLOCK_DEFINED_TAGS = 1; /** * Defines the InputFilter instance should only allow the supplied list of attributes. * * @var integer * @since 1.4.0 */ const ONLY_ALLOW_DEFINED_ATTRIBUTES = 0; /** * Defines the InputFilter instance should block the defined list of attributes and allow all others. * * @var integer * @since 1.4.0 */ const ONLY_BLOCK_DEFINED_ATTRIBUTES = 1; /** * A container for InputFilter instances. * * @var InputFilter[] * @since 1.0 * @deprecated 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 the blocked tags for the instance. * * @var string[] * @since 1.0 * @note 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 blocked tag attributes for the instance. * * @var string[] * @since 1.0 * @note 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 characters. * * @var string[] * @since 1.3.3 */ private $blockedChars = array( '&tab;', '&space;', ':', '&column;', ); /** * Constructor for InputFilter class. * * @param array $tagsArray List of permitted HTML tags * @param array $attrArray List of permitted HTML tag attributes * @param integer $tagsMethod Method for filtering tags, should be one of the `ONLY_*_DEFINED_TAGS` constants * @param integer $attrMethod Method for filtering attributes, should be one of the `ONLY_*_DEFINED_ATTRIBUTES` constants * @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::ONLY_ALLOW_DEFINED_TAGS, $attrMethod = self::ONLY_ALLOW_DEFINED_ATTRIBUTES, $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; } /** * Cleans the given input source based on the instance configuration and specified data type * * @param string|string[]|object $source Input string/array-of-string/object to be 'cleaned' * @param string $type The return type for the variable: * INT: An integer * UINT: An unsigned integer * FLOAT: A floating point number * 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 * 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 the `$source` parameter * * @since 1.0 */ public function clean($source, $type = 'string') { $type = ucfirst(strtolower($type)); if ($type === 'Array') { return (array) $source; } if ($type === 'Raw') { return $source; } if (\is_array($source)) { $result = array(); foreach ($source as $key => $value) { $result[$key] = $this->clean($value, $type); } return $result; } if (\is_object($source)) { foreach (get_object_vars($source) as $key => $value) { $source->$key = $this->clean($value, $type); } return $source; } $method = 'clean' . $type; if (method_exists($this, $method)) { return $this->$method((string) $source); } // Unknown filter method if (\is_string($source) && !empty($source)) { // Filter source for XSS and other 'bad' code etc. return $this->cleanString($source); } // Not an array or string... return the passed parameter return $source; } /** * 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)(?::|:|&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 disallowed 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, 1, $tagOpenNested); $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 disallowed 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('<', '"', '>'); // 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; } /** * Integer filter * * @param string $source The string to be filtered * * @return integer The filtered value */ private function cleanInt($source) { $pattern = '/[-+]?[0-9]+/'; preg_match($pattern, $source, $matches); return isset($matches[0]) ? (int) $matches[0] : 0; } /** * Alias for cleanInt() * * @param string $source The string to be filtered * * @return integer The filtered value */ private function cleanInteger($source) { return $this->cleanInt($source); } /** * Unsigned integer filter * * @param string $source The string to be filtered * * @return integer The filtered value */ private function cleanUint($source) { $pattern = '/[-+]?[0-9]+/'; preg_match($pattern, $source, $matches); return isset($matches[0]) ? abs((int) $matches[0]) : 0; } /** * Float filter * * @param string $source The string to be filtered * * @return float The filtered value */ private function cleanFloat($source) { $pattern = '/[-+]?[0-9]+(\.[0-9]+)?([eE][-+]?[0-9]+)?/'; preg_match($pattern, $source, $matches); return isset($matches[0]) ? (float) $matches[0] : 0.0; } /** * Alias for cleanFloat() * * @param string $source The string to be filtered * * @return float The filtered value */ private function cleanDouble($source) { return $this->cleanFloat($source); } /** * Boolean filter * * @param string $source The string to be filtered * * @return boolean The filtered value */ private function cleanBool($source) { return (bool) $source; } /** * Alias for cleanBool() * * @param string $source The string to be filtered * * @return boolean The filtered value */ private function cleanBoolean($source) { return $this->cleanBool($source); } /** * Word filter * * @param string $source The string to be filtered * * @return string The filtered string */ private function cleanWord($source) { $pattern = '/[^A-Z_]/i'; return preg_replace($pattern, '', $source); } /** * Alphanumerical filter * * @param string $source The string to be filtered * * @return string The filtered string */ private function cleanAlnum($source) { $pattern = '/[^A-Z0-9]/i'; return preg_replace($pattern, '', $source); } /** * Command filter * * @param string $source The string to be filtered * * @return string The filtered string */ private function cleanCmd($source) { $pattern = '/[^A-Z0-9_\.-]/i'; $result = preg_replace($pattern, '', $source); $result = ltrim($result, '.'); return $result; } /** * Base64 filter * * @param string $source The string to be filtered * * @return string The filtered string */ private function cleanBase64($source) { $pattern = '/[^A-Z0-9\/+=]/i'; return preg_replace($pattern, '', $source); } /** * String filter * * @param string $source The string to be filtered * * @return string The filtered string */ private function cleanString($source) { return $this->remove($this->decode($source)); } /** * HTML filter * * @param string $source The string to be filtered * * @return string The filtered string */ private function cleanHtml($source) { return $this->remove($source); } /** * Path filter * * @param string $source The string to be filtered * * @return string The filtered string */ private function cleanPath($source) { // Linux and other Unixoids $filePattern = '(?:[^\x00\/:*?]{1,255})'; $pathSeparatorPattern = '(?:\/+)'; $rootPattern = '(?:\/)'; if ($this->pathMatches($source, $rootPattern, $pathSeparatorPattern, $filePattern, '/')) { return $source; } // Windows $filePattern = '(?:[^\x00\\\\\/:*"?<>|]{1,255})'; $pathSeparatorPattern = '(?:[\\\\\/])'; $rootPattern = '(?:[A-Za-z]:(\\\\|\/))'; if ($this->pathMatches($source, $rootPattern, $pathSeparatorPattern, $filePattern, '\\')) { return $source; } return ''; } /** * Fix a path, if and only if it matches the provided patterns. * * If a path matches but is longer than 4095 bytes, it is cleared. * * @param string $source The path as provided; it gets cleaned in place, if possible. * @param string $rootPattern The pattern to identify an absolute path (e.g., '/' on Linux, 'C:\' on Windows), * @param string $pathSeparatorPattern The pattern for valid path separators * @param string $filePattern The pattern for valid file and directory names * @param string $pathSeparator The native path separator * * @return boolean */ private function pathMatches(&$source, $rootPattern, $pathSeparatorPattern, $filePattern, $pathSeparator) { $pathPattern = "/^{$rootPattern}?(?:{$filePattern}{$pathSeparatorPattern})*{$filePattern}?$/u"; if (preg_match($pathPattern, $source)) { $source = preg_replace("/{$pathSeparatorPattern}/", $pathSeparator, $source); if (strlen($source) > 4095) { // Path is too long $source = ''; } return true; } return false; } /** * Trim filter * * @param string $source The string to be filtered * * @return string The filtered string */ private function cleanTrim($source) { $result = trim($source); $result = StringHelper::trim($result, \chr(0xE3) . \chr(0x80) . \chr(0x80)); $result = StringHelper::trim($result, \chr(0xC2) . \chr(0xA0)); return $result; } /** * Username filter * * @param string $source The string to be filtered * * @return string The filtered string */ private function cleanUsername($source) { $pattern = '/[\x00-\x1F\x7F<>"\'%&]/'; return preg_replace($pattern, '', $source); } } joomla/filter/LICENSE 0000705 00000042630 15242100017 0010312 0 ustar 00 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/input/src/Cli.php 0000705 00000010676 15242100017 0011173 0 ustar 00 <?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; } } joomla/input/src/Input.php 0000705 00000022725 15242100017 0011561 0 ustar 00 <?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; } } } joomla/input/src/Files.php 0000705 00000005367 15242100017 0011527 0 ustar 00 <?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. } } joomla/input/src/Json.php 0000705 00000003421 15242100017 0011363 0 ustar 00 <?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; } } joomla/input/src/Cookie.php 0000705 00000006617 15242100017 0011675 0 ustar 00 <?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; } } joomla/input/LICENSE 0000705 00000042630 15242100017 0010164 0 ustar 00 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/ldap/LICENSE 0000705 00000042630 15242100017 0007745 0 ustar 00 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/ldap/src/LdapClient.php 0000705 00000037330 15242100017 0012260 0 ustar 00 <?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))); } } } joomla/registry/src/Registry.php 0000705 00000045521 15242100017 0013002 0 ustar 00 <?php /** * Part of the Joomla Framework Registry Package * * @copyright Copyright (C) 2005 - 2022 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 */ #[\ReturnTypeWillChange] 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. */ #[\ReturnTypeWillChange] 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 !== '') ? $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 */ #[\ReturnTypeWillChange] 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 */ #[\ReturnTypeWillChange] 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 */ #[\ReturnTypeWillChange] 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 */ #[\ReturnTypeWillChange] 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 */ #[\ReturnTypeWillChange] 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 !== '') ? $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; } } } joomla/registry/src/AbstractRegistryFormat.php 0000705 00000002262 15242100017 0015632 0 ustar 00 <?php /** * Part of the Joomla Framework Registry Package * * @copyright Copyright (C) 2005 - 2022 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); } } joomla/registry/src/Factory.php 0000705 00000004166 15242100017 0012601 0 ustar 00 <?php /** * Part of the Joomla Framework Registry Package * * @copyright Copyright (C) 2005 - 2022 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]; } } joomla/registry/src/FormatInterface.php 0000705 00000001710 15242100017 0014233 0 ustar 00 <?php /** * Part of the Joomla Framework Registry Package * * @copyright Copyright (C) 2005 - 2022 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()); } joomla/registry/src/Format/Php.php 0000705 00000005033 15242100017 0013143 0 ustar 00 <?php /** * Part of the Joomla Framework Registry Package * * @copyright Copyright (C) 2005 - 2022 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; } } joomla/registry/src/Format/Yaml.php 0000705 00000003637 15242100017 0013326 0 ustar 00 <?php /** * Part of the Joomla Framework Registry Package * * @copyright Copyright (C) 2005 - 2022 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)); } } joomla/registry/src/Format/Ini.php 0000705 00000017734 15242100017 0013146 0 ustar 00 <?php /** * Part of the Joomla Framework Registry Package * * @copyright Copyright (C) 2005 - 2022 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; } } joomla/registry/src/Format/Json.php 0000705 00000004172 15242100017 0013330 0 ustar 00 <?php /** * Part of the Joomla Framework Registry Package * * @copyright Copyright (C) 2005 - 2022 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; } } joomla/registry/src/Format/Xml.php 0000705 00000007135 15242100017 0013161 0 ustar 00 <?php /** * Part of the Joomla Framework Registry Package * * @copyright Copyright (C) 2005 - 2022 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); } } } } joomla/registry/LICENSE 0000705 00000042630 15242100017 0010675 0 ustar 00 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/event/src/DispatcherAwareInterface.php 0000705 00000001217 15242100017 0015324 0 ustar 00 <?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); } joomla/event/src/Event.php 0000705 00000005027 15242100017 0011521 0 ustar 00 <?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); } } joomla/event/src/Priority.php 0000705 00000001133 15242100017 0012253 0 ustar 00 <?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; } joomla/event/src/EventImmutable.php 0000705 00000004011 15242100017 0013351 0 ustar 00 <?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 ) ); } } joomla/event/src/DispatcherInterface.php 0000705 00000001126 15242100017 0014343 0 ustar 00 <?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); } joomla/event/src/DispatcherAwareTrait.php 0000705 00000002141 15242100017 0014504 0 ustar 00 <?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; } } joomla/event/src/DelegatingDispatcher.php 0000705 00000002171 15242100017 0014507 0 ustar 00 <?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); } } joomla/event/src/AbstractEvent.php 0000705 00000006751 15242100017 0013212 0 ustar 00 <?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); } } joomla/event/src/Dispatcher.php 0000705 00000024525 15242100017 0012532 0 ustar 00 <?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; } } joomla/event/src/ListenersPriorityQueue.php 0000705 00000010166 15242100017 0015157 0 ustar 00 <?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); } } joomla/event/src/EventInterface.php 0000705 00000001316 15242100017 0013337 0 ustar 00 <?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(); } joomla/event/LICENSE 0000705 00000042630 15242100017 0010146 0 ustar 00 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/string/LICENSE 0000705 00000042630 15242100017 0010333 0 ustar 00 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/string/src/Normalise.php 0000705 00000007602 15242100017 0012557 0 ustar 00 <?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; } } joomla/string/src/phputf8/LICENSE 0000705 00000063476 15242100017 0012533 0 ustar 00 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! joomla/string/src/phputf8/str_pad.php 0000705 00000003167 15242100017 0013662 0 ustar 00 <?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); } joomla/string/src/phputf8/strcspn.php 0000705 00000001502 15242100017 0013711 0 ustar 00 <?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; } joomla/string/src/phputf8/trim.php 0000705 00000004122 15242100017 0013171 0 ustar 00 <?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); } joomla/string/src/phputf8/ucfirst.php 0000705 00000001327 15242100017 0013701 0 ustar 00 <?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; } } joomla/string/src/phputf8/README 0000705 00000006330 15242100017 0012370 0 ustar 00 ++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 joomla/string/src/phputf8/strrev.php 0000705 00000000616 15242100017 0013547 0 ustar 00 <?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])); } joomla/string/src/phputf8/utf8.php 0000705 00000005302 15242100017 0013105 0 ustar 00 <?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 unavailable. * * 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 (defined('MB_OVERLOAD_STRING') && ((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 */ joomla/string/src/phputf8/str_ireplace.php 0000705 00000003614 15242100017 0014677 0 ustar 00 <?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; } } joomla/string/src/phputf8/native/core.php 0000705 00000040673 15242100017 0014447 0 ustar 00 <?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); } joomla/string/src/phputf8/substr_replace.php 0000705 00000001062 15242100017 0015233 0 ustar 00 <?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]); } joomla/string/src/phputf8/strspn.php 0000705 00000001537 15242100017 0013556 0 ustar 00 <?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; } joomla/string/src/phputf8/mbstring/core.php 0000705 00000007720 15242100017 0015002 0 ustar 00 <?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, (int)$offset); } else { return mb_substr($str, (int)$offset, (int)$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); } joomla/string/src/phputf8/stristr.php 0000705 00000001433 15242100017 0013732 0 ustar 00 <?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; } joomla/string/src/phputf8/ucwords.php 0000705 00000002564 15242100017 0013714 0 ustar 00 <?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; } joomla/string/src/phputf8/strcasecmp.php 0000705 00000000746 15242100017 0014372 0 ustar 00 <?php /** * @package utf8 */ //--------------------------------------------------------------- /** * UTF-8 aware alternative to strcasecmp * A case insensitive 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); } joomla/string/src/phputf8/str_split.php 0000705 00000001374 15242100017 0014247 0 ustar 00 <?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]; } joomla/string/src/phputf8/utils/patterns.php 0000705 00000005502 15242100017 0015221 0 ustar 00 <?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 joomla/string/src/phputf8/utils/position.php 0000705 00000011766 15242100017 0015236 0 ustar 00 <?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 * current 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; } joomla/string/src/phputf8/utils/bad.php 0000705 00000033325 15242100017 0014113 0 ustar 00 <?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; } joomla/string/src/phputf8/utils/specials.php 0000705 00000015502 15242100017 0015165 0 ustar 00 <?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); } joomla/string/src/phputf8/utils/ascii.php 0000705 00000020433 15242100017 0014451 0 ustar 00 <?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; } joomla/string/src/phputf8/utils/unicode.php 0000705 00000022457 15242100017 0015017 0 ustar 00 <?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; } joomla/string/src/phputf8/utils/validation.php 0000705 00000015326 15242100017 0015520 0 ustar 00 <?php /** * Tools for validating 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); } joomla/string/src/Inflector.php 0000705 00000026632 15242100017 0012557 0 ustar 00 <?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; } } joomla/string/src/StringHelper.php 0000705 00000053440 15242100017 0013235 0 ustar 00 <?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 reference * * @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; } } joomla/string/src/String.php 0000705 00000000765 15242100017 0012077 0 ustar 00 <?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 { } joomla/compat/src/JsonSerializable.php 0000705 00000001251 15242100017 0014035 0 ustar 00 <?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(); } joomla/compat/src/CallbackFilterIterator.php 0000705 00000004314 15242100017 0015154 0 ustar 00 <?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 ) ); } } joomla/compat/LICENSE 0000705 00000042630 15242100017 0010310 0 ustar 00 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/uri/src/Uri.php 0000705 00000006237 15242100017 0010661 0 ustar 00 <?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, '&') !== false) { $query = str_replace('&', '&', $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; } } joomla/uri/src/UriImmutable.php 0000705 00000002572 15242100017 0012517 0 ustar 00 <?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); } } joomla/uri/src/UriHelper.php 0000705 00000003025 15242100017 0012011 0 ustar 00 <?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 array|boolean Associative array or false if badly formed URL. * * @link https://www.php.net/manual/en/function.parse-url.php * @since 1.0 */ public static function parse_url($url) { $result = array(); // 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 count($result) > 0 ? $result : false; } } joomla/uri/src/AbstractUri.php 0000705 00000021155 15242100017 0012341 0 ustar 00 <?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; /** * @var string Protocol * @since 1.0 */ protected $scheme; /** * @var string Host * @since 1.0 */ protected $host; /** * @var integer Port * @since 1.0 */ protected $port; /** * @var string Username * @since 1.0 */ protected $user; /** * @var string Password * @since 1.0 */ protected $pass; /** * @var string Path * @since 1.0 */ protected $path; /** * @var string Query * @since 1.0 */ protected $query; /** * @var string Anchor * @since 1.0 */ protected $fragment; /** * @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 ($uri !== null) { $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 ($this->query === null) { $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 & with & for parse_str to work right... if (isset($parts['query']) && strpos($parts['query'], '&') !== false) { $parts['query'] = str_replace('&', '&', $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], $path[$i - 1]); $path = array_values($path); $i -= 2; $n -= 2; } } } return implode('/', $path); } } joomla/uri/src/UriInterface.php 0000705 00000007534 15242100017 0012503 0 ustar 00 <?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 anchor 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(); } joomla/uri/LICENSE 0000705 00000042630 15242100017 0007624 0 ustar 00 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/di/src/ContainerAwareInterface.php 0000705 00000001502 15242100017 0014430 0 ustar 00 <?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); } joomla/di/src/ServiceProviderInterface.php 0000705 00000001077 15242100017 0014650 0 ustar 00 <?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); } joomla/di/src/ContainerAwareTrait.php 0000705 00000002223 15242100017 0013614 0 ustar 00 <?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; } } joomla/di/src/Exception/ProtectedKeyException.php 0000705 00000000765 15242100017 0016136 0 ustar 00 <?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 { } joomla/di/src/Exception/DependencyResolutionException.php 0000705 00000000763 15242100017 0017674 0 ustar 00 <?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 { } joomla/di/src/Exception/KeyNotFoundException.php 0000705 00000000731 15242100017 0015732 0 ustar 00 <?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 { } joomla/di/src/Container.php 0000705 00000032560 15242100017 0011637 0 ustar 00 <?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))); } } joomla/di/LICENSE 0000705 00000042630 15242100017 0007421 0 ustar 00 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/image/src/Filter/Contrast.php 0000705 00000002165 15242100017 0013423 0 ustar 00 <?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]); } } joomla/image/src/Filter/Backgroundfill.php 0000705 00000006646 15242100017 0014564 0 ustar 00 <?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; } } joomla/image/src/Filter/Smooth.php 0000705 00000002160 15242100017 0013072 0 ustar 00 <?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]); } } joomla/image/src/Filter/Negate.php 0000705 00000001416 15242100017 0013027 0 ustar 00 <?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); } } joomla/image/src/Filter/Grayscale.php 0000705 00000001427 15242100017 0013540 0 ustar 00 <?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); } } joomla/image/src/Filter/Emboss.php 0000705 00000001376 15242100017 0013061 0 ustar 00 <?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); } } joomla/image/src/Filter/Brightness.php 0000705 00000002207 15242100017 0013733 0 ustar 00 <?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]); } } joomla/image/src/Filter/Edgedetect.php 0000705 00000001444 15242100017 0013662 0 ustar 00 <?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); } } joomla/image/src/Filter/Sketchy.php 0000705 00000001425 15242100017 0013236 0 ustar 00 <?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); } } joomla/image/src/ImageFilter.php 0000705 00000005333 15242100017 0012571 0 ustar 00 <?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); } } joomla/image/src/Image.php 0000705 00000076050 15242100017 0011427 0 ustar 00 <?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); } } joomla/image/LICENSE 0000705 00000042630 15242100017 0010107 0 ustar 00 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/session/Joomla/Session/Session.php 0000705 00000056072 15242100017 0014510 0 ustar 00 <?php /** * Part of the Joomla Framework Session Package * * @copyright Copyright (C) 2005 - 2020 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE */ namespace Joomla\Session; use Joomla\Event\DispatcherInterface; use Joomla\Input\Input; /** * Class for managing HTTP sessions * * Provides access to session-state values as well as session-level * settings and lifetime management methods. * Based on the standard PHP session handling mechanism it provides * more advanced features such as expire timeouts. * * @since 1.0 */ class Session implements \IteratorAggregate { /** * Internal state. * One of 'inactive'|'active'|'expired'|'destroyed'|'error' * * @var string * @see getState() * @since 1.0 */ protected $state = 'inactive'; /** * Maximum age of unused session in minutes * * @var string * @since 1.0 */ protected $expire = 15; /** * The session store object. * * @var Storage * @since 1.0 */ protected $store; /** * Security policy. * List of checks that will be done. * * Default values: * - fix_browser * - fix_adress * * @var array * @since 1.0 */ protected $security = array('fix_browser'); /** * Force cookies to be SSL only * Default false * * @var boolean * @since 1.0 */ protected $force_ssl = false; /** * The domain to use when setting cookies. * * @var mixed * @since 1.0 * @deprecated 2.0 */ protected $cookie_domain; /** * The path to use when setting cookies. * * @var mixed * @since 1.0 * @deprecated 2.0 */ protected $cookie_path; /** * The configuration of the HttpOnly cookie. * * @var mixed * @since 1.5.0 * @deprecated 2.0 */ protected $cookie_httponly = true; /** * The configuration of the SameSite cookie. * * @var mixed * @since 1.5.0 * @deprecated 2.0 */ protected $cookie_samesite; /** * Session instances container. * * @var Session * @since 1.0 * @deprecated 2.0 */ protected static $instance; /** * The type of storage for the session. * * @var string * @since 1.0 * @deprecated 2.0 */ protected $storeName; /** * Holds the Input object * * @var Input * @since 1.0 */ private $input; /** * Holds the Dispatcher object * * @var DispatcherInterface * @since 1.0 */ private $dispatcher; /** * Constructor * * @param string $store The type of storage for the session. * @param array $options Optional parameters * * @since 1.0 */ public function __construct($store = 'none', array $options = array()) { // Need to destroy any existing sessions started with session.auto_start if (session_id()) { session_unset(); session_destroy(); } // Disable transparent sid support ini_set('session.use_trans_sid', '0'); // Only allow the session ID to come from cookies and nothing else. ini_set('session.use_only_cookies', '1'); // Create handler $this->store = Storage::getInstance($store, $options); $this->storeName = $store; // Set options $this->_setOptions($options); $this->_setCookieParams(); $this->setState('inactive'); } /** * Magic method to get read-only access to properties. * * @param string $name Name of property to retrieve * * @return mixed The value of the property * * @since 1.0 * @deprecated 2.0 Use get methods for non-deprecated properties */ public function __get($name) { if ($name === 'storeName' || $name === 'state' || $name === 'expire') { return $this->$name; } } /** * Returns the global Session object, only creating it * if it doesn't already exist. * * @param string $handler The type of session handler. * @param array $options An array of configuration options (for new sessions only). * * @return Session The Session object. * * @since 1.0 * @deprecated 2.0 A singleton object store will no longer be supported */ public static function getInstance($handler, array $options = array()) { if (!\is_object(self::$instance)) { self::$instance = new self($handler, $options); } return self::$instance; } /** * Get current state of session * * @return string The session state * * @since 1.0 */ public function getState() { return $this->state; } /** * Get expiration time in minutes * * @return integer The session expiration time in minutes * * @since 1.0 */ public function getExpire() { return $this->expire; } /** * Get a session token, if a token isn't set yet one will be generated. * * Tokens are used to secure forms from spamming attacks. Once a token * has been generated the system will check the post request to see if * it is present, if not it will invalidate the session. * * @param boolean $forceNew If true, force a new token to be created * * @return string The session token * * @since 1.0 */ public function getToken($forceNew = false) { $token = $this->get('session.token'); // Create a token if ($token === null || $forceNew) { $token = $this->_createToken(); $this->set('session.token', $token); } return $token; } /** * Method to determine if a token exists in the session. If not the * session will be set to expired * * @param string $tCheck Hashed token to be verified * @param boolean $forceExpire If true, expires the session * * @return boolean * * @since 1.0 */ public function hasToken($tCheck, $forceExpire = true) { // Check if a token exists in the session $tStored = $this->get('session.token'); // Check token if (($tStored !== $tCheck)) { if ($forceExpire) { $this->setState('expired'); } return false; } return true; } /** * Retrieve an external iterator. * * @return \ArrayIterator Return an ArrayIterator of $_SESSION. * * @since 1.0 */ public function getIterator() { return new \ArrayIterator($_SESSION); } /** * Get session name * * @return string The session name * * @since 1.0 */ public function getName() { if ($this->getState() === 'destroyed') { // @codingStandardsIgnoreLine return; } return session_name(); } /** * Get session id * * @return string The session name * * @since 1.0 */ public function getId() { if ($this->getState() === 'destroyed') { // @codingStandardsIgnoreLine return; } return session_id(); } /** * Get the session handlers * * @return array An array of available session handlers * * @since 1.0 * @deprecated 2.0 The Storage class chain will be removed */ public static function getStores() { $connectors = array(); // Get an iterator and loop trough the driver classes. $iterator = new \DirectoryIterator(__DIR__ . '/Storage'); foreach ($iterator as $file) { $fileName = $file->getFilename(); // Only load for php files. if (!$file->isFile() || $file->getExtension() != 'php') { continue; } // Derive the class name from the type. $class = str_ireplace('.php', '', '\\Joomla\\Session\\Storage\\' . ucfirst(trim($fileName))); // If the class doesn't exist we have nothing left to do but look at the next type. We did our best. if (!class_exists($class)) { continue; } // Sweet! Our class exists, so now we just need to know if it passes its test method. if ($class::isSupported()) { // Connector names should not have file extensions. $connectors[] = str_ireplace('.php', '', $fileName); } } return $connectors; } /** * Shorthand to check if the session is active * * @return boolean * * @since 1.0 */ public function isActive() { return (bool) ($this->getState() == 'active'); } /** * Check whether this session is currently created * * @return boolean True on success. * * @since 1.0 */ public function isNew() { $counter = $this->get('session.counter'); return (bool) ($counter === 1); } /** * Check whether this session is currently created * * @param Input $input Input object for the session to use. * @param DispatcherInterface $dispatcher Dispatcher object for the session to use. * * @return void * * @since 1.0 * @deprecated 2.0 In 2.0 the DispatcherInterface should be injected via the object constructor */ public function initialise(Input $input, DispatcherInterface $dispatcher = null) { $this->input = $input; $this->dispatcher = $dispatcher; } /** * Get data from the session store * * @param string $name Name of a variable * @param mixed $default Default value of a variable if not set * @param string $namespace Namespace to use, default to 'default' {@deprecated 2.0 Namespace support will be removed.} * * @return mixed Value of a variable * * @since 1.0 */ public function get($name, $default = null, $namespace = 'default') { // Add prefix to namespace to avoid collisions $namespace = '__' . $namespace; if ($this->getState() !== 'active' && $this->getState() !== 'expired') { return; } if (isset($_SESSION[$namespace][$name])) { return $_SESSION[$namespace][$name]; } return $default; } /** * Set data into the session store. * * @param string $name Name of a variable. * @param mixed $value Value of a variable. * @param string $namespace Namespace to use, default to 'default' {@deprecated 2.0 Namespace support will be removed.} * * @return mixed Old value of a variable. * * @since 1.0 */ public function set($name, $value = null, $namespace = 'default') { // Add prefix to namespace to avoid collisions $namespace = '__' . $namespace; if ($this->getState() !== 'active') { return; } $old = isset($_SESSION[$namespace][$name]) ? $_SESSION[$namespace][$name] : null; if ($value === null) { unset($_SESSION[$namespace][$name]); } else { $_SESSION[$namespace][$name] = $value; } return $old; } /** * Check whether data exists in the session store * * @param string $name Name of variable * @param string $namespace Namespace to use, default to 'default' {@deprecated 2.0 Namespace support will be removed.} * * @return boolean True if the variable exists * * @since 1.0 */ public function has($name, $namespace = 'default') { // Add prefix to namespace to avoid collisions. $namespace = '__' . $namespace; if ($this->getState() !== 'active') { // @codingStandardsIgnoreLine return; } return isset($_SESSION[$namespace][$name]); } /** * Unset data from the session store * * @param string $name Name of variable * @param string $namespace Namespace to use, default to 'default' {@deprecated 2.0 Namespace support will be removed.} * * @return mixed The value from session or NULL if not set * * @since 1.0 */ public function clear($name, $namespace = 'default') { // Add prefix to namespace to avoid collisions $namespace = '__' . $namespace; if ($this->getState() !== 'active') { // @TODO :: generated error here return; } $value = null; if (isset($_SESSION[$namespace][$name])) { $value = $_SESSION[$namespace][$name]; unset($_SESSION[$namespace][$name]); } return $value; } /** * Start a session. * * @return void * * @since 1.0 */ public function start() { if ($this->getState() === 'active') { return; } $this->_start(); $this->setState('active'); // Initialise the session $this->_setCounter(); $this->_setTimers(); // Perform security checks $this->_validate(); if ($this->dispatcher instanceof DispatcherInterface) { $this->dispatcher->triggerEvent('onAfterSessionStart'); } } /** * Start a session. * * Creates a session (or resumes the current one based on the state of the session) * * @return boolean true on success * * @since 1.0 * @deprecated 2.0 */ protected function _start() { // Start session if not started if ($this->getState() === 'restart') { session_regenerate_id(true); } else { $session_name = session_name(); // Get the Joomla\Input\Cookie object $cookie = $this->input->cookie; if ($cookie->get($session_name) === null) { $session_clean = $this->input->get($session_name, false, 'string'); if ($session_clean) { session_id($session_clean); $cookie->set($session_name, '', array('expires' => 1)); } } } /** * Write and Close handlers are called after destructing objects since PHP 5.0.5. * Thus destructors can use sessions but session handler can't use objects. * So we are moving session closure before destructing objects. * * Replace with session_register_shutdown() when dropping compatibility with PHP 5.3 */ register_shutdown_function('session_write_close'); session_cache_limiter('none'); session_start(); return true; } /** * Frees all session variables and destroys all data registered to a session * * This method resets the $_SESSION variable and destroys all of the data associated * with the current session in its storage (file or DB). It forces new session to be * started after this method is called. It does not unset the session cookie. * * @return boolean True on success * * @see session_destroy() * @see session_unset() * @since 1.0 */ public function destroy() { // Session was already destroyed if ($this->getState() === 'destroyed') { return true; } /* * In order to kill the session altogether, such as to log the user out, the session id * must also be unset. If a cookie is used to propagate the session id (default behavior), * then the session cookie must be deleted. */ $cookie = session_get_cookie_params(); $cookieOptions = array( 'expires' => 1, 'path' => $cookie['path'], 'domain' => $cookie['domain'], 'secure' => $cookie['secure'], 'httponly' => true, ); if (isset($cookie['samesite'])) { $cookieOptions['samesite'] = $cookie['samesite']; } $this->input->cookie->set($this->getName(), '', $cookieOptions); session_unset(); session_destroy(); $this->setState('destroyed'); return true; } /** * Restart an expired or locked session. * * @return boolean True on success * * @see destroy * @since 1.0 */ public function restart() { $this->destroy(); if ($this->getState() !== 'destroyed') { // @TODO :: generated error here return false; } // Re-register the session handler after a session has been destroyed, to avoid PHP bug $this->store->register(); $this->setState('restart'); // Regenerate session id session_regenerate_id(true); $this->_start(); $this->setState('active'); $this->_validate(); $this->_setCounter(); return true; } /** * Create a new session and copy variables from the old one * * @return boolean $result true on success * * @since 1.0 */ public function fork() { if ($this->getState() !== 'active') { // @TODO :: generated error here return false; } // Keep session config $cookie = session_get_cookie_params(); // Kill session session_destroy(); // Re-register the session store after a session has been destroyed, to avoid PHP bug $this->store->register(); // Restore config if (version_compare(PHP_VERSION, '7.3', '>=')) { session_set_cookie_params($cookie); } else { session_set_cookie_params($cookie['lifetime'], $cookie['path'], $cookie['domain'], $cookie['secure'], $cookie['httponly']); } // Restart session with new id session_regenerate_id(true); session_start(); return true; } /** * Writes session data and ends session * * Session data is usually stored after your script terminated without the need * to call JSession::close(), but as session data is locked to prevent concurrent * writes only one script may operate on a session at any time. When using * framesets together with sessions you will experience the frames loading one * by one due to this locking. You can reduce the time needed to load all the * frames by ending the session as soon as all changes to session variables are * done. * * @return void * * @see session_write_close() * @since 1.0 */ public function close() { session_write_close(); } /** * Set the session expiration * * @param integer $expire Maximum age of unused session in minutes * * @return $this * * @since 1.3.0 */ protected function setExpire($expire) { $this->expire = $expire; return $this; } /** * Set the session state * * @param string $state Internal state * * @return $this * * @since 1.3.0 */ protected function setState($state) { $this->state = $state; return $this; } /** * Set session cookie parameters * * @return void * * @since 1.0 * @deprecated 2.0 */ protected function _setCookieParams() { $cookie = session_get_cookie_params(); if ($this->force_ssl) { $cookie['secure'] = true; } if ($this->cookie_domain) { $cookie['domain'] = $this->cookie_domain; } if ($this->cookie_path) { $cookie['path'] = $this->cookie_path; } $cookie['httponly'] = $this->cookie_httponly; if ($this->cookie_samesite) { $cookie['samesite'] = $this->cookie_samesite; } if (version_compare(PHP_VERSION, '7.3', '>=')) { session_set_cookie_params($cookie); } else { session_set_cookie_params($cookie['lifetime'], $cookie['path'], $cookie['domain'], $cookie['secure'], $cookie['httponly']); } } /** * Create a token-string * * @param integer $length Length of string {@deprecated As of 2.0 the session token will be a fixed length} * * @return string Generated token * * @since 1.0 * @deprecated 2.0 Use createToken instead */ protected function _createToken($length = 32) { return $this->createToken($length); } /** * Create a token-string * * @param integer $length Length of string {@deprecated As of 2.0 the session token will be a fixed length} * * @return string Generated token * * @since 1.3.1 */ protected function createToken($length = 32) { return bin2hex(random_bytes($length)); } /** * Set counter of session usage * * @return boolean True on success * * @since 1.0 * @deprecated 2.0 Use setCounter instead */ protected function _setCounter() { return $this->setCounter(); } /** * Set counter of session usage * * @return boolean True on success * * @since 1.3.0 */ protected function setCounter() { $counter = $this->get('session.counter', 0); ++$counter; $this->set('session.counter', $counter); return true; } /** * Set the session timers * * @return boolean True on success * * @since 1.0 * @deprecated 2.0 Use setTimers instead */ protected function _setTimers() { return $this->setTimers(); } /** * Set the session timers * * @return boolean True on success * * @since 1.3.0 */ protected function setTimers() { if (!$this->has('session.timer.start')) { $start = time(); $this->set('session.timer.start', $start); $this->set('session.timer.last', $start); $this->set('session.timer.now', $start); } $this->set('session.timer.last', $this->get('session.timer.now')); $this->set('session.timer.now', time()); return true; } /** * Set additional session options * * @param array $options List of parameter * * @return boolean True on success * * @since 1.0 * @deprecated 2.0 Use setOptions instead */ protected function _setOptions(array $options) { return $this->setOptions($options); } /** * Set additional session options * * @param array $options List of parameter * * @return boolean True on success * * @since 1.3.0 */ protected function setOptions(array $options) { // Set name if (isset($options['name'])) { session_name(md5($options['name'])); } // Set id if (isset($options['id'])) { session_id($options['id']); } // Set expire time if (isset($options['expire'])) { $this->setExpire($options['expire']); } // Get security options if (isset($options['security'])) { $this->security = explode(',', $options['security']); } if (isset($options['force_ssl'])) { $this->force_ssl = (bool) $options['force_ssl']; } if (isset($options['cookie_domain'])) { $this->cookie_domain = $options['cookie_domain']; } if (isset($options['cookie_path'])) { $this->cookie_path = $options['cookie_path']; } if (isset($options['cookie_httponly'])) { $this->cookie_httponly = (bool) $options['cookie_httponly']; } if (isset($options['cookie_samesite'])) { $this->cookie_samesite = $options['cookie_samesite']; } // Sync the session maxlifetime if (!headers_sent()) { ini_set('session.gc_maxlifetime', $this->getExpire()); } return true; } /** * Do some checks for security reason * * - timeout check (expire) * - ip-fixiation * - browser-fixiation * * If one check failed, session data has to be cleaned. * * @param boolean $restart Reactivate session * * @return boolean True on success * * @link http://shiflett.org/articles/the-truth-about-sessions * @since 1.0 * @deprecated 2.0 Use validate instead */ protected function _validate($restart = false) { return $this->validate($restart); } /** * Do some checks for security reason * * - timeout check (expire) * - ip-fixiation * - browser-fixiation * * If one check failed, session data has to be cleaned. * * @param boolean $restart Reactivate session * * @return boolean True on success * * @link http://shiflett.org/articles/the-truth-about-sessions * @since 1.3.0 */ protected function validate($restart = false) { // Allow to restart a session if ($restart) { $this->setState('active'); $this->set('session.client.address', null); $this->set('session.client.forwarded', null); $this->set('session.token', null); } // Check if session has expired if ($this->getExpire()) { $curTime = $this->get('session.timer.now', 0); $maxTime = $this->get('session.timer.last', 0) + $this->getExpire(); // Empty session variables if ($maxTime < $curTime) { $this->setState('expired'); return false; } } $remoteAddr = $this->input->server->getString('REMOTE_ADDR', ''); // Check for client address if (\in_array('fix_adress', $this->security) && !empty($remoteAddr) && filter_var($remoteAddr, FILTER_VALIDATE_IP) !== false) { $ip = $this->get('session.client.address'); if ($ip === null) { $this->set('session.client.address', $remoteAddr); } elseif ($remoteAddr !== $ip) { $this->setState('error'); return false; } } $xForwardedFor = $this->input->server->getString('HTTP_X_FORWARDED_FOR', ''); // Record proxy forwarded for in the session in case we need it later if (!empty($xForwardedFor) && filter_var($xForwardedFor, FILTER_VALIDATE_IP) !== false) { $this->set('session.client.forwarded', $xForwardedFor); } return true; } } joomla/session/Joomla/Session/LICENSE 0000705 00000042630 15242100017 0013354 0 ustar 00 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/session/Joomla/Session/Storage/Xcache.php 0000705 00000004415 15242100017 0015656 0 ustar 00 <?php /** * Part of the Joomla Framework Session Package * * @copyright Copyright (C) 2005 - 2020 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE */ namespace Joomla\Session\Storage; use Joomla\Session\Storage; /** * XCache session storage handler * * @since 1.0 * @deprecated 2.0 The Storage class chain will be removed */ class Xcache extends Storage { /** * Constructor * * @param array $options Optional parameters. * * @since 1.0 * @throws \RuntimeException * @deprecated 2.0 */ public function __construct($options = array()) { if (!self::isSupported()) { throw new \RuntimeException('XCache Extension is not available', 404); } parent::__construct($options); } /** * Read the data for a particular session identifier from the SessionHandler backend. * * @param string $id The session identifier. * * @return string The session data. * * @since 1.0 * @deprecated 2.0 */ public function read($id) { $sess_id = 'sess_' . $id; // Check if id exists if (!xcache_isset($sess_id)) { return ''; } return (string) xcache_get($sess_id); } /** * Write session data to the SessionHandler backend. * * @param string $id The session identifier. * @param string $sessionData The session data. * * @return boolean True on success, false otherwise. * * @since 1.0 * @deprecated 2.0 */ public function write($id, $sessionData) { $sess_id = 'sess_' . $id; return xcache_set($sess_id, $sessionData, ini_get('session.gc_maxlifetime')); } /** * Destroy the data for a particular session identifier in the SessionHandler backend. * * @param string $id The session identifier. * * @return boolean True on success, false otherwise. * * @since 1.0 * @deprecated 2.0 */ public function destroy($id) { $sess_id = 'sess_' . $id; if (!xcache_isset($sess_id)) { return true; } return xcache_unset($sess_id); } /** * Test to see if the SessionHandler is available. * * @return boolean True on success, false otherwise. * * @since 1.0 * @deprecated 2.0 */ public static function isSupported() { return \extension_loaded('xcache'); } } joomla/session/Joomla/Session/Storage/Memcache.php 0000705 00000003554 15242100017 0016170 0 ustar 00 <?php /** * Part of the Joomla Framework Session Package * * @copyright Copyright (C) 2005 - 2020 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE */ namespace Joomla\Session\Storage; use Joomla\Session\Storage; /** * Memcache session storage handler for PHP * * @since 1.0 * @deprecated 2.0 The Storage class chain will be removed */ class Memcache extends Storage { /** * Container for server data * * @var array * @since 1.0 * @deprecated 2.0 */ protected $_servers = array(); /** * Constructor * * @param array $options Optional parameters. * * @since 1.0 * @throws \RuntimeException * @deprecated 2.0 */ public function __construct($options = array()) { if (!self::isSupported()) { throw new \RuntimeException('Memcache Extension is not available', 404); } // This will be an array of loveliness // @todo: multiple servers $this->_servers = array( array( 'host' => isset($options['memcache_server_host']) ? $options['memcache_server_host'] : 'localhost', 'port' => isset($options['memcache_server_port']) ? $options['memcache_server_port'] : 11211, ), ); parent::__construct($options); } /** * Register the functions of this class with PHP's session handler * * @return void * * @since 1.0 * @deprecated 2.0 */ public function register() { if (!headers_sent()) { ini_set('session.save_path', $this->_servers[0]['host'] . ':' . $this->_servers[0]['port']); ini_set('session.save_handler', 'memcache'); } } /** * Test to see if the SessionHandler is available. * * @return boolean True on success, false otherwise. * * @since 1.0 * @deprecated 2.0 */ public static function isSupported() { return \extension_loaded('memcache') && class_exists('Memcache'); } } joomla/session/Joomla/Session/Storage/Apc.php 0000705 00000004326 15242100017 0015167 0 ustar 00 <?php /** * Part of the Joomla Framework Session Package * * @copyright Copyright (C) 2005 - 2020 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE */ namespace Joomla\Session\Storage; use Joomla\Session\Storage; /** * APC session storage handler for PHP * * @link https://www.php.net/manual/en/function.session-set-save-handler.php * @since 1.0 * @deprecated 2.0 The Storage class chain will be removed. */ class Apc extends Storage { /** * Constructor * * @param array $options Optional parameters * * @since 1.0 * @throws \RuntimeException * @deprecated 2.0 */ public function __construct($options = array()) { if (!self::isSupported()) { throw new \RuntimeException('APC Extension is not available', 404); } parent::__construct($options); } /** * Read the data for a particular session identifier from the * SessionHandler backend. * * @param string $id The session identifier. * * @return string The session data. * * @since 1.0 * @deprecated 2.0 */ public function read($id) { $sess_id = 'sess_' . $id; return (string) apc_fetch($sess_id); } /** * Write session data to the SessionHandler backend. * * @param string $id The session identifier. * @param string $sessionData The session data. * * @return boolean True on success, false otherwise. * * @since 1.0 * @deprecated 2.0 */ public function write($id, $sessionData) { $sess_id = 'sess_' . $id; return apc_store($sess_id, $sessionData, ini_get('session.gc_maxlifetime')); } /** * Destroy the data for a particular session identifier in the SessionHandler backend. * * @param string $id The session identifier. * * @return boolean True on success, false otherwise. * * @since 1.0 * @deprecated 2.0 */ public function destroy($id) { $sess_id = 'sess_' . $id; return apc_delete($sess_id); } /** * Test to see if the SessionHandler is available. * * @return boolean True on success, false otherwise. * * @since 1.0 * @deprecated 2.0 */ public static function isSupported() { return \extension_loaded('apc'); } } joomla/session/Joomla/Session/Storage/None.php 0000705 00000001331 15242100017 0015354 0 ustar 00 <?php /** * Part of the Joomla Framework Session Package * * @copyright Copyright (C) 2005 - 2020 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE */ namespace Joomla\Session\Storage; use Joomla\Session\Storage; /** * Default PHP configured session handler for Joomla! * * @link https://www.php.net/manual/en/function.session-set-save-handler.php * @since 1.0 * @deprecated 2.0 The Storage class chain will be removed */ class None extends Storage { /** * Register the functions of this class with PHP's session handler * * @return void * * @since 1.0 * @deprecated 2.0 */ public function register() { } } joomla/session/Joomla/Session/Storage/Database.php 0000705 00000010500 15242100017 0016157 0 ustar 00 <?php /** * Part of the Joomla Framework Session Package * * @copyright Copyright (C) 2005 - 2020 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE */ namespace Joomla\Session\Storage; use Joomla\Database\DatabaseDriver; use Joomla\Session\Storage; /** * Database session storage handler for PHP * * @link https://www.php.net/manual/en/function.session-set-save-handler.php * @since 1.0 * @deprecated 2.0 The Storage class chain will be removed */ class Database extends Storage { /** * The DatabaseDriver to use when querying. * * @var DatabaseDriver * @since 1.0 * @deprecated 2.0 */ protected $db; /** * Constructor * * @param array $options Optional parameters. A `dbo` options is required. * * @since 1.0 * @throws \RuntimeException * @deprecated 2.0 */ public function __construct($options = array()) { if (isset($options['db']) && ($options['db'] instanceof DatabaseDriver)) { parent::__construct($options); $this->db = $options['db']; } else { throw new \RuntimeException( sprintf('The %s storage engine requires a `db` option that is an instance of Joomla\\Database\\DatabaseDriver.', __CLASS__) ); } } /** * Read the data for a particular session identifier from the SessionHandler backend. * * @param string $id The session identifier. * * @return string The session data. * * @since 1.0 * @deprecated 2.0 */ public function read($id) { try { // Get the session data from the database table. $query = $this->db->getQuery(true); $query->select($this->db->quoteName('data')) ->from($this->db->quoteName('#__session')) ->where($this->db->quoteName('session_id') . ' = ' . $this->db->quote($id)); $this->db->setQuery($query); return (string) $this->db->loadResult(); } catch (\Exception $e) { return false; } } /** * Write session data to the SessionHandler backend. * * @param string $id The session identifier. * @param string $data The session data. * * @return boolean True on success, false otherwise. * * @since 1.0 * @deprecated 2.0 */ public function write($id, $data) { try { $query = $this->db->getQuery(true); $query->update($this->db->quoteName('#__session')) ->set($this->db->quoteName('data') . ' = ' . $this->db->quote($data)) ->set($this->db->quoteName('time') . ' = ' . $this->db->quote((int) time())) ->where($this->db->quoteName('session_id') . ' = ' . $this->db->quote($id)); // Try to update the session data in the database table. $this->db->setQuery($query); if (!$this->db->execute()) { return false; } // Since $this->db->execute did not throw an exception the query was successful. // Either the data changed, or the data was identical. In either case we are done. return true; } catch (\Exception $e) { return false; } } /** * Destroy the data for a particular session identifier in the SessionHandler backend. * * @param string $id The session identifier. * * @return boolean True on success, false otherwise. * * @since 1.0 * @deprecated 2.0 */ public function destroy($id) { try { $query = $this->db->getQuery(true); $query->delete($this->db->quoteName('#__session')) ->where($this->db->quoteName('session_id') . ' = ' . $this->db->quote($id)); // Remove a session from the database. $this->db->setQuery($query); return (boolean) $this->db->execute(); } catch (\Exception $e) { return false; } } /** * Garbage collect stale sessions from the SessionHandler backend. * * @param integer $lifetime The maximum age of a session. * * @return boolean True on success, false otherwise. * * @since 1.0 * @deprecated 2.0 */ public function gc($lifetime = 1440) { // Determine the timestamp threshold with which to purge old sessions. $past = time() - $lifetime; try { $query = $this->db->getQuery(true); $query->delete($this->db->quoteName('#__session')) ->where($this->db->quoteName('time') . ' < ' . $this->db->quote((int) $past)); // Remove expired sessions from the database. $this->db->setQuery($query); return (boolean) $this->db->execute(); } catch (\Exception $e) { return false; } } } joomla/session/Joomla/Session/Storage/Apcu.php 0000705 00000004201 15242100017 0015344 0 ustar 00 <?php /** * Part of the Joomla Framework Session Package * * @copyright Copyright (C) 2005 - 2020 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE */ namespace Joomla\Session\Storage; use Joomla\Session\Storage; /** * APCU session storage handler for PHP * * @link https://www.php.net/manual/en/function.session-set-save-handler.php * @since 1.4.0 * @deprecated 2.0 The Storage class chain will be removed. */ class Apcu extends Storage { /** * Constructor * * @param array $options Optional parameters * * @since 1.4.0 * @throws \RuntimeException */ public function __construct($options = array()) { if (!self::isSupported()) { throw new \RuntimeException('APCU Extension is not available', 404); } parent::__construct($options); } /** * Read the data for a particular session identifier from the * SessionHandler backend. * * @param string $id The session identifier. * * @return string The session data. * * @since 1.4.0 */ public function read($id) { $sess_id = 'sess_' . $id; return (string) apcu_fetch($sess_id); } /** * Write session data to the SessionHandler backend. * * @param string $id The session identifier. * @param string $sessionData The session data. * * @return boolean True on success, false otherwise. * * @since 1.4.0 */ public function write($id, $sessionData) { $sess_id = 'sess_' . $id; return apcu_store($sess_id, $sessionData, ini_get('session.gc_maxlifetime')); } /** * Destroy the data for a particular session identifier in the SessionHandler backend. * * @param string $id The session identifier. * * @return boolean True on success, false otherwise. * * @since 1.4.0 */ public function destroy($id) { $sess_id = 'sess_' . $id; return apcu_delete($sess_id); } /** * Test to see if the SessionHandler is available. * * @return boolean True on success, false otherwise. * * @since 1.4.0 */ public static function isSupported() { return \extension_loaded('apcu'); } } joomla/session/Joomla/Session/Storage/Memcached.php 0000705 00000004147 15242100017 0016333 0 ustar 00 <?php /** * Part of the Joomla Framework Session Package * * @copyright Copyright (C) 2005 - 2020 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE */ namespace Joomla\Session\Storage; use Joomla\Session\Storage; /** * Memcached session storage handler for PHP * * @since 1.0 * @deprecated 2.0 The Storage class chain will be removed */ class Memcached extends Storage { /** * Container for server data * * @var array * @since 1.0 * @deprecated 2.0 */ protected $_servers = array(); /** * Constructor * * @param array $options Optional parameters. * * @since 1.0 * @throws \RuntimeException * @deprecated 2.0 */ public function __construct($options = array()) { if (!self::isSupported()) { throw new \RuntimeException('Memcached Extension is not available', 404); } // This will be an array of loveliness // @todo: multiple servers $this->_servers = array( array( 'host' => isset($options['memcache_server_host']) ? $options['memcache_server_host'] : 'localhost', 'port' => isset($options['memcache_server_port']) ? $options['memcache_server_port'] : 11211, ), ); // Only construct parent AFTER host and port are sent, otherwise when register is called this will fail. parent::__construct($options); } /** * Register the functions of this class with PHP's session handler * * @return void * * @since 1.0 * @deprecated 2.0 */ public function register() { if (!headers_sent()) { ini_set('session.save_path', $this->_servers[0]['host'] . ':' . $this->_servers[0]['port']); ini_set('session.save_handler', 'memcached'); } } /** * Test to see if the SessionHandler is available. * * @return boolean True on success, false otherwise. * * @since 1.0 * @deprecated 2.0 */ public static function isSupported() { /* * GAE and HHVM have both had instances where Memcached the class was defined but no extension was loaded. * If the class is there, we can assume it works. */ return class_exists('Memcached'); } } joomla/session/Joomla/Session/Storage/Wincache.php 0000705 00000002605 15242100017 0016203 0 ustar 00 <?php /** * Part of the Joomla Framework Session Package * * @copyright Copyright (C) 2005 - 2020 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE */ namespace Joomla\Session\Storage; use Joomla\Session\Storage; /** * WINCACHE session storage handler for PHP * * @since 1.0 * @deprecated 2.0 The Storage class chain will be removed */ class Wincache extends Storage { /** * Constructor * * @param array $options Optional parameters. * * @since 1.0 * @throws \RuntimeException * @deprecated 2.0 */ public function __construct($options = array()) { if (!self::isSupported()) { throw new \RuntimeException('Wincache Extension is not available', 404); } parent::__construct($options); } /** * Register the functions of this class with PHP's session handler * * @return void * * @since 1.0 * @deprecated 2.0 */ public function register() { if (!headers_sent()) { ini_set('session.save_handler', 'wincache'); } } /** * Test to see if the SessionHandler is available. * * @return boolean True on success, false otherwise. * * @since 1.0 * @deprecated 2.0 */ public static function isSupported() { return \extension_loaded('wincache') && \function_exists('wincache_ucache_get') && !strcmp(ini_get('wincache.ucenabled'), '1'); } } joomla/session/Joomla/Session/Storage.php 0000705 00000010270 15242100017 0014457 0 ustar 00 <?php /** * Part of the Joomla Framework Session Package * * @copyright Copyright (C) 2005 - 2020 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE */ namespace Joomla\Session; use Joomla\Filter\InputFilter; /** * Custom session storage handler for PHP * * @link https://www.php.net/manual/en/function.session-set-save-handler.php * @since 1.0 * @deprecated 2.0 The Storage class chain will be removed. */ abstract class Storage { /** * @var Storage[] Storage instances container. * @since 1.0 * @deprecated 2.0 */ protected static $instances = array(); /** * Constructor * * @param array $options Optional parameters. * * @since 1.0 * @deprecated 2.0 */ public function __construct($options = array()) { $this->register($options); } /** * Returns a session storage handler object, only creating it if it doesn't already exist. * * @param string $name The session store to instantiate * @param array $options Array of options * * @return Storage * * @since 1.0 * @deprecated 2.0 */ public static function getInstance($name = 'none', $options = array()) { $filter = new InputFilter; $name = strtolower($filter->clean($name, 'word')); if (empty(self::$instances[$name])) { $class = '\\Joomla\\Session\\Storage\\' . ucfirst($name); if (!class_exists($class)) { $path = __DIR__ . '/storage/' . $name . '.php'; if (file_exists($path)) { require_once $path; } else { // No attempt to die gracefully here, as it tries to close the non-existing session exit('Unable to load session storage class: ' . $name); } } self::$instances[$name] = new $class($options); } return self::$instances[$name]; } /** * Register the functions of this class with PHP's session handler * * @return void * * @since 1.0 * @deprecated 2.0 */ public function register() { if (!headers_sent()) { session_set_save_handler( array($this, 'open'), array($this, 'close'), array($this, 'read'), array($this, 'write'), array($this, 'destroy'), array($this, 'gc') ); } } /** * Open the SessionHandler backend. * * @param string $savePath The path to the session object. * @param string $sessionName The name of the session. * * @return boolean True on success, false otherwise. * * @since 1.0 * @deprecated 2.0 */ public function open($savePath, $sessionName) { return true; } /** * Close the SessionHandler backend. * * @return boolean True on success, false otherwise. * * @since 1.0 * @deprecated 2.0 */ public function close() { return true; } /** * Read the data for a particular session identifier from the * SessionHandler backend. * * @param string $id The session identifier. * * @return string The session data. * * @since 1.0 * @deprecated 2.0 */ public function read($id) { return ''; } /** * Write session data to the SessionHandler backend. * * @param string $id The session identifier. * @param string $sessionData The session data. * * @return boolean True on success, false otherwise. * * @since 1.0 * @deprecated 2.0 */ public function write($id, $sessionData) { return true; } /** * Destroy the data for a particular session identifier in the * SessionHandler backend. * * @param string $id The session identifier. * * @return boolean True on success, false otherwise. * * @since 1.0 * @deprecated 2.0 */ public function destroy($id) { return true; } /** * Garbage collect stale sessions from the SessionHandler backend. * * @param integer $maxlifetime The maximum age of a session. * * @return boolean True on success, false otherwise. * * @since 1.0 * @deprecated 2.0 */ public function gc($maxlifetime = null) { return true; } /** * Test to see if the SessionHandler is available. * * @return boolean True on success, false otherwise. * * @since 1.0 * @deprecated 2.0 */ public static function isSupported() { return true; } } joomla/utilities/LICENSE 0000705 00000042630 15242100017 0011040 0 ustar 00 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/utilities/src/ArrayHelper.php 0000705 00000041777 15242100017 0013564 0 ustar 00 <?php /** * Part of the Joomla Framework Utilities Package * * @copyright Copyright (C) 2005 - 2021 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; } } joomla/utilities/src/IpHelper.php 0000705 00000030021 15242100017 0013032 0 ustar 00 <?php /** * Part of the Joomla Framework Utilities Package * * @copyright Copyright (C) 2010-2016 Nicholas K. Dionysopoulos / Akeeba Ltd. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt * @note This file has been modified by the Joomla! Project and no longer reflects the original work of its author. */ namespace Joomla\Utilities; /** * IpHelper is a utility class for processing IP addresses * * @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 * @note The default value is false in version 2.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 strpos($ip, ':') !== false; } /** * 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_shift($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; } } joomla/application/src/AbstractCliApplication.php 0000705 00000007531 15242100017 0016203 0 ustar 00 <?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(); } } joomla/application/src/Web/WebClient.php 0000705 00000041074 15242100017 0014215 0 ustar 00 <?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 mentioned in iPad user agent string $this->mobile = true; $this->platform = self::IPAD; } elseif (stripos($userAgent, 'iPod') !== false) { // In case where iPhone is not mentioned 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; } } joomla/application/src/AbstractWebApplication.php 0000705 00000066035 15242100017 0016215 0 ustar 00 <?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 compatibility 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 string|string[] 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; } } joomla/application/src/Cli/Output/Stdout.php 0000705 00000001620 15242100017 0015106 0 ustar 00 <?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; } } joomla/application/src/Cli/Output/Xml.php 0000705 00000001521 15242100017 0014364 0 ustar 00 <?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)); } } joomla/application/src/Cli/Output/Processor/ColorProcessor.php 0000705 00000007547 15242100017 0020577 0 ustar 00 <?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 string * * @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; } } joomla/application/src/Cli/Output/Processor/ProcessorInterface.php 0000705 00000001175 15242100017 0021410 0 ustar 00 <?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); } joomla/application/src/Cli/CliOutput.php 0000705 00000003216 15242100017 0014257 0 ustar 00 <?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 */ public function getProcessor() { return $this->processor; } /** * 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); } joomla/application/src/Cli/CliInput.php 0000705 00000001164 15242100017 0014056 0 ustar 00 <?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"); } } joomla/application/src/Cli/ColorStyle.php 0000705 00000010452 15242100017 0014426 0 ustar 00 <?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); } } joomla/application/src/Cli/ColorProcessor.php 0000705 00000001011 15242100017 0015274 0 ustar 00 <?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 { } joomla/application/src/AbstractDaemonApplication.php 0000705 00000060450 15242100017 0016676 0 ustar 00 <?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://www.php.net/manual/en/book.pcntl.php * @link https://www.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://www.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); } } joomla/application/src/AbstractApplication.php 0000705 00000011254 15242100017 0015550 0 ustar 00 <?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; } } joomla/application/LICENSE 0000705 00000042630 15242100017 0011330 0 ustar 00 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/filesystem/meta/language/en-GB/en-GB.lib_joomla_filesystem_patcher.ini 0000705 00000001322 15242100017 0023247 0 ustar 00 ; 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_UNEXISTING_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" joomla/filesystem/LICENSE 0000705 00000042630 15242100017 0011211 0 ustar 00 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/filesystem/src/Patcher.php 0000705 00000026641 15242100017 0013076 0 ustar 00 <?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 patcher * * @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: ' . Path::removeRoot($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', Path::removeRoot($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]; } } joomla/filesystem/src/Folder.php 0000705 00000034556 15242100017 0012727 0 ustar 00 <?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::removeRoot($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::removeRoot($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::removeRoot($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); } } joomla/filesystem/src/Stream/String.php 0000705 00000001022 15242100017 0014173 0 ustar 00 <?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 { } joomla/filesystem/src/Stream/StringWrapper.php 0000705 00000012402 15242100017 0015540 0 ustar 00 <?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'); } joomla/filesystem/src/Stream.php 0000705 00000112510 15242100017 0012732 0 ustar 00 <?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 if (PHP_VERSION_ID < 70000) { // @Todo Remove this path, when PHP5 support is dropped. set_error_handler( function () { return false; } ); @trigger_error(''); restore_error_handler(); } else { /** @noinspection PhpElementIsNotAvailableInCurrentPhpVersionInspection */ error_clear_last(); } // 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; } if (!$this->fh) { $error = error_get_last(); if ($error === null || $error['message'] === '') { // Error but nothing from php? Create our own $error = array( 'message' => sprintf('Unknown error opening file %s', $filename) ); } throw new FilesystemException($error['message']); } // 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 if (PHP_VERSION_ID < 70000) { // @Todo Remove this path, when PHP5 support is dropped. set_error_handler( function () { return false; } ); @trigger_error(''); restore_error_handler(); } else { /** @noinspection PhpElementIsNotAvailableInCurrentPhpVersionInspection */ error_clear_last(); } 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; } if (!$res) { $error = error_get_last(); if ($error === null || $error['message'] === '') { // Error but nothing from php? Create our own $error = array( 'message' => 'Unable to close stream' ); } throw new FilesystemException($error['message']); } // 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 if (PHP_VERSION_ID < 70000) { // @Todo Remove this path, when PHP5 support is dropped. set_error_handler( function () { return false; } ); @trigger_error(''); restore_error_handler(); } else { /** @noinspection PhpElementIsNotAvailableInCurrentPhpVersionInspection */ error_clear_last(); } switch ($this->processingmethod) { case 'gz': $res = gzeof($this->fh); break; case 'bz': case 'f': default: $res = feof($this->fh); break; } $error = error_get_last(); if ($error !== null && $error['message'] !== '') { throw new FilesystemException($error['message']); } // 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 if (PHP_VERSION_ID < 70000) { // @Todo Remove this path, when PHP5 support is dropped. set_error_handler( function () { return false; } ); @trigger_error(''); restore_error_handler(); } else { /** @noinspection PhpElementIsNotAvailableInCurrentPhpVersionInspection */ error_clear_last(); } $res = @filesize($this->filename); if (!$res) { $res = Helper::remotefsize($this->filename); } if (!$res) { $error = error_get_last(); if ($error === null || $error['message'] === '') { // Error but nothing from php? Create our own $error = array( 'message' => 'Failed to get file size. This may not work for all streams.' ); } throw new FilesystemException($error['message']); } $this->filesize = $res; // Return the result return $this->filesize; } /** * 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 if (PHP_VERSION_ID < 70000) { // @Todo Remove this path, when PHP5 support is dropped. set_error_handler( function () { return false; } ); @trigger_error(''); restore_error_handler(); } else { /** @noinspection PhpElementIsNotAvailableInCurrentPhpVersionInspection */ error_clear_last(); } 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; } if (!$res) { $error = error_get_last(); if ($error === null || $error['message'] === '') { // Error but nothing from php? Create our own $error = array( 'message' => 'Unable to read from stream' ); } throw new FilesystemException($error['message']); } // 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 if (PHP_VERSION_ID < 70000) { // @Todo Remove this path, when PHP5 support is dropped. set_error_handler( function () { return false; } ); @trigger_error(''); restore_error_handler(); } else { /** @noinspection PhpElementIsNotAvailableInCurrentPhpVersionInspection */ error_clear_last(); } $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) { $error = error_get_last(); if ($error === null || $error['message'] === '') { // Error but nothing from php? Create our own $error = array( 'message' => 'Unable to read from stream' ); } throw new FilesystemException($error['message']); } 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); // 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 if (PHP_VERSION_ID < 70000) { // @Todo Remove this path, when PHP5 support is dropped. set_error_handler( function () { return false; } ); @trigger_error(''); restore_error_handler(); } else { /** @noinspection PhpElementIsNotAvailableInCurrentPhpVersionInspection */ error_clear_last(); } switch ($this->processingmethod) { case 'gz': $res = gzseek($this->fh, $offset, $whence); break; case 'bz': case 'f': default: $res = fseek($this->fh, $offset, $whence); break; } // Seek, interestingly, returns 0 on success or -1 on failure. if ($res == -1) { $error = error_get_last(); if ($error === null || $error['message'] === '') { // Error but nothing from php? Create our own $error = array( 'message' => 'Unable to seek in stream' ); } throw new FilesystemException($error['message']); } // 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 if (PHP_VERSION_ID < 70000) { // @Todo Remove this path, when PHP5 support is dropped. set_error_handler( function () { return false; } ); @trigger_error(''); restore_error_handler(); } else { /** @noinspection PhpElementIsNotAvailableInCurrentPhpVersionInspection */ error_clear_last(); } switch ($this->processingmethod) { case 'gz': $res = gztell($this->fh); break; case 'bz': case 'f': default: $res = ftell($this->fh); break; } // May return 0 so check if it's really false if ($res === false) { $error = error_get_last(); if ($error === null || $error['message'] === '') { // Error but nothing from php? Create our own $error = array( 'message' => 'Unable to determine the current position in stream' ); } throw new FilesystemException($error['message']); } // 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 if (PHP_VERSION_ID < 70000) { // @Todo Remove this path, when PHP5 support is dropped. set_error_handler( function () { return false; } ); @trigger_error(''); restore_error_handler(); } else { /** @noinspection PhpElementIsNotAvailableInCurrentPhpVersionInspection */ error_clear_last(); } $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) { $error = error_get_last(); if ($error === null || $error['message'] === '') { // Error but nothing from php? Create our own $error = array( 'message' => 'Unable to write to stream' ); } throw new FilesystemException($error['message']); } if ($res === 0) { // Wrote nothing? throw new FilesystemException('Warning: No data written'); } // Wrote something $start += $amount; $remaining -= $res; } while ($remaining); // 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 if (PHP_VERSION_ID < 70000) { // @Todo Remove this path, when PHP5 support is dropped. set_error_handler( function () { return false; } ); @trigger_error(''); restore_error_handler(); } else { /** @noinspection PhpElementIsNotAvailableInCurrentPhpVersionInspection */ error_clear_last(); } $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; } if ($res === false) { $error = error_get_last(); if ($error === null || $error['message'] === '') { // Error but nothing from php? Create our own $error = array( 'message' => 'Unable to change mode of stream' ); } throw new FilesystemException($error['message']); } // 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 if (PHP_VERSION_ID < 70000) { // @Todo Remove this path, when PHP5 support is dropped. set_error_handler( function () { return false; } ); @trigger_error(''); restore_error_handler(); } else { /** @noinspection PhpElementIsNotAvailableInCurrentPhpVersionInspection */ error_clear_last(); } $retval = @stream_context_set_option($this->fh, $this->contextOptions); if (!$retval) { $error = error_get_last(); if ($error === null || $error['message'] === '') { // Error but nothing from php? Create our own $error = array( 'message' => 'Unable to apply context to stream' ); } throw new FilesystemException($error['message']); } } 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 if (PHP_VERSION_ID < 70000) { // @Todo Remove this path, when PHP5 support is dropped. set_error_handler( function () { return false; } ); @trigger_error(''); restore_error_handler(); } else { /** @noinspection PhpElementIsNotAvailableInCurrentPhpVersionInspection */ error_clear_last(); } $res = @stream_filter_append($this->fh, $filtername, $readWrite, $params); if (!$res) { $error = error_get_last(); if ($error !== null && $error['message'] !== '') { throw new FilesystemException($error['message']); } } $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 if (PHP_VERSION_ID < 70000) { // @Todo Remove this path, when PHP5 support is dropped. set_error_handler( function () { return false; } ); @trigger_error(''); restore_error_handler(); } else { /** @noinspection PhpElementIsNotAvailableInCurrentPhpVersionInspection */ error_clear_last(); } $res = @stream_filter_prepend($this->fh, $filtername, $readWrite, $params); if (!$res) { $error = error_get_last(); if ($error !== null && $error['message'] !== '') { throw new FilesystemException($error['message']); } } 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 if (PHP_VERSION_ID < 70000) { // @Todo Remove this path, when PHP5 support is dropped. set_error_handler( function () { return false; } ); @trigger_error(''); restore_error_handler(); } else { /** @noinspection PhpElementIsNotAvailableInCurrentPhpVersionInspection */ error_clear_last(); } if ($byindex) { $res = stream_filter_remove($this->filters[$resource]); } else { $res = stream_filter_remove($resource); } if (!$res) { $error = error_get_last(); if ($error === null || $error['message'] === '') { // Error but nothing from php? Create our own $error = array( 'message' => 'Unable to remove filter from stream' ); } throw new FilesystemException($error['message']); } 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 if (PHP_VERSION_ID < 70000) { // @Todo Remove this path, when PHP5 support is dropped. set_error_handler( function () { return false; } ); @trigger_error(''); restore_error_handler(); } else { /** @noinspection PhpElementIsNotAvailableInCurrentPhpVersionInspection */ error_clear_last(); } $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); } if (!$res) { $error = error_get_last(); if ($error !== null && $error['message'] !== '') { throw new FilesystemException($error['message']); } } $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 if (PHP_VERSION_ID < 70000) { // @Todo Remove this path, when PHP5 support is dropped. set_error_handler( function () { return false; } ); @trigger_error(''); restore_error_handler(); } else { /** @noinspection PhpElementIsNotAvailableInCurrentPhpVersionInspection */ error_clear_last(); } $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); } if (!$res) { $error = error_get_last(); if ($error === null || $error['message'] === '') { // Error but nothing from php? Create our own $error = array( 'message' => 'Unable to move stream' ); } throw new FilesystemException($error['message']); } $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 if (PHP_VERSION_ID < 70000) { // @Todo Remove this path, when PHP5 support is dropped. set_error_handler( function () { return false; } ); @trigger_error(''); restore_error_handler(); } else { /** @noinspection PhpElementIsNotAvailableInCurrentPhpVersionInspection */ error_clear_last(); } $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); } if (!$res) { $error = error_get_last(); if ($error === null || $error['message'] === '') { // Error but nothing from php? Create our own $error = array( 'message' => 'Unable to delete stream' ); } throw new FilesystemException($error['message']); } 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; } } joomla/filesystem/src/Buffer.php 0000705 00000010150 15242100017 0012705 0 ustar 00 <?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'); joomla/filesystem/src/Exception/FilesystemException.php 0000705 00000001773 15242100017 0017450 0 ustar 00 <?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; use Joomla\Filesystem\Path; /** * Exception class for handling errors in the Filesystem package * * @since 1.2.0 * @change 1.6.2 If the message containes a full path, the root path (JPATH_ROOT) is removed from it * to avoid any full path disclosure. Before 1.6.2, the path was propagated as provided. */ class FilesystemException extends \RuntimeException { /** * Constructor. * * @param string $message The message * @param integer $code The code * @param \Throwable|null $previous A previous exception */ public function __construct($message = "", $code = 0, \Throwable $previous = null) { parent::__construct( Path::removeRoot($message), $code, $previous ); } } joomla/filesystem/src/Clients/FtpClient.php 0000705 00000122143 15242100017 0014773 0 ustar 00 <?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 received 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; } } joomla/filesystem/src/Support/StringController.php 0000705 00000002622 15242100017 0016467 0 ustar 00 <?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; } } joomla/filesystem/src/Helper.php 0000705 00000012164 15242100017 0012722 0 ustar 00 <?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()); } } joomla/filesystem/src/File.php 0000705 00000015417 15242100017 0012366 0 ustar 00 <?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( sprintf( "%s: Cannot find or read file: %s", __METHOD__, Path::removeRoot($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.'); } } autoload.php 0000705 00000000262 15242100017 0007053 0 ustar 00 <?php // autoload.php @generated by Composer require_once __DIR__ . '/composer/autoload_real.php'; return ComposerAutoloaderInitc14bde14f8c86840049f5c1809c453dd::getLoader(); simplepie/simplepie/db.sql 0000705 00000001420 15242100017 0011613 0 ustar 00 /* SQLite */ CREATE TABLE cache_data ( id TEXT NOT NULL, items SMALLINT NOT NULL DEFAULT 0, data BLOB NOT NULL, mtime INTEGER UNSIGNED NOT NULL ); CREATE UNIQUE INDEX id ON cache_data(id); CREATE TABLE items ( feed_id TEXT NOT NULL, id TEXT NOT NULL, data TEXT NOT NULL, posted INTEGER UNSIGNED NOT NULL ); CREATE INDEX feed_id ON items(feed_id); /* MySQL */ CREATE TABLE `cache_data` ( `id` TEXT CHARACTER SET utf8 NOT NULL, `items` SMALLINT NOT NULL DEFAULT 0, `data` BLOB NOT NULL, `mtime` INT UNSIGNED NOT NULL, UNIQUE ( `id`(125) ) ); CREATE TABLE `items` ( `feed_id` TEXT CHARACTER SET utf8 NOT NULL, `id` TEXT CHARACTER SET utf8 NOT NULL, `data` TEXT CHARACTER SET utf8 NOT NULL, `posted` INT UNSIGNED NOT NULL, INDEX `feed_id` ( `feed_id`(125) ) ); simplepie/simplepie/LICENSE.txt 0000705 00000003001 15242100017 0012325 0 ustar 00 Copyright (c) 2004-2007, Ryan Parman and Geoffrey Sneddon. 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 the SimplePie Team 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 HOLDERS AND 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. simplepie/simplepie/idn/LICENCE 0000705 00000063623 15242100017 0012261 0 ustar 00 GNU LESSER GENERAL PUBLIC LICENSE Version 2.1, February 1999 Copyright (C) 1991, 1999 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. [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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 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! simplepie/simplepie/idn/idna_convert.class.php 0000705 00000113046 15242100017 0015557 0 ustar 00 <?php // {{{ license /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker: */ // // +----------------------------------------------------------------------+ // | 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 | // | USA. | // +----------------------------------------------------------------------+ // // }}} /** * Encode/decode Internationalized Domain Names. * * The class allows to convert internationalized domain names * (see RFC 3490 for details) as they can be used with various registries worldwide * to be translated between their original (localized) form and their encoded form * as it will be used in the DNS (Domain Name System). * * The class provides two public methods, encode() and decode(), which do exactly * what you would expect them to do. You are allowed to use complete domain names, * simple strings and complete email addresses as well. That means, that you might * use any of the following notations: * * - www.nörgler.com * - xn--nrgler-wxa * - xn--brse-5qa.xn--knrz-1ra.info * * Unicode input might be given as either UTF-8 string, UCS-4 string or UCS-4 * array. Unicode output is available in the same formats. * You can select your preferred format via {@link set_paramter()}. * * ACE input and output is always expected to be ASCII. * * @author Matthias Sommerfeld <mso@phlylabs.de> * @copyright 2004-2007 phlyLabs Berlin, http://phlylabs.de * @version 0.5.1 * */ class idna_convert { /** * Holds all relevant mapping tables, loaded from a seperate file on construct * See RFC3454 for details * * @var array * @access private */ var $NP = array(); // Internal settings, do not mess with them var $_punycode_prefix = 'xn--'; var $_invalid_ucs = 0x80000000; var $_max_ucs = 0x10FFFF; var $_base = 36; var $_tmin = 1; var $_tmax = 26; var $_skew = 38; var $_damp = 700; var $_initial_bias = 72; var $_initial_n = 0x80; var $_sbase = 0xAC00; var $_lbase = 0x1100; var $_vbase = 0x1161; var $_tbase = 0x11A7; var $_lcount = 19; var $_vcount = 21; var $_tcount = 28; var $_ncount = 588; // _vcount * _tcount var $_scount = 11172; // _lcount * _tcount * _vcount var $_error = false; // See {@link set_paramter()} for details of how to change the following // settings from within your script / application var $_api_encoding = 'utf8'; // Default input charset is UTF-8 var $_allow_overlong = false; // Overlong UTF-8 encodings are forbidden var $_strict_mode = false; // Behave strict or not // The constructor function idna_convert($options = false) { $this->slast = $this->_sbase + $this->_lcount * $this->_vcount * $this->_tcount; if (function_exists('file_get_contents')) { $this->NP = unserialize(file_get_contents(dirname(__FILE__).'/npdata.ser')); } else { $this->NP = unserialize(join('', file(dirname(__FILE__).'/npdata.ser'))); } // If parameters are given, pass these to the respective method if (is_array($options)) { return $this->set_parameter($options); } return true; } /** * Sets a new option value. Available options and values: * [encoding - Use either UTF-8, UCS4 as array or UCS4 as string as input ('utf8' for UTF-8, * 'ucs4_string' and 'ucs4_array' respectively for UCS4); The output is always UTF-8] * [overlong - Unicode does not allow unnecessarily long encodings of chars, * to allow this, set this parameter to true, else to false; * default is false.] * [strict - true: strict mode, good for registration purposes - Causes errors * on failures; false: loose mode, ideal for "wildlife" applications * by silently ignoring errors and returning the original input instead * * @param mixed Parameter to set (string: single parameter; array of Parameter => Value pairs) * @param string Value to use (if parameter 1 is a string) * @return boolean true on success, false otherwise * @access public */ function set_parameter($option, $value = false) { if (!is_array($option)) { $option = array($option => $value); } foreach ($option as $k => $v) { switch ($k) { case 'encoding': switch ($v) { case 'utf8': case 'ucs4_string': case 'ucs4_array': $this->_api_encoding = $v; break; default: $this->_error('Set Parameter: Unknown parameter '.$v.' for option '.$k); return false; } break; case 'overlong': $this->_allow_overlong = ($v) ? true : false; break; case 'strict': $this->_strict_mode = ($v) ? true : false; break; default: $this->_error('Set Parameter: Unknown option '.$k); return false; } } return true; } /** * Decode a given ACE domain name * @param string Domain name (ACE string) * [@param string Desired output encoding, see {@link set_parameter}] * @return string Decoded Domain name (UTF-8 or UCS-4) * @access public */ function decode($input, $one_time_encoding = false) { // Optionally set if ($one_time_encoding) { switch ($one_time_encoding) { case 'utf8': case 'ucs4_string': case 'ucs4_array': break; default: $this->_error('Unknown encoding '.$one_time_encoding); return false; } } // Make sure to drop any newline characters around $input = trim($input); // Negotiate input and try to determine, whether it is a plain string, // an email address or something like a complete URL if (strpos($input, '@')) { // Maybe it is an email address // No no in strict mode if ($this->_strict_mode) { $this->_error('Only simple domain name parts can be handled in strict mode'); return false; } list ($email_pref, $input) = explode('@', $input, 2); $arr = explode('.', $input); foreach ($arr as $k => $v) { if (preg_match('!^'.preg_quote($this->_punycode_prefix, '!').'!', $v)) { $conv = $this->_decode($v); if ($conv) $arr[$k] = $conv; } } $input = join('.', $arr); $arr = explode('.', $email_pref); foreach ($arr as $k => $v) { if (preg_match('!^'.preg_quote($this->_punycode_prefix, '!').'!', $v)) { $conv = $this->_decode($v); if ($conv) $arr[$k] = $conv; } } $email_pref = join('.', $arr); $return = $email_pref . '@' . $input; } elseif (preg_match('![:\./]!', $input)) { // Or a complete domain name (with or without paths / parameters) // No no in strict mode if ($this->_strict_mode) { $this->_error('Only simple domain name parts can be handled in strict mode'); return false; } $parsed = parse_url($input); if (isset($parsed['host'])) { $arr = explode('.', $parsed['host']); foreach ($arr as $k => $v) { $conv = $this->_decode($v); if ($conv) $arr[$k] = $conv; } $parsed['host'] = join('.', $arr); $return = (empty($parsed['scheme']) ? '' : $parsed['scheme'].(strtolower($parsed['scheme']) == 'mailto' ? ':' : '://')) .(empty($parsed['user']) ? '' : $parsed['user'].(empty($parsed['pass']) ? '' : ':'.$parsed['pass']).'@') .$parsed['host'] .(empty($parsed['port']) ? '' : ':'.$parsed['port']) .(empty($parsed['path']) ? '' : $parsed['path']) .(empty($parsed['query']) ? '' : '?'.$parsed['query']) .(empty($parsed['fragment']) ? '' : '#'.$parsed['fragment']); } else { // parse_url seems to have failed, try without it $arr = explode('.', $input); foreach ($arr as $k => $v) { $conv = $this->_decode($v); $arr[$k] = ($conv) ? $conv : $v; } $return = join('.', $arr); } } else { // Otherwise we consider it being a pure domain name string $return = $this->_decode($input); if (!$return) $return = $input; } // The output is UTF-8 by default, other output formats need conversion here // If one time encoding is given, use this, else the objects property switch (($one_time_encoding) ? $one_time_encoding : $this->_api_encoding) { case 'utf8': return $return; break; case 'ucs4_string': return $this->_ucs4_to_ucs4_string($this->_utf8_to_ucs4($return)); break; case 'ucs4_array': return $this->_utf8_to_ucs4($return); break; default: $this->_error('Unsupported output format'); return false; } } /** * Encode a given UTF-8 domain name * @param string Domain name (UTF-8 or UCS-4) * [@param string Desired input encoding, see {@link set_parameter}] * @return string Encoded Domain name (ACE string) * @access public */ function encode($decoded, $one_time_encoding = false) { // Forcing conversion of input to UCS4 array // If one time encoding is given, use this, else the objects property switch ($one_time_encoding ? $one_time_encoding : $this->_api_encoding) { case 'utf8': $decoded = $this->_utf8_to_ucs4($decoded); break; case 'ucs4_string': $decoded = $this->_ucs4_string_to_ucs4($decoded); case 'ucs4_array': break; default: $this->_error('Unsupported input format: '.($one_time_encoding ? $one_time_encoding : $this->_api_encoding)); return false; } // No input, no output, what else did you expect? if (empty($decoded)) return ''; // Anchors for iteration $last_begin = 0; // Output string $output = ''; foreach ($decoded as $k => $v) { // Make sure to use just the plain dot switch($v) { case 0x3002: case 0xFF0E: case 0xFF61: $decoded[$k] = 0x2E; // Right, no break here, the above are converted to dots anyway // Stumbling across an anchoring character case 0x2E: case 0x2F: case 0x3A: case 0x3F: case 0x40: // Neither email addresses nor URLs allowed in strict mode if ($this->_strict_mode) { $this->_error('Neither email addresses nor URLs are allowed in strict mode.'); return false; } else { // Skip first char if ($k) { $encoded = ''; $encoded = $this->_encode(array_slice($decoded, $last_begin, (($k)-$last_begin))); if ($encoded) { $output .= $encoded; } else { $output .= $this->_ucs4_to_utf8(array_slice($decoded, $last_begin, (($k)-$last_begin))); } $output .= chr($decoded[$k]); } $last_begin = $k + 1; } } } // Catch the rest of the string if ($last_begin) { $inp_len = sizeof($decoded); $encoded = ''; $encoded = $this->_encode(array_slice($decoded, $last_begin, (($inp_len)-$last_begin))); if ($encoded) { $output .= $encoded; } else { $output .= $this->_ucs4_to_utf8(array_slice($decoded, $last_begin, (($inp_len)-$last_begin))); } return $output; } else { if ($output = $this->_encode($decoded)) { return $output; } else { return $this->_ucs4_to_utf8($decoded); } } } /** * Use this method to get the last error ocurred * @param void * @return string The last error, that occured * @access public */ function get_last_error() { return $this->_error; } /** * The actual decoding algorithm * @access private */ function _decode($encoded) { // We do need to find the Punycode prefix if (!preg_match('!^'.preg_quote($this->_punycode_prefix, '!').'!', $encoded)) { $this->_error('This is not a punycode string'); return false; } $encode_test = preg_replace('!^'.preg_quote($this->_punycode_prefix, '!').'!', '', $encoded); // If nothing left after removing the prefix, it is hopeless if (!$encode_test) { $this->_error('The given encoded string was empty'); return false; } // Find last occurence of the delimiter $delim_pos = strrpos($encoded, '-'); if ($delim_pos > strlen($this->_punycode_prefix)) { for ($k = strlen($this->_punycode_prefix); $k < $delim_pos; ++$k) { $decoded[] = ord($encoded{$k}); } } else { $decoded = array(); } $deco_len = count($decoded); $enco_len = strlen($encoded); // Wandering through the strings; init $is_first = true; $bias = $this->_initial_bias; $idx = 0; $char = $this->_initial_n; for ($enco_idx = ($delim_pos) ? ($delim_pos + 1) : 0; $enco_idx < $enco_len; ++$deco_len) { for ($old_idx = $idx, $w = 1, $k = $this->_base; 1 ; $k += $this->_base) { $digit = $this->_decode_digit($encoded{$enco_idx++}); $idx += $digit * $w; $t = ($k <= $bias) ? $this->_tmin : (($k >= $bias + $this->_tmax) ? $this->_tmax : ($k - $bias)); if ($digit < $t) break; $w = (int) ($w * ($this->_base - $t)); } $bias = $this->_adapt($idx - $old_idx, $deco_len + 1, $is_first); $is_first = false; $char += (int) ($idx / ($deco_len + 1)); $idx %= ($deco_len + 1); if ($deco_len > 0) { // Make room for the decoded char for ($i = $deco_len; $i > $idx; $i--) { $decoded[$i] = $decoded[($i - 1)]; } } $decoded[$idx++] = $char; } return $this->_ucs4_to_utf8($decoded); } /** * The actual encoding algorithm * @access private */ function _encode($decoded) { // We cannot encode a domain name containing the Punycode prefix $extract = strlen($this->_punycode_prefix); $check_pref = $this->_utf8_to_ucs4($this->_punycode_prefix); $check_deco = array_slice($decoded, 0, $extract); if ($check_pref == $check_deco) { $this->_error('This is already a punycode string'); return false; } // We will not try to encode strings consisting of basic code points only $encodable = false; foreach ($decoded as $k => $v) { if ($v > 0x7a) { $encodable = true; break; } } if (!$encodable) { $this->_error('The given string does not contain encodable chars'); return false; } // Do NAMEPREP $decoded = $this->_nameprep($decoded); if (!$decoded || !is_array($decoded)) return false; // NAMEPREP failed $deco_len = count($decoded); if (!$deco_len) return false; // Empty array $codecount = 0; // How many chars have been consumed $encoded = ''; // Copy all basic code points to output for ($i = 0; $i < $deco_len; ++$i) { $test = $decoded[$i]; // Will match [-0-9a-zA-Z] if ((0x2F < $test && $test < 0x40) || (0x40 < $test && $test < 0x5B) || (0x60 < $test && $test <= 0x7B) || (0x2D == $test)) { $encoded .= chr($decoded[$i]); $codecount++; } } if ($codecount == $deco_len) return $encoded; // All codepoints were basic ones // Start with the prefix; copy it to output $encoded = $this->_punycode_prefix.$encoded; // If we have basic code points in output, add an hyphen to the end if ($codecount) $encoded .= '-'; // Now find and encode all non-basic code points $is_first = true; $cur_code = $this->_initial_n; $bias = $this->_initial_bias; $delta = 0; while ($codecount < $deco_len) { // Find the smallest code point >= the current code point and // remember the last ouccrence of it in the input for ($i = 0, $next_code = $this->_max_ucs; $i < $deco_len; $i++) { if ($decoded[$i] >= $cur_code && $decoded[$i] <= $next_code) { $next_code = $decoded[$i]; } } $delta += ($next_code - $cur_code) * ($codecount + 1); $cur_code = $next_code; // Scan input again and encode all characters whose code point is $cur_code for ($i = 0; $i < $deco_len; $i++) { if ($decoded[$i] < $cur_code) { $delta++; } elseif ($decoded[$i] == $cur_code) { for ($q = $delta, $k = $this->_base; 1; $k += $this->_base) { $t = ($k <= $bias) ? $this->_tmin : (($k >= $bias + $this->_tmax) ? $this->_tmax : $k - $bias); if ($q < $t) break; $encoded .= $this->_encode_digit(intval($t + (($q - $t) % ($this->_base - $t)))); //v0.4.5 Changed from ceil() to intval() $q = (int) (($q - $t) / ($this->_base - $t)); } $encoded .= $this->_encode_digit($q); $bias = $this->_adapt($delta, $codecount+1, $is_first); $codecount++; $delta = 0; $is_first = false; } } $delta++; $cur_code++; } return $encoded; } /** * Adapt the bias according to the current code point and position * @access private */ function _adapt($delta, $npoints, $is_first) { $delta = intval($is_first ? ($delta / $this->_damp) : ($delta / 2)); $delta += intval($delta / $npoints); for ($k = 0; $delta > (($this->_base - $this->_tmin) * $this->_tmax) / 2; $k += $this->_base) { $delta = intval($delta / ($this->_base - $this->_tmin)); } return intval($k + ($this->_base - $this->_tmin + 1) * $delta / ($delta + $this->_skew)); } /** * Encoding a certain digit * @access private */ function _encode_digit($d) { return chr($d + 22 + 75 * ($d < 26)); } /** * Decode a certain digit * @access private */ function _decode_digit($cp) { $cp = ord($cp); return ($cp - 48 < 10) ? $cp - 22 : (($cp - 65 < 26) ? $cp - 65 : (($cp - 97 < 26) ? $cp - 97 : $this->_base)); } /** * Internal error handling method * @access private */ function _error($error = '') { $this->_error = $error; } /** * Do Nameprep according to RFC3491 and RFC3454 * @param array Unicode Characters * @return string Unicode Characters, Nameprep'd * @access private */ function _nameprep($input) { $output = array(); $error = false; // // Mapping // Walking through the input array, performing the required steps on each of // the input chars and putting the result into the output array // While mapping required chars we apply the cannonical ordering foreach ($input as $v) { // Map to nothing == skip that code point if (in_array($v, $this->NP['map_nothing'])) continue; // Try to find prohibited input if (in_array($v, $this->NP['prohibit']) || in_array($v, $this->NP['general_prohibited'])) { $this->_error('NAMEPREP: Prohibited input U+'.sprintf('%08X', $v)); return false; } foreach ($this->NP['prohibit_ranges'] as $range) { if ($range[0] <= $v && $v <= $range[1]) { $this->_error('NAMEPREP: Prohibited input U+'.sprintf('%08X', $v)); return false; } } // // Hangul syllable decomposition if (0xAC00 <= $v && $v <= 0xD7AF) { foreach ($this->_hangul_decompose($v) as $out) { $output[] = (int) $out; } // There's a decomposition mapping for that code point } elseif (isset($this->NP['replacemaps'][$v])) { foreach ($this->_apply_cannonical_ordering($this->NP['replacemaps'][$v]) as $out) { $output[] = (int) $out; } } else { $output[] = (int) $v; } } // Before applying any Combining, try to rearrange any Hangul syllables $output = $this->_hangul_compose($output); // // Combine code points // $last_class = 0; $last_starter = 0; $out_len = count($output); for ($i = 0; $i < $out_len; ++$i) { $class = $this->_get_combining_class($output[$i]); if ((!$last_class || $last_class > $class) && $class) { // Try to match $seq_len = $i - $last_starter; $out = $this->_combine(array_slice($output, $last_starter, $seq_len)); // On match: Replace the last starter with the composed character and remove // the now redundant non-starter(s) if ($out) { $output[$last_starter] = $out; if (count($out) != $seq_len) { for ($j = $i+1; $j < $out_len; ++$j) { $output[$j-1] = $output[$j]; } unset($output[$out_len]); } // Rewind the for loop by one, since there can be more possible compositions $i--; $out_len--; $last_class = ($i == $last_starter) ? 0 : $this->_get_combining_class($output[$i-1]); continue; } } // The current class is 0 if (!$class) $last_starter = $i; $last_class = $class; } return $output; } /** * Decomposes a Hangul syllable * (see http://www.unicode.org/unicode/reports/tr15/#Hangul * @param integer 32bit UCS4 code point * @return array Either Hangul Syllable decomposed or original 32bit value as one value array * @access private */ function _hangul_decompose($char) { $sindex = (int) $char - $this->_sbase; if ($sindex < 0 || $sindex >= $this->_scount) { return array($char); } $result = array(); $result[] = (int) $this->_lbase + $sindex / $this->_ncount; $result[] = (int) $this->_vbase + ($sindex % $this->_ncount) / $this->_tcount; $T = intval($this->_tbase + $sindex % $this->_tcount); if ($T != $this->_tbase) $result[] = $T; return $result; } /** * Ccomposes a Hangul syllable * (see http://www.unicode.org/unicode/reports/tr15/#Hangul * @param array Decomposed UCS4 sequence * @return array UCS4 sequence with syllables composed * @access private */ function _hangul_compose($input) { $inp_len = count($input); if (!$inp_len) return array(); $result = array(); $last = (int) $input[0]; $result[] = $last; // copy first char from input to output for ($i = 1; $i < $inp_len; ++$i) { $char = (int) $input[$i]; $sindex = $last - $this->_sbase; $lindex = $last - $this->_lbase; $vindex = $char - $this->_vbase; $tindex = $char - $this->_tbase; // Find out, whether two current characters are LV and T if (0 <= $sindex && $sindex < $this->_scount && ($sindex % $this->_tcount == 0) && 0 <= $tindex && $tindex <= $this->_tcount) { // create syllable of form LVT $last += $tindex; $result[(count($result) - 1)] = $last; // reset last continue; // discard char } // Find out, whether two current characters form L and V if (0 <= $lindex && $lindex < $this->_lcount && 0 <= $vindex && $vindex < $this->_vcount) { // create syllable of form LV $last = (int) $this->_sbase + ($lindex * $this->_vcount + $vindex) * $this->_tcount; $result[(count($result) - 1)] = $last; // reset last continue; // discard char } // if neither case was true, just add the character $last = $char; $result[] = $char; } return $result; } /** * Returns the combining class of a certain wide char * @param integer Wide char to check (32bit integer) * @return integer Combining class if found, else 0 * @access private */ function _get_combining_class($char) { return isset($this->NP['norm_combcls'][$char]) ? $this->NP['norm_combcls'][$char] : 0; } /** * Apllies the cannonical ordering of a decomposed UCS4 sequence * @param array Decomposed UCS4 sequence * @return array Ordered USC4 sequence * @access private */ function _apply_cannonical_ordering($input) { $swap = true; $size = count($input); while ($swap) { $swap = false; $last = $this->_get_combining_class(intval($input[0])); for ($i = 0; $i < $size-1; ++$i) { $next = $this->_get_combining_class(intval($input[$i+1])); if ($next != 0 && $last > $next) { // Move item leftward until it fits for ($j = $i + 1; $j > 0; --$j) { if ($this->_get_combining_class(intval($input[$j-1])) <= $next) break; $t = intval($input[$j]); $input[$j] = intval($input[$j-1]); $input[$j-1] = $t; $swap = true; } // Reentering the loop looking at the old character again $next = $last; } $last = $next; } } return $input; } /** * Do composition of a sequence of starter and non-starter * @param array UCS4 Decomposed sequence * @return array Ordered USC4 sequence * @access private */ function _combine($input) { $inp_len = count($input); foreach ($this->NP['replacemaps'] as $np_src => $np_target) { if ($np_target[0] != $input[0]) continue; if (count($np_target) != $inp_len) continue; $hit = false; foreach ($input as $k2 => $v2) { if ($v2 == $np_target[$k2]) { $hit = true; } else { $hit = false; break; } } if ($hit) return $np_src; } return false; } /** * This converts an UTF-8 encoded string to its UCS-4 representation * By talking about UCS-4 "strings" we mean arrays of 32bit integers representing * each of the "chars". This is due to PHP not being able to handle strings with * bit depth different from 8. This apllies to the reverse method _ucs4_to_utf8(), too. * The following UTF-8 encodings are supported: * bytes bits representation * 1 7 0xxxxxxx * 2 11 110xxxxx 10xxxxxx * 3 16 1110xxxx 10xxxxxx 10xxxxxx * 4 21 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx * 5 26 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx * 6 31 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx * Each x represents a bit that can be used to store character data. * The five and six byte sequences are part of Annex D of ISO/IEC 10646-1:2000 * @access private */ function _utf8_to_ucs4($input) { $output = array(); $out_len = 0; $inp_len = strlen($input); $mode = 'next'; $test = 'none'; for ($k = 0; $k < $inp_len; ++$k) { $v = ord($input{$k}); // Extract byte from input string if ($v < 128) { // We found an ASCII char - put into stirng as is $output[$out_len] = $v; ++$out_len; if ('add' == $mode) { $this->_error('Conversion from UTF-8 to UCS-4 failed: malformed input at byte '.$k); return false; } continue; } if ('next' == $mode) { // Try to find the next start byte; determine the width of the Unicode char $start_byte = $v; $mode = 'add'; $test = 'range'; if ($v >> 5 == 6) { // &110xxxxx 10xxxxx $next_byte = 0; // Tells, how many times subsequent bitmasks must rotate 6bits to the left $v = ($v - 192) << 6; } elseif ($v >> 4 == 14) { // &1110xxxx 10xxxxxx 10xxxxxx $next_byte = 1; $v = ($v - 224) << 12; } elseif ($v >> 3 == 30) { // &11110xxx 10xxxxxx 10xxxxxx 10xxxxxx $next_byte = 2; $v = ($v - 240) << 18; } elseif ($v >> 2 == 62) { // &111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx $next_byte = 3; $v = ($v - 248) << 24; } elseif ($v >> 1 == 126) { // &1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx $next_byte = 4; $v = ($v - 252) << 30; } else { $this->_error('This might be UTF-8, but I don\'t understand it at byte '.$k); return false; } if ('add' == $mode) { $output[$out_len] = (int) $v; ++$out_len; continue; } } if ('add' == $mode) { if (!$this->_allow_overlong && $test == 'range') { $test = 'none'; if (($v < 0xA0 && $start_byte == 0xE0) || ($v < 0x90 && $start_byte == 0xF0) || ($v > 0x8F && $start_byte == 0xF4)) { $this->_error('Bogus UTF-8 character detected (out of legal range) at byte '.$k); return false; } } if ($v >> 6 == 2) { // Bit mask must be 10xxxxxx $v = ($v - 128) << ($next_byte * 6); $output[($out_len - 1)] += $v; --$next_byte; } else { $this->_error('Conversion from UTF-8 to UCS-4 failed: malformed input at byte '.$k); return false; } if ($next_byte < 0) { $mode = 'next'; } } } // for return $output; } /** * Convert UCS-4 string into UTF-8 string * See _utf8_to_ucs4() for details * @access private */ function _ucs4_to_utf8($input) { $output = ''; $k = 0; foreach ($input as $v) { ++$k; // $v = ord($v); if ($v < 128) { // 7bit are transferred literally $output .= chr($v); } elseif ($v < (1 << 11)) { // 2 bytes $output .= chr(192 + ($v >> 6)) . chr(128 + ($v & 63)); } elseif ($v < (1 << 16)) { // 3 bytes $output .= chr(224 + ($v >> 12)) . chr(128 + (($v >> 6) & 63)) . chr(128 + ($v & 63)); } elseif ($v < (1 << 21)) { // 4 bytes $output .= chr(240 + ($v >> 18)) . chr(128 + (($v >> 12) & 63)) . chr(128 + (($v >> 6) & 63)) . chr(128 + ($v & 63)); } elseif ($v < (1 << 26)) { // 5 bytes $output .= chr(248 + ($v >> 24)) . chr(128 + (($v >> 18) & 63)) . chr(128 + (($v >> 12) & 63)) . chr(128 + (($v >> 6) & 63)) . chr(128 + ($v & 63)); } elseif ($v < (1 << 31)) { // 6 bytes $output .= chr(252 + ($v >> 30)) . chr(128 + (($v >> 24) & 63)) . chr(128 + (($v >> 18) & 63)) . chr(128 + (($v >> 12) & 63)) . chr(128 + (($v >> 6) & 63)) . chr(128 + ($v & 63)); } else { $this->_error('Conversion from UCS-4 to UTF-8 failed: malformed input at byte '.$k); return false; } } return $output; } /** * Convert UCS-4 array into UCS-4 string * * @access private */ function _ucs4_to_ucs4_string($input) { $output = ''; // Take array values and split output to 4 bytes per value // The bit mask is 255, which reads &11111111 foreach ($input as $v) { $output .= chr(($v >> 24) & 255).chr(($v >> 16) & 255).chr(($v >> 8) & 255).chr($v & 255); } return $output; } /** * Convert UCS-4 strin into UCS-4 garray * * @access private */ function _ucs4_string_to_ucs4($input) { $output = array(); $inp_len = strlen($input); // Input length must be dividable by 4 if ($inp_len % 4) { $this->_error('Input UCS4 string is broken'); return false; } // Empty input - return empty output if (!$inp_len) return $output; for ($i = 0, $out_len = -1; $i < $inp_len; ++$i) { // Increment output position every 4 input bytes if (!($i % 4)) { $out_len++; $output[$out_len] = 0; } $output[$out_len] += ord($input{$i}) << (8 * (3 - ($i % 4) ) ); } return $output; } } /** * Adapter class for aligning the API of idna_convert with that of Net_IDNA * @author Matthias Sommerfeld <mso@phlylabs.de> */ class Net_IDNA_php4 extends idna_convert { /** * Sets a new option value. Available options and values: * [encoding - Use either UTF-8, UCS4 as array or UCS4 as string as input ('utf8' for UTF-8, * 'ucs4_string' and 'ucs4_array' respectively for UCS4); The output is always UTF-8] * [overlong - Unicode does not allow unnecessarily long encodings of chars, * to allow this, set this parameter to true, else to false; * default is false.] * [strict - true: strict mode, good for registration purposes - Causes errors * on failures; false: loose mode, ideal for "wildlife" applications * by silently ignoring errors and returning the original input instead * * @param mixed Parameter to set (string: single parameter; array of Parameter => Value pairs) * @param string Value to use (if parameter 1 is a string) * @return boolean true on success, false otherwise * @access public */ function setParams($option, $param = false) { return $this->IC->set_parameters($option, $param); } } ?>