urlmapper.php 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  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_dynamics = [];
  57. protected $reverse_statics = [];
  58. protected $allpaths = [];
  59. /**
  60. * Route creation.
  61. * $acceptHeaders should be set to true when, for whatever reason,
  62. * a path is being re-connected. The $headers list is still optional,
  63. * in this case, given that being empty means "accept everything".
  64. *
  65. * @author Evan Prodromou <evan@status.net>
  66. * @author Bruno Casteleiro <brunoccast@fc.up.pt>
  67. * @param string $path route path
  68. * @param array $args route action and, if needed, action settings
  69. * @param array $paramPatterns regex patterns for path's parameters
  70. * @param bool $acceptHeaders whether a path is being re-connected
  71. * @param array $headers headers that should be set for route creation
  72. * @throws Exception If can't connect
  73. * @return void
  74. */
  75. public function connect(string $path, array $args, array $paramPatterns = [], bool $acceptHeaders = false, array $headers = [])
  76. {
  77. if (!array_key_exists(self::ACTION, $args)) {
  78. throw new Exception(sprintf("Can't connect %s; path has no action.", $path));
  79. }
  80. $should = true;
  81. if ($acceptHeaders) {
  82. // even if it shouldn't be used as a route, we still want
  83. // to store some information to allow common_local_url
  84. // to generate urls
  85. $should = empty($headers) || self::should($headers);
  86. }
  87. $this->allpaths[] = $path;
  88. $action = $args[self::ACTION];
  89. $paramNames = $this->getParamNames($path);
  90. if (empty($paramNames)) {
  91. $this->statics[$path] = $args;
  92. if (array_key_exists($action, $this->reverse_statics)) {
  93. $this->reverse_statics[$action][] = [$args, $path];
  94. } else {
  95. $this->reverse_statics[$action] = [[$args, $path]];
  96. }
  97. } else {
  98. // fix for the code that still make improper use of this function's params
  99. foreach ($paramNames as $name) {
  100. if (!array_key_exists($name, $paramPatterns) &&
  101. array_key_exists($name, $args)) {
  102. $paramPatterns[$name] = $args[$name];
  103. unset($args[$name]);
  104. }
  105. }
  106. // $variables is used for path matching, so we can't store invalid routes
  107. if ($should) {
  108. $regex = self::makeRegex($path, $paramPatterns);
  109. if (isset($this->variables[$regex]) || !$acceptHeaders) {
  110. $this->variables[$regex] = [$args, $paramNames];
  111. } else {
  112. // URLs that differ only in the attribute names will generate
  113. // different regexes, so in order to avoid the wrong one (oldest)
  114. // to be matched first, fresh regexes are stored at the front
  115. $this->variables = [$regex => [$args, $paramNames]] + $this->variables;
  116. }
  117. }
  118. $format = $this->makeFormat($path);
  119. if (array_key_exists($action, $this->reverse_dynamics)) {
  120. $this->reverse_dynamics[$action][] = [$args, $format, $paramNames];
  121. } else {
  122. $this->reverse_dynamics[$action] = [[$args, $format, $paramNames]];
  123. }
  124. }
  125. }
  126. public function match($path)
  127. {
  128. if (array_key_exists($path, $this->statics)) {
  129. return $this->statics[$path];
  130. }
  131. foreach ($this->variables as $regex => $pattern) {
  132. list($args, $paramNames) = $pattern;
  133. if (preg_match($regex, $path, $match)) {
  134. $results = $args;
  135. foreach ($paramNames as $name) {
  136. $results[$name] = $match[$name];
  137. }
  138. return $results;
  139. }
  140. }
  141. throw new NoRouteMapException($path);
  142. }
  143. public function generate($args, $qstring, $fragment)
  144. {
  145. if (!array_key_exists(self::ACTION, $args)) {
  146. throw new Exception("Every path needs an action.");
  147. }
  148. $action = $args[self::ACTION];
  149. if (!array_key_exists($action, $this->reverse_dynamics) && !array_key_exists($action, $this->reverse_statics)) {
  150. throw new Exception(sprintf('No candidate paths for action "%s"', $action));
  151. }
  152. $candidates = $this->reverse_dynamics[$action];
  153. foreach ($candidates as $candidate) {
  154. list($tryArgs, $format, $paramNames) = $candidate;
  155. foreach ($tryArgs as $key => $value) {
  156. if (!array_key_exists($key, $args) || $args[$key] != $value) {
  157. // next candidate
  158. continue 2;
  159. }
  160. }
  161. // success
  162. $toFormat = [];
  163. foreach ($paramNames as $name) {
  164. if (!array_key_exists($name, $args)) {
  165. // next candidate
  166. continue 2;
  167. }
  168. $toFormat[] = $args[$name];
  169. }
  170. $path = vsprintf($format, $toFormat);
  171. if (!empty($qstring)) {
  172. $formatted = http_build_query($qstring);
  173. $path .= '?' . $formatted;
  174. }
  175. return $path;
  176. }
  177. $candidates = $this->reverse_statics[$action];
  178. foreach ($candidates as $candidate) {
  179. list($tryArgs, $tryPath) = $candidate;
  180. foreach ($tryArgs as $key => $value) {
  181. if (!array_key_exists($key, $args) || $args[$key] != $value) {
  182. // next candidate
  183. continue 2;
  184. }
  185. }
  186. // success
  187. $path = $tryPath;
  188. if (!empty($qstring)) {
  189. $formatted = http_build_query($qstring);
  190. $path .= '?' . $formatted;
  191. }
  192. return $path;
  193. }
  194. // failure; some reporting twiddles
  195. unset($args['action']);
  196. if (empty($args)) {
  197. throw new Exception(sprintf('No matches for action "%s"', $action));
  198. }
  199. $argstring = '';
  200. foreach ($args as $key => $value) {
  201. $argstring .= "$key=$value ";
  202. }
  203. throw new Exception(sprintf('No matches for action "%s" with arguments "%s"', $action, $argstring));
  204. }
  205. protected function getParamNames($path)
  206. {
  207. preg_match_all('/:(?P<name>\w+)/', $path, $match);
  208. return $match['name'];
  209. }
  210. public static function makeRegex($path, $paramPatterns)
  211. {
  212. $pr = new PatternReplacer($paramPatterns);
  213. $regex = preg_replace_callback('/:(\w+)/',
  214. [$pr, 'toPattern'],
  215. $path);
  216. $regex = '#^' . str_replace('#', '\#', $regex) . '$#';
  217. return $regex;
  218. }
  219. protected function makeFormat($path)
  220. {
  221. $format = preg_replace('/(:\w+)/', '%s', $path);
  222. return $format;
  223. }
  224. public function getPaths()
  225. {
  226. return array_unique($this->allpaths);
  227. }
  228. /**
  229. * Determines whether the route should or not be overwrited.
  230. * If ACCEPT header isn't set, false will be returned.
  231. *
  232. * @author Diogo Cordeiro <diogo@fc.up.pt>
  233. * @param array $headers accept-headers that should be set to
  234. * mark the route for overwrite. This array must be associative
  235. * and contain the headers in the value-set.
  236. * @return bool true if should overwrite, false otherwise
  237. */
  238. public static function should(array $headers): bool
  239. {
  240. if (!isset($_SERVER['HTTP_ACCEPT'])) {
  241. return false;
  242. }
  243. $acceptHeader = new AcceptHeader($_SERVER['HTTP_ACCEPT']);
  244. foreach ($acceptHeader as $ah) {
  245. if (isset($headers[$ah['raw']])) {
  246. return true;
  247. }
  248. }
  249. return false;
  250. }
  251. }
  252. class PatternReplacer
  253. {
  254. private $patterns;
  255. public function __construct($patterns)
  256. {
  257. $this->patterns = $patterns;
  258. }
  259. public function toPattern($matches)
  260. {
  261. // trim out the :
  262. $name = $matches[1];
  263. if (array_key_exists($name, $this->patterns)) {
  264. $pattern = $this->patterns[$name];
  265. } else {
  266. // ???
  267. $pattern = '\w+';
  268. }
  269. return '(?P<'.$name.'>'.$pattern.')';
  270. }
  271. }