5 * A PHP-Based RSS and Atom Feed Framework.
6 * Takes the hard work out of managing a complete RSS/Atom solution.
8 * Copyright (c) 2004-2012, Ryan Parman, Geoffrey Sneddon, Ryan McCue, and contributors
11 * Redistribution and use in source and binary forms, with or without modification, are
12 * permitted provided that the following conditions are met:
14 * * Redistributions of source code must retain the above copyright notice, this list of
15 * conditions and the following disclaimer.
17 * * Redistributions in binary form must reproduce the above copyright notice, this list
18 * of conditions and the following disclaimer in the documentation and/or other materials
19 * provided with the distribution.
21 * * Neither the name of the SimplePie Team nor the names of its contributors may be used
22 * to endorse or promote products derived from this software without specific prior
25 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
26 * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
27 * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS
28 * AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
29 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
30 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
31 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
32 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
33 * POSSIBILITY OF SUCH DAMAGE.
37 * @copyright 2004-2012 Ryan Parman, Geoffrey Sneddon, Ryan McCue
39 * @author Geoffrey Sneddon
41 * @link http://simplepie.org/ SimplePie
42 * @license http://www.opensource.org/licenses/bsd-license.php BSD License
46 * IRI parser/serialiser/normaliser
50 * @author Geoffrey Sneddon
51 * @author Steve Minutillo
53 * @copyright 2007-2012 Geoffrey Sneddon, Steve Minutillo, Ryan McCue
54 * @license http://www.opensource.org/licenses/bsd-license.php
63 protected $scheme = null;
70 protected $iuserinfo = null;
77 protected $ihost = null;
84 protected $port = null;
91 protected $ipath = '';
98 protected $iquery = null;
105 protected $ifragment = null;
108 * Normalization database
110 * Each key is the scheme, each value is an array with each key as the IRI
111 * part and value as the default value for that part.
113 protected $normalization = array(
121 'ihost' => 'localhost'
134 * Return the entire IRI when you try and read the object as a string
138 public function __toString()
140 return $this->get_iri();
144 * Overload __set() to provide access via properties
146 * @param string $name Property name
147 * @param mixed $value Property value
149 public function __set($name, $value)
151 if (method_exists($this, 'set_' . $name))
153 call_user_func(array($this, 'set_' . $name), $value);
156 $name === 'iauthority'
157 || $name === 'iuserinfo'
160 || $name === 'iquery'
161 || $name === 'ifragment'
164 call_user_func(array($this, 'set_' . substr($name, 1)), $value);
169 * Overload __get() to provide access via properties
171 * @param string $name Property name
174 public function __get($name)
176 // isset() returns false for null, we don't want to do that
177 // Also why we use array_key_exists below instead of isset()
178 $props = get_object_vars($this);
183 $name === 'iauthority' ||
184 $name === 'authority'
187 $return = $this->{"get_$name"}();
189 elseif (array_key_exists($name, $props))
191 $return = $this->$name;
194 elseif (($prop = 'i' . $name) && array_key_exists($prop, $props))
197 $return = $this->$prop;
200 elseif (($prop = substr($name, 1)) && array_key_exists($prop, $props))
203 $return = $this->$prop;
207 trigger_error('Undefined property: ' . get_class($this) . '::' . $name, E_USER_NOTICE);
211 if ($return === null && isset($this->normalization[$this->scheme][$name]))
213 return $this->normalization[$this->scheme][$name];
222 * Overload __isset() to provide access via properties
224 * @param string $name Property name
227 public function __isset($name)
229 if (method_exists($this, 'get_' . $name) || isset($this->$name))
240 * Overload __unset() to provide access via properties
242 * @param string $name Property name
244 public function __unset($name)
246 if (method_exists($this, 'set_' . $name))
248 call_user_func(array($this, 'set_' . $name), '');
253 * Create a new IRI object, from a specified string
257 public function __construct($iri = null)
259 $this->set_iri($iri);
263 * Create a new IRI object by resolving a relative IRI
265 * Returns false if $base is not absolute, otherwise an IRI.
267 * @param IRI|string $base (Absolute) Base IRI
268 * @param IRI|string $relative Relative IRI
271 public static function absolutize($base, $relative)
273 if (!($relative instanceof SimplePie_IRI))
275 $relative = new SimplePie_IRI($relative);
277 if (!$relative->is_valid())
281 elseif ($relative->scheme !== null)
283 return clone $relative;
287 if (!($base instanceof SimplePie_IRI))
289 $base = new SimplePie_IRI($base);
291 if ($base->scheme !== null && $base->is_valid())
293 if ($relative->get_iri() !== '')
295 if ($relative->iuserinfo !== null || $relative->ihost !== null || $relative->port !== null)
297 $target = clone $relative;
298 $target->scheme = $base->scheme;
302 $target = new SimplePie_IRI;
303 $target->scheme = $base->scheme;
304 $target->iuserinfo = $base->iuserinfo;
305 $target->ihost = $base->ihost;
306 $target->port = $base->port;
307 if ($relative->ipath !== '')
309 if ($relative->ipath[0] === '/')
311 $target->ipath = $relative->ipath;
313 elseif (($base->iuserinfo !== null || $base->ihost !== null || $base->port !== null) && $base->ipath === '')
315 $target->ipath = '/' . $relative->ipath;
317 elseif (($last_segment = strrpos($base->ipath, '/')) !== false)
319 $target->ipath = substr($base->ipath, 0, $last_segment + 1) . $relative->ipath;
323 $target->ipath = $relative->ipath;
325 $target->ipath = $target->remove_dot_segments($target->ipath);
326 $target->iquery = $relative->iquery;
330 $target->ipath = $base->ipath;
331 if ($relative->iquery !== null)
333 $target->iquery = $relative->iquery;
335 elseif ($base->iquery !== null)
337 $target->iquery = $base->iquery;
340 $target->ifragment = $relative->ifragment;
345 $target = clone $base;
346 $target->ifragment = null;
348 $target->scheme_normalization();
359 * Parse an IRI into scheme/authority/path/query/fragment segments
364 protected function parse_iri($iri)
366 $iri = trim($iri, "\x20\x09\x0A\x0C\x0D");
367 if (preg_match('/^((?P<scheme>[^:\/?#]+):)?(\/\/(?P<authority>[^\/?#]*))?(?P<path>[^?#]*)(\?(?P<query>[^#]*))?(#(?P<fragment>.*))?$/', $iri, $match))
369 if ($match[1] === '')
371 $match['scheme'] = null;
373 if (!isset($match[3]) || $match[3] === '')
375 $match['authority'] = null;
377 if (!isset($match[5]))
381 if (!isset($match[6]) || $match[6] === '')
383 $match['query'] = null;
385 if (!isset($match[8]) || $match[8] === '')
387 $match['fragment'] = null;
393 // This can occur when a paragraph is accidentally parsed as a URI
399 * Remove dot segments from a path
401 * @param string $input
404 protected function remove_dot_segments($input)
407 while (strpos($input, './') !== false || strpos($input, '/.') !== false || $input === '.' || $input === '..')
409 // A: If the input buffer begins with a prefix of "../" or "./", then remove that prefix from the input buffer; otherwise,
410 if (strpos($input, '../') === 0)
412 $input = substr($input, 3);
414 elseif (strpos($input, './') === 0)
416 $input = substr($input, 2);
418 // B: if the input buffer begins with a prefix of "/./" or "/.", where "." is a complete path segment, then replace that prefix with "/" in the input buffer; otherwise,
419 elseif (strpos($input, '/./') === 0)
421 $input = substr($input, 2);
423 elseif ($input === '/.')
427 // C: if the input buffer begins with a prefix of "/../" or "/..", where ".." is a complete path segment, then replace that prefix with "/" in the input buffer and remove the last segment and its preceding "/" (if any) from the output buffer; otherwise,
428 elseif (strpos($input, '/../') === 0)
430 $input = substr($input, 3);
431 $output = substr_replace($output, '', strrpos($output, '/'));
433 elseif ($input === '/..')
436 $output = substr_replace($output, '', strrpos($output, '/'));
438 // D: if the input buffer consists only of "." or "..", then remove that from the input buffer; otherwise,
439 elseif ($input === '.' || $input === '..')
443 // E: move the first path segment in the input buffer to the end of the output buffer, including the initial "/" character (if any) and any subsequent characters up to, but not including, the next "/" character or the end of the input buffer
444 elseif (($pos = strpos($input, '/', 1)) !== false)
446 $output .= substr($input, 0, $pos);
447 $input = substr_replace($input, '', 0, $pos);
455 return $output . $input;
459 * Replace invalid character with percent encoding
461 * @param string $string Input string
462 * @param string $extra_chars Valid characters not in iunreserved or
463 * iprivate (this is ASCII-only)
464 * @param bool $iprivate Allow iprivate
467 protected function replace_invalid_with_pct_encoding($string, $extra_chars, $iprivate = false)
469 // Normalize as many pct-encoded sections as possible
470 $string = preg_replace_callback('/(?:%[A-Fa-f0-9]{2})+/', array($this, 'remove_iunreserved_percent_encoded'), $string);
472 // Replace invalid percent characters
473 $string = preg_replace('/%(?![A-Fa-f0-9]{2})/', '%25', $string);
475 // Add unreserved and % to $extra_chars (the latter is safe because all
476 // pct-encoded sections are now valid).
477 $extra_chars .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~%';
479 // Now replace any bytes that aren't allowed with their pct-encoded versions
481 $strlen = strlen($string);
482 while (($position += strspn($string, $extra_chars, $position)) < $strlen)
484 $value = ord($string[$position]);
489 // By default we are valid
492 // No one byte sequences are valid due to the while.
493 // Two byte sequence:
494 if (($value & 0xE0) === 0xC0)
496 $character = ($value & 0x1F) << 6;
500 // Three byte sequence:
501 elseif (($value & 0xF0) === 0xE0)
503 $character = ($value & 0x0F) << 12;
507 // Four byte sequence:
508 elseif (($value & 0xF8) === 0xF0)
510 $character = ($value & 0x07) << 18;
524 if ($position + $length <= $strlen)
526 for ($position++; $remaining; $position++)
528 $value = ord($string[$position]);
530 // Check that the byte is valid, then add it to the character:
531 if (($value & 0xC0) === 0x80)
533 $character |= ($value & 0x3F) << (--$remaining * 6);
535 // If it is invalid, count the sequence as invalid and reprocess the current byte:
546 $position = $strlen - 1;
551 // Percent encode anything invalid or not in ucschar
555 // Non-shortest form sequences are invalid
556 || $length > 1 && $character <= 0x7F
557 || $length > 2 && $character <= 0x7FF
558 || $length > 3 && $character <= 0xFFFF
559 // Outside of range of ucschar codepoints
561 || ($character & 0xFFFE) === 0xFFFE
562 || $character >= 0xFDD0 && $character <= 0xFDEF
564 // Everything else not in ucschar
565 $character > 0xD7FF && $character < 0xF900
567 || $character > 0xEFFFD
570 // Everything not in iprivate, if it applies
572 || $character < 0xE000
573 || $character > 0x10FFFD
577 // If we were a character, pretend we weren't, but rather an error.
581 for ($j = $start; $j <= $position; $j++)
583 $string = substr_replace($string, sprintf('%%%02X', ord($string[$j])), $j, 1);
595 * Callback function for preg_replace_callback.
597 * Removes sequences of percent encoded bytes that represent UTF-8
598 * encoded characters in iunreserved
600 * @param array $match PCRE match
601 * @return string Replacement
603 protected function remove_iunreserved_percent_encoded($match)
605 // As we just have valid percent encoded sequences we can just explode
606 // and ignore the first member of the returned array (an empty string).
607 $bytes = explode('%', $match[0]);
609 // Initialize the new string (this is what will be returned) and that
610 // there are no bytes remaining in the current sequence (unsurprising
611 // at the first byte!).
615 // Loop over each and every byte, and set $value to its value
616 for ($i = 1, $len = count($bytes); $i < $len; $i++)
618 $value = hexdec($bytes[$i]);
620 // If we're the first byte of sequence:
626 // By default we are valid
629 // One byte sequence:
635 // Two byte sequence:
636 elseif (($value & 0xE0) === 0xC0)
638 $character = ($value & 0x1F) << 6;
642 // Three byte sequence:
643 elseif (($value & 0xF0) === 0xE0)
645 $character = ($value & 0x0F) << 12;
649 // Four byte sequence:
650 elseif (($value & 0xF8) === 0xF0)
652 $character = ($value & 0x07) << 18;
663 // Continuation byte:
666 // Check that the byte is valid, then add it to the character:
667 if (($value & 0xC0) === 0x80)
670 $character |= ($value & 0x3F) << ($remaining * 6);
672 // If it is invalid, count the sequence as invalid and reprocess the current byte as the start of a sequence:
681 // If we've reached the end of the current byte sequence, append it to Unicode::$data
684 // Percent encode anything invalid or not in iunreserved
688 // Non-shortest form sequences are invalid
689 || $length > 1 && $character <= 0x7F
690 || $length > 2 && $character <= 0x7FF
691 || $length > 3 && $character <= 0xFFFF
692 // Outside of range of iunreserved codepoints
694 || $character > 0xEFFFD
696 || ($character & 0xFFFE) === 0xFFFE
697 || $character >= 0xFDD0 && $character <= 0xFDEF
698 // Everything else not in iunreserved (this is all BMP)
699 || $character === 0x2F
700 || $character > 0x39 && $character < 0x41
701 || $character > 0x5A && $character < 0x61
702 || $character > 0x7A && $character < 0x7E
703 || $character > 0x7E && $character < 0xA0
704 || $character > 0xD7FF && $character < 0xF900
707 for ($j = $start; $j <= $i; $j++)
709 $string .= '%' . strtoupper($bytes[$j]);
714 for ($j = $start; $j <= $i; $j++)
716 $string .= chr(hexdec($bytes[$j]));
722 // If we have any bytes left over they are invalid (i.e., we are
723 // mid-way through a multi-byte sequence)
726 for ($j = $start; $j < $len; $j++)
728 $string .= '%' . strtoupper($bytes[$j]);
735 protected function scheme_normalization()
737 if (isset($this->normalization[$this->scheme]['iuserinfo']) && $this->iuserinfo === $this->normalization[$this->scheme]['iuserinfo'])
739 $this->iuserinfo = null;
741 if (isset($this->normalization[$this->scheme]['ihost']) && $this->ihost === $this->normalization[$this->scheme]['ihost'])
745 if (isset($this->normalization[$this->scheme]['port']) && $this->port === $this->normalization[$this->scheme]['port'])
749 if (isset($this->normalization[$this->scheme]['ipath']) && $this->ipath === $this->normalization[$this->scheme]['ipath'])
753 if (isset($this->normalization[$this->scheme]['iquery']) && $this->iquery === $this->normalization[$this->scheme]['iquery'])
755 $this->iquery = null;
757 if (isset($this->normalization[$this->scheme]['ifragment']) && $this->ifragment === $this->normalization[$this->scheme]['ifragment'])
759 $this->ifragment = null;
764 * Check if the object represents a valid IRI. This needs to be done on each
765 * call as some things change depending on another part of the IRI.
769 public function is_valid()
771 $isauthority = $this->iuserinfo !== null || $this->ihost !== null || $this->port !== null;
772 if ($this->ipath !== '' &&
775 $this->ipath[0] !== '/' ||
776 substr($this->ipath, 0, 2) === '//'
779 $this->scheme === null &&
781 strpos($this->ipath, ':') !== false &&
782 (strpos($this->ipath, '/') === false ? true : strpos($this->ipath, ':') < strpos($this->ipath, '/'))
794 * Set the entire IRI. Returns true on success, false on failure (if there
795 * are any invalid characters).
800 public function set_iri($iri)
812 elseif (isset($cache[$iri]))
821 $return) = $cache[$iri];
826 $parsed = $this->parse_iri((string) $iri);
832 $return = $this->set_scheme($parsed['scheme'])
833 && $this->set_authority($parsed['authority'])
834 && $this->set_path($parsed['path'])
835 && $this->set_query($parsed['query'])
836 && $this->set_fragment($parsed['fragment']);
838 $cache[$iri] = array($this->scheme,
851 * Set the scheme. Returns true on success, false on failure (if there are
852 * any invalid characters).
854 * @param string $scheme
857 public function set_scheme($scheme)
859 if ($scheme === null)
861 $this->scheme = null;
863 elseif (!preg_match('/^[A-Za-z][0-9A-Za-z+\-.]*$/', $scheme))
865 $this->scheme = null;
870 $this->scheme = strtolower($scheme);
876 * Set the authority. Returns true on success, false on failure (if there are
877 * any invalid characters).
879 * @param string $authority
882 public function set_authority($authority)
888 if ($authority === null)
890 $this->iuserinfo = null;
895 elseif (isset($cache[$authority]))
897 list($this->iuserinfo,
900 $return) = $cache[$authority];
906 $remaining = $authority;
907 if (($iuserinfo_end = strrpos($remaining, '@')) !== false)
909 $iuserinfo = substr($remaining, 0, $iuserinfo_end);
910 $remaining = substr($remaining, $iuserinfo_end + 1);
916 if (($port_start = strpos($remaining, ':', strpos($remaining, ']'))) !== false)
918 if (($port = substr($remaining, $port_start + 1)) === false)
922 $remaining = substr($remaining, 0, $port_start);
929 $return = $this->set_userinfo($iuserinfo) &&
930 $this->set_host($remaining) &&
931 $this->set_port($port);
933 $cache[$authority] = array($this->iuserinfo,
945 * @param string $iuserinfo
948 public function set_userinfo($iuserinfo)
950 if ($iuserinfo === null)
952 $this->iuserinfo = null;
956 $this->iuserinfo = $this->replace_invalid_with_pct_encoding($iuserinfo, '!$&\'()*+,;=:');
957 $this->scheme_normalization();
964 * Set the ihost. Returns true on success, false on failure (if there are
965 * any invalid characters).
967 * @param string $ihost
970 public function set_host($ihost)
977 elseif (substr($ihost, 0, 1) === '[' && substr($ihost, -1) === ']')
979 if (SimplePie_Net_IPv6::check_ipv6(substr($ihost, 1, -1)))
981 $this->ihost = '[' . SimplePie_Net_IPv6::compress(substr($ihost, 1, -1)) . ']';
991 $ihost = $this->replace_invalid_with_pct_encoding($ihost, '!$&\'()*+,;=');
993 // Lowercase, but ignore pct-encoded sections (as they should
994 // remain uppercase). This must be done after the previous step
995 // as that can add unescaped characters.
997 $strlen = strlen($ihost);
998 while (($position += strcspn($ihost, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ%', $position)) < $strlen)
1000 if ($ihost[$position] === '%')
1006 $ihost[$position] = strtolower($ihost[$position]);
1011 $this->ihost = $ihost;
1014 $this->scheme_normalization();
1020 * Set the port. Returns true on success, false on failure (if there are
1021 * any invalid characters).
1023 * @param string $port
1026 public function set_port($port)
1033 elseif (strspn($port, '0123456789') === strlen($port))
1035 $this->port = (int) $port;
1036 $this->scheme_normalization();
1049 * @param string $ipath
1052 public function set_path($ipath)
1060 $ipath = (string) $ipath;
1062 if (isset($cache[$ipath]))
1064 $this->ipath = $cache[$ipath][(int) ($this->scheme !== null)];
1068 $valid = $this->replace_invalid_with_pct_encoding($ipath, '!$&\'()*+,;=@:/');
1069 $removed = $this->remove_dot_segments($valid);
1071 $cache[$ipath] = array($valid, $removed);
1072 $this->ipath = ($this->scheme !== null) ? $removed : $valid;
1075 $this->scheme_normalization();
1082 * @param string $iquery
1085 public function set_query($iquery)
1087 if ($iquery === null)
1089 $this->iquery = null;
1093 $this->iquery = $this->replace_invalid_with_pct_encoding($iquery, '!$&\'()*+,;=:@/?', true);
1094 $this->scheme_normalization();
1100 * Set the ifragment.
1102 * @param string $ifragment
1105 public function set_fragment($ifragment)
1107 if ($ifragment === null)
1109 $this->ifragment = null;
1113 $this->ifragment = $this->replace_invalid_with_pct_encoding($ifragment, '!$&\'()*+,;=:@/?');
1114 $this->scheme_normalization();
1120 * Convert an IRI to a URI (or parts thereof)
1124 public function to_uri($string)
1129 $non_ascii = implode('', range("\x80", "\xFF"));
1133 $strlen = strlen($string);
1134 while (($position += strcspn($string, $non_ascii, $position)) < $strlen)
1136 $string = substr_replace($string, sprintf('%%%02X', ord($string[$position])), $position, 1);
1145 * Get the complete IRI
1149 public function get_iri()
1151 if (!$this->is_valid())
1157 if ($this->scheme !== null)
1159 $iri .= $this->scheme . ':';
1161 if (($iauthority = $this->get_iauthority()) !== null)
1163 $iri .= '//' . $iauthority;
1165 if ($this->ipath !== '')
1167 $iri .= $this->ipath;
1169 elseif (!empty($this->normalization[$this->scheme]['ipath']) && $iauthority !== null && $iauthority !== '')
1171 $iri .= $this->normalization[$this->scheme]['ipath'];
1173 if ($this->iquery !== null)
1175 $iri .= '?' . $this->iquery;
1177 if ($this->ifragment !== null)
1179 $iri .= '#' . $this->ifragment;
1186 * Get the complete URI
1190 public function get_uri()
1192 return $this->to_uri($this->get_iri());
1196 * Get the complete iauthority
1200 protected function get_iauthority()
1202 if ($this->iuserinfo !== null || $this->ihost !== null || $this->port !== null)
1205 if ($this->iuserinfo !== null)
1207 $iauthority .= $this->iuserinfo . '@';
1209 if ($this->ihost !== null)
1211 $iauthority .= $this->ihost;
1213 if ($this->port !== null)
1215 $iauthority .= ':' . $this->port;
1226 * Get the complete authority
1230 protected function get_authority()
1232 $iauthority = $this->get_iauthority();
1233 if (is_string($iauthority))
1234 return $this->to_uri($iauthority);