urlmapper.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  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. if (array_key_exists($action, $this->reverse_dynamics)){
  153. $candidates = $this->reverse_dynamics[$action];
  154. foreach ($candidates as $candidate) {
  155. list($tryArgs, $format, $paramNames) = $candidate;
  156. foreach ($tryArgs as $key => $value) {
  157. if (!array_key_exists($key, $args) || $args[$key] != $value) {
  158. // next candidate
  159. continue 2;
  160. }
  161. }
  162. // success
  163. $toFormat = [];
  164. foreach ($paramNames as $name) {
  165. if (!array_key_exists($name, $args)) {
  166. // next candidate
  167. continue 2;
  168. }
  169. $toFormat[] = $args[$name];
  170. }
  171. $path = vsprintf($format, $toFormat);
  172. if (!empty($qstring)) {
  173. $formatted = http_build_query($qstring);
  174. $path .= '?' . $formatted;
  175. }
  176. return $path;
  177. }
  178. }
  179. if (array_key_exists($action, $this->reverse_statics)) {
  180. $candidates = $this->reverse_statics[$action];
  181. foreach ($candidates as $candidate) {
  182. list($tryArgs, $tryPath) = $candidate;
  183. foreach ($tryArgs as $key => $value) {
  184. if (!array_key_exists($key, $args) || $args[$key] != $value) {
  185. // next candidate
  186. continue 2;
  187. }
  188. }
  189. // success
  190. $path = $tryPath;
  191. if (!empty($qstring)) {
  192. $formatted = http_build_query($qstring);
  193. $path .= '?' . $formatted;
  194. }
  195. return $path;
  196. }
  197. }
  198. // failure; some reporting twiddles
  199. unset($args['action']);
  200. if (empty($args)) {
  201. throw new Exception(sprintf('No matches for action "%s"', $action));
  202. }
  203. $argstring = '';
  204. foreach ($args as $key => $value) {
  205. $argstring .= "$key=$value ";
  206. }
  207. throw new Exception(sprintf('No matches for action "%s" with arguments "%s"', $action, $argstring));
  208. }
  209. protected function getParamNames($path)
  210. {
  211. preg_match_all('/:(?P<name>\w+)/', $path, $match);
  212. return $match['name'];
  213. }
  214. public static function makeRegex($path, $paramPatterns)
  215. {
  216. $pr = new PatternReplacer($paramPatterns);
  217. $regex = preg_replace_callback('/:(\w+)/',
  218. [$pr, 'toPattern'],
  219. $path);
  220. $regex = '#^' . str_replace('#', '\#', $regex) . '$#';
  221. return $regex;
  222. }
  223. protected function makeFormat($path)
  224. {
  225. $format = preg_replace('/(:\w+)/', '%s', $path);
  226. return $format;
  227. }
  228. public function getPaths()
  229. {
  230. return array_unique($this->allpaths);
  231. }
  232. /**
  233. * Determines whether the route should or not be overwrited.
  234. * If ACCEPT header isn't set, false will be returned.
  235. *
  236. * @author Diogo Cordeiro <diogo@fc.up.pt>
  237. * @param array $headers accept-headers that should be set to
  238. * mark the route for overwrite. This array must be associative
  239. * and contain the headers in the value-set.
  240. * @return bool true if should overwrite, false otherwise
  241. */
  242. public static function should(array $headers): bool
  243. {
  244. if (!isset($_SERVER['HTTP_ACCEPT'])) {
  245. return false;
  246. }
  247. $acceptHeader = new AcceptHeader($_SERVER['HTTP_ACCEPT']);
  248. foreach ($acceptHeader as $ah) {
  249. if (isset($headers[$ah['raw']])) {
  250. return true;
  251. }
  252. }
  253. return false;
  254. }
  255. }
  256. class PatternReplacer
  257. {
  258. private $patterns;
  259. public function __construct($patterns)
  260. {
  261. $this->patterns = $patterns;
  262. }
  263. public function toPattern($matches)
  264. {
  265. // trim out the :
  266. $name = $matches[1];
  267. if (array_key_exists($name, $this->patterns)) {
  268. $pattern = $this->patterns[$name];
  269. } else {
  270. // ???
  271. $pattern = '\w+';
  272. }
  273. return '(?P<'.$name.'>'.$pattern.')';
  274. }
  275. }