MediaWiki  REL1_31
PathRouter.php
Go to the documentation of this file.
1 <?php
73 class PathRouter {
74 
78  private $patterns = [];
79 
90  protected function doAdd( $path, $params, $options, $key = null ) {
91  // Make sure all paths start with a /
92  if ( $path[0] !== '/' ) {
93  $path = '/' . $path;
94  }
95 
96  if ( !isset( $options['strict'] ) || !$options['strict'] ) {
97  // Unless this is a strict path make sure that the path has a $1
98  if ( strpos( $path, '$1' ) === false ) {
99  if ( substr( $path, -1 ) !== '/' ) {
100  $path .= '/';
101  }
102  $path .= '$1';
103  }
104  }
105 
106  // If 'title' is not specified and our path pattern contains a $1
107  // Add a default 'title' => '$1' rule to the parameters.
108  if ( !isset( $params['title'] ) && strpos( $path, '$1' ) !== false ) {
109  $params['title'] = '$1';
110  }
111  // If the user explicitly marked 'title' as false then omit it from the matches
112  if ( isset( $params['title'] ) && $params['title'] === false ) {
113  unset( $params['title'] );
114  }
115 
116  // Loop over our parameters and convert basic key => string
117  // patterns into fully descriptive array form
118  foreach ( $params as $paramName => $paramData ) {
119  if ( is_string( $paramData ) ) {
120  if ( preg_match( '/\$(\d+|key)/u', $paramData ) ) {
121  $paramArrKey = 'pattern';
122  } else {
123  // If there's no replacement use a value instead
124  // of a pattern for a little more efficiency
125  $paramArrKey = 'value';
126  }
127  $params[$paramName] = [
128  $paramArrKey => $paramData
129  ];
130  }
131  }
132 
133  // Loop over our options and convert any single value $# restrictions
134  // into an array so we only have to do in_array tests.
135  foreach ( $options as $optionName => $optionData ) {
136  if ( preg_match( '/^\$\d+$/u', $optionName ) ) {
137  if ( !is_array( $optionData ) ) {
138  $options[$optionName] = [ $optionData ];
139  }
140  }
141  }
142 
143  $pattern = (object)[
144  'path' => $path,
145  'params' => $params,
146  'options' => $options,
147  'key' => $key,
148  ];
149  $pattern->weight = self::makeWeight( $pattern );
150  $this->patterns[] = $pattern;
151  }
152 
160  public function add( $path, $params = [], $options = [] ) {
161  if ( is_array( $path ) ) {
162  foreach ( $path as $key => $onePath ) {
163  $this->doAdd( $onePath, $params, $options, $key );
164  }
165  } else {
166  $this->doAdd( $path, $params, $options );
167  }
168  }
169 
177  public function addStrict( $path, $params = [], $options = [] ) {
178  $options['strict'] = true;
179  $this->add( $path, $params, $options );
180  }
181 
186  protected function sortByWeight() {
187  $weights = [];
188  foreach ( $this->patterns as $key => $pattern ) {
189  $weights[$key] = $pattern->weight;
190  }
191  array_multisort( $weights, SORT_DESC, SORT_NUMERIC, $this->patterns );
192  }
193 
198  protected static function makeWeight( $pattern ) {
199  # Start with a weight of 0
200  $weight = 0;
201 
202  // Explode the path to work with
203  $path = explode( '/', $pattern->path );
204 
205  # For each level of the path
206  foreach ( $path as $piece ) {
207  if ( preg_match( '/^\$(\d+|key)$/u', $piece ) ) {
208  # For a piece that is only a $1 variable add 1 points of weight
209  $weight += 1;
210  } elseif ( preg_match( '/\$(\d+|key)/u', $piece ) ) {
211  # For a piece that simply contains a $1 variable add 2 points of weight
212  $weight += 2;
213  } else {
214  # For a solid piece add a full 3 points of weight
215  $weight += 3;
216  }
217  }
218 
219  foreach ( $pattern->options as $key => $option ) {
220  if ( preg_match( '/^\$\d+$/u', $key ) ) {
221  # Add 0.5 for restrictions to values
222  # This way given two separate "/$2/$1" patterns the
223  # one with a limited set of $2 values will dominate
224  # the one that'll match more loosely
225  $weight += 0.5;
226  }
227  }
228 
229  return $weight;
230  }
231 
238  public function parse( $path ) {
239  // Make sure our patterns are sorted by weight so the most specific
240  // matches are tested first
241  $this->sortByWeight();
242 
243  $matches = null;
244 
245  foreach ( $this->patterns as $pattern ) {
246  $matches = self::extractTitle( $path, $pattern );
247  if ( !is_null( $matches ) ) {
248  break;
249  }
250  }
251 
252  // We know the difference between null (no matches) and
253  // array() (a match with no data) but our WebRequest caller
254  // expects array() even when we have no matches so return
255  // a array() when we have null
256  return is_null( $matches ) ? [] : $matches;
257  }
258 
264  protected static function extractTitle( $path, $pattern ) {
265  // Convert the path pattern into a regexp we can match with
266  $regexp = preg_quote( $pattern->path, '#' );
267  // .* for the $1
268  $regexp = preg_replace( '#\\\\\$1#u', '(?P<par1>.*)', $regexp );
269  // .+ for the rest of the parameter numbers
270  $regexp = preg_replace( '#\\\\\$(\d+)#u', '(?P<par$1>.+?)', $regexp );
271  $regexp = "#^{$regexp}$#";
272 
273  $matches = [];
274  $data = [];
275 
276  // Try to match the path we were asked to parse with our regexp
277  if ( preg_match( $regexp, $path, $m ) ) {
278  // Ensure that any $# restriction we have set in our {$option}s
279  // matches properly here.
280  foreach ( $pattern->options as $key => $option ) {
281  if ( preg_match( '/^\$\d+$/u', $key ) ) {
282  $n = intval( substr( $key, 1 ) );
283  $value = rawurldecode( $m["par{$n}"] );
284  if ( !in_array( $value, $option ) ) {
285  // If any restriction does not match return null
286  // to signify that this rule did not match.
287  return null;
288  }
289  }
290  }
291 
292  // Give our $data array a copy of every $# that was matched
293  foreach ( $m as $matchKey => $matchValue ) {
294  if ( preg_match( '/^par\d+$/u', $matchKey ) ) {
295  $n = intval( substr( $matchKey, 3 ) );
296  $data['$' . $n] = rawurldecode( $matchValue );
297  }
298  }
299  // If present give our $data array a $key as well
300  if ( isset( $pattern->key ) ) {
301  $data['$key'] = $pattern->key;
302  }
303 
304  // Go through our parameters for this match and add data to our matches and data arrays
305  foreach ( $pattern->params as $paramName => $paramData ) {
306  $value = null;
307  // Differentiate data: from normal parameters and keep the correct
308  // array key around (ie: foo for data:foo)
309  if ( preg_match( '/^data:/u', $paramName ) ) {
310  $isData = true;
311  $key = substr( $paramName, 5 );
312  } else {
313  $isData = false;
314  $key = $paramName;
315  }
316 
317  if ( isset( $paramData['value'] ) ) {
318  // For basic values just set the raw data as the value
319  $value = $paramData['value'];
320  } elseif ( isset( $paramData['pattern'] ) ) {
321  // For patterns we have to make value replacements on the string
322  $value = $paramData['pattern'];
323  $replacer = new PathRouterPatternReplacer;
324  $replacer->params = $m;
325  if ( isset( $pattern->key ) ) {
326  $replacer->key = $pattern->key;
327  }
328  $value = $replacer->replace( $value );
329  if ( $value === false ) {
330  // Pattern required data that wasn't available, abort
331  return null;
332  }
333  }
334 
335  // Send things that start with data: to $data, the rest to $matches
336  if ( $isData ) {
337  $data[$key] = $value;
338  } else {
339  $matches[$key] = $value;
340  }
341  }
342 
343  // If this match includes a callback, execute it
344  if ( isset( $pattern->options['callback'] ) ) {
345  call_user_func_array( $pattern->options['callback'], [ &$matches, $data ] );
346  }
347  } else {
348  // Our regexp didn't match, return null to signify no match.
349  return null;
350  }
351  // Fall through, everything went ok, return our matches array
352  return $matches;
353  }
354 
355 }
356 
358 
359  public $key, $params, $error;
360 
369  public function replace( $value ) {
370  $this->error = false;
371  $value = preg_replace_callback( '/\$(\d+|key)/u', [ $this, 'callback' ], $value );
372  if ( $this->error ) {
373  return false;
374  }
375  return $value;
376  }
377 
382  protected function callback( $m ) {
383  if ( $m[1] == "key" ) {
384  if ( is_null( $this->key ) ) {
385  $this->error = true;
386  return '';
387  }
388  return $this->key;
389  } else {
390  $d = $m[1];
391  if ( !isset( $this->params["par$d"] ) ) {
392  $this->error = true;
393  return '';
394  }
395  return rawurldecode( $this->params["par$d"] );
396  }
397  }
398 
399 }
PathRouter\add
add( $path, $params=[], $options=[])
Add a new path pattern to the path router.
Definition: PathRouter.php:160
object
globals will be eliminated from MediaWiki replaced by an application object which would be passed to constructors Whether that would be an convenient solution remains to be but certainly PHP makes such object oriented programming models easier than they were in previous versions For the time being MediaWiki programmers will have to work in an environment with some global context At the time of globals were initialised on startup by MediaWiki of these were configuration which are documented in DefaultSettings php There is no comprehensive documentation for the remaining however some of the most important ones are listed below They are typically initialised either in index php or in Setup php For a description of the see design txt $wgTitle Title object created from the request URL $wgOut OutputPage object for HTTP response $wgUser User object for the user associated with the current request $wgLang Language object selected by user preferences $wgContLang Language object associated with the wiki being viewed $wgParser Parser object Parser extensions register their hooks here $wgRequest WebRequest object
Definition: globals.txt:64
error
do that in ParserLimitReportFormat instead use this to modify the parameters of the image all existing parser cache entries will be invalid To avoid you ll need to handle that somehow(e.g. with the RejectParserCacheValue hook) because MediaWiki won 't do it for you. & $defaults error
Definition: hooks.txt:2612
array
the array() calling protocol came about after MediaWiki 1.4rc1.
PathRouter\doAdd
doAdd( $path, $params, $options, $key=null)
Protected helper to do the actual bulk work of adding a single pattern.
Definition: PathRouter.php:90
PathRouter\addStrict
addStrict( $path, $params=[], $options=[])
Add a new path pattern to the path router with the strict option on.
Definition: PathRouter.php:177
PathRouter\parse
parse( $path)
Parse a path and return the query matches for the path.
Definition: PathRouter.php:238
PathRouter\makeWeight
static makeWeight( $pattern)
Definition: PathRouter.php:198
$params
$params
Definition: styleTest.css.php:40
PathRouterPatternReplacer\callback
callback( $m)
Definition: PathRouter.php:382
php
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:37
key
design txt This is a brief overview of the new design More thorough and up to date information is available on the documentation wiki at etc Handles the details of getting and saving to the user table of the and dealing with sessions and cookies OutputPage Encapsulates the entire HTML page that will be sent in response to any server request It is used by calling its functions to add in any and then calling but I prefer the flexibility This should also do the output encoding The system allocates a global one in $wgOut Title Represents the title of an and does all the work of translating among various forms such as plain database key
Definition: design.txt:26
PathRouterPatternReplacer\$key
$key
Definition: PathRouter.php:359
PathRouterPatternReplacer
Definition: PathRouter.php:357
$matches
$matches
Definition: NoLocalSettings.php:24
$options
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped & $options
Definition: hooks.txt:2001
$value
$value
Definition: styleTest.css.php:45
PathRouterPatternReplacer\replace
replace( $value)
Replace keys inside path router patterns with text.
Definition: PathRouter.php:369
PathRouterPatternReplacer\$error
$error
Definition: PathRouter.php:359
PathRouter\$patterns
array $patterns
Definition: PathRouter.php:78
$path
$path
Definition: NoLocalSettings.php:25
as
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
Definition: distributors.txt:22
PathRouter\sortByWeight
sortByWeight()
Protected helper to re-sort our patterns so that the most specific (most heavily weighted) patterns a...
Definition: PathRouter.php:186
PathRouterPatternReplacer\$params
$params
Definition: PathRouter.php:359
PathRouter
PathRouter class.
Definition: PathRouter.php:73
PathRouter\extractTitle
static extractTitle( $path, $pattern)
Definition: PathRouter.php:264