FU r106752: added b/c code to FSRepo to make things easy for extensions (like Confirm...
[lhc/web/wiklou.git] / includes / PathRouter.php
1 <?php
2 /**
3 * PathRouter class.
4 * This class can take patterns such as /wiki/$1 and use them to
5 * parse query parameters out of REQUEST_URI paths.
6 *
7 * $router->add( "/wiki/$1" );
8 * - Matches /wiki/Foo style urls and extracts the title
9 * $router->add( array( 'edit' => "/edit/$1" ), array( 'action' => '$key' ) );
10 * - Matches /edit/Foo style urls and sets action=edit
11 * $router->add( '/$2/$1',
12 * array( 'variant' => '$2' ),
13 * array( '$2' => array( 'zh-hant', 'zh-hans' )
14 * );
15 * - Matches /zh-hant/Foo or /zh-hans/Foo
16 * $router->addStrict( "/foo/Bar", array( 'title' => 'Baz' ) );
17 * - Matches /foo/Bar explicitly and uses "Baz" as the title
18 * $router->add( '/help/$1', array( 'title' => 'Help:$1' ) );
19 * - Matches /help/Foo with "Help:Foo" as the title
20 * $router->add( '/$1', array( 'foo' => array( 'value' => 'bar$2' ) );
21 * - Matches /Foo and sets 'foo' to 'bar$2' without $2 being replaced
22 * $router->add( '/$1', array( 'data:foo' => 'bar' ), array( 'callback' => 'functionname' ) );
23 * - Matches /Foo, adds the key 'foo' with the value 'bar' to the data array
24 * and calls functionname( &$matches, $data );
25 *
26 * Path patterns:
27 * - Paths may contain $# patterns such as $1, $2, etc...
28 * - $1 will match 0 or more while the rest will match 1 or more
29 * - Unless you use addStrict "/wiki" and "/wiki/" will be expanded to "/wiki/$1"
30 *
31 * Params:
32 * - In a pattern $1, $2, etc... will be replaced with the relevant contents
33 * - If you used a keyed array as a path pattern, $key will be replaced with
34 * the relevant contents
35 * - The default behavior is equivalent to `array( 'title' => '$1' )`,
36 * if you don't want the title parameter you can explicitly use `array( 'title' => false )`
37 * - You can specify a value that won't have replacements in it
38 * using `'foo' => array( 'value' => 'bar' );`
39 *
40 * Options:
41 * - The option keys $1, $2, etc... can be specified to restrict the possible values
42 * of that variable. A string can be used for a single value, or an array for multiple.
43 * - When the option key 'strict' is set (Using addStrict is simpler than doing this directly)
44 * the path won't have $1 implicitly added to it.
45 * - The option key 'callback' can specify a callback that will be run when a path is matched.
46 * The callback will have the arguments ( &$matches, $data ) and the matches array can
47 * be modified.
48 *
49 * @since 1.19
50 * @author Daniel Friesen
51 */
52 class PathRouter {
53
54 /**
55 * Protected helper to do the actual bulk work of adding a single pattern.
56 * This is in a separate method so that add() can handle the difference between
57 * a single string $path and an array() $path that contains multiple path
58 * patterns each with an associated $key to pass on.
59 */
60 protected function doAdd( $path, $params, $options, $key = null ) {
61 // Make sure all paths start with a /
62 if ( $path[0] !== '/' ) {
63 $path = '/' . $path;
64 }
65
66 if ( !isset( $options['strict'] ) || !$options['strict'] ) {
67 // Unless this is a strict path make sure that the path has a $1
68 if ( strpos( $path, '$1' ) === false ) {
69 if ( substr( $path, -1 ) !== '/' ) {
70 $path .= '/';
71 }
72 $path .= '$1';
73 }
74 }
75
76 // If 'title' is not specified and our path pattern contains a $1
77 // Add a default 'title' => '$1' rule to the parameters.
78 if ( !isset( $params['title'] ) && strpos( $path, '$1' ) !== false ) {
79 $params['title'] = '$1';
80 }
81 // If the user explicitly marked 'title' as false then omit it from the matches
82 if ( isset( $params['title'] ) && $params['title'] === false ) {
83 unset( $params['title'] );
84 }
85
86 // Loop over our parameters and convert basic key => string
87 // patterns into fully descriptive array form
88 foreach ( $params as $paramName => $paramData ) {
89 if ( is_string( $paramData ) ) {
90 if ( preg_match( '/\$(\d+|key)/u', $paramData ) ) {
91 $paramArrKey = 'pattern';
92 } else {
93 // If there's no replacement use a value instead
94 // of a pattern for a little more efficiency
95 $paramArrKey = 'value';
96 }
97 $params[$paramName] = array(
98 $paramArrKey => $paramData
99 );
100 }
101 }
102
103 // Loop over our options and convert any single value $# restrictions
104 // into an array so we only have to do in_array tests.
105 foreach ( $options as $optionName => $optionData ) {
106 if ( preg_match( '/^\$\d+$/u', $optionName ) ) {
107 if ( !is_array( $optionData ) ) {
108 $options[$optionName] = array( $optionData );
109 }
110 }
111 }
112
113 $pattern = (object)array(
114 'path' => $path,
115 'params' => $params,
116 'options' => $options,
117 'key' => $key,
118 );
119 $pattern->weight = self::makeWeight( $pattern );
120 $this->patterns[] = $pattern;
121 }
122
123 /**
124 * Add a new path pattern to the path router
125 *
126 * @param $path The path pattern to add
127 * @param $params The params for this path pattern
128 * @param $options The options for this path pattern
129 */
130 public function add( $path, $params = array(), $options = array() ) {
131 if ( is_array( $path ) ) {
132 foreach ( $path as $key => $onePath ) {
133 $this->doAdd( $onePath, $params, $options, $key );
134 }
135 } else {
136 $this->doAdd( $path, $params, $options );
137 }
138 }
139
140 /**
141 * Add a new path pattern to the path router with the strict option on
142 * @see self::add
143 */
144 public function addStrict( $path, $params = array(), $options = array() ) {
145 $options['strict'] = true;
146 $this->add( $path, $params, $options );
147 }
148
149 /**
150 * Protected helper to re-sort our patterns so that the most specific
151 * (most heavily weighted) patterns are at the start of the array.
152 */
153 protected function sortByWeight() {
154 $weights = array();
155 foreach( $this->patterns as $key => $pattern ) {
156 $weights[$key] = $pattern->weight;
157 }
158 array_multisort( $weights, SORT_DESC, SORT_NUMERIC, $this->patterns );
159 }
160
161 protected static function makeWeight( $pattern ) {
162 # Start with a weight of 0
163 $weight = 0;
164
165 // Explode the path to work with
166 $path = explode( '/', $pattern->path );
167
168 # For each level of the path
169 foreach( $path as $piece ) {
170 if ( preg_match( '/^\$(\d+|key)$/u', $piece ) ) {
171 # For a piece that is only a $1 variable add 1 points of weight
172 $weight += 1;
173 } elseif ( preg_match( '/\$(\d+|key)/u', $piece ) ) {
174 # For a piece that simply contains a $1 variable add 2 points of weight
175 $weight += 2;
176 } else {
177 # For a solid piece add a full 3 points of weight
178 $weight += 3;
179 }
180 }
181
182 foreach ( $pattern->options as $key => $option ) {
183 if ( preg_match( '/^\$\d+$/u', $key ) ) {
184 # Add 0.5 for restrictions to values
185 # This way given two separate "/$2/$1" patterns the
186 # one with a limited set of $2 values will dominate
187 # the one that'll match more loosely
188 $weight += 0.5;
189 }
190 }
191
192 return $weight;
193 }
194
195 /**
196 * Parse a path and return the query matches for the path
197 *
198 * @param $path The path to parse
199 * @return Array The array of matches for the path
200 */
201 public function parse( $path ) {
202 // Make sure our patterns are sorted by weight so the most specific
203 // matches are tested first
204 $this->sortByWeight();
205
206 $matches = null;
207
208 foreach ( $this->patterns as $pattern ) {
209 $matches = self::extractTitle( $path, $pattern );
210 if ( !is_null( $matches ) ) {
211 break;
212 }
213 }
214
215 // We know the difference between null (no matches) and
216 // array() (a match with no data) but our WebRequest caller
217 // expects array() even when we have no matches so return
218 // a array() when we have null
219 return is_null( $matches ) ? array() : $matches;
220 }
221
222 protected static function extractTitle( $path, $pattern ) {
223 // Convert the path pattern into a regexp we can match with
224 $regexp = preg_quote( $pattern->path, '#' );
225 // .* for the $1
226 $regexp = preg_replace( '#\\\\\$1#u', '(?P<par1>.*)', $regexp );
227 // .+ for the rest of the parameter numbers
228 $regexp = preg_replace( '#\\\\\$(\d+)#u', '(?P<par$1>.+?)', $regexp );
229 $regexp = "#^{$regexp}$#";
230
231 $matches = array();
232 $data = array();
233
234 // Try to match the path we were asked to parse with our regexp
235 if ( preg_match( $regexp, $path, $m ) ) {
236 // Ensure that any $# restriction we have set in our {$option}s
237 // matches properly here.
238 foreach ( $pattern->options as $key => $option ) {
239 if ( preg_match( '/^\$\d+$/u', $key ) ) {
240 $n = intval( substr( $key, 1 ) );
241 $value = rawurldecode( $m["par{$n}"] );
242 if ( !in_array( $value, $option ) ) {
243 // If any restriction does not match return null
244 // to signify that this rule did not match.
245 return null;
246 }
247 }
248 }
249
250 // Give our $data array a copy of every $# that was matched
251 foreach ( $m as $matchKey => $matchValue ) {
252 if ( preg_match( '/^par\d+$/u', $matchKey ) ) {
253 $n = intval( substr( $matchKey, 3 ) );
254 $data['$'.$n] = rawurldecode( $matchValue );
255 }
256 }
257 // If present give our $data array a $key as well
258 if ( isset( $pattern->key ) ) {
259 $data['$key'] = $pattern->key;
260 }
261
262 // Go through our parameters for this match and add data to our matches and data arrays
263 foreach ( $pattern->params as $paramName => $paramData ) {
264 $value = null;
265 // Differentiate data: from normal parameters and keep the correct
266 // array key around (ie: foo for data:foo)
267 if ( preg_match( '/^data:/u', $paramName ) ) {
268 $isData = true;
269 $key = substr( $paramName, 5 );
270 } else {
271 $isData = false;
272 $key = $paramName;
273 }
274
275 if ( isset( $paramData['value'] ) ) {
276 // For basic values just set the raw data as the value
277 $value = $paramData['value'];
278 } elseif ( isset( $paramData['pattern'] ) ) {
279 // For patterns we have to make value replacements on the string
280 $value = $paramData['pattern'];
281 // For each $# match replace any $# within the value
282 foreach ( $m as $matchKey => $matchValue ) {
283 if ( preg_match( '/^par\d+$/u', $matchKey ) ) {
284 $n = intval( substr( $matchKey, 3 ) );
285 $value = str_replace( '$' . $n, rawurldecode( $matchValue ), $value );
286 }
287 }
288 // If a key was set replace any $key within the value
289 if ( isset( $pattern->key ) ) {
290 $value = str_replace( '$key', $pattern->key, $value );
291 }
292 if ( preg_match( '/\$(\d+|key)/u', $value ) ) {
293 // Still contains $# or $key patterns after replacement
294 // Seams like we don't have all the data, abort
295 return null;
296 }
297 }
298
299 // Send things that start with data: to $data, the rest to $matches
300 if ( $isData ) {
301 $data[$key] = $value;
302 } else {
303 $matches[$key] = $value;
304 }
305 }
306
307 // If this match includes a callback, execute it
308 if ( isset( $pattern->options['callback'] ) ) {
309 call_user_func_array( $pattern->options['callback'], array( &$matches, $data ) );
310 }
311 } else {
312 // Our regexp didn't match, return null to signify no match.
313 return null;
314 }
315 // Fall through, everything went ok, return our matches array
316 return $matches;
317 }
318
319 }