urlmapper.php 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  1. <?php
  2. /**
  3. * StatusNet - the distributed open-source microblogging tool
  4. * Copyright (C) 2011, StatusNet, Inc.
  5. *
  6. * URL mapper
  7. *
  8. * PHP version 5
  9. *
  10. * This program is free software: you can redistribute it and/or modify
  11. * it under the terms of the GNU Affero General Public License as published by
  12. * the Free Software Foundation, either version 3 of the License, or
  13. * (at your option) any later version.
  14. *
  15. * This program is distributed in the hope that it will be useful,
  16. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. * GNU Affero General Public License for more details.
  19. *
  20. * You should have received a copy of the GNU Affero General Public License
  21. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. *
  23. * @category URL
  24. * @package StatusNet
  25. * @author Evan Prodromou <evan@status.net>
  26. * @copyright 2011 StatusNet, Inc.
  27. * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPL 3.0
  28. * @link http://status.net/
  29. */
  30. if (!defined('STATUSNET')) {
  31. // This check helps protect against security problems;
  32. // your code file can't be executed directly from the web.
  33. exit(1);
  34. }
  35. /**
  36. * URL mapper
  37. *
  38. * Converts a path into a set of parameters, and vice versa
  39. *
  40. * We used to use Net_URL_Mapper, so there's a wrapper class at Router, q.v.
  41. *
  42. * NUM's vagaries are the main reason we have weirdnesses here.
  43. *
  44. * @category URL
  45. * @package StatusNet
  46. * @author Evan Prodromou <evan@status.net>
  47. * @copyright 2011 StatusNet, Inc.
  48. * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPL 3.0
  49. * @link http://status.net/
  50. */
  51. class URLMapper
  52. {
  53. const ACTION = 'action';
  54. protected $statics = [];
  55. protected $variables = [];
  56. protected $reverse = [];
  57. protected $allpaths = [];
  58. /**
  59. * Route creation.
  60. * $acceptHeaders should be set to true when, for whatever reason,
  61. * a path is being re-connected. The $headers list is still optional,
  62. * in this case, given that being empty means "accept everything".
  63. *
  64. * @author Evan Prodromou <evan@status.net>
  65. * @author Bruno Casteleiro <brunoccast@fc.up.pt>
  66. * @param string $path route path
  67. * @param array $args route action and, if needed, action settings
  68. * @param array $paramPatterns regex patterns for path's parameters
  69. * @param bool $acceptHeaders whether a path is being re-connected
  70. * @param array $headers headers that should be set for route creation
  71. * @return void
  72. */
  73. public function connect(string $path, array $args, array $paramPatterns = [], bool $acceptHeaders = false, array $headers = [])
  74. {
  75. if (!array_key_exists(self::ACTION, $args)) {
  76. throw new Exception(sprintf("Can't connect %s; path has no action.", $path));
  77. }
  78. $should = true;
  79. if ($acceptHeaders) {
  80. // even if it shouldn't be used as a route, we still want
  81. // to store some information to allow common_local_url
  82. // to generate urls
  83. $should = empty($headers) || self::should($headers);
  84. }
  85. $this->allpaths[] = $path;
  86. $action = $args[self::ACTION];
  87. $paramNames = $this->getParamNames($path);
  88. if (empty($paramNames)) {
  89. $this->statics[$path] = $args;
  90. if (array_key_exists($action, $this->reverse)) {
  91. $this->reverse[$action][] = [$args, $path];
  92. } else {
  93. $this->reverse[$action] = [[$args, $path]];
  94. }
  95. } else {
  96. // fix for the code that still make improper use of this function's params
  97. foreach ($paramNames as $name) {
  98. if (!array_key_exists($name, $paramPatterns) &&
  99. array_key_exists($name, $args)) {
  100. $paramPatterns[$name] = $args[$name];
  101. unset($args[$name]);
  102. }
  103. }
  104. // $variables is used for path matching, so we can't store invalid routes
  105. if ($should) {
  106. $regex = self::makeRegex($path, $paramPatterns);
  107. if (isset($this->variables[$regex]) || !$acceptHeaders) {
  108. $this->variables[$regex] = [$args, $paramNames];
  109. } else {
  110. // URLs that differ only in the attribute names will generate
  111. // different regexes, so in order to avoid the wrong one (oldest)
  112. // to be matched first, fresh regexes are stored at the front
  113. $this->variables = [$regex => [$args, $paramNames]] + $this->variables;
  114. }
  115. }
  116. $format = $this->makeFormat($path);
  117. if (array_key_exists($action, $this->reverse)) {
  118. $this->reverse[$action][] = [$args, $format, $paramNames];
  119. } else {
  120. $this->reverse[$action] = [[$args, $format, $paramNames]];
  121. }
  122. }
  123. }
  124. public function match($path)
  125. {
  126. if (array_key_exists($path, $this->statics)) {
  127. return $this->statics[$path];
  128. }
  129. foreach ($this->variables as $regex => $pattern) {
  130. list($args, $paramNames) = $pattern;
  131. if (preg_match($regex, $path, $match)) {
  132. $results = $args;
  133. foreach ($paramNames as $name) {
  134. $results[$name] = $match[$name];
  135. }
  136. return $results;
  137. }
  138. }
  139. throw new NoRouteMapException($path);
  140. }
  141. public function generate($args, $qstring, $fragment)
  142. {
  143. if (!array_key_exists(self::ACTION, $args)) {
  144. throw new Exception("Every path needs an action.");
  145. }
  146. $action = $args[self::ACTION];
  147. if (!array_key_exists($action, $this->reverse)) {
  148. throw new Exception(sprintf('No candidate paths for action "%s"', $action));
  149. }
  150. $candidates = $this->reverse[$action];
  151. foreach ($candidates as $candidate) {
  152. if (count($candidate) == 2) { // static
  153. list($tryArgs, $tryPath) = $candidate;
  154. foreach ($tryArgs as $key => $value) {
  155. if (!array_key_exists($key, $args) || $args[$key] != $value) {
  156. // next candidate
  157. continue 2;
  158. }
  159. }
  160. // success
  161. $path = $tryPath;
  162. } else {
  163. list($tryArgs, $format, $paramNames) = $candidate;
  164. foreach ($tryArgs as $key => $value) {
  165. if (!array_key_exists($key, $args) || $args[$key] != $value) {
  166. // next candidate
  167. continue 2;
  168. }
  169. }
  170. // success
  171. $toFormat = [];
  172. foreach ($paramNames as $name) {
  173. if (!array_key_exists($name, $args)) {
  174. // next candidate
  175. continue 2;
  176. }
  177. $toFormat[] = $args[$name];
  178. }
  179. $path = vsprintf($format, $toFormat);
  180. }
  181. if (!empty($qstring)) {
  182. $formatted = http_build_query($qstring);
  183. $path .= '?' . $formatted;
  184. }
  185. return $path;
  186. }
  187. // failure; some reporting twiddles
  188. unset($args['action']);
  189. if (empty($args)) {
  190. throw new Exception(sprintf('No matches for action "%s"', $action));
  191. }
  192. $argstring = '';
  193. foreach ($args as $key => $value) {
  194. $argstring .= "$key=$value ";
  195. }
  196. throw new Exception(sprintf('No matches for action "%s" with arguments "%s"', $action, $argstring));
  197. }
  198. protected function getParamNames($path)
  199. {
  200. preg_match_all('/:(?P<name>\w+)/', $path, $match);
  201. return $match['name'];
  202. }
  203. public static function makeRegex($path, $paramPatterns)
  204. {
  205. $pr = new PatternReplacer($paramPatterns);
  206. $regex = preg_replace_callback('/:(\w+)/',
  207. [$pr, 'toPattern'],
  208. $path);
  209. $regex = '#^' . str_replace('#', '\#', $regex) . '$#';
  210. return $regex;
  211. }
  212. protected function makeFormat($path)
  213. {
  214. $format = preg_replace('/(:\w+)/', '%s', $path);
  215. return $format;
  216. }
  217. public function getPaths()
  218. {
  219. return array_unique($this->allpaths);
  220. }
  221. /**
  222. * Determines whether the route should or not be overwrited.
  223. * If ACCEPT header isn't set, false will be returned.
  224. *
  225. * @author Diogo Cordeiro <diogo@fc.up.pt>
  226. * @param array $headers accept-headers that should be set to
  227. * mark the route for overwrite. This array must be associative
  228. * and contain the headers in the value-set.
  229. * @return bool true if should overwrite, false otherwise
  230. */
  231. public static function should(array $headers): bool
  232. {
  233. if (!isset($_SERVER['HTTP_ACCEPT'])) {
  234. return false;
  235. }
  236. $acceptHeader = new AcceptHeader($_SERVER['HTTP_ACCEPT']);
  237. foreach ($acceptHeader as $ah) {
  238. if (isset($headers[$ah['raw']])) {
  239. return true;
  240. }
  241. }
  242. return false;
  243. }
  244. }
  245. class PatternReplacer
  246. {
  247. private $patterns;
  248. public function __construct($patterns)
  249. {
  250. $this->patterns = $patterns;
  251. }
  252. public function toPattern($matches)
  253. {
  254. // trim out the :
  255. $name = $matches[1];
  256. if (array_key_exists($name, $this->patterns)) {
  257. $pattern = $this->patterns[$name];
  258. } else {
  259. // ???
  260. $pattern = '\w+';
  261. }
  262. return '(?P<'.$name.'>'.$pattern.')';
  263. }
  264. }