<?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
 */

/**
 * Decode HTML Entities
 *
 * This implements HTML5 as of revision 967 (2007-06-28)
 *
 * @deprecated Use DOMDocument instead!
 * @package SimplePie
 */
class SimplePie_Decode_HTML_Entities
{
	/**
	 * Data to be parsed
	 *
	 * @access private
	 * @var string
	 */
	var $data = '';

	/**
	 * Currently consumed bytes
	 *
	 * @access private
	 * @var string
	 */
	var $consumed = '';

	/**
	 * Position of the current byte being parsed
	 *
	 * @access private
	 * @var int
	 */
	var $position = 0;

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

	/**
	 * Parse the input data
	 *
	 * @access public
	 * @return string Output data
	 */
	public function parse()
	{
		while (($this->position = strpos($this->data, '&', $this->position)) !== false)
		{
			$this->consume();
			$this->entity();
			$this->consumed = '';
		}
		return $this->data;
	}

	/**
	 * Consume the next byte
	 *
	 * @access private
	 * @return mixed The next byte, or false, if there is no more data
	 */
	public function consume()
	{
		if (isset($this->data[$this->position]))
		{
			$this->consumed .= $this->data[$this->position];
			return $this->data[$this->position++];
		}

		return false;
	}

	/**
	 * Consume a range of characters
	 *
	 * @access private
	 * @param string $chars Characters to consume
	 * @return mixed A series of characters that match the range, or false
	 */
	public function consume_range($chars)
	{
		if ($len = strspn($this->data, $chars, $this->position))
		{
			$data = substr($this->data, $this->position, $len);
			$this->consumed .= $data;
			$this->position += $len;
			return $data;
		}

		return false;
	}

	/**
	 * Unconsume one byte
	 *
	 * @access private
	 */
	public function unconsume()
	{
		$this->consumed = substr($this->consumed, 0, -1);
		$this->position--;
	}

	/**
	 * Decode an entity
	 *
	 * @access private
	 */
	public function entity()
	{
		switch ($this->consume())
		{
			case "\x09":
			case "\x0A":
			case "\x0B":
			case "\x0C":
			case "\x20":
			case "\x3C":
			case "\x26":
			case false:
				break;

			case "\x23":
				switch ($this->consume())
				{
					case "\x78":
					case "\x58":
						$range = '0123456789ABCDEFabcdef';
						$hex = true;
						break;

					default:
						$range = '0123456789';
						$hex = false;
						$this->unconsume();
						break;
				}

				if ($codepoint = $this->consume_range($range))
				{
					static $windows_1252_specials = array(0x0D => "\x0A", 0x80 => "\xE2\x82\xAC", 0x81 => "\xEF\xBF\xBD", 0x82 => "\xE2\x80\x9A", 0x83 => "\xC6\x92", 0x84 => "\xE2\x80\x9E", 0x85 => "\xE2\x80\xA6", 0x86 => "\xE2\x80\xA0", 0x87 => "\xE2\x80\xA1", 0x88 => "\xCB\x86", 0x89 => "\xE2\x80\xB0", 0x8A => "\xC5\xA0", 0x8B => "\xE2\x80\xB9", 0x8C => "\xC5\x92", 0x8D => "\xEF\xBF\xBD", 0x8E => "\xC5\xBD", 0x8F => "\xEF\xBF\xBD", 0x90 => "\xEF\xBF\xBD", 0x91 => "\xE2\x80\x98", 0x92 => "\xE2\x80\x99", 0x93 => "\xE2\x80\x9C", 0x94 => "\xE2\x80\x9D", 0x95 => "\xE2\x80\xA2", 0x96 => "\xE2\x80\x93", 0x97 => "\xE2\x80\x94", 0x98 => "\xCB\x9C", 0x99 => "\xE2\x84\xA2", 0x9A => "\xC5\xA1", 0x9B => "\xE2\x80\xBA", 0x9C => "\xC5\x93", 0x9D => "\xEF\xBF\xBD", 0x9E => "\xC5\xBE", 0x9F => "\xC5\xB8");

					if ($hex)
					{
						$codepoint = hexdec($codepoint);
					}
					else
					{
						$codepoint = intval($codepoint);
					}

					if (isset($windows_1252_specials[$codepoint]))
					{
						$replacement = $windows_1252_specials[$codepoint];
					}
					else
					{
						$replacement = SimplePie_Misc::codepoint_to_utf8($codepoint);
					}

					if (!in_array($this->consume(), array(';', false), true))
					{
						$this->unconsume();
					}

					$consumed_length = strlen($this->consumed);
					$this->data = substr_replace($this->data, $replacement, $this->position - $consumed_length, $consumed_length);
					$this->position += strlen($replacement) - $consumed_length;
				}
				break;

			default:
				static $entities = array(
					'Aacute' => "\xC3\x81",
					'aacute' => "\xC3\xA1",
					'Aacute;' => "\xC3\x81",
					'aacute;' => "\xC3\xA1",
					'Acirc' => "\xC3\x82",
					'acirc' => "\xC3\xA2",
					'Acirc;' => "\xC3\x82",
					'acirc;' => "\xC3\xA2",
					'acute' => "\xC2\xB4",
					'acute;' => "\xC2\xB4",
					'AElig' => "\xC3\x86",
					'aelig' => "\xC3\xA6",
					'AElig;' => "\xC3\x86",
					'aelig;' => "\xC3\xA6",
					'Agrave' => "\xC3\x80",
					'agrave' => "\xC3\xA0",
					'Agrave;' => "\xC3\x80",
					'agrave;' => "\xC3\xA0",
					'alefsym;' => "\xE2\x84\xB5",
					'Alpha;' => "\xCE\x91",
					'alpha;' => "\xCE\xB1",
					'AMP' => "\x26",
					'amp' => "\x26",
					'AMP;' => "\x26",
					'amp;' => "\x26",
					'and;' => "\xE2\x88\xA7",
					'ang;' => "\xE2\x88\xA0",
					'apos;' => "\x27",
					'Aring' => "\xC3\x85",
					'aring' => "\xC3\xA5",
					'Aring;' => "\xC3\x85",
					'aring;' => "\xC3\xA5",
					'asymp;' => "\xE2\x89\x88",
					'Atilde' => "\xC3\x83",
					'atilde' => "\xC3\xA3",
					'Atilde;' => "\xC3\x83",
					'atilde;' => "\xC3\xA3",
					'Auml' => "\xC3\x84",
					'auml' => "\xC3\xA4",
					'Auml;' => "\xC3\x84",
					'auml;' => "\xC3\xA4",
					'bdquo;' => "\xE2\x80\x9E",
					'Beta;' => "\xCE\x92",
					'beta;' => "\xCE\xB2",
					'brvbar' => "\xC2\xA6",
					'brvbar;' => "\xC2\xA6",
					'bull;' => "\xE2\x80\xA2",
					'cap;' => "\xE2\x88\xA9",
					'Ccedil' => "\xC3\x87",
					'ccedil' => "\xC3\xA7",
					'Ccedil;' => "\xC3\x87",
					'ccedil;' => "\xC3\xA7",
					'cedil' => "\xC2\xB8",
					'cedil;' => "\xC2\xB8",
					'cent' => "\xC2\xA2",
					'cent;' => "\xC2\xA2",
					'Chi;' => "\xCE\xA7",
					'chi;' => "\xCF\x87",
					'circ;' => "\xCB\x86",
					'clubs;' => "\xE2\x99\xA3",
					'cong;' => "\xE2\x89\x85",
					'COPY' => "\xC2\xA9",
					'copy' => "\xC2\xA9",
					'COPY;' => "\xC2\xA9",
					'copy;' => "\xC2\xA9",
					'crarr;' => "\xE2\x86\xB5",
					'cup;' => "\xE2\x88\xAA",
					'curren' => "\xC2\xA4",
					'curren;' => "\xC2\xA4",
					'Dagger;' => "\xE2\x80\xA1",
					'dagger;' => "\xE2\x80\xA0",
					'dArr;' => "\xE2\x87\x93",
					'darr;' => "\xE2\x86\x93",
					'deg' => "\xC2\xB0",
					'deg;' => "\xC2\xB0",
					'Delta;' => "\xCE\x94",
					'delta;' => "\xCE\xB4",
					'diams;' => "\xE2\x99\xA6",
					'divide' => "\xC3\xB7",
					'divide;' => "\xC3\xB7",
					'Eacute' => "\xC3\x89",
					'eacute' => "\xC3\xA9",
					'Eacute;' => "\xC3\x89",
					'eacute;' => "\xC3\xA9",
					'Ecirc' => "\xC3\x8A",
					'ecirc' => "\xC3\xAA",
					'Ecirc;' => "\xC3\x8A",
					'ecirc;' => "\xC3\xAA",
					'Egrave' => "\xC3\x88",
					'egrave' => "\xC3\xA8",
					'Egrave;' => "\xC3\x88",
					'egrave;' => "\xC3\xA8",
					'empty;' => "\xE2\x88\x85",
					'emsp;' => "\xE2\x80\x83",
					'ensp;' => "\xE2\x80\x82",
					'Epsilon;' => "\xCE\x95",
					'epsilon;' => "\xCE\xB5",
					'equiv;' => "\xE2\x89\xA1",
					'Eta;' => "\xCE\x97",
					'eta;' => "\xCE\xB7",
					'ETH' => "\xC3\x90",
					'eth' => "\xC3\xB0",
					'ETH;' => "\xC3\x90",
					'eth;' => "\xC3\xB0",
					'Euml' => "\xC3\x8B",
					'euml' => "\xC3\xAB",
					'Euml;' => "\xC3\x8B",
					'euml;' => "\xC3\xAB",
					'euro;' => "\xE2\x82\xAC",
					'exist;' => "\xE2\x88\x83",
					'fnof;' => "\xC6\x92",
					'forall;' => "\xE2\x88\x80",
					'frac12' => "\xC2\xBD",
					'frac12;' => "\xC2\xBD",
					'frac14' => "\xC2\xBC",
					'frac14;' => "\xC2\xBC",
					'frac34' => "\xC2\xBE",
					'frac34;' => "\xC2\xBE",
					'frasl;' => "\xE2\x81\x84",
					'Gamma;' => "\xCE\x93",
					'gamma;' => "\xCE\xB3",
					'ge;' => "\xE2\x89\xA5",
					'GT' => "\x3E",
					'gt' => "\x3E",
					'GT;' => "\x3E",
					'gt;' => "\x3E",
					'hArr;' => "\xE2\x87\x94",
					'harr;' => "\xE2\x86\x94",
					'hearts;' => "\xE2\x99\xA5",
					'hellip;' => "\xE2\x80\xA6",
					'Iacute' => "\xC3\x8D",
					'iacute' => "\xC3\xAD",
					'Iacute;' => "\xC3\x8D",
					'iacute;' => "\xC3\xAD",
					'Icirc' => "\xC3\x8E",
					'icirc' => "\xC3\xAE",
					'Icirc;' => "\xC3\x8E",
					'icirc;' => "\xC3\xAE",
					'iexcl' => "\xC2\xA1",
					'iexcl;' => "\xC2\xA1",
					'Igrave' => "\xC3\x8C",
					'igrave' => "\xC3\xAC",
					'Igrave;' => "\xC3\x8C",
					'igrave;' => "\xC3\xAC",
					'image;' => "\xE2\x84\x91",
					'infin;' => "\xE2\x88\x9E",
					'int;' => "\xE2\x88\xAB",
					'Iota;' => "\xCE\x99",
					'iota;' => "\xCE\xB9",
					'iquest' => "\xC2\xBF",
					'iquest;' => "\xC2\xBF",
					'isin;' => "\xE2\x88\x88",
					'Iuml' => "\xC3\x8F",
					'iuml' => "\xC3\xAF",
					'Iuml;' => "\xC3\x8F",
					'iuml;' => "\xC3\xAF",
					'Kappa;' => "\xCE\x9A",
					'kappa;' => "\xCE\xBA",
					'Lambda;' => "\xCE\x9B",
					'lambda;' => "\xCE\xBB",
					'lang;' => "\xE3\x80\x88",
					'laquo' => "\xC2\xAB",
					'laquo;' => "\xC2\xAB",
					'lArr;' => "\xE2\x87\x90",
					'larr;' => "\xE2\x86\x90",
					'lceil;' => "\xE2\x8C\x88",
					'ldquo;' => "\xE2\x80\x9C",
					'le;' => "\xE2\x89\xA4",
					'lfloor;' => "\xE2\x8C\x8A",
					'lowast;' => "\xE2\x88\x97",
					'loz;' => "\xE2\x97\x8A",
					'lrm;' => "\xE2\x80\x8E",
					'lsaquo;' => "\xE2\x80\xB9",
					'lsquo;' => "\xE2\x80\x98",
					'LT' => "\x3C",
					'lt' => "\x3C",
					'LT;' => "\x3C",
					'lt;' => "\x3C",
					'macr' => "\xC2\xAF",
					'macr;' => "\xC2\xAF",
					'mdash;' => "\xE2\x80\x94",
					'micro' => "\xC2\xB5",
					'micro;' => "\xC2\xB5",
					'middot' => "\xC2\xB7",
					'middot;' => "\xC2\xB7",
					'minus;' => "\xE2\x88\x92",
					'Mu;' => "\xCE\x9C",
					'mu;' => "\xCE\xBC",
					'nabla;' => "\xE2\x88\x87",
					'nbsp' => "\xC2\xA0",
					'nbsp;' => "\xC2\xA0",
					'ndash;' => "\xE2\x80\x93",
					'ne;' => "\xE2\x89\xA0",
					'ni;' => "\xE2\x88\x8B",
					'not' => "\xC2\xAC",
					'not;' => "\xC2\xAC",
					'notin;' => "\xE2\x88\x89",
					'nsub;' => "\xE2\x8A\x84",
					'Ntilde' => "\xC3\x91",
					'ntilde' => "\xC3\xB1",
					'Ntilde;' => "\xC3\x91",
					'ntilde;' => "\xC3\xB1",
					'Nu;' => "\xCE\x9D",
					'nu;' => "\xCE\xBD",
					'Oacute' => "\xC3\x93",
					'oacute' => "\xC3\xB3",
					'Oacute;' => "\xC3\x93",
					'oacute;' => "\xC3\xB3",
					'Ocirc' => "\xC3\x94",
					'ocirc' => "\xC3\xB4",
					'Ocirc;' => "\xC3\x94",
					'ocirc;' => "\xC3\xB4",
					'OElig;' => "\xC5\x92",
					'oelig;' => "\xC5\x93",
					'Ograve' => "\xC3\x92",
					'ograve' => "\xC3\xB2",
					'Ograve;' => "\xC3\x92",
					'ograve;' => "\xC3\xB2",
					'oline;' => "\xE2\x80\xBE",
					'Omega;' => "\xCE\xA9",
					'omega;' => "\xCF\x89",
					'Omicron;' => "\xCE\x9F",
					'omicron;' => "\xCE\xBF",
					'oplus;' => "\xE2\x8A\x95",
					'or;' => "\xE2\x88\xA8",
					'ordf' => "\xC2\xAA",
					'ordf;' => "\xC2\xAA",
					'ordm' => "\xC2\xBA",
					'ordm;' => "\xC2\xBA",
					'Oslash' => "\xC3\x98",
					'oslash' => "\xC3\xB8",
					'Oslash;' => "\xC3\x98",
					'oslash;' => "\xC3\xB8",
					'Otilde' => "\xC3\x95",
					'otilde' => "\xC3\xB5",
					'Otilde;' => "\xC3\x95",
					'otilde;' => "\xC3\xB5",
					'otimes;' => "\xE2\x8A\x97",
					'Ouml' => "\xC3\x96",
					'ouml' => "\xC3\xB6",
					'Ouml;' => "\xC3\x96",
					'ouml;' => "\xC3\xB6",
					'para' => "\xC2\xB6",
					'para;' => "\xC2\xB6",
					'part;' => "\xE2\x88\x82",
					'permil;' => "\xE2\x80\xB0",
					'perp;' => "\xE2\x8A\xA5",
					'Phi;' => "\xCE\xA6",
					'phi;' => "\xCF\x86",
					'Pi;' => "\xCE\xA0",
					'pi;' => "\xCF\x80",
					'piv;' => "\xCF\x96",
					'plusmn' => "\xC2\xB1",
					'plusmn;' => "\xC2\xB1",
					'pound' => "\xC2\xA3",
					'pound;' => "\xC2\xA3",
					'Prime;' => "\xE2\x80\xB3",
					'prime;' => "\xE2\x80\xB2",
					'prod;' => "\xE2\x88\x8F",
					'prop;' => "\xE2\x88\x9D",
					'Psi;' => "\xCE\xA8",
					'psi;' => "\xCF\x88",
					'QUOT' => "\x22",
					'quot' => "\x22",
					'QUOT;' => "\x22",
					'quot;' => "\x22",
					'radic;' => "\xE2\x88\x9A",
					'rang;' => "\xE3\x80\x89",
					'raquo' => "\xC2\xBB",
					'raquo;' => "\xC2\xBB",
					'rArr;' => "\xE2\x87\x92",
					'rarr;' => "\xE2\x86\x92",
					'rceil;' => "\xE2\x8C\x89",
					'rdquo;' => "\xE2\x80\x9D",
					'real;' => "\xE2\x84\x9C",
					'REG' => "\xC2\xAE",
					'reg' => "\xC2\xAE",
					'REG;' => "\xC2\xAE",
					'reg;' => "\xC2\xAE",
					'rfloor;' => "\xE2\x8C\x8B",
					'Rho;' => "\xCE\xA1",
					'rho;' => "\xCF\x81",
					'rlm;' => "\xE2\x80\x8F",
					'rsaquo;' => "\xE2\x80\xBA",
					'rsquo;' => "\xE2\x80\x99",
					'sbquo;' => "\xE2\x80\x9A",
					'Scaron;' => "\xC5\xA0",
					'scaron;' => "\xC5\xA1",
					'sdot;' => "\xE2\x8B\x85",
					'sect' => "\xC2\xA7",
					'sect;' => "\xC2\xA7",
					'shy' => "\xC2\xAD",
					'shy;' => "\xC2\xAD",
					'Sigma;' => "\xCE\xA3",
					'sigma;' => "\xCF\x83",
					'sigmaf;' => "\xCF\x82",
					'sim;' => "\xE2\x88\xBC",
					'spades;' => "\xE2\x99\xA0",
					'sub;' => "\xE2\x8A\x82",
					'sube;' => "\xE2\x8A\x86",
					'sum;' => "\xE2\x88\x91",
					'sup;' => "\xE2\x8A\x83",
					'sup1' => "\xC2\xB9",
					'sup1;' => "\xC2\xB9",
					'sup2' => "\xC2\xB2",
					'sup2;' => "\xC2\xB2",
					'sup3' => "\xC2\xB3",
					'sup3;' => "\xC2\xB3",
					'supe;' => "\xE2\x8A\x87",
					'szlig' => "\xC3\x9F",
					'szlig;' => "\xC3\x9F",
					'Tau;' => "\xCE\xA4",
					'tau;' => "\xCF\x84",
					'there4;' => "\xE2\x88\xB4",
					'Theta;' => "\xCE\x98",
					'theta;' => "\xCE\xB8",
					'thetasym;' => "\xCF\x91",
					'thinsp;' => "\xE2\x80\x89",
					'THORN' => "\xC3\x9E",
					'thorn' => "\xC3\xBE",
					'THORN;' => "\xC3\x9E",
					'thorn;' => "\xC3\xBE",
					'tilde;' => "\xCB\x9C",
					'times' => "\xC3\x97",
					'times;' => "\xC3\x97",
					'TRADE;' => "\xE2\x84\xA2",
					'trade;' => "\xE2\x84\xA2",
					'Uacute' => "\xC3\x9A",
					'uacute' => "\xC3\xBA",
					'Uacute;' => "\xC3\x9A",
					'uacute;' => "\xC3\xBA",
					'uArr;' => "\xE2\x87\x91",
					'uarr;' => "\xE2\x86\x91",
					'Ucirc' => "\xC3\x9B",
					'ucirc' => "\xC3\xBB",
					'Ucirc;' => "\xC3\x9B",
					'ucirc;' => "\xC3\xBB",
					'Ugrave' => "\xC3\x99",
					'ugrave' => "\xC3\xB9",
					'Ugrave;' => "\xC3\x99",
					'ugrave;' => "\xC3\xB9",
					'uml' => "\xC2\xA8",
					'uml;' => "\xC2\xA8",
					'upsih;' => "\xCF\x92",
					'Upsilon;' => "\xCE\xA5",
					'upsilon;' => "\xCF\x85",
					'Uuml' => "\xC3\x9C",
					'uuml' => "\xC3\xBC",
					'Uuml;' => "\xC3\x9C",
					'uuml;' => "\xC3\xBC",
					'weierp;' => "\xE2\x84\x98",
					'Xi;' => "\xCE\x9E",
					'xi;' => "\xCE\xBE",
					'Yacute' => "\xC3\x9D",
					'yacute' => "\xC3\xBD",
					'Yacute;' => "\xC3\x9D",
					'yacute;' => "\xC3\xBD",
					'yen' => "\xC2\xA5",
					'yen;' => "\xC2\xA5",
					'yuml' => "\xC3\xBF",
					'Yuml;' => "\xC5\xB8",
					'yuml;' => "\xC3\xBF",
					'Zeta;' => "\xCE\x96",
					'zeta;' => "\xCE\xB6",
					'zwj;' => "\xE2\x80\x8D",
					'zwnj;' => "\xE2\x80\x8C"
				);

				for ($i = 0, $match = null; $i < 9 && $this->consume() !== false; $i++)
				{
					$consumed = substr($this->consumed, 1);
					if (isset($entities[$consumed]))
					{
						$match = $consumed;
					}
				}

				if ($match !== null)
				{
 					$this->data = substr_replace($this->data, $entities[$match], $this->position - strlen($consumed) - 1, strlen($match) + 1);
					$this->position += strlen($entities[$match]) - strlen($consumed) - 1;
				}
				break;
		}
	}
}


<?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
 */

/**
 * HTTP Response Parser
 *
 * @package SimplePie
 * @subpackage HTTP
 */
class SimplePie_HTTP_Parser
{
	/**
	 * HTTP Version
	 *
	 * @var float
	 */
	public $http_version = 0.0;

	/**
	 * Status code
	 *
	 * @var int
	 */
	public $status_code = 0;

	/**
	 * Reason phrase
	 *
	 * @var string
	 */
	public $reason = '';

	/**
	 * Key/value pairs of the headers
	 *
	 * @var array
	 */
	public $headers = array();

	/**
	 * Body of the response
	 *
	 * @var string
	 */
	public $body = '';

	/**
	 * Current state of the state machine
	 *
	 * @var string
	 */
	protected $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 hedaer currently being parsed
	 *
	 * @var string
	 */
	protected $name = '';

	/**
	 * Value of the hedaer currently being parsed
	 *
	 * @var string
	 */
	protected $value = '';

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

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

		$this->http_version = '';
		$this->status_code = '';
		$this->reason = '';
		$this->headers = array();
		$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
	 */
	protected function http_version()
	{
		if (strpos($this->data, "\x0A") !== false && strtoupper(substr($this->data, 0, 5)) === 'HTTP/')
		{
			$len = strspn($this->data, '0123456789.', 5);
			$this->http_version = substr($this->data, 5, $len);
			$this->position += 5 + $len;
			if (substr_count($this->http_version, '.') <= 1)
			{
				$this->http_version = (float) $this->http_version;
				$this->position += strspn($this->data, "\x09\x20", $this->position);
				$this->state = 'status';
			}
			else
			{
				$this->state = false;
			}
		}
		else
		{
			$this->state = false;
		}
	}

	/**
	 * Parse the status code
	 */
	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 = 'reason';
		}
		else
		{
			$this->state = false;
		}
	}

	/**
	 * Parse the reason phrase
	 */
	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 = 'new_line';
	}

	/**
	 * Deal with a new line, shifting data around as needed
	 */
	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->headers[$this->name] .= ', ' . $this->value;
			}
			else
			{
				$this->headers[$this->name] = $this->value;
			}
		}
		$this->name = '';
		$this->value = '';
		if (substr($this->data[$this->position], 0, 2) === "\x0D\x0A")
		{
			$this->position += 2;
			$this->state = 'body';
		}
		elseif ($this->data[$this->position] === "\x0A")
		{
			$this->position++;
			$this->state = 'body';
		}
		else
		{
			$this->state = 'name';
		}
	}

	/**
	 * Parse a header name
	 */
	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 = 'new_line';
			}
			else
			{
				$this->name = substr($this->data, $this->position, $len);
				$this->position += $len + 1;
				$this->state = 'value';
			}
		}
		else
		{
			$this->state = false;
		}
	}

	/**
	 * Parse LWS, replacing consecutive LWS characters with a single space
	 */
	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
	 */
	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 = 'value_char';
						break;
					}
					$this->position++;
					$this->state = 'quote';
					break;

				case "\x0A":
					$this->position++;
					$this->state = 'new_line';
					break;

				default:
					$this->state = 'value_char';
					break;
			}
		}
	}

	/**
	 * Parse a header value while outside quotes
	 */
	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 = 'value';
	}

	/**
	 * See what state to move to while within quoted header values
	 */
	protected function quote()
	{
		if ($this->is_linear_whitespace())
		{
			$this->linear_whitespace();
		}
		else
		{
			switch ($this->data[$this->position])
			{
				case '"':
					$this->position++;
					$this->state = 'value';
					break;

				case "\x0A":
					$this->position++;
					$this->state = 'new_line';
					break;

				case '\\':
					$this->position++;
					$this->state = 'quote_escaped';
					break;

				default:
					$this->state = 'quote_char';
					break;
			}
		}
	}

	/**
	 * Parse a header value while within quotes
	 */
	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 = 'value';
	}

	/**
	 * Parse an escaped character within quotes
	 */
	protected function quote_escaped()
	{
		$this->value .= $this->data[$this->position];
		$this->position++;
		$this->state = 'quote';
	}

	/**
	 * Parse the body
	 */
	protected function body()
	{
		$this->body = substr($this->data, $this->position);
		if (!empty($this->headers['transfer-encoding']))
		{
			unset($this->headers['transfer-encoding']);
			$this->state = 'chunked';
		}
		else
		{
			$this->state = 'emit';
		}
	}

	/**
	 * Parsed a "Transfer-Encoding: chunked" body
	 */
	protected function chunked()
	{
		if (!preg_match('/^([0-9a-f]+)[^\r\n]*\r\n/i', trim($this->body)))
		{
			$this->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 = 'emit';
				return;
			}

			$length = hexdec(trim($matches[1]));
			if ($length === 0)
			{
				// Ignore trailer headers
				$this->state = 'emit';
				$this->body = $decoded;
				return;
			}

			$chunk_length = strlen($matches[0]);
			$decoded .= $part = substr($encoded, $chunk_length, $length);
			$encoded = substr($encoded, $chunk_length + $length + 2);

			if (trim($encoded) === '0' || empty($encoded))
			{
				$this->state = 'emit';
				$this->body = $decoded;
				return;
			}
		}
	}

	/**
	 * Prepare headers (take care of proxies headers)
	 *
	 * @param string  $headers Raw headers
	 * @param integer $count   Redirection count. Default to 1.
	 *
	 * @return string
	 */
	static public function prepareHeaders($headers, $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\r\n")) {
			$data = str_ireplace("HTTP/1.0 200 Connection established\r\n\r\n", '', $data);
		}
		if (false !== stripos($data, "HTTP/1.1 200 Connection established\r\n\r\n")) {
			$data = str_ireplace("HTTP/1.1 200 Connection established\r\n\r\n", '', $data);
		}
		return $data;
	}
}


<?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
 */

/**
 * Class to validate and to work with IPv6 addresses.
 *
 * @package SimplePie
 * @subpackage HTTP
 * @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 SimplePie_Net_IPv6
{
	/**
	 * Uncompresses an IPv6 address
	 *
	 * RFC 4291 allows you to compress concecutive 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($ip)
	{
		$c1 = -1;
		$c2 = -1;
		if (substr_count($ip, '::') === 1)
		{
			list($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
			else if ($c1 === -1)
			{
				$fill = str_repeat('0:', 7 - $c2);
				$ip = str_replace('::', $fill, $ip);
			}
			// xxx::
			else if ($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 concecutive 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($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] = 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);
		}

		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 [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 array($ipv6_part, $ipv4_part);
		}

		return array($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)
	{
		$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;
		}

		return false;
	}

	/**
	 * Checks if the given IP is a valid IPv6 address
	 *
	 * @codeCoverageIgnore
	 * @deprecated Use {@see SimplePie_Net_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($ip)
	{
		return self::check_ipv6($ip);
	}
}


<?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
 */

/**
 * Parses the XML Declaration
 *
 * @package SimplePie
 * @subpackage Parsing
 */
class SimplePie_XML_Declaration_Parser
{
	/**
	 * XML Version
	 *
	 * @access public
	 * @var string
	 */
	var $version = '1.0';

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

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

	/**
	 * Current state of the state machine
	 *
	 * @access private
	 * @var string
	 */
	var $state = 'before_version_name';

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

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

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

	/**
	 * Create an instance of the class with the input data
	 *
	 * @access public
	 * @param string $data Input data
	 */
	public function __construct($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()
	{
		while ($this->state && $this->state !== 'emit' && $this->has_data())
		{
			$state = $this->state;
			$this->$state();
		}
		$this->data = '';
		if ($this->state === 'emit')
		{
			return true;
		}

		$this->version = '';
		$this->encoding = '';
		$this->standalone = '';
		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()
	{
		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
	 */
	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()
	{
		if ($this->skip_whitespace())
		{
			$this->state = 'version_name';
		}
		else
		{
			$this->state = false;
		}
	}

	public function version_name()
	{
		if (substr($this->data, $this->position, 7) === 'version')
		{
			$this->position += 7;
			$this->skip_whitespace();
			$this->state = 'version_equals';
		}
		else
		{
			$this->state = false;
		}
	}

	public function version_equals()
	{
		if (substr($this->data, $this->position, 1) === '=')
		{
			$this->position++;
			$this->skip_whitespace();
			$this->state = 'version_value';
		}
		else
		{
			$this->state = false;
		}
	}

	public function version_value()
	{
		if ($this->version = $this->get_value())
		{
			$this->skip_whitespace();
			if ($this->has_data())
			{
				$this->state = 'encoding_name';
			}
			else
			{
				$this->state = 'emit';
			}
		}
		else
		{
			$this->state = false;
		}
	}

	public function encoding_name()
	{
		if (substr($this->data, $this->position, 8) === 'encoding')
		{
			$this->position += 8;
			$this->skip_whitespace();
			$this->state = 'encoding_equals';
		}
		else
		{
			$this->state = 'standalone_name';
		}
	}

	public function encoding_equals()
	{
		if (substr($this->data, $this->position, 1) === '=')
		{
			$this->position++;
			$this->skip_whitespace();
			$this->state = 'encoding_value';
		}
		else
		{
			$this->state = false;
		}
	}

	public function encoding_value()
	{
		if ($this->encoding = $this->get_value())
		{
			$this->skip_whitespace();
			if ($this->has_data())
			{
				$this->state = 'standalone_name';
			}
			else
			{
				$this->state = 'emit';
			}
		}
		else
		{
			$this->state = false;
		}
	}

	public function standalone_name()
	{
		if (substr($this->data, $this->position, 10) === 'standalone')
		{
			$this->position += 10;
			$this->skip_whitespace();
			$this->state = 'standalone_equals';
		}
		else
		{
			$this->state = false;
		}
	}

	public function standalone_equals()
	{
		if (substr($this->data, $this->position, 1) === '=')
		{
			$this->position++;
			$this->skip_whitespace();
			$this->state = 'standalone_value';
		}
		else
		{
			$this->state = false;
		}
	}

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

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

				default:
					$this->state = false;
					return;
			}

			$this->skip_whitespace();
			if ($this->has_data())
			{
				$this->state = false;
			}
			else
			{
				$this->state = 'emit';
			}
		}
		else
		{
			$this->state = false;
		}
	}
}


<?php
/**
 * Sitemaps: WP_Sitemaps_Index class.
 *
 * Generates the sitemap index.
 *
 * @package WordPress
 * @subpackage Sitemaps
 * @since 5.5.0
 */

/**
 * Class WP_Sitemaps_Index.
 * Builds the sitemap index page that lists the links to all of the sitemaps.
 *
 * @since 5.5.0
 */
class WP_Sitemaps_Index {
	/**
	 * The main registry of supported sitemaps.
	 *
	 * @since 5.5.0
	 * @var WP_Sitemaps_Registry
	 */
	protected $registry;

	/**
	 * Maximum number of sitemaps to include in an index.
	 *
	 * @sincee 5.5.0
	 *
	 * @var int Maximum number of sitemaps.
	 */
	private $max_sitemaps = 50000;

	/**
	 * WP_Sitemaps_Index constructor.
	 *
	 * @since 5.5.0
	 *
	 * @param WP_Sitemaps_Registry $registry Sitemap provider registry.
	 */
	public function __construct( WP_Sitemaps_Registry $registry ) {
		$this->registry = $registry;
	}

	/**
	 * Gets a sitemap list for the index.
	 *
	 * @since 5.5.0
	 *
	 * @return array[] Array of all sitemaps.
	 */
	public function get_sitemap_list() {
		$sitemaps = array();

		$providers = $this->registry->get_providers();
		/* @var WP_Sitemaps_Provider $provider */
		foreach ( $providers as $name => $provider ) {
			$sitemap_entries = $provider->get_sitemap_entries();

			// Prevent issues with array_push and empty arrays on PHP < 7.3.
			if ( ! $sitemap_entries ) {
				continue;
			}

			// Using array_push is more efficient than array_merge in a loop.
			array_push( $sitemaps, ...$sitemap_entries );
			if ( count( $sitemaps ) >= $this->max_sitemaps ) {
				break;
			}
		}

		return array_slice( $sitemaps, 0, $this->max_sitemaps, true );
	}

	/**
	 * Builds the URL for the sitemap index.
	 *
	 * @since 5.5.0
	 *
	 * @global WP_Rewrite $wp_rewrite WordPress rewrite component.
	 *
	 * @return string The sitemap index URL.
	 */
	public function get_index_url() {
		global $wp_rewrite;

		if ( ! $wp_rewrite->using_permalinks() ) {
			return home_url( '/?sitemap=index' );
		}

		return home_url( '/wp-sitemap.xml' );
	}
}


<?php
/**
 * Sitemaps: WP_Sitemaps_Provider class
 *
 * This class is a base class for other sitemap providers to extend and contains shared functionality.
 *
 * @package WordPress
 * @subpackage Sitemaps
 * @since 5.5.0
 */

/**
 * Class WP_Sitemaps_Provider.
 *
 * @since 5.5.0
 */
abstract class WP_Sitemaps_Provider {
	/**
	 * Provider name.
	 *
	 * This will also be used as the public-facing name in URLs.
	 *
	 * @since 5.5.0
	 *
	 * @var string
	 */
	protected $name = '';

	/**
	 * Object type name (e.g. 'post', 'term', 'user').
	 *
	 * @since 5.5.0
	 *
	 * @var string
	 */
	protected $object_type = '';

	/**
	 * Gets a URL list for a sitemap.
	 *
	 * @since 5.5.0
	 *
	 * @param int    $page_num       Page of results.
	 * @param string $object_subtype Optional. Object subtype name. Default empty.
	 * @return array Array of URLs for a sitemap.
	 */
	abstract public function get_url_list( $page_num, $object_subtype = '' );

	/**
	 * Gets the max number of pages available for the object type.
	 *
	 * @since 5.5.0
	 *
	 * @param string $object_subtype Optional. Object subtype. Default empty.
	 * @return int Total number of pages.
	 */
	abstract public function get_max_num_pages( $object_subtype = '' );

	/**
	 * Gets data about each sitemap type.
	 *
	 * @since 5.5.0
	 *
	 * @return array[] Array of sitemap types including object subtype name and number of pages.
	 */
	public function get_sitemap_type_data() {
		$sitemap_data = array();

		$object_subtypes = $this->get_object_subtypes();

		// If there are no object subtypes, include a single sitemap for the
		// entire object type.
		if ( empty( $object_subtypes ) ) {
			$sitemap_data[] = array(
				'name'  => '',
				'pages' => $this->get_max_num_pages(),
			);
			return $sitemap_data;
		}

		// Otherwise, include individual sitemaps for every object subtype.
		foreach ( $object_subtypes as $object_subtype_name => $data ) {
			$object_subtype_name = (string) $object_subtype_name;

			$sitemap_data[] = array(
				'name'  => $object_subtype_name,
				'pages' => $this->get_max_num_pages( $object_subtype_name ),
			);
		}

		return $sitemap_data;
	}

	/**
	 * Lists sitemap pages exposed by this provider.
	 *
	 * The returned data is used to populate the sitemap entries of the index.
	 *
	 * @since 5.5.0
	 *
	 * @return array[] Array of sitemap entries.
	 */
	public function get_sitemap_entries() {
		$sitemaps = array();

		$sitemap_types = $this->get_sitemap_type_data();

		foreach ( $sitemap_types as $type ) {
			for ( $page = 1; $page <= $type['pages']; $page ++ ) {
				$sitemap_entry = array(
					'loc' => $this->get_sitemap_url( $type['name'], $page ),
				);

				/**
				 * Filters the sitemap entry for the sitemap index.
				 *
				 * @since 5.5.0
				 *
				 * @param array  $sitemap_entry  Sitemap entry for the post.
				 * @param string $object_type    Object empty name.
				 * @param string $object_subtype Object subtype name.
				 *                               Empty string if the object type does not support subtypes.
				 * @param int    $page           Page number of results.
				 */
				$sitemap_entry = apply_filters( 'wp_sitemaps_index_entry', $sitemap_entry, $this->object_type, $type['name'], $page );

				$sitemaps[] = $sitemap_entry;
			}
		}

		return $sitemaps;
	}

	/**
	 * Gets the URL of a sitemap entry.
	 *
	 * @since 5.5.0
	 *
	 * @global WP_Rewrite $wp_rewrite WordPress rewrite component.
	 *
	 * @param string $name The name of the sitemap.
	 * @param int    $page The page of the sitemap.
	 * @return string The composed URL for a sitemap entry.
	 */
	public function get_sitemap_url( $name, $page ) {
		global $wp_rewrite;

		// Accounts for cases where name is not included, ex: sitemaps-users-1.xml.
		$params = array_filter(
			array(
				'sitemap'         => $this->name,
				'sitemap-subtype' => $name,
				'paged'           => $page,
			)
		);

		$basename = sprintf(
			'/wp-sitemap-%1$s.xml',
			implode( '-', $params )
		);

		if ( ! $wp_rewrite->using_permalinks() ) {
			$basename = '/?' . http_build_query( $params, null, '&' );
		}

		return home_url( $basename );
	}

	/**
	 * Returns the list of supported object subtypes exposed by the provider.
	 *
	 * @since 5.5.0
	 *
	 * @return array List of object subtypes objects keyed by their name.
	 */
	public function get_object_subtypes() {
		return array();
	}
}


<?php
/**
 * Sitemaps: WP_Sitemaps_Registry class
 *
 * Handles registering sitemap providers.
 *
 * @package WordPress
 * @subpackage Sitemaps
 * @since 5.5.0
 */

/**
 * Class WP_Sitemaps_Registry.
 *
 * @since 5.5.0
 */
class WP_Sitemaps_Registry {
	/**
	 * Registered sitemap providers.
	 *
	 * @since 5.5.0
	 *
	 * @var WP_Sitemaps_Provider[] Array of registered sitemap providers.
	 */
	private $providers = array();

	/**
	 * Adds a new sitemap provider.
	 *
	 * @since 5.5.0
	 *
	 * @param string               $name     Name of the sitemap provider.
	 * @param WP_Sitemaps_Provider $provider Instance of a WP_Sitemaps_Provider.
	 * @return bool Whether the provider was added successfully.
	 */
	public function add_provider( $name, WP_Sitemaps_Provider $provider ) {
		if ( isset( $this->providers[ $name ] ) ) {
			return false;
		}

		/**
		 * Filters the sitemap provider before it is added.
		 *
		 * @since 5.5.0
		 *
		 * @param WP_Sitemaps_Provider $provider Instance of a WP_Sitemaps_Provider.
		 * @param string               $name     Name of the sitemap provider.
		 */
		$provider = apply_filters( 'wp_sitemaps_add_provider', $provider, $name );
		if ( ! $provider instanceof WP_Sitemaps_Provider ) {
			return false;
		}

		$this->providers[ $name ] = $provider;

		return true;
	}

	/**
	 * Returns a single registered sitemap provider.
	 *
	 * @since 5.5.0
	 *
	 * @param string $name Sitemap provider name.
	 * @return WP_Sitemaps_Provider|null Sitemap provider if it exists, null otherwise.
	 */
	public function get_provider( $name ) {
		if ( ! isset( $this->providers[ $name ] ) ) {
			return null;
		}

		return $this->providers[ $name ];
	}

	/**
	 * Returns all registered sitemap providers.
	 *
	 * @since 5.5.0
	 *
	 * @return WP_Sitemaps_Provider[] Array of sitemap providers.
	 */
	public function get_providers() {
		return $this->providers;
	}
}


<?php
/**
 * Sitemaps: WP_Sitemaps_Renderer class
 *
 * Responsible for rendering Sitemaps data to XML in accordance with sitemap protocol.
 *
 * @package WordPress
 * @subpackage Sitemaps
 * @since 5.5.0
 */

/**
 * Class WP_Sitemaps_Renderer
 *
 * @since 5.5.0
 */
class WP_Sitemaps_Renderer {
	/**
	 * XSL stylesheet for styling a sitemap for web browsers.
	 *
	 * @since 5.5.0
	 *
	 * @var string
	 */
	protected $stylesheet = '';

	/**
	 * XSL stylesheet for styling a sitemap for web browsers.
	 *
	 * @since 5.5.0
	 *
	 * @var string
	 */
	protected $stylesheet_index = '';

	/**
	 * WP_Sitemaps_Renderer constructor.
	 *
	 * @since 5.5.0
	 */
	public function __construct() {
		$stylesheet_url = $this->get_sitemap_stylesheet_url();

		if ( $stylesheet_url ) {
			$this->stylesheet = '<?xml-stylesheet type="text/xsl" href="' . esc_url( $stylesheet_url ) . '" ?>';
		}

		$stylesheet_index_url = $this->get_sitemap_index_stylesheet_url();

		if ( $stylesheet_index_url ) {
			$this->stylesheet_index = '<?xml-stylesheet type="text/xsl" href="' . esc_url( $stylesheet_index_url ) . '" ?>';
		}
	}

	/**
	 * Gets the URL for the sitemap stylesheet.
	 *
	 * @since 5.5.0
	 *
	 * @global WP_Rewrite $wp_rewrite WordPress rewrite component.
	 *
	 * @return string The sitemap stylesheet URL.
	 */
	public function get_sitemap_stylesheet_url() {
		global $wp_rewrite;

		$sitemap_url = home_url( '/wp-sitemap.xsl' );

		if ( ! $wp_rewrite->using_permalinks() ) {
			$sitemap_url = home_url( '/?sitemap-stylesheet=sitemap' );
		}

		/**
		 * Filters the URL for the sitemap stylesheet.
		 *
		 * If a falsey value is returned, no stylesheet will be used and
		 * the "raw" XML of the sitemap will be displayed.
		 *
		 * @since 5.5.0
		 *
		 * @param string $sitemap_url Full URL for the sitemaps XSL file.
		 */
		return apply_filters( 'wp_sitemaps_stylesheet_url', $sitemap_url );
	}

	/**
	 * Gets the URL for the sitemap index stylesheet.
	 *
	 * @since 5.5.0
	 *
	 * @global WP_Rewrite $wp_rewrite WordPress rewrite component.
	 *
	 * @return string The sitemap index stylesheet URL.
	 */
	public function get_sitemap_index_stylesheet_url() {
		global $wp_rewrite;

		$sitemap_url = home_url( '/wp-sitemap-index.xsl' );

		if ( ! $wp_rewrite->using_permalinks() ) {
			$sitemap_url = home_url( '/?sitemap-stylesheet=index' );
		}

		/**
		 * Filters the URL for the sitemap index stylesheet.
		 *
		 * If a falsey value is returned, no stylesheet will be used and
		 * the "raw" XML of the sitemap index will be displayed.
		 *
		 * @since 5.5.0
		 *
		 * @param string $sitemap_url Full URL for the sitemaps index XSL file.
		 */
		return apply_filters( 'wp_sitemaps_stylesheet_index_url', $sitemap_url );
	}

	/**
	 * Renders a sitemap index.
	 *
	 * @since 5.5.0
	 *
	 * @param array $sitemaps Array of sitemap URLs.
	 */
	public function render_index( $sitemaps ) {
		header( 'Content-type: application/xml; charset=UTF-8' );

		$this->check_for_simple_xml_availability();

		$index_xml = $this->get_sitemap_index_xml( $sitemaps );

		if ( ! empty( $index_xml ) ) {
			// All output is escaped within get_sitemap_index_xml().
			// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
			echo $index_xml;
		}
	}

	/**
	 * Gets XML for a sitemap index.
	 *
	 * @since 5.5.0
	 *
	 * @param array $sitemaps Array of sitemap URLs.
	 * @return string|false A well-formed XML string for a sitemap index. False on error.
	 */
	public function get_sitemap_index_xml( $sitemaps ) {
		$sitemap_index = new SimpleXMLElement(
			sprintf(
				'%1$s%2$s%3$s',
				'<?xml version="1.0" encoding="UTF-8" ?>',
				$this->stylesheet_index,
				'<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" />'
			)
		);

		foreach ( $sitemaps as $entry ) {
			$sitemap = $sitemap_index->addChild( 'sitemap' );

			// Add each element as a child node to the <sitemap> entry.
			foreach ( $entry as $name => $value ) {
				if ( 'loc' === $name ) {
					$sitemap->addChild( $name, esc_url( $value ) );
				} elseif ( 'lastmod' === $name ) {
					$sitemap->addChild( $name, esc_xml( $value ) );
				} else {
					_doing_it_wrong(
						__METHOD__,
						sprintf(
							/* translators: %s: List of element names. */
							__( 'Fields other than %s are not currently supported for the sitemap index.' ),
							implode( ',', array( 'loc', 'lastmod' ) )
						),
						'5.5.0'
					);
				}
			}
		}

		return $sitemap_index->asXML();
	}

	/**
	 * Renders a sitemap.
	 *
	 * @since 5.5.0
	 *
	 * @param array $url_list Array of URLs for a sitemap.
	 */
	public function render_sitemap( $url_list ) {
		header( 'Content-type: application/xml; charset=UTF-8' );

		$this->check_for_simple_xml_availability();

		$sitemap_xml = $this->get_sitemap_xml( $url_list );

		if ( ! empty( $sitemap_xml ) ) {
			// All output is escaped within get_sitemap_xml().
			// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
			echo $sitemap_xml;
		}
	}

	/**
	 * Gets XML for a sitemap.
	 *
	 * @since 5.5.0
	 *
	 * @param array $url_list Array of URLs for a sitemap.
	 * @return string|false A well-formed XML string for a sitemap index. False on error.
	 */
	public function get_sitemap_xml( $url_list ) {
		$urlset = new SimpleXMLElement(
			sprintf(
				'%1$s%2$s%3$s',
				'<?xml version="1.0" encoding="UTF-8" ?>',
				$this->stylesheet,
				'<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" />'
			)
		);

		foreach ( $url_list as $url_item ) {
			$url = $urlset->addChild( 'url' );

			// Add each element as a child node to the <url> entry.
			foreach ( $url_item as $name => $value ) {
				if ( 'loc' === $name ) {
					$url->addChild( $name, esc_url( $value ) );
				} elseif ( in_array( $name, array( 'lastmod', 'changefreq', 'priority' ), true ) ) {
					$url->addChild( $name, esc_xml( $value ) );
				} else {
					_doing_it_wrong(
						__METHOD__,
						sprintf(
							/* translators: %s: List of element names. */
							__( 'Fields other than %s are not currently supported for sitemaps.' ),
							implode( ',', array( 'loc', 'lastmod', 'changefreq', 'priority' ) )
						),
						'5.5.0'
					);
				}
			}
		}

		return $urlset->asXML();
	}

	/**
	 * Checks for the availability of the SimpleXML extension and errors if missing.
	 *
	 * @since 5.5.0
	 */
	private function check_for_simple_xml_availability() {
		if ( ! class_exists( 'SimpleXMLElement' ) ) {
			add_filter(
				'wp_die_handler',
				static function () {
					return '_xml_wp_die_handler';
				}
			);

			wp_die(
				sprintf(
					/* translators: %s: SimpleXML */
					esc_xml( __( 'Could not generate XML sitemap due to missing %s extension' ) ),
					'SimpleXML'
				),
				esc_xml( __( 'WordPress › Error' ) ),
				array(
					'response' => 501, // "Not implemented".
				)
			);
		}
	}
}


<?php
/**
 * Sitemaps: WP_Sitemaps_Stylesheet class
 *
 * This class provides the XSL stylesheets to style all sitemaps.
 *
 * @package WordPress
 * @subpackage Sitemaps
 * @since 5.5.0
 */

/**
 * Stylesheet provider class.
 *
 * @since 5.5.0
 */
class WP_Sitemaps_Stylesheet {
	/**
	 * Renders the XSL stylesheet depending on whether it's the sitemap index or not.
	 *
	 * @param string $type Stylesheet type. Either 'sitemap' or 'index'.
	 */
	public function render_stylesheet( $type ) {
		header( 'Content-type: application/xml; charset=UTF-8' );

		if ( 'sitemap' === $type ) {
			// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- All content escaped below.
			echo $this->get_sitemap_stylesheet();
		}

		if ( 'index' === $type ) {
			// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- All content escaped below.
			echo $this->get_sitemap_index_stylesheet();
		}

		exit;
	}

	/**
	 * Returns the escaped XSL for all sitemaps, except index.
	 *
	 * @since 5.5.0
	 */
	public function get_sitemap_stylesheet() {
		$css         = $this->get_stylesheet_css();
		$title       = esc_xml( __( 'XML Sitemap' ) );
		$description = esc_xml( __( 'This XML Sitemap is generated by WordPress to make your content more visible for search engines.' ) );
		$learn_more  = sprintf(
			'%s',
			esc_url( __( 'https://www.sitemaps.org/' ) ),
			esc_xml( __( 'Learn more about XML sitemaps.' ) )
		);

		$text = sprintf(
			/* translators: %s: Number of URLs. */
			esc_xml( __( 'Number of URLs in this XML Sitemap: %s.' ) ),
			'<xsl:value-of select="count( sitemap:urlset/sitemap:url )" />'
		);

		$lang       = get_language_attributes( 'html' );
		$url        = esc_xml( __( 'URL' ) );
		$lastmod    = esc_xml( __( 'Last Modified' ) );
		$changefreq = esc_xml( __( 'Change Frequency' ) );
		$priority   = esc_xml( __( 'Priority' ) );

		$xsl_content = <<<XSL
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet
		version="1.0"
		xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
		xmlns:sitemap="http://www.sitemaps.org/schemas/sitemap/0.9"
		exclude-result-prefixes="sitemap"
		>

	<xsl:output method="html" encoding="UTF-8" indent="yes"/>

	<xsl:variable name="has-lastmod"    select="count( /sitemap:urlset/sitemap:url/sitemap:lastmod )"    />
	<xsl:variable name="has-changefreq" select="count( /sitemap:urlset/sitemap:url/sitemap:changefreq )" />
	<xsl:variable name="has-priority"   select="count( /sitemap:urlset/sitemap:url/sitemap:priority )"   />

	<xsl:template match="/">

				<title>{$title}</title>

{$title}

{$description}

{$learn_more}

{$text}

									{$url}
									<xsl:if test="\$has-lastmod">
										{$lastmod}
									</xsl:if>
									<xsl:if test="\$has-changefreq">
										{$changefreq}
									</xsl:if>
									<xsl:if test="\$has-priority">
										{$priority}
									</xsl:if>

								<xsl:for-each select="sitemap:urlset/sitemap:url">

										<xsl:value-of select="sitemap:loc" />
										<xsl:if test="\$has-lastmod">
											<xsl:value-of select="sitemap:lastmod" />
										</xsl:if>
										<xsl:if test="\$has-changefreq">
											<xsl:value-of select="sitemap:changefreq" />
										</xsl:if>
										<xsl:if test="\$has-priority">
											<xsl:value-of select="sitemap:priority" />
										</xsl:if>

								</xsl:for-each>

	</xsl:template>
</xsl:stylesheet>

XSL;

		/**
		 * Filters the content of the sitemap stylesheet.
		 *
		 * @since 5.5.0
		 *
		 * @param string $xsl_content Full content for the XML stylesheet.
		 */
		return apply_filters( 'wp_sitemaps_stylesheet_content', $xsl_content );
	}

	/**
	 * Returns the escaped XSL for the index sitemaps.
	 *
	 * @since 5.5.0
	 */
	public function get_sitemap_index_stylesheet() {
		$css         = $this->get_stylesheet_css();
		$title       = esc_xml( __( 'XML Sitemap' ) );
		$description = esc_xml( __( 'This XML Sitemap is generated by WordPress to make your content more visible for search engines.' ) );
		$learn_more  = sprintf(
			'%s',
			esc_url( __( 'https://www.sitemaps.org/' ) ),
			esc_xml( __( 'Learn more about XML sitemaps.' ) )
		);

		$text = sprintf(
			/* translators: %s: Number of URLs. */
			esc_xml( __( 'Number of URLs in this XML Sitemap: %s.' ) ),
			'<xsl:value-of select="count( sitemap:sitemapindex/sitemap:sitemap )" />'
		);

		$lang    = get_language_attributes( 'html' );
		$url     = esc_xml( __( 'URL' ) );
		$lastmod = esc_xml( __( 'Last Modified' ) );

		$xsl_content = <<<XSL
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet
		version="1.0"
		xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
		xmlns:sitemap="http://www.sitemaps.org/schemas/sitemap/0.9"
		exclude-result-prefixes="sitemap"
		>

	<xsl:output method="html" encoding="UTF-8" indent="yes" />

	<xsl:variable name="has-lastmod" select="count( /sitemap:sitemapindex/sitemap:sitemap/sitemap:lastmod )" />

	<xsl:template match="/">

				<title>{$title}</title>

{$title}

{$description}

{$learn_more}

{$text}

									{$url}
									<xsl:if test="\$has-lastmod">
										{$lastmod}
									</xsl:if>

								<xsl:for-each select="sitemap:sitemapindex/sitemap:sitemap">

										<xsl:value-of select="sitemap:loc" />
										<xsl:if test="\$has-lastmod">
											<xsl:value-of select="sitemap:lastmod" />
										</xsl:if>

								</xsl:for-each>

	</xsl:template>
</xsl:stylesheet>

XSL;

		/**
		 * Filters the content of the sitemap index stylesheet.
		 *
		 * @since 5.5.0
		 *
		 * @param string $xsl_content Full content for the XML stylesheet.
		 */
		return apply_filters( 'wp_sitemaps_stylesheet_index_content', $xsl_content );
	}

	/**
	 * Gets the CSS to be included in sitemap XSL stylesheets.
	 *
	 * @since 5.5.0
	 *
	 * @return string The CSS.
	 */
	public function get_stylesheet_css() {
		$text_align = is_rtl() ? 'right' : 'left';

		$css = <<<EOF

					body {
						font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif;
						color: #444;
					}

					#sitemap__table {
						border: solid 1px #ccc;
						border-collapse: collapse;
					}

			 		#sitemap__table tr td.loc {
						/*
						 * URLs should always be LTR.
						 * See https://core.trac.wordpress.org/ticket/16834
						 * and https://core.trac.wordpress.org/ticket/49949
						 */
						direction: ltr;
					}

					#sitemap__table tr th {
						text-align: {$text_align};
					}

					#sitemap__table tr td,
					#sitemap__table tr th {
						padding: 10px;
					}

					#sitemap__table tr:nth-child(odd) td {
						background-color: #eee;
					}

					a:hover {
						text-decoration: none;
					}

EOF;

		/**
		 * Filters the CSS only for the sitemap stylesheet.
		 *
		 * @since 5.5.0
		 *
		 * @param string $css CSS to be applied to default XSL file.
		 */
		return apply_filters( 'wp_sitemaps_stylesheet_css', $css );
	}
}


<?php
/**
 * Sitemaps: WP_Sitemaps class
 *
 * This is the main class integrating all other classes.
 *
 * @package WordPress
 * @subpackage Sitemaps
 * @since 5.5.0
 */

/**
 * Class WP_Sitemaps.
 *
 * @since 5.5.0
 */
class WP_Sitemaps {
	/**
	 * The main index of supported sitemaps.
	 *
	 * @since 5.5.0
	 *
	 * @var WP_Sitemaps_Index
	 */
	public $index;

	/**
	 * The main registry of supported sitemaps.
	 *
	 * @since 5.5.0
	 *
	 * @var WP_Sitemaps_Registry
	 */
	public $registry;

	/**
	 * An instance of the renderer class.
	 *
	 * @since 5.5.0
	 *
	 * @var WP_Sitemaps_Renderer
	 */
	public $renderer;

	/**
	 * WP_Sitemaps constructor.
	 *
	 * @since 5.5.0
	 */
	public function __construct() {
		$this->registry = new WP_Sitemaps_Registry();
		$this->renderer = new WP_Sitemaps_Renderer();
		$this->index    = new WP_Sitemaps_Index( $this->registry );
	}

	/**
	 * Initiates all sitemap functionality.
	 *
	 * If sitemaps are disabled, only the rewrite rules will be registered
	 * by this method, in order to properly send 404s.
	 *
	 * @since 5.5.0
	 */
	public function init() {
		// These will all fire on the init hook.
		$this->register_rewrites();

		add_action( 'template_redirect', array( $this, 'render_sitemaps' ) );

		if ( ! $this->sitemaps_enabled() ) {
			return;
		}

		$this->register_sitemaps();

		// Add additional action callbacks.
		add_filter( 'pre_handle_404', array( $this, 'redirect_sitemapxml' ), 10, 2 );
		add_filter( 'robots_txt', array( $this, 'add_robots' ), 0, 2 );
	}

	/**
	 * Determines whether sitemaps are enabled or not.
	 *
	 * @since 5.5.0
	 *
	 * @return bool Whether sitemaps are enabled.
	 */
	public function sitemaps_enabled() {
		$is_enabled = (bool) get_option( 'blog_public' );

		/**
		 * Filters whether XML Sitemaps are enabled or not.
		 *
		 * When XML Sitemaps are disabled via this filter, rewrite rules are still
		 * in place to ensure a 404 is returned.
		 *
		 * @see WP_Sitemaps::register_rewrites()
		 *
		 * @since 5.5.0
		 *
		 * @param bool $is_enabled Whether XML Sitemaps are enabled or not. Defaults
		 * to true for public sites.
		 */
		return (bool) apply_filters( 'wp_sitemaps_enabled', $is_enabled );
	}

	/**
	 * Registers and sets up the functionality for all supported sitemaps.
	 *
	 * @since 5.5.0
	 */
	public function register_sitemaps() {
		$providers = array(
			'posts'      => new WP_Sitemaps_Posts(),
			'taxonomies' => new WP_Sitemaps_Taxonomies(),
			'users'      => new WP_Sitemaps_Users(),
		);

		/* @var WP_Sitemaps_Provider $provider */
		foreach ( $providers as $name => $provider ) {
			$this->registry->add_provider( $name, $provider );
		}
	}

	/**
	 * Registers sitemap rewrite tags and routing rules.
	 *
	 * @since 5.5.0
	 */
	public function register_rewrites() {
		// Add rewrite tags.
		add_rewrite_tag( '%sitemap%', '([^?]+)' );
		add_rewrite_tag( '%sitemap-subtype%', '([^?]+)' );

		// Register index route.
		add_rewrite_rule( '^wp-sitemap\.xml$', 'index.php?sitemap=index', 'top' );

		// Register rewrites for the XSL stylesheet.
		add_rewrite_tag( '%sitemap-stylesheet%', '([^?]+)' );
		add_rewrite_rule( '^wp-sitemap\.xsl$', 'index.php?sitemap-stylesheet=sitemap', 'top' );
		add_rewrite_rule( '^wp-sitemap-index\.xsl$', 'index.php?sitemap-stylesheet=index', 'top' );

		// Register routes for providers.
		add_rewrite_rule(
			'^wp-sitemap-([a-z]+?)-([a-z\d_-]+?)-(\d+?)\.xml$',
			'index.php?sitemap=$matches[1]&sitemap-subtype=$matches[2]&paged=$matches[3]',
			'top'
		);
		add_rewrite_rule(
			'^wp-sitemap-([a-z]+?)-(\d+?)\.xml$',
			'index.php?sitemap=$matches[1]&paged=$matches[2]',
			'top'
		);
	}

	/**
	 * Renders sitemap templates based on rewrite rules.
	 *
	 * @since 5.5.0
	 *
	 * @global WP_Query $wp_query WordPress Query object.
	 */
	public function render_sitemaps() {
		global $wp_query;

		$sitemap         = sanitize_text_field( get_query_var( 'sitemap' ) );
		$object_subtype  = sanitize_text_field( get_query_var( 'sitemap-subtype' ) );
		$stylesheet_type = sanitize_text_field( get_query_var( 'sitemap-stylesheet' ) );
		$paged           = absint( get_query_var( 'paged' ) );

		// Bail early if this isn't a sitemap or stylesheet route.
		if ( ! ( $sitemap || $stylesheet_type ) ) {
			return;
		}

		if ( ! $this->sitemaps_enabled() ) {
			$wp_query->set_404();
			status_header( 404 );
			return;
		}

		// Render stylesheet if this is stylesheet route.
		if ( $stylesheet_type ) {
			$stylesheet = new WP_Sitemaps_Stylesheet();

			$stylesheet->render_stylesheet( $stylesheet_type );
			exit;
		}

		// Render the index.
		if ( 'index' === $sitemap ) {
			$sitemap_list = $this->index->get_sitemap_list();

			$this->renderer->render_index( $sitemap_list );
			exit;
		}

		$provider = $this->registry->get_provider( $sitemap );

		if ( ! $provider ) {
			return;
		}

		if ( empty( $paged ) ) {
			$paged = 1;
		}

		$url_list = $provider->get_url_list( $paged, $object_subtype );

		// Force a 404 and bail early if no URLs are present.
		if ( empty( $url_list ) ) {
			$wp_query->set_404();
			status_header( 404 );
			return;
		}

		$this->renderer->render_sitemap( $url_list );
		exit;
	}

	/**
	 * Redirects a URL to the wp-sitemap.xml
	 *
	 * @since 5.5.0
	 *
	 * @param bool     $bypass Pass-through of the pre_handle_404 filter value.
	 * @param WP_Query $query  The WP_Query object.
	 * @return bool Bypass value.
	 */
	public function redirect_sitemapxml( $bypass, $query ) {
		// If a plugin has already utilized the pre_handle_404 function, return without action to avoid conflicts.
		if ( $bypass ) {
			return $bypass;
		}

		// 'pagename' is for most permalink types, name is for when the %postname% is used as a top-level field.
		if ( 'sitemap-xml' === $query->get( 'pagename' )
			|| 'sitemap-xml' === $query->get( 'name' )
		) {
			wp_safe_redirect( $this->index->get_index_url() );
			exit();
		}

		return $bypass;
	}

	/**
	 * Adds the sitemap index to robots.txt.
	 *
	 * @since 5.5.0
	 *
	 * @param string $output robots.txt output.
	 * @param bool   $public Whether the site is public.
	 * @return string The robots.txt output.
	 */
	public function add_robots( $output, $public ) {
		if ( $public ) {
			$output .= "\nSitemap: " . esc_url( $this->index->get_index_url() ) . "\n";
		}

		return $output;
	}
}


<?php
/**
 * Sitemaps: WP_Sitemaps_Posts class
 *
 * Builds the sitemaps for the 'post' object type.
 *
 * @package WordPress
 * @subpackage Sitemaps
 * @since 5.5.0
 */

/**
 * Posts XML sitemap provider.
 *
 * @since 5.5.0
 */
class WP_Sitemaps_Posts extends WP_Sitemaps_Provider {
	/**
	 * WP_Sitemaps_Posts constructor.
	 *
	 * @since 5.5.0
	 */
	public function __construct() {
		$this->name        = 'posts';
		$this->object_type = 'post';
	}

	/**
	 * Returns the public post types, which excludes nav_items and similar types.
	 * Attachments are also excluded. This includes custom post types with public = true.
	 *
	 * @since 5.5.0
	 *
	 * @return WP_Post_Type[] Array of registered post type objects keyed by their name.
	 */
	public function get_object_subtypes() {
		$post_types = get_post_types( array( 'public' => true ), 'objects' );
		unset( $post_types['attachment'] );

		$post_types = array_filter( $post_types, 'is_post_type_viewable' );

		/**
		 * Filters the list of post object sub types available within the sitemap.
		 *
		 * @since 5.5.0
		 *
		 * @param WP_Post_Type[] $post_types Array of registered post type objects keyed by their name.
		 */
		return apply_filters( 'wp_sitemaps_post_types', $post_types );
	}

	/**
	 * Gets a URL list for a post type sitemap.
	 *
	 * @since 5.5.0
	 *
	 * @param int    $page_num  Page of results.
	 * @param string $post_type Optional. Post type name. Default empty.
	 * @return array Array of URLs for a sitemap.
	 */
	public function get_url_list( $page_num, $post_type = '' ) {
		// Bail early if the queried post type is not supported.
		$supported_types = $this->get_object_subtypes();

		if ( ! isset( $supported_types[ $post_type ] ) ) {
			return array();
		}

		/**
		 * Filters the posts URL list before it is generated.
		 *
		 * Passing a non-null value will effectively short-circuit the generation,
		 * returning that value instead.
		 *
		 * @since 5.5.0
		 *
		 * @param array  $url_list  The URL list. Default null.
		 * @param string $post_type Post type name.
		 * @param int    $page_num  Page of results.
		 */
		$url_list = apply_filters(
			'wp_sitemaps_posts_pre_url_list',
			null,
			$post_type,
			$page_num
		);

		if ( null !== $url_list ) {
			return $url_list;
		}

		$args          = $this->get_posts_query_args( $post_type );
		$args['paged'] = $page_num;

		$query = new WP_Query( $args );

		$url_list = array();

		/*
		 * Add a URL for the homepage in the pages sitemap.
		 * Shows only on the first page if the reading settings are set to display latest posts.
		 */
		if ( 'page' === $post_type && 1 === $page_num && 'posts' === get_option( 'show_on_front' ) ) {
			// Extract the data needed for home URL to add to the array.
			$sitemap_entry = array(
				'loc' => home_url( '/' ),
			);

			/**
			 * Filters the sitemap entry for the home page when the 'show_on_front' option equals 'posts'.
			 *
			 * @since 5.5.0
			 *
			 * @param array $sitemap_entry Sitemap entry for the home page.
			 */
			$sitemap_entry = apply_filters( 'wp_sitemaps_posts_show_on_front_entry', $sitemap_entry );
			$url_list[]    = $sitemap_entry;
		}

		foreach ( $query->posts as $post ) {
			$sitemap_entry = array(
				'loc' => get_permalink( $post ),
			);

			/**
			 * Filters the sitemap entry for an individual post.
			 *
			 * @since 5.5.0
			 *
			 * @param array   $sitemap_entry Sitemap entry for the post.
			 * @param WP_Post $post          Post object.
			 * @param string  $post_type     Name of the post_type.
			 */
			$sitemap_entry = apply_filters( 'wp_sitemaps_posts_entry', $sitemap_entry, $post, $post_type );
			$url_list[]    = $sitemap_entry;
		}

		return $url_list;
	}

	/**
	 * Gets the max number of pages available for the object type.
	 *
	 * @since 5.5.0
	 *
	 * @param string $post_type Optional. Post type name. Default empty.
	 * @return int Total number of pages.
	 */
	public function get_max_num_pages( $post_type = '' ) {
		if ( empty( $post_type ) ) {
			return 0;
		}

		/**
		 * Filters the max number of pages before it is generated.
		 *
		 * Passing a non-null value will short-circuit the generation,
		 * returning that value instead.
		 *
		 * @since 5.5.0
		 *
		 * @param int|null $max_num_pages The maximum number of pages. Default null.
		 * @param string   $post_type     Post type name.
		 */
		$max_num_pages = apply_filters( 'wp_sitemaps_posts_pre_max_num_pages', null, $post_type );

		if ( null !== $max_num_pages ) {
			return $max_num_pages;
		}

		$args                  = $this->get_posts_query_args( $post_type );
		$args['fields']        = 'ids';
		$args['no_found_rows'] = false;

		$query = new WP_Query( $args );

		$min_num_pages = ( 'page' === $post_type && 'posts' === get_option( 'show_on_front' ) ) ? 1 : 0;
		return isset( $query->max_num_pages ) ? max( $min_num_pages, $query->max_num_pages ) : 1;
	}

	/**
	 * Returns the query args for retrieving posts to list in the sitemap.
	 *
	 * @since 5.5.0
	 *
	 * @param string $post_type Post type name.
	 * @return array Array of WP_Query arguments.
	 */
	protected function get_posts_query_args( $post_type ) {
		/**
		 * Filters the query arguments for post type sitemap queries.
		 *
		 * @see WP_Query for a full list of arguments.
		 *
		 * @since 5.5.0
		 *
		 * @param array  $args      Array of WP_Query arguments.
		 * @param string $post_type Post type name.
		 */
		$args = apply_filters(
			'wp_sitemaps_posts_query_args',
			array(
				'orderby'                => 'ID',
				'order'                  => 'ASC',
				'post_type'              => $post_type,
				'posts_per_page'         => wp_sitemaps_get_max_urls( $this->object_type ),
				'post_status'            => array( 'publish' ),
				'no_found_rows'          => true,
				'update_post_term_cache' => false,
				'update_post_meta_cache' => false,
			),
			$post_type
		);

		return $args;
	}
}


<?php
/**
 * Sitemaps: WP_Sitemaps_Taxonomies class
 *
 * Builds the sitemaps for the 'taxonomy' object type.
 *
 * @package WordPress
 * @subpackage Sitemaps
 * @since 5.5.0
 */

/**
 * Taxonomies XML sitemap provider.
 *
 * @since 5.5.0
 */
class WP_Sitemaps_Taxonomies extends WP_Sitemaps_Provider {
	/**
	 * WP_Sitemaps_Taxonomies constructor.
	 *
	 * @since 5.5.0
	 */
	public function __construct() {
		$this->name        = 'taxonomies';
		$this->object_type = 'term';
	}

	/**
	 * Returns all public, registered taxonomies.
	 *
	 * @since 5.5.0
	 *
	 * @return WP_Taxonomy[] Array of registered taxonomy objects keyed by their name.
	 */
	public function get_object_subtypes() {
		$taxonomies = get_taxonomies( array( 'public' => true ), 'objects' );

		$taxonomies = array_filter( $taxonomies, 'is_taxonomy_viewable' );

		/**
		 * Filter the list of taxonomy object subtypes available within the sitemap.
		 *
		 * @since 5.5.0
		 *
		 * @param WP_Taxonomy[] $taxonomies Array of registered taxonomy objects keyed by their name.
		 */
		return apply_filters( 'wp_sitemaps_taxonomies', $taxonomies );
	}

	/**
	 * Gets a URL list for a taxonomy sitemap.
	 *
	 * @since 5.5.0
	 *
	 * @param int    $page_num Page of results.
	 * @param string $taxonomy Optional. Taxonomy name. Default empty.
	 * @return array Array of URLs for a sitemap.
	 */
	public function get_url_list( $page_num, $taxonomy = '' ) {
		$supported_types = $this->get_object_subtypes();

		// Bail early if the queried taxonomy is not supported.
		if ( ! isset( $supported_types[ $taxonomy ] ) ) {
			return array();
		}

		/**
		 * Filters the taxonomies URL list before it is generated.
		 *
		 * Passing a non-null value will effectively short-circuit the generation,
		 * returning that value instead.
		 *
		 * @since 5.5.0
		 *
		 * @param array  $url_list The URL list. Default null.
		 * @param string $taxonomy Taxonomy name.
		 * @param int    $page_num Page of results.
		 */
		$url_list = apply_filters(
			'wp_sitemaps_taxonomies_pre_url_list',
			null,
			$taxonomy,
			$page_num
		);

		if ( null !== $url_list ) {
			return $url_list;
		}

		$url_list = array();

		// Offset by how many terms should be included in previous pages.
		$offset = ( $page_num - 1 ) * wp_sitemaps_get_max_urls( $this->object_type );

		$args           = $this->get_taxonomies_query_args( $taxonomy );
		$args['offset'] = $offset;

		$taxonomy_terms = new WP_Term_Query( $args );

		if ( ! empty( $taxonomy_terms->terms ) ) {
			foreach ( $taxonomy_terms->terms as $term ) {
				$sitemap_entry = array(
					'loc' => get_term_link( $term ),
				);

				/**
				 * Filters the sitemap entry for an individual term.
				 *
				 * @since 5.5.0
				 *
				 * @param array   $sitemap_entry Sitemap entry for the term.
				 * @param WP_Term $term          Term object.
				 * @param string  $taxonomy      Taxonomy name.
				 */
				$sitemap_entry = apply_filters( 'wp_sitemaps_taxonomies_entry', $sitemap_entry, $term, $taxonomy );
				$url_list[]    = $sitemap_entry;
			}
		}

		return $url_list;
	}

	/**
	 * Gets the max number of pages available for the object type.
	 *
	 * @since 5.5.0
	 *
	 * @param string $taxonomy Taxonomy name.
	 * @return int Total number of pages.
	 */
	public function get_max_num_pages( $taxonomy = '' ) {
		if ( empty( $taxonomy ) ) {
			return 0;
		}

		/**
		 * Filters the max number of pages before it is generated.
		 *
		 * Passing a non-null value will short-circuit the generation,
		 * returning that value instead.
		 *
		 * @since 5.5.0
		 *
		 * @param int    $max_num_pages The maximum number of pages. Default null.
		 * @param string $taxonomy      Taxonomy name.
		 */
		$max_num_pages = apply_filters( 'wp_sitemaps_taxonomies_pre_max_num_pages', null, $taxonomy );

		if ( null !== $max_num_pages ) {
			return $max_num_pages;
		}

		$term_count = wp_count_terms( $taxonomy, $this->get_taxonomies_query_args( $taxonomy ) );

		return (int) ceil( $term_count / wp_sitemaps_get_max_urls( $this->object_type ) );
	}

	/**
	 * Returns the query args for retrieving taxonomy terms to list in the sitemap.
	 *
	 * @since 5.5.0
	 *
	 * @param string $taxonomy Taxonomy name.
	 * @return array Array of WP_Term_Query arguments.
	 */
	protected function get_taxonomies_query_args( $taxonomy ) {
		/**
		 * Filters the taxonomy terms query arguments.
		 *
		 * Allows modification of the taxonomy query arguments before querying.
		 *
		 * @see WP_Term_Query for a full list of arguments
		 *
		 * @since 5.5.0
		 *
		 * @param array  $args     Array of WP_Term_Query arguments.
		 * @param string $taxonomy Taxonomy name.
		 */
		$args = apply_filters(
			'wp_sitemaps_taxonomies_query_args',
			array(
				'fields'                 => 'ids',
				'taxonomy'               => $taxonomy,
				'orderby'                => 'term_order',
				'number'                 => wp_sitemaps_get_max_urls( $this->object_type ),
				'hide_empty'             => true,
				'hierarchical'           => false,
				'update_term_meta_cache' => false,
			),
			$taxonomy
		);

		return $args;
	}
}


<?php
/**
 * Sitemaps: WP_Sitemaps_Users class
 *
 * Builds the sitemaps for the 'user' object type.
 *
 * @package WordPress
 * @subpackage Sitemaps
 * @since 5.5.0
 */

/**
 * Users XML sitemap provider.
 *
 * @since 5.5.0
 */
class WP_Sitemaps_Users extends WP_Sitemaps_Provider {
	/**
	 * WP_Sitemaps_Users constructor.
	 *
	 * @since 5.5.0
	 */
	public function __construct() {
		$this->name        = 'users';
		$this->object_type = 'user';
	}

	/**
	 * Gets a URL list for a user sitemap.
	 *
	 * @since 5.5.0
	 *
	 * @param int    $page_num       Page of results.
	 * @param string $object_subtype Optional. Not applicable for Users but
	 *                               required for compatibility with the parent
	 *                               provider class. Default empty.
	 * @return array Array of URLs for a sitemap.
	 */
	public function get_url_list( $page_num, $object_subtype = '' ) {
		/**
		 * Filters the users URL list before it is generated.
		 *
		 * Passing a non-null value will effectively short-circuit the generation,
		 * returning that value instead.
		 *
		 * @since 5.5.0
		 *
		 * @param array  $url_list The URL list. Default null.
		 * @param int    $page_num Page of results.
		 */
		$url_list = apply_filters(
			'wp_sitemaps_users_pre_url_list',
			null,
			$page_num
		);

		if ( null !== $url_list ) {
			return $url_list;
		}

		$args          = $this->get_users_query_args();
		$args['paged'] = $page_num;

		$query    = new WP_User_Query( $args );
		$users    = $query->get_results();
		$url_list = array();

		foreach ( $users as $user ) {
			$sitemap_entry = array(
				'loc' => get_author_posts_url( $user->ID ),
			);

			/**
			 * Filters the sitemap entry for an individual user.
			 *
			 * @since 5.5.0
			 *
			 * @param array   $sitemap_entry Sitemap entry for the user.
			 * @param WP_User $user          User object.
			 */
			$sitemap_entry = apply_filters( 'wp_sitemaps_users_entry', $sitemap_entry, $user );
			$url_list[]    = $sitemap_entry;
		}

		return $url_list;
	}

	/**
	 * Gets the max number of pages available for the object type.
	 *
	 * @since 5.5.0
	 *
	 * @see WP_Sitemaps_Provider::max_num_pages
	 *
	 * @param string $object_subtype Optional. Not applicable for Users but
	 *                               required for compatibility with the parent
	 *                               provider class. Default empty.
	 * @return int Total page count.
	 */
	public function get_max_num_pages( $object_subtype = '' ) {
		/**
		 * Filters the max number of pages before it is generated.
		 *
		 * Passing a non-null value will effectively short-circuit the generation,
		 * returning that value instead.
		 *
		 * @since 5.5.0
		 *
		 * @param int $max_num_pages The maximum number of pages. Default null.
		 */
		$max_num_pages = apply_filters( 'wp_sitemaps_users_pre_max_num_pages', null );

		if ( null !== $max_num_pages ) {
			return $max_num_pages;
		}

		$args  = $this->get_users_query_args();
		$query = new WP_User_Query( $args );

		$total_users = $query->get_total();

		return (int) ceil( $total_users / wp_sitemaps_get_max_urls( $this->object_type ) );
	}

	/**
	 * Returns the query args for retrieving users to list in the sitemap.
	 *
	 * @since 5.5.0
	 *
	 * @return array Array of WP_User_Query arguments.
	 */
	protected function get_users_query_args() {
		$public_post_types = get_post_types(
			array(
				'public' => true,
			)
		);

		// We're not supporting sitemaps for author pages for attachments.
		unset( $public_post_types['attachment'] );

		/**
		 * Filters the query arguments for authors with public posts.
		 *
		 * Allows modification of the authors query arguments before querying.
		 *
		 * @see WP_User_Query for a full list of arguments
		 *
		 * @since 5.5.0
		 *
		 * @param array $args Array of WP_User_Query arguments.
		 */
		$args = apply_filters(
			'wp_sitemaps_users_query_args',
			array(
				'has_published_posts' => array_keys( $public_post_types ),
				'number'              => wp_sitemaps_get_max_urls( $this->object_type ),
			)
		);

		return $args;
	}
}


<?php

if (!is_callable('sodiumCompatAutoloader')) {
    /**
     * Sodium_Compat autoloader.
     *
     * @param string $class Class name to be autoloaded.
     *
     * @return bool         Stop autoloading?
     */
    function sodiumCompatAutoloader($class)
    {
        $namespace = 'ParagonIE_Sodium_';
        // Does the class use the namespace prefix?
        $len = strlen($namespace);
        if (strncmp($namespace, $class, $len) !== 0) {
            // no, move to the next registered autoloader
            return false;
        }

        // Get the relative class name
        $relative_class = substr($class, $len);

        // Replace the namespace prefix with the base directory, replace namespace
        // separators with directory separators in the relative class name, append
        // with .php
        $file = dirname(__FILE__) . '/src/' . str_replace('_', '/', $relative_class) . '.php';
        // if the file exists, require it
        if (file_exists($file)) {
            require_once $file;
            return true;
        }
        return false;
    }

    // Now that we have an autoloader, let's register it!
    spl_autoload_register('sodiumCompatAutoloader');
}

require_once dirname(__FILE__) . '/src/SodiumException.php';
if (PHP_VERSION_ID >= 50300) {
    // Namespaces didn't exist before 5.3.0, so don't even try to use this
    // unless PHP >= 5.3.0
    require_once dirname(__FILE__) . '/lib/namespaced.php';
    require_once dirname(__FILE__) . '/lib/sodium_compat.php';
} else {
    require_once dirname(__FILE__) . '/src/PHP52/SplFixedArray.php';
}
if (PHP_VERSION_ID < 70200 || !extension_loaded('sodium')) {
    if (PHP_VERSION_ID >= 50300 && !defined('SODIUM_CRYPTO_SCALARMULT_BYTES')) {
        require_once dirname(__FILE__) . '/lib/php72compat_const.php';
    }
    if (PHP_VERSION_ID >= 70000) {
        assert(class_exists('ParagonIE_Sodium_Compat'), 'Possible filesystem/autoloader bug?');
    } else {
        assert(class_exists('ParagonIE_Sodium_Compat'));
    }
    require_once (dirname(__FILE__) . '/lib/php72compat.php');
}


<?php
namespace Sodium;

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

use ParagonIE_Sodium_Compat;

const CRYPTO_AEAD_AES256GCM_KEYBYTES = ParagonIE_Sodium_Compat::CRYPTO_AEAD_AES256GCM_KEYBYTES;
const CRYPTO_AEAD_AES256GCM_NSECBYTES = ParagonIE_Sodium_Compat::CRYPTO_AEAD_AES256GCM_NSECBYTES;
const CRYPTO_AEAD_AES256GCM_NPUBBYTES = ParagonIE_Sodium_Compat::CRYPTO_AEAD_AES256GCM_NPUBBYTES;
const CRYPTO_AEAD_AES256GCM_ABYTES = ParagonIE_Sodium_Compat::CRYPTO_AEAD_AES256GCM_ABYTES;
const CRYPTO_AEAD_CHACHA20POLY1305_KEYBYTES = ParagonIE_Sodium_Compat::CRYPTO_AEAD_CHACHA20POLY1305_KEYBYTES;
const CRYPTO_AEAD_CHACHA20POLY1305_NSECBYTES = ParagonIE_Sodium_Compat::CRYPTO_AEAD_CHACHA20POLY1305_NSECBYTES;
const CRYPTO_AEAD_CHACHA20POLY1305_NPUBBYTES = ParagonIE_Sodium_Compat::CRYPTO_AEAD_CHACHA20POLY1305_NPUBBYTES;
const CRYPTO_AEAD_CHACHA20POLY1305_ABYTES = ParagonIE_Sodium_Compat::CRYPTO_AEAD_CHACHA20POLY1305_ABYTES;
const CRYPTO_AEAD_CHACHA20POLY1305_IETF_KEYBYTES = ParagonIE_Sodium_Compat::CRYPTO_AEAD_CHACHA20POLY1305_IETF_KEYBYTES;
const CRYPTO_AEAD_CHACHA20POLY1305_IETF_NSECBYTES = ParagonIE_Sodium_Compat::CRYPTO_AEAD_CHACHA20POLY1305_IETF_NSECBYTES;
const CRYPTO_AEAD_CHACHA20POLY1305_IETF_NPUBBYTES = ParagonIE_Sodium_Compat::CRYPTO_AEAD_CHACHA20POLY1305_IETF_NPUBBYTES;
const CRYPTO_AEAD_CHACHA20POLY1305_IETF_ABYTES = ParagonIE_Sodium_Compat::CRYPTO_AEAD_CHACHA20POLY1305_IETF_ABYTES;
const CRYPTO_AUTH_BYTES = ParagonIE_Sodium_Compat::CRYPTO_AUTH_BYTES;
const CRYPTO_AUTH_KEYBYTES = ParagonIE_Sodium_Compat::CRYPTO_AUTH_KEYBYTES;
const CRYPTO_BOX_SEALBYTES = ParagonIE_Sodium_Compat::CRYPTO_BOX_SEALBYTES;
const CRYPTO_BOX_SECRETKEYBYTES = ParagonIE_Sodium_Compat::CRYPTO_BOX_SECRETKEYBYTES;
const CRYPTO_BOX_PUBLICKEYBYTES = ParagonIE_Sodium_Compat::CRYPTO_BOX_PUBLICKEYBYTES;
const CRYPTO_BOX_KEYPAIRBYTES = ParagonIE_Sodium_Compat::CRYPTO_BOX_KEYPAIRBYTES;
const CRYPTO_BOX_MACBYTES = ParagonIE_Sodium_Compat::CRYPTO_BOX_MACBYTES;
const CRYPTO_BOX_NONCEBYTES = ParagonIE_Sodium_Compat::CRYPTO_BOX_NONCEBYTES;
const CRYPTO_BOX_SEEDBYTES = ParagonIE_Sodium_Compat::CRYPTO_BOX_SEEDBYTES;
const CRYPTO_KX_BYTES = ParagonIE_Sodium_Compat::CRYPTO_KX_BYTES;
const CRYPTO_KX_SEEDBYTES = ParagonIE_Sodium_Compat::CRYPTO_KX_SEEDBYTES;
const CRYPTO_KX_PUBLICKEYBYTES = ParagonIE_Sodium_Compat::CRYPTO_KX_PUBLICKEYBYTES;
const CRYPTO_KX_SECRETKEYBYTES = ParagonIE_Sodium_Compat::CRYPTO_KX_SECRETKEYBYTES;
const CRYPTO_GENERICHASH_BYTES = ParagonIE_Sodium_Compat::CRYPTO_GENERICHASH_BYTES;
const CRYPTO_GENERICHASH_BYTES_MIN = ParagonIE_Sodium_Compat::CRYPTO_GENERICHASH_BYTES_MIN;
const CRYPTO_GENERICHASH_BYTES_MAX = ParagonIE_Sodium_Compat::CRYPTO_GENERICHASH_BYTES_MAX;
const CRYPTO_GENERICHASH_KEYBYTES = ParagonIE_Sodium_Compat::CRYPTO_GENERICHASH_KEYBYTES;
const CRYPTO_GENERICHASH_KEYBYTES_MIN = ParagonIE_Sodium_Compat::CRYPTO_GENERICHASH_KEYBYTES_MIN;
const CRYPTO_GENERICHASH_KEYBYTES_MAX = ParagonIE_Sodium_Compat::CRYPTO_GENERICHASH_KEYBYTES_MAX;
const CRYPTO_SCALARMULT_BYTES = ParagonIE_Sodium_Compat::CRYPTO_SCALARMULT_BYTES;
const CRYPTO_SCALARMULT_SCALARBYTES = ParagonIE_Sodium_Compat::CRYPTO_SCALARMULT_SCALARBYTES;
const CRYPTO_SHORTHASH_BYTES = ParagonIE_Sodium_Compat::CRYPTO_SHORTHASH_BYTES;
const CRYPTO_SHORTHASH_KEYBYTES = ParagonIE_Sodium_Compat::CRYPTO_SHORTHASH_KEYBYTES;
const CRYPTO_SECRETBOX_KEYBYTES = ParagonIE_Sodium_Compat::CRYPTO_SECRETBOX_KEYBYTES;
const CRYPTO_SECRETBOX_MACBYTES = ParagonIE_Sodium_Compat::CRYPTO_SECRETBOX_MACBYTES;
const CRYPTO_SECRETBOX_NONCEBYTES = ParagonIE_Sodium_Compat::CRYPTO_SECRETBOX_NONCEBYTES;
const CRYPTO_SIGN_BYTES = ParagonIE_Sodium_Compat::CRYPTO_SIGN_BYTES;
const CRYPTO_SIGN_SEEDBYTES = ParagonIE_Sodium_Compat::CRYPTO_SIGN_SEEDBYTES;
const CRYPTO_SIGN_PUBLICKEYBYTES = ParagonIE_Sodium_Compat::CRYPTO_SIGN_PUBLICKEYBYTES;
const CRYPTO_SIGN_SECRETKEYBYTES = ParagonIE_Sodium_Compat::CRYPTO_SIGN_SECRETKEYBYTES;
const CRYPTO_SIGN_KEYPAIRBYTES = ParagonIE_Sodium_Compat::CRYPTO_SIGN_KEYPAIRBYTES;
const CRYPTO_STREAM_KEYBYTES = ParagonIE_Sodium_Compat::CRYPTO_STREAM_KEYBYTES;
const CRYPTO_STREAM_NONCEBYTES = ParagonIE_Sodium_Compat::CRYPTO_STREAM_NONCEBYTES;


<?php

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

if (PHP_VERSION_ID < 50300) {
    return;
}

/*
 * This file is just for convenience, to allow developers to reduce verbosity when
 * they add this project to their libraries.
 *
 * Replace this:
 *
 * $x = ParagonIE_Sodium_Compat::crypto_aead_xchacha20poly1305_encrypt(...$args);
 *
 * with this:
 *
 * use ParagonIE\Sodium\Compat;
 *
 * $x = Compat::crypto_aead_xchacha20poly1305_encrypt(...$args);
 */
spl_autoload_register(function ($class) {
    if ($class[0] === '\\') {
        $class = substr($class, 1);
    }
    $namespace = 'ParagonIE\\Sodium';
    // Does the class use the namespace prefix?
    $len = strlen($namespace);
    if (strncmp($namespace, $class, $len) !== 0) {
        // no, move to the next registered autoloader
        return false;
    }

    // Get the relative class name
    $relative_class = substr($class, $len);

    // Replace the namespace prefix with the base directory, replace namespace
    // separators with directory separators in the relative class name, append
    // with .php
    $file = dirname(dirname(__FILE__)) . '/namespaced/' . str_replace('\\', '/', $relative_class) . '.php';
    // if the file exists, require it
    if (file_exists($file)) {
        require_once $file;
        return true;
    }
    return false;
});