截流自动化的商城平台
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

IRI.php 28KB

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