PageRenderTime 63ms CodeModel.GetById 28ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/simplepie/library/SimplePie/IRI.php

http://github.com/moodle/moodle
PHP | 1236 lines | 825 code | 90 blank | 321 comment | 165 complexity | 24f0002a0e14614ea06c2bca68048cb0 MD5 | raw file
Possible License(s): MIT, AGPL-3.0, MPL-2.0-no-copyleft-exception, LGPL-3.0, GPL-3.0, Apache-2.0, LGPL-2.1, BSD-3-Clause
  1. <?php
  2. /**
  3. * SimplePie
  4. *
  5. * A PHP-Based RSS and Atom Feed Framework.
  6. * Takes the hard work out of managing a complete RSS/Atom solution.
  7. *
  8. * Copyright (c) 2004-2016, Ryan Parman, Geoffrey Sneddon, Ryan McCue, and contributors
  9. * All rights reserved.
  10. *
  11. * Redistribution and use in source and binary forms, with or without modification, are
  12. * permitted provided that the following conditions are met:
  13. *
  14. * * Redistributions of source code must retain the above copyright notice, this list of
  15. * conditions and the following disclaimer.
  16. *
  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.
  20. *
  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
  23. * written permission.
  24. *
  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.
  34. *
  35. * @package SimplePie
  36. * @copyright 2004-2016 Ryan Parman, Geoffrey Sneddon, Ryan McCue
  37. * @author Ryan Parman
  38. * @author Geoffrey Sneddon
  39. * @author Ryan McCue
  40. * @link http://simplepie.org/ SimplePie
  41. * @license http://www.opensource.org/licenses/bsd-license.php BSD License
  42. */
  43. /**
  44. * IRI parser/serialiser/normaliser
  45. *
  46. * @package SimplePie
  47. * @subpackage HTTP
  48. * @author Geoffrey Sneddon
  49. * @author Steve Minutillo
  50. * @author Ryan McCue
  51. * @copyright 2007-2012 Geoffrey Sneddon, Steve Minutillo, Ryan McCue
  52. * @license http://www.opensource.org/licenses/bsd-license.php
  53. */
  54. class SimplePie_IRI
  55. {
  56. /**
  57. * Scheme
  58. *
  59. * @var string
  60. */
  61. protected $scheme = null;
  62. /**
  63. * User Information
  64. *
  65. * @var string
  66. */
  67. protected $iuserinfo = null;
  68. /**
  69. * ihost
  70. *
  71. * @var string
  72. */
  73. protected $ihost = null;
  74. /**
  75. * Port
  76. *
  77. * @var string
  78. */
  79. protected $port = null;
  80. /**
  81. * ipath
  82. *
  83. * @var string
  84. */
  85. protected $ipath = '';
  86. /**
  87. * iquery
  88. *
  89. * @var string
  90. */
  91. protected $iquery = null;
  92. /**
  93. * ifragment
  94. *
  95. * @var string
  96. */
  97. protected $ifragment = null;
  98. /**
  99. * Normalization database
  100. *
  101. * Each key is the scheme, each value is an array with each key as the IRI
  102. * part and value as the default value for that part.
  103. */
  104. protected $normalization = array(
  105. 'acap' => array(
  106. 'port' => 674
  107. ),
  108. 'dict' => array(
  109. 'port' => 2628
  110. ),
  111. 'file' => array(
  112. 'ihost' => 'localhost'
  113. ),
  114. 'http' => array(
  115. 'port' => 80,
  116. 'ipath' => '/'
  117. ),
  118. 'https' => array(
  119. 'port' => 443,
  120. 'ipath' => '/'
  121. ),
  122. );
  123. /**
  124. * Return the entire IRI when you try and read the object as a string
  125. *
  126. * @return string
  127. */
  128. public function __toString()
  129. {
  130. return $this->get_iri();
  131. }
  132. /**
  133. * Overload __set() to provide access via properties
  134. *
  135. * @param string $name Property name
  136. * @param mixed $value Property value
  137. */
  138. public function __set($name, $value)
  139. {
  140. if (method_exists($this, 'set_' . $name))
  141. {
  142. call_user_func(array($this, 'set_' . $name), $value);
  143. }
  144. elseif (
  145. $name === 'iauthority'
  146. || $name === 'iuserinfo'
  147. || $name === 'ihost'
  148. || $name === 'ipath'
  149. || $name === 'iquery'
  150. || $name === 'ifragment'
  151. )
  152. {
  153. call_user_func(array($this, 'set_' . substr($name, 1)), $value);
  154. }
  155. }
  156. /**
  157. * Overload __get() to provide access via properties
  158. *
  159. * @param string $name Property name
  160. * @return mixed
  161. */
  162. public function __get($name)
  163. {
  164. // isset() returns false for null, we don't want to do that
  165. // Also why we use array_key_exists below instead of isset()
  166. $props = get_object_vars($this);
  167. if (
  168. $name === 'iri' ||
  169. $name === 'uri' ||
  170. $name === 'iauthority' ||
  171. $name === 'authority'
  172. )
  173. {
  174. $return = $this->{"get_$name"}();
  175. }
  176. elseif (array_key_exists($name, $props))
  177. {
  178. $return = $this->$name;
  179. }
  180. // host -> ihost
  181. elseif (($prop = 'i' . $name) && array_key_exists($prop, $props))
  182. {
  183. $name = $prop;
  184. $return = $this->$prop;
  185. }
  186. // ischeme -> scheme
  187. elseif (($prop = substr($name, 1)) && array_key_exists($prop, $props))
  188. {
  189. $name = $prop;
  190. $return = $this->$prop;
  191. }
  192. else
  193. {
  194. trigger_error('Undefined property: ' . get_class($this) . '::' . $name, E_USER_NOTICE);
  195. $return = null;
  196. }
  197. if ($return === null && isset($this->normalization[$this->scheme][$name]))
  198. {
  199. return $this->normalization[$this->scheme][$name];
  200. }
  201. return $return;
  202. }
  203. /**
  204. * Overload __isset() to provide access via properties
  205. *
  206. * @param string $name Property name
  207. * @return bool
  208. */
  209. public function __isset($name)
  210. {
  211. return method_exists($this, 'get_' . $name) || isset($this->$name);
  212. }
  213. /**
  214. * Overload __unset() to provide access via properties
  215. *
  216. * @param string $name Property name
  217. */
  218. public function __unset($name)
  219. {
  220. if (method_exists($this, 'set_' . $name))
  221. {
  222. call_user_func(array($this, 'set_' . $name), '');
  223. }
  224. }
  225. /**
  226. * Create a new IRI object, from a specified string
  227. *
  228. * @param string $iri
  229. */
  230. public function __construct($iri = null)
  231. {
  232. $this->set_iri($iri);
  233. }
  234. /**
  235. * Clean up
  236. */
  237. public function __destruct() {
  238. $this->set_iri(null, true);
  239. $this->set_path(null, true);
  240. $this->set_authority(null, true);
  241. }
  242. /**
  243. * Create a new IRI object by resolving a relative IRI
  244. *
  245. * Returns false if $base is not absolute, otherwise an IRI.
  246. *
  247. * @param IRI|string $base (Absolute) Base IRI
  248. * @param IRI|string $relative Relative IRI
  249. * @return IRI|false
  250. */
  251. public static function absolutize($base, $relative)
  252. {
  253. if (!($relative instanceof SimplePie_IRI))
  254. {
  255. $relative = new SimplePie_IRI($relative);
  256. }
  257. if (!$relative->is_valid())
  258. {
  259. return false;
  260. }
  261. elseif ($relative->scheme !== null)
  262. {
  263. return clone $relative;
  264. }
  265. else
  266. {
  267. if (!($base instanceof SimplePie_IRI))
  268. {
  269. $base = new SimplePie_IRI($base);
  270. }
  271. if ($base->scheme !== null && $base->is_valid())
  272. {
  273. if ($relative->get_iri() !== '')
  274. {
  275. if ($relative->iuserinfo !== null || $relative->ihost !== null || $relative->port !== null)
  276. {
  277. $target = clone $relative;
  278. $target->scheme = $base->scheme;
  279. }
  280. else
  281. {
  282. $target = new SimplePie_IRI;
  283. $target->scheme = $base->scheme;
  284. $target->iuserinfo = $base->iuserinfo;
  285. $target->ihost = $base->ihost;
  286. $target->port = $base->port;
  287. if ($relative->ipath !== '')
  288. {
  289. if ($relative->ipath[0] === '/')
  290. {
  291. $target->ipath = $relative->ipath;
  292. }
  293. elseif (($base->iuserinfo !== null || $base->ihost !== null || $base->port !== null) && $base->ipath === '')
  294. {
  295. $target->ipath = '/' . $relative->ipath;
  296. }
  297. elseif (($last_segment = strrpos($base->ipath, '/')) !== false)
  298. {
  299. $target->ipath = substr($base->ipath, 0, $last_segment + 1) . $relative->ipath;
  300. }
  301. else
  302. {
  303. $target->ipath = $relative->ipath;
  304. }
  305. $target->ipath = $target->remove_dot_segments($target->ipath);
  306. $target->iquery = $relative->iquery;
  307. }
  308. else
  309. {
  310. $target->ipath = $base->ipath;
  311. if ($relative->iquery !== null)
  312. {
  313. $target->iquery = $relative->iquery;
  314. }
  315. elseif ($base->iquery !== null)
  316. {
  317. $target->iquery = $base->iquery;
  318. }
  319. }
  320. $target->ifragment = $relative->ifragment;
  321. }
  322. }
  323. else
  324. {
  325. $target = clone $base;
  326. $target->ifragment = null;
  327. }
  328. $target->scheme_normalization();
  329. return $target;
  330. }
  331. return false;
  332. }
  333. }
  334. /**
  335. * Parse an IRI into scheme/authority/path/query/fragment segments
  336. *
  337. * @param string $iri
  338. * @return array
  339. */
  340. protected function parse_iri($iri)
  341. {
  342. $iri = trim($iri, "\x20\x09\x0A\x0C\x0D");
  343. if (preg_match('/^((?P<scheme>[^:\/?#]+):)?(\/\/(?P<authority>[^\/?#]*))?(?P<path>[^?#]*)(\?(?P<query>[^#]*))?(#(?P<fragment>.*))?$/', $iri, $match))
  344. {
  345. if ($match[1] === '')
  346. {
  347. $match['scheme'] = null;
  348. }
  349. if (!isset($match[3]) || $match[3] === '')
  350. {
  351. $match['authority'] = null;
  352. }
  353. if (!isset($match[5]))
  354. {
  355. $match['path'] = '';
  356. }
  357. if (!isset($match[6]) || $match[6] === '')
  358. {
  359. $match['query'] = null;
  360. }
  361. if (!isset($match[8]) || $match[8] === '')
  362. {
  363. $match['fragment'] = null;
  364. }
  365. return $match;
  366. }
  367. // This can occur when a paragraph is accidentally parsed as a URI
  368. return false;
  369. }
  370. /**
  371. * Remove dot segments from a path
  372. *
  373. * @param string $input
  374. * @return string
  375. */
  376. protected function remove_dot_segments($input)
  377. {
  378. $output = '';
  379. while (strpos($input, './') !== false || strpos($input, '/.') !== false || $input === '.' || $input === '..')
  380. {
  381. // A: If the input buffer begins with a prefix of "../" or "./", then remove that prefix from the input buffer; otherwise,
  382. if (strpos($input, '../') === 0)
  383. {
  384. $input = substr($input, 3);
  385. }
  386. elseif (strpos($input, './') === 0)
  387. {
  388. $input = substr($input, 2);
  389. }
  390. // 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,
  391. elseif (strpos($input, '/./') === 0)
  392. {
  393. $input = substr($input, 2);
  394. }
  395. elseif ($input === '/.')
  396. {
  397. $input = '/';
  398. }
  399. // 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,
  400. elseif (strpos($input, '/../') === 0)
  401. {
  402. $input = substr($input, 3);
  403. $output = substr_replace($output, '', strrpos($output, '/'));
  404. }
  405. elseif ($input === '/..')
  406. {
  407. $input = '/';
  408. $output = substr_replace($output, '', strrpos($output, '/'));
  409. }
  410. // D: if the input buffer consists only of "." or "..", then remove that from the input buffer; otherwise,
  411. elseif ($input === '.' || $input === '..')
  412. {
  413. $input = '';
  414. }
  415. // 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
  416. elseif (($pos = strpos($input, '/', 1)) !== false)
  417. {
  418. $output .= substr($input, 0, $pos);
  419. $input = substr_replace($input, '', 0, $pos);
  420. }
  421. else
  422. {
  423. $output .= $input;
  424. $input = '';
  425. }
  426. }
  427. return $output . $input;
  428. }
  429. /**
  430. * Replace invalid character with percent encoding
  431. *
  432. * @param string $string Input string
  433. * @param string $extra_chars Valid characters not in iunreserved or
  434. * iprivate (this is ASCII-only)
  435. * @param bool $iprivate Allow iprivate
  436. * @return string
  437. */
  438. protected function replace_invalid_with_pct_encoding($string, $extra_chars, $iprivate = false)
  439. {
  440. // Normalize as many pct-encoded sections as possible
  441. $string = preg_replace_callback('/(?:%[A-Fa-f0-9]{2})+/', array($this, 'remove_iunreserved_percent_encoded'), $string);
  442. // Replace invalid percent characters
  443. $string = preg_replace('/%(?![A-Fa-f0-9]{2})/', '%25', $string);
  444. // Add unreserved and % to $extra_chars (the latter is safe because all
  445. // pct-encoded sections are now valid).
  446. $extra_chars .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~%';
  447. // Now replace any bytes that aren't allowed with their pct-encoded versions
  448. $position = 0;
  449. $strlen = strlen($string);
  450. while (($position += strspn($string, $extra_chars, $position)) < $strlen)
  451. {
  452. $value = ord($string[$position]);
  453. // Start position
  454. $start = $position;
  455. // By default we are valid
  456. $valid = true;
  457. // No one byte sequences are valid due to the while.
  458. // Two byte sequence:
  459. if (($value & 0xE0) === 0xC0)
  460. {
  461. $character = ($value & 0x1F) << 6;
  462. $length = 2;
  463. $remaining = 1;
  464. }
  465. // Three byte sequence:
  466. elseif (($value & 0xF0) === 0xE0)
  467. {
  468. $character = ($value & 0x0F) << 12;
  469. $length = 3;
  470. $remaining = 2;
  471. }
  472. // Four byte sequence:
  473. elseif (($value & 0xF8) === 0xF0)
  474. {
  475. $character = ($value & 0x07) << 18;
  476. $length = 4;
  477. $remaining = 3;
  478. }
  479. // Invalid byte:
  480. else
  481. {
  482. $valid = false;
  483. $length = 1;
  484. $remaining = 0;
  485. }
  486. if ($remaining)
  487. {
  488. if ($position + $length <= $strlen)
  489. {
  490. for ($position++; $remaining; $position++)
  491. {
  492. $value = ord($string[$position]);
  493. // Check that the byte is valid, then add it to the character:
  494. if (($value & 0xC0) === 0x80)
  495. {
  496. $character |= ($value & 0x3F) << (--$remaining * 6);
  497. }
  498. // If it is invalid, count the sequence as invalid and reprocess the current byte:
  499. else
  500. {
  501. $valid = false;
  502. $position--;
  503. break;
  504. }
  505. }
  506. }
  507. else
  508. {
  509. $position = $strlen - 1;
  510. $valid = false;
  511. }
  512. }
  513. // Percent encode anything invalid or not in ucschar
  514. if (
  515. // Invalid sequences
  516. !$valid
  517. // Non-shortest form sequences are invalid
  518. || $length > 1 && $character <= 0x7F
  519. || $length > 2 && $character <= 0x7FF
  520. || $length > 3 && $character <= 0xFFFF
  521. // Outside of range of ucschar codepoints
  522. // Noncharacters
  523. || ($character & 0xFFFE) === 0xFFFE
  524. || $character >= 0xFDD0 && $character <= 0xFDEF
  525. || (
  526. // Everything else not in ucschar
  527. $character > 0xD7FF && $character < 0xF900
  528. || $character < 0xA0
  529. || $character > 0xEFFFD
  530. )
  531. && (
  532. // Everything not in iprivate, if it applies
  533. !$iprivate
  534. || $character < 0xE000
  535. || $character > 0x10FFFD
  536. )
  537. )
  538. {
  539. // If we were a character, pretend we weren't, but rather an error.
  540. if ($valid)
  541. $position--;
  542. for ($j = $start; $j <= $position; $j++)
  543. {
  544. $string = substr_replace($string, sprintf('%%%02X', ord($string[$j])), $j, 1);
  545. $j += 2;
  546. $position += 2;
  547. $strlen += 2;
  548. }
  549. }
  550. }
  551. return $string;
  552. }
  553. /**
  554. * Callback function for preg_replace_callback.
  555. *
  556. * Removes sequences of percent encoded bytes that represent UTF-8
  557. * encoded characters in iunreserved
  558. *
  559. * @param array $match PCRE match
  560. * @return string Replacement
  561. */
  562. protected function remove_iunreserved_percent_encoded($match)
  563. {
  564. // As we just have valid percent encoded sequences we can just explode
  565. // and ignore the first member of the returned array (an empty string).
  566. $bytes = explode('%', $match[0]);
  567. // Initialize the new string (this is what will be returned) and that
  568. // there are no bytes remaining in the current sequence (unsurprising
  569. // at the first byte!).
  570. $string = '';
  571. $remaining = 0;
  572. // Loop over each and every byte, and set $value to its value
  573. for ($i = 1, $len = count($bytes); $i < $len; $i++)
  574. {
  575. $value = hexdec($bytes[$i]);
  576. // If we're the first byte of sequence:
  577. if (!$remaining)
  578. {
  579. // Start position
  580. $start = $i;
  581. // By default we are valid
  582. $valid = true;
  583. // One byte sequence:
  584. if ($value <= 0x7F)
  585. {
  586. $character = $value;
  587. $length = 1;
  588. }
  589. // Two byte sequence:
  590. elseif (($value & 0xE0) === 0xC0)
  591. {
  592. $character = ($value & 0x1F) << 6;
  593. $length = 2;
  594. $remaining = 1;
  595. }
  596. // Three byte sequence:
  597. elseif (($value & 0xF0) === 0xE0)
  598. {
  599. $character = ($value & 0x0F) << 12;
  600. $length = 3;
  601. $remaining = 2;
  602. }
  603. // Four byte sequence:
  604. elseif (($value & 0xF8) === 0xF0)
  605. {
  606. $character = ($value & 0x07) << 18;
  607. $length = 4;
  608. $remaining = 3;
  609. }
  610. // Invalid byte:
  611. else
  612. {
  613. $valid = false;
  614. $remaining = 0;
  615. }
  616. }
  617. // Continuation byte:
  618. else
  619. {
  620. // Check that the byte is valid, then add it to the character:
  621. if (($value & 0xC0) === 0x80)
  622. {
  623. $remaining--;
  624. $character |= ($value & 0x3F) << ($remaining * 6);
  625. }
  626. // If it is invalid, count the sequence as invalid and reprocess the current byte as the start of a sequence:
  627. else
  628. {
  629. $valid = false;
  630. $remaining = 0;
  631. $i--;
  632. }
  633. }
  634. // If we've reached the end of the current byte sequence, append it to Unicode::$data
  635. if (!$remaining)
  636. {
  637. // Percent encode anything invalid or not in iunreserved
  638. if (
  639. // Invalid sequences
  640. !$valid
  641. // Non-shortest form sequences are invalid
  642. || $length > 1 && $character <= 0x7F
  643. || $length > 2 && $character <= 0x7FF
  644. || $length > 3 && $character <= 0xFFFF
  645. // Outside of range of iunreserved codepoints
  646. || $character < 0x2D
  647. || $character > 0xEFFFD
  648. // Noncharacters
  649. || ($character & 0xFFFE) === 0xFFFE
  650. || $character >= 0xFDD0 && $character <= 0xFDEF
  651. // Everything else not in iunreserved (this is all BMP)
  652. || $character === 0x2F
  653. || $character > 0x39 && $character < 0x41
  654. || $character > 0x5A && $character < 0x61
  655. || $character > 0x7A && $character < 0x7E
  656. || $character > 0x7E && $character < 0xA0
  657. || $character > 0xD7FF && $character < 0xF900
  658. )
  659. {
  660. for ($j = $start; $j <= $i; $j++)
  661. {
  662. $string .= '%' . strtoupper($bytes[$j]);
  663. }
  664. }
  665. else
  666. {
  667. for ($j = $start; $j <= $i; $j++)
  668. {
  669. $string .= chr(hexdec($bytes[$j]));
  670. }
  671. }
  672. }
  673. }
  674. // If we have any bytes left over they are invalid (i.e., we are
  675. // mid-way through a multi-byte sequence)
  676. if ($remaining)
  677. {
  678. for ($j = $start; $j < $len; $j++)
  679. {
  680. $string .= '%' . strtoupper($bytes[$j]);
  681. }
  682. }
  683. return $string;
  684. }
  685. protected function scheme_normalization()
  686. {
  687. if (isset($this->normalization[$this->scheme]['iuserinfo']) && $this->iuserinfo === $this->normalization[$this->scheme]['iuserinfo'])
  688. {
  689. $this->iuserinfo = null;
  690. }
  691. if (isset($this->normalization[$this->scheme]['ihost']) && $this->ihost === $this->normalization[$this->scheme]['ihost'])
  692. {
  693. $this->ihost = null;
  694. }
  695. if (isset($this->normalization[$this->scheme]['port']) && $this->port === $this->normalization[$this->scheme]['port'])
  696. {
  697. $this->port = null;
  698. }
  699. if (isset($this->normalization[$this->scheme]['ipath']) && $this->ipath === $this->normalization[$this->scheme]['ipath'])
  700. {
  701. $this->ipath = '';
  702. }
  703. if (isset($this->normalization[$this->scheme]['iquery']) && $this->iquery === $this->normalization[$this->scheme]['iquery'])
  704. {
  705. $this->iquery = null;
  706. }
  707. if (isset($this->normalization[$this->scheme]['ifragment']) && $this->ifragment === $this->normalization[$this->scheme]['ifragment'])
  708. {
  709. $this->ifragment = null;
  710. }
  711. }
  712. /**
  713. * Check if the object represents a valid IRI. This needs to be done on each
  714. * call as some things change depending on another part of the IRI.
  715. *
  716. * @return bool
  717. */
  718. public function is_valid()
  719. {
  720. if ($this->ipath === '') return true;
  721. $isauthority = $this->iuserinfo !== null || $this->ihost !== null ||
  722. $this->port !== null;
  723. if ($isauthority && $this->ipath[0] === '/') return true;
  724. if (!$isauthority && (substr($this->ipath, 0, 2) === '//')) return false;
  725. // Relative urls cannot have a colon in the first path segment (and the
  726. // slashes themselves are not included so skip the first character).
  727. if (!$this->scheme && !$isauthority &&
  728. strpos($this->ipath, ':') !== false &&
  729. strpos($this->ipath, '/', 1) !== false &&
  730. strpos($this->ipath, ':') < strpos($this->ipath, '/', 1)) return false;
  731. return true;
  732. }
  733. /**
  734. * Set the entire IRI. Returns true on success, false on failure (if there
  735. * are any invalid characters).
  736. *
  737. * @param string $iri
  738. * @return bool
  739. */
  740. public function set_iri($iri, $clear_cache = false)
  741. {
  742. static $cache;
  743. if ($clear_cache)
  744. {
  745. $cache = null;
  746. return;
  747. }
  748. if (!$cache)
  749. {
  750. $cache = array();
  751. }
  752. if ($iri === null)
  753. {
  754. return true;
  755. }
  756. elseif (isset($cache[$iri]))
  757. {
  758. list($this->scheme,
  759. $this->iuserinfo,
  760. $this->ihost,
  761. $this->port,
  762. $this->ipath,
  763. $this->iquery,
  764. $this->ifragment,
  765. $return) = $cache[$iri];
  766. return $return;
  767. }
  768. $parsed = $this->parse_iri((string) $iri);
  769. if (!$parsed)
  770. {
  771. return false;
  772. }
  773. $return = $this->set_scheme($parsed['scheme'])
  774. && $this->set_authority($parsed['authority'])
  775. && $this->set_path($parsed['path'])
  776. && $this->set_query($parsed['query'])
  777. && $this->set_fragment($parsed['fragment']);
  778. $cache[$iri] = array($this->scheme,
  779. $this->iuserinfo,
  780. $this->ihost,
  781. $this->port,
  782. $this->ipath,
  783. $this->iquery,
  784. $this->ifragment,
  785. $return);
  786. return $return;
  787. }
  788. /**
  789. * Set the scheme. Returns true on success, false on failure (if there are
  790. * any invalid characters).
  791. *
  792. * @param string $scheme
  793. * @return bool
  794. */
  795. public function set_scheme($scheme)
  796. {
  797. if ($scheme === null)
  798. {
  799. $this->scheme = null;
  800. }
  801. elseif (!preg_match('/^[A-Za-z][0-9A-Za-z+\-.]*$/', $scheme))
  802. {
  803. $this->scheme = null;
  804. return false;
  805. }
  806. else
  807. {
  808. $this->scheme = strtolower($scheme);
  809. }
  810. return true;
  811. }
  812. /**
  813. * Set the authority. Returns true on success, false on failure (if there are
  814. * any invalid characters).
  815. *
  816. * @param string $authority
  817. * @return bool
  818. */
  819. public function set_authority($authority, $clear_cache = false)
  820. {
  821. static $cache;
  822. if ($clear_cache)
  823. {
  824. $cache = null;
  825. return;
  826. }
  827. if (!$cache)
  828. $cache = array();
  829. if ($authority === null)
  830. {
  831. $this->iuserinfo = null;
  832. $this->ihost = null;
  833. $this->port = null;
  834. return true;
  835. }
  836. elseif (isset($cache[$authority]))
  837. {
  838. list($this->iuserinfo,
  839. $this->ihost,
  840. $this->port,
  841. $return) = $cache[$authority];
  842. return $return;
  843. }
  844. $remaining = $authority;
  845. if (($iuserinfo_end = strrpos($remaining, '@')) !== false)
  846. {
  847. $iuserinfo = substr($remaining, 0, $iuserinfo_end);
  848. $remaining = substr($remaining, $iuserinfo_end + 1);
  849. }
  850. else
  851. {
  852. $iuserinfo = null;
  853. }
  854. if (($port_start = strpos($remaining, ':', strpos($remaining, ']'))) !== false)
  855. {
  856. if (($port = substr($remaining, $port_start + 1)) === false)
  857. {
  858. $port = null;
  859. }
  860. $remaining = substr($remaining, 0, $port_start);
  861. }
  862. else
  863. {
  864. $port = null;
  865. }
  866. $return = $this->set_userinfo($iuserinfo) &&
  867. $this->set_host($remaining) &&
  868. $this->set_port($port);
  869. $cache[$authority] = array($this->iuserinfo,
  870. $this->ihost,
  871. $this->port,
  872. $return);
  873. return $return;
  874. }
  875. /**
  876. * Set the iuserinfo.
  877. *
  878. * @param string $iuserinfo
  879. * @return bool
  880. */
  881. public function set_userinfo($iuserinfo)
  882. {
  883. if ($iuserinfo === null)
  884. {
  885. $this->iuserinfo = null;
  886. }
  887. else
  888. {
  889. $this->iuserinfo = $this->replace_invalid_with_pct_encoding($iuserinfo, '!$&\'()*+,;=:');
  890. $this->scheme_normalization();
  891. }
  892. return true;
  893. }
  894. /**
  895. * Set the ihost. Returns true on success, false on failure (if there are
  896. * any invalid characters).
  897. *
  898. * @param string $ihost
  899. * @return bool
  900. */
  901. public function set_host($ihost)
  902. {
  903. if ($ihost === null)
  904. {
  905. $this->ihost = null;
  906. return true;
  907. }
  908. elseif (substr($ihost, 0, 1) === '[' && substr($ihost, -1) === ']')
  909. {
  910. if (SimplePie_Net_IPv6::check_ipv6(substr($ihost, 1, -1)))
  911. {
  912. $this->ihost = '[' . SimplePie_Net_IPv6::compress(substr($ihost, 1, -1)) . ']';
  913. }
  914. else
  915. {
  916. $this->ihost = null;
  917. return false;
  918. }
  919. }
  920. else
  921. {
  922. $ihost = $this->replace_invalid_with_pct_encoding($ihost, '!$&\'()*+,;=');
  923. // Lowercase, but ignore pct-encoded sections (as they should
  924. // remain uppercase). This must be done after the previous step
  925. // as that can add unescaped characters.
  926. $position = 0;
  927. $strlen = strlen($ihost);
  928. while (($position += strcspn($ihost, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ%', $position)) < $strlen)
  929. {
  930. if ($ihost[$position] === '%')
  931. {
  932. $position += 3;
  933. }
  934. else
  935. {
  936. $ihost[$position] = strtolower($ihost[$position]);
  937. $position++;
  938. }
  939. }
  940. $this->ihost = $ihost;
  941. }
  942. $this->scheme_normalization();
  943. return true;
  944. }
  945. /**
  946. * Set the port. Returns true on success, false on failure (if there are
  947. * any invalid characters).
  948. *
  949. * @param string $port
  950. * @return bool
  951. */
  952. public function set_port($port)
  953. {
  954. if ($port === null)
  955. {
  956. $this->port = null;
  957. return true;
  958. }
  959. elseif (strspn($port, '0123456789') === strlen($port))
  960. {
  961. $this->port = (int) $port;
  962. $this->scheme_normalization();
  963. return true;
  964. }
  965. $this->port = null;
  966. return false;
  967. }
  968. /**
  969. * Set the ipath.
  970. *
  971. * @param string $ipath
  972. * @return bool
  973. */
  974. public function set_path($ipath, $clear_cache = false)
  975. {
  976. static $cache;
  977. if ($clear_cache)
  978. {
  979. $cache = null;
  980. return;
  981. }
  982. if (!$cache)
  983. {
  984. $cache = array();
  985. }
  986. $ipath = (string) $ipath;
  987. if (isset($cache[$ipath]))
  988. {
  989. $this->ipath = $cache[$ipath][(int) ($this->scheme !== null)];
  990. }
  991. else
  992. {
  993. $valid = $this->replace_invalid_with_pct_encoding($ipath, '!$&\'()*+,;=@:/');
  994. $removed = $this->remove_dot_segments($valid);
  995. $cache[$ipath] = array($valid, $removed);
  996. $this->ipath = ($this->scheme !== null) ? $removed : $valid;
  997. }
  998. $this->scheme_normalization();
  999. return true;
  1000. }
  1001. /**
  1002. * Set the iquery.
  1003. *
  1004. * @param string $iquery
  1005. * @return bool
  1006. */
  1007. public function set_query($iquery)
  1008. {
  1009. if ($iquery === null)
  1010. {
  1011. $this->iquery = null;
  1012. }
  1013. else
  1014. {
  1015. $this->iquery = $this->replace_invalid_with_pct_encoding($iquery, '!$&\'()*+,;=:@/?', true);
  1016. $this->scheme_normalization();
  1017. }
  1018. return true;
  1019. }
  1020. /**
  1021. * Set the ifragment.
  1022. *
  1023. * @param string $ifragment
  1024. * @return bool
  1025. */
  1026. public function set_fragment($ifragment)
  1027. {
  1028. if ($ifragment === null)
  1029. {
  1030. $this->ifragment = null;
  1031. }
  1032. else
  1033. {
  1034. $this->ifragment = $this->replace_invalid_with_pct_encoding($ifragment, '!$&\'()*+,;=:@/?');
  1035. $this->scheme_normalization();
  1036. }
  1037. return true;
  1038. }
  1039. /**
  1040. * Convert an IRI to a URI (or parts thereof)
  1041. *
  1042. * @return string
  1043. */
  1044. public function to_uri($string)
  1045. {
  1046. static $non_ascii;
  1047. if (!$non_ascii)
  1048. {
  1049. $non_ascii = implode('', range("\x80", "\xFF"));
  1050. }
  1051. $position = 0;
  1052. $strlen = strlen($string);
  1053. while (($position += strcspn($string, $non_ascii, $position)) < $strlen)
  1054. {
  1055. $string = substr_replace($string, sprintf('%%%02X', ord($string[$position])), $position, 1);
  1056. $position += 3;
  1057. $strlen += 2;
  1058. }
  1059. return $string;
  1060. }
  1061. /**
  1062. * Get the complete IRI
  1063. *
  1064. * @return string
  1065. */
  1066. public function get_iri()
  1067. {
  1068. if (!$this->is_valid())
  1069. {
  1070. return false;
  1071. }
  1072. $iri = '';
  1073. if ($this->scheme !== null)
  1074. {
  1075. $iri .= $this->scheme . ':';
  1076. }
  1077. if (($iauthority = $this->get_iauthority()) !== null)
  1078. {
  1079. $iri .= '//' . $iauthority;
  1080. }
  1081. if ($this->ipath !== '')
  1082. {
  1083. $iri .= $this->ipath;
  1084. }
  1085. elseif (!empty($this->normalization[$this->scheme]['ipath']) && $iauthority !== null && $iauthority !== '')
  1086. {
  1087. $iri .= $this->normalization[$this->scheme]['ipath'];
  1088. }
  1089. if ($this->iquery !== null)
  1090. {
  1091. $iri .= '?' . $this->iquery;
  1092. }
  1093. if ($this->ifragment !== null)
  1094. {
  1095. $iri .= '#' . $this->ifragment;
  1096. }
  1097. return $iri;
  1098. }
  1099. /**
  1100. * Get the complete URI
  1101. *
  1102. * @return string
  1103. */
  1104. public function get_uri()
  1105. {
  1106. return $this->to_uri($this->get_iri());
  1107. }
  1108. /**
  1109. * Get the complete iauthority
  1110. *
  1111. * @return string
  1112. */
  1113. protected function get_iauthority()
  1114. {
  1115. if ($this->iuserinfo !== null || $this->ihost !== null || $this->port !== null)
  1116. {
  1117. $iauthority = '';
  1118. if ($this->iuserinfo !== null)
  1119. {
  1120. $iauthority .= $this->iuserinfo . '@';
  1121. }
  1122. if ($this->ihost !== null)
  1123. {
  1124. $iauthority .= $this->ihost;
  1125. }
  1126. if ($this->port !== null && $this->port !== 0)
  1127. {
  1128. $iauthority .= ':' . $this->port;
  1129. }
  1130. return $iauthority;
  1131. }
  1132. return null;
  1133. }
  1134. /**
  1135. * Get the complete authority
  1136. *
  1137. * @return string
  1138. */
  1139. protected function get_authority()
  1140. {
  1141. $iauthority = $this->get_iauthority();
  1142. if (is_string($iauthority))
  1143. return $this->to_uri($iauthority);
  1144. return $iauthority;
  1145. }
  1146. }