Adding a new right, move-rootuserpages.
[lhc/web/wiklou.git] / includes / Title.php
1 <?php
2 /**
3 * See title.txt
4 * @file
5 */
6
7 if ( !class_exists( 'UtfNormal' ) ) {
8 require_once( dirname(__FILE__) . '/normal/UtfNormal.php' );
9 }
10
11 define ( 'GAID_FOR_UPDATE', 1 );
12
13
14 /**
15 * Constants for pr_cascade bitfield
16 */
17 define( 'CASCADE', 1 );
18
19 /**
20 * Represents a title within MediaWiki.
21 * Optionally may contain an interwiki designation or namespace.
22 * @note This class can fetch various kinds of data from the database;
23 * however, it does so inefficiently.
24 */
25 class Title {
26 /** @name Static cache variables */
27 //@{
28 static private $titleCache=array();
29 static private $interwikiCache=array();
30 //@}
31
32 /**
33 * Title::newFromText maintains a cache to avoid expensive re-normalization of
34 * commonly used titles. On a batch operation this can become a memory leak
35 * if not bounded. After hitting this many titles reset the cache.
36 */
37 const CACHE_MAX = 1000;
38
39
40 /**
41 * @name Private member variables
42 * Please use the accessor functions instead.
43 * @private
44 */
45 //@{
46
47 var $mTextform = ''; ///< Text form (spaces not underscores) of the main part
48 var $mUrlform = ''; ///< URL-encoded form of the main part
49 var $mDbkeyform = ''; ///< Main part with underscores
50 var $mUserCaseDBKey; ///< DB key with the initial letter in the case specified by the user
51 var $mNamespace = NS_MAIN; ///< Namespace index, i.e. one of the NS_xxxx constants
52 var $mInterwiki = ''; ///< Interwiki prefix (or null string)
53 var $mFragment; ///< Title fragment (i.e. the bit after the #)
54 var $mArticleID = -1; ///< Article ID, fetched from the link cache on demand
55 var $mLatestID = false; ///< ID of most recent revision
56 var $mRestrictions = array(); ///< Array of groups allowed to edit this article
57 var $mOldRestrictions = false;
58 var $mCascadeRestriction; ///< Cascade restrictions on this page to included templates and images?
59 var $mRestrictionsExpiry = array(); ///< When do the restrictions on this page expire?
60 var $mHasCascadingRestrictions; ///< Are cascading restrictions in effect on this page?
61 var $mCascadeSources; ///< Where are the cascading restrictions coming from on this page?
62 var $mRestrictionsLoaded = false; ///< Boolean for initialisation on demand
63 var $mPrefixedText; ///< Text form including namespace/interwiki, initialised on demand
64 # Don't change the following default, NS_MAIN is hardcoded in several
65 # places. See bug 696.
66 var $mDefaultNamespace = NS_MAIN; ///< Namespace index when there is no namespace
67 # Zero except in {{transclusion}} tags
68 var $mWatched = null; ///< Is $wgUser watching this page? null if unfilled, accessed through userIsWatching()
69 var $mLength = -1; ///< The page length, 0 for special pages
70 var $mRedirect = null; ///< Is the article at this title a redirect?
71 //@}
72
73
74 /**
75 * Constructor
76 * @private
77 */
78 /* private */ function __construct() {}
79
80 /**
81 * Create a new Title from a prefixed DB key
82 * @param $key \type{\string} The database key, which has underscores
83 * instead of spaces, possibly including namespace and
84 * interwiki prefixes
85 * @return \type{Title} the new object, or NULL on an error
86 */
87 public static function newFromDBkey( $key ) {
88 $t = new Title();
89 $t->mDbkeyform = $key;
90 if( $t->secureAndSplit() )
91 return $t;
92 else
93 return NULL;
94 }
95
96 /**
97 * Create a new Title from text, such as what one would
98 * find in a link. Decodes any HTML entities in the text.
99 *
100 * @param $text \type{\string} the link text; spaces, prefixes,
101 * and an initial ':' indicating the main namespace
102 * are accepted
103 * @param $defaultNamespace \type{\int} the namespace to use if
104 * none is specified by a prefix
105 * @return \type{Title} the new object, or NULL on an error
106 */
107 public static function newFromText( $text, $defaultNamespace = NS_MAIN ) {
108 if( is_object( $text ) ) {
109 throw new MWException( 'Title::newFromText given an object' );
110 }
111
112 /**
113 * Wiki pages often contain multiple links to the same page.
114 * Title normalization and parsing can become expensive on
115 * pages with many links, so we can save a little time by
116 * caching them.
117 *
118 * In theory these are value objects and won't get changed...
119 */
120 if( $defaultNamespace == NS_MAIN && isset( Title::$titleCache[$text] ) ) {
121 return Title::$titleCache[$text];
122 }
123
124 /**
125 * Convert things like &eacute; &#257; or &#x3017; into real text...
126 */
127 $filteredText = Sanitizer::decodeCharReferences( $text );
128
129 $t = new Title();
130 $t->mDbkeyform = str_replace( ' ', '_', $filteredText );
131 $t->mDefaultNamespace = $defaultNamespace;
132
133 static $cachedcount = 0 ;
134 if( $t->secureAndSplit() ) {
135 if( $defaultNamespace == NS_MAIN ) {
136 if( $cachedcount >= self::CACHE_MAX ) {
137 # Avoid memory leaks on mass operations...
138 Title::$titleCache = array();
139 $cachedcount=0;
140 }
141 $cachedcount++;
142 Title::$titleCache[$text] =& $t;
143 }
144 return $t;
145 } else {
146 $ret = NULL;
147 return $ret;
148 }
149 }
150
151 /**
152 * Create a new Title from URL-encoded text. Ensures that
153 * the given title's length does not exceed the maximum.
154 * @param $url \type{\string} the title, as might be taken from a URL
155 * @return \type{Title} the new object, or NULL on an error
156 */
157 public static function newFromURL( $url ) {
158 global $wgLegalTitleChars;
159 $t = new Title();
160
161 # For compatibility with old buggy URLs. "+" is usually not valid in titles,
162 # but some URLs used it as a space replacement and they still come
163 # from some external search tools.
164 if ( strpos( $wgLegalTitleChars, '+' ) === false ) {
165 $url = str_replace( '+', ' ', $url );
166 }
167
168 $t->mDbkeyform = str_replace( ' ', '_', $url );
169 if( $t->secureAndSplit() ) {
170 return $t;
171 } else {
172 return NULL;
173 }
174 }
175
176 /**
177 * Create a new Title from an article ID
178 *
179 * @todo This is inefficiently implemented, the page row is requested
180 * but not used for anything else
181 *
182 * @param $id \type{\int} the page_id corresponding to the Title to create
183 * @param $flags \type{\int} use GAID_FOR_UPDATE to use master
184 * @return \type{Title} the new object, or NULL on an error
185 */
186 public static function newFromID( $id, $flags = 0 ) {
187 $fname = 'Title::newFromID';
188 $db = ($flags & GAID_FOR_UPDATE) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
189 $row = $db->selectRow( 'page', array( 'page_namespace', 'page_title' ),
190 array( 'page_id' => $id ), $fname );
191 if ( $row !== false ) {
192 $title = Title::makeTitle( $row->page_namespace, $row->page_title );
193 } else {
194 $title = NULL;
195 }
196 return $title;
197 }
198
199 /**
200 * Make an array of titles from an array of IDs
201 * @param $ids \type{\arrayof{\int}} Array of IDs
202 * @return \type{\arrayof{Title}} Array of Titles
203 */
204 public static function newFromIDs( $ids ) {
205 if ( !count( $ids ) ) {
206 return array();
207 }
208 $dbr = wfGetDB( DB_SLAVE );
209 $res = $dbr->select( 'page', array( 'page_namespace', 'page_title' ),
210 'page_id IN (' . $dbr->makeList( $ids ) . ')', __METHOD__ );
211
212 $titles = array();
213 foreach( $res as $row ) {
214 $titles[] = Title::makeTitle( $row->page_namespace, $row->page_title );
215 }
216 return $titles;
217 }
218
219 /**
220 * Make a Title object from a DB row
221 * @param $row \type{Row} (needs at least page_title,page_namespace)
222 * @return \type{Title} corresponding Title
223 */
224 public static function newFromRow( $row ) {
225 $t = self::makeTitle( $row->page_namespace, $row->page_title );
226
227 $t->mArticleID = isset($row->page_id) ? intval($row->page_id) : -1;
228 $t->mLength = isset($row->page_len) ? intval($row->page_len) : -1;
229 $t->mRedirect = isset($row->page_is_redirect) ? (bool)$row->page_is_redirect : NULL;
230 $t->mLatestID = isset($row->page_latest) ? $row->page_latest : false;
231
232 return $t;
233 }
234
235 /**
236 * Create a new Title from a namespace index and a DB key.
237 * It's assumed that $ns and $title are *valid*, for instance when
238 * they came directly from the database or a special page name.
239 * For convenience, spaces are converted to underscores so that
240 * eg user_text fields can be used directly.
241 *
242 * @param $ns \type{\int} the namespace of the article
243 * @param $title \type{\string} the unprefixed database key form
244 * @param $fragment \type{\string} The link fragment (after the "#")
245 * @return \type{Title} the new object
246 */
247 public static function &makeTitle( $ns, $title, $fragment = '' ) {
248 $t = new Title();
249 $t->mInterwiki = '';
250 $t->mFragment = $fragment;
251 $t->mNamespace = $ns = intval( $ns );
252 $t->mDbkeyform = str_replace( ' ', '_', $title );
253 $t->mArticleID = ( $ns >= 0 ) ? -1 : 0;
254 $t->mUrlform = wfUrlencode( $t->mDbkeyform );
255 $t->mTextform = str_replace( '_', ' ', $title );
256 return $t;
257 }
258
259 /**
260 * Create a new Title from a namespace index and a DB key.
261 * The parameters will be checked for validity, which is a bit slower
262 * than makeTitle() but safer for user-provided data.
263 *
264 * @param $ns \type{\int} the namespace of the article
265 * @param $title \type{\string} the database key form
266 * @param $fragment \type{\string} The link fragment (after the "#")
267 * @return \type{Title} the new object, or NULL on an error
268 */
269 public static function makeTitleSafe( $ns, $title, $fragment = '' ) {
270 $t = new Title();
271 $t->mDbkeyform = Title::makeName( $ns, $title, $fragment );
272 if( $t->secureAndSplit() ) {
273 return $t;
274 } else {
275 return NULL;
276 }
277 }
278
279 /**
280 * Create a new Title for the Main Page
281 * @return \type{Title} the new object
282 */
283 public static function newMainPage() {
284 $title = Title::newFromText( wfMsgForContent( 'mainpage' ) );
285 // Don't give fatal errors if the message is broken
286 if ( !$title ) {
287 $title = Title::newFromText( 'Main Page' );
288 }
289 return $title;
290 }
291
292 /**
293 * Extract a redirect destination from a string and return the
294 * Title, or null if the text doesn't contain a valid redirect
295 *
296 * @param $text \type{String} Text with possible redirect
297 * @return \type{Title} The corresponding Title
298 */
299 public static function newFromRedirect( $text ) {
300 $redir = MagicWord::get( 'redirect' );
301 $text = trim($text);
302 if( $redir->matchStartAndRemove( $text ) ) {
303 // Extract the first link and see if it's usable
304 // Ensure that it really does come directly after #REDIRECT
305 // Some older redirects included a colon, so don't freak about that!
306 $m = array();
307 if( preg_match( '!^\s*:?\s*\[{2}(.*?)(?:\|.*?)?\]{2}!', $text, $m ) ) {
308 // Strip preceding colon used to "escape" categories, etc.
309 // and URL-decode links
310 if( strpos( $m[1], '%' ) !== false ) {
311 // Match behavior of inline link parsing here;
312 // don't interpret + as " " most of the time!
313 // It might be safe to just use rawurldecode instead, though.
314 $m[1] = urldecode( ltrim( $m[1], ':' ) );
315 }
316 $title = Title::newFromText( $m[1] );
317 // Redirects to Special:Userlogout are not permitted
318 if( $title instanceof Title && !$title->isSpecial( 'Userlogout' ) )
319 return $title;
320 }
321 }
322 return null;
323 }
324
325 #----------------------------------------------------------------------------
326 # Static functions
327 #----------------------------------------------------------------------------
328
329 /**
330 * Get the prefixed DB key associated with an ID
331 * @param $id \type{\int} the page_id of the article
332 * @return \type{Title} an object representing the article, or NULL
333 * if no such article was found
334 */
335 public static function nameOf( $id ) {
336 $dbr = wfGetDB( DB_SLAVE );
337
338 $s = $dbr->selectRow( 'page', array( 'page_namespace','page_title' ), array( 'page_id' => $id ), __METHOD__ );
339 if ( $s === false ) { return NULL; }
340
341 $n = self::makeName( $s->page_namespace, $s->page_title );
342 return $n;
343 }
344
345 /**
346 * Get a regex character class describing the legal characters in a link
347 * @return \type{\string} the list of characters, not delimited
348 */
349 public static function legalChars() {
350 global $wgLegalTitleChars;
351 return $wgLegalTitleChars;
352 }
353
354 /**
355 * Get a string representation of a title suitable for
356 * including in a search index
357 *
358 * @param $ns \type{\int} a namespace index
359 * @param $title \type{\string} text-form main part
360 * @return \type{\string} a stripped-down title string ready for the
361 * search index
362 */
363 public static function indexTitle( $ns, $title ) {
364 global $wgContLang;
365
366 $lc = SearchEngine::legalSearchChars() . '&#;';
367 $t = $wgContLang->stripForSearch( $title );
368 $t = preg_replace( "/[^{$lc}]+/", ' ', $t );
369 $t = $wgContLang->lc( $t );
370
371 # Handle 's, s'
372 $t = preg_replace( "/([{$lc}]+)'s( |$)/", "\\1 \\1's ", $t );
373 $t = preg_replace( "/([{$lc}]+)s'( |$)/", "\\1s ", $t );
374
375 $t = preg_replace( "/\\s+/", ' ', $t );
376
377 if ( $ns == NS_IMAGE ) {
378 $t = preg_replace( "/ (png|gif|jpg|jpeg|ogg)$/", "", $t );
379 }
380 return trim( $t );
381 }
382
383 /*
384 * Make a prefixed DB key from a DB key and a namespace index
385 * @param $ns \type{\int} numerical representation of the namespace
386 * @param $title \type{\string} the DB key form the title
387 * @param $fragment \type{\string} The link fragment (after the "#")
388 * @return \type{\string} the prefixed form of the title
389 */
390 public static function makeName( $ns, $title, $fragment = '' ) {
391 global $wgContLang;
392
393 $namespace = $wgContLang->getNsText( $ns );
394 $name = $namespace == '' ? $title : "$namespace:$title";
395 if ( strval( $fragment ) != '' ) {
396 $name .= '#' . $fragment;
397 }
398 return $name;
399 }
400
401 /**
402 * Returns the URL associated with an interwiki prefix
403 * @param $key \type{\string} the interwiki prefix (e.g. "MeatBall")
404 * @return \type{\string} the associated URL, containing "$1",
405 * which should be replaced by an article title
406 * @static (arguably)
407 * @deprecated See Interwiki class
408 */
409 public function getInterwikiLink( $key ) {
410 return Interwiki::fetch( $key )->getURL( );
411 }
412
413 /**
414 * Determine whether the object refers to a page within
415 * this project.
416 *
417 * @return \type{\bool} TRUE if this is an in-project interwiki link
418 * or a wikilink, FALSE otherwise
419 */
420 public function isLocal() {
421 if ( $this->mInterwiki != '' ) {
422 return Interwiki::fetch( $this->mInterwiki )->isLocal();
423 } else {
424 return true;
425 }
426 }
427
428 /**
429 * Determine whether the object refers to a page within
430 * this project and is transcludable.
431 *
432 * @return \type{\bool} TRUE if this is transcludable
433 */
434 public function isTrans() {
435 if ($this->mInterwiki == '')
436 return false;
437
438 return Interwiki::fetch( $this->mInterwiki )->isTranscludable();
439 }
440
441 /**
442 * Escape a text fragment, say from a link, for a URL
443 */
444 static function escapeFragmentForURL( $fragment ) {
445 $fragment = str_replace( ' ', '_', $fragment );
446 $fragment = urlencode( Sanitizer::decodeCharReferences( $fragment ) );
447 $replaceArray = array(
448 '%3A' => ':',
449 '%' => '.'
450 );
451 return strtr( $fragment, $replaceArray );
452 }
453
454 #----------------------------------------------------------------------------
455 # Other stuff
456 #----------------------------------------------------------------------------
457
458 /** Simple accessors */
459 /**
460 * Get the text form (spaces not underscores) of the main part
461 * @return \type{\string} Main part of the title
462 */
463 public function getText() { return $this->mTextform; }
464 /**
465 * Get the URL-encoded form of the main part
466 * @return \type{\string} Main part of the title, URL-encoded
467 */
468 public function getPartialURL() { return $this->mUrlform; }
469 /**
470 * Get the main part with underscores
471 * @return \type{\string} Main part of the title, with underscores
472 */
473 public function getDBkey() { return $this->mDbkeyform; }
474 /**
475 * Get the namespace index, i.e.\ one of the NS_xxxx constants.
476 * @return \type{\int} Namespace index
477 */
478 public function getNamespace() { return $this->mNamespace; }
479 /**
480 * Get the namespace text
481 * @return \type{\string} Namespace text
482 */
483 public function getNsText() {
484 global $wgContLang, $wgCanonicalNamespaceNames;
485
486 if ( '' != $this->mInterwiki ) {
487 // This probably shouldn't even happen. ohh man, oh yuck.
488 // But for interwiki transclusion it sometimes does.
489 // Shit. Shit shit shit.
490 //
491 // Use the canonical namespaces if possible to try to
492 // resolve a foreign namespace.
493 if( isset( $wgCanonicalNamespaceNames[$this->mNamespace] ) ) {
494 return $wgCanonicalNamespaceNames[$this->mNamespace];
495 }
496 }
497 return $wgContLang->getNsText( $this->mNamespace );
498 }
499 /**
500 * Get the DB key with the initial letter case as specified by the user
501 * @return \type{\string} DB key
502 */
503 function getUserCaseDBKey() {
504 return $this->mUserCaseDBKey;
505 }
506 /**
507 * Get the namespace text of the subject (rather than talk) page
508 * @return \type{\string} Namespace text
509 */
510 public function getSubjectNsText() {
511 global $wgContLang;
512 return $wgContLang->getNsText( MWNamespace::getSubject( $this->mNamespace ) );
513 }
514 /**
515 * Get the namespace text of the talk page
516 * @return \type{\string} Namespace text
517 */
518 public function getTalkNsText() {
519 global $wgContLang;
520 return( $wgContLang->getNsText( MWNamespace::getTalk( $this->mNamespace ) ) );
521 }
522 /**
523 * Could this title have a corresponding talk page?
524 * @return \type{\bool} TRUE or FALSE
525 */
526 public function canTalk() {
527 return( MWNamespace::canTalk( $this->mNamespace ) );
528 }
529 /**
530 * Get the interwiki prefix (or null string)
531 * @return \type{\string} Interwiki prefix
532 */
533 public function getInterwiki() { return $this->mInterwiki; }
534 /**
535 * Get the Title fragment (i.e.\ the bit after the #) in text form
536 * @return \type{\string} Title fragment
537 */
538 public function getFragment() { return $this->mFragment; }
539 /**
540 * Get the fragment in URL form, including the "#" character if there is one
541 * @return \type{\string} Fragment in URL form
542 */
543 public function getFragmentForURL() {
544 if ( $this->mFragment == '' ) {
545 return '';
546 } else {
547 return '#' . Title::escapeFragmentForURL( $this->mFragment );
548 }
549 }
550 /**
551 * Get the default namespace index, for when there is no namespace
552 * @return \type{\int} Default namespace index
553 */
554 public function getDefaultNamespace() { return $this->mDefaultNamespace; }
555
556 /**
557 * Get title for search index
558 * @return \type{\string} a stripped-down title string ready for the
559 * search index
560 */
561 public function getIndexTitle() {
562 return Title::indexTitle( $this->mNamespace, $this->mTextform );
563 }
564
565 /**
566 * Get the prefixed database key form
567 * @return \type{\string} the prefixed title, with underscores and
568 * any interwiki and namespace prefixes
569 */
570 public function getPrefixedDBkey() {
571 $s = $this->prefix( $this->mDbkeyform );
572 $s = str_replace( ' ', '_', $s );
573 return $s;
574 }
575
576 /**
577 * Get the prefixed title with spaces.
578 * This is the form usually used for display
579 * @return \type{\string} the prefixed title, with spaces
580 */
581 public function getPrefixedText() {
582 if ( empty( $this->mPrefixedText ) ) { // FIXME: bad usage of empty() ?
583 $s = $this->prefix( $this->mTextform );
584 $s = str_replace( '_', ' ', $s );
585 $this->mPrefixedText = $s;
586 }
587 return $this->mPrefixedText;
588 }
589
590 /**
591 * Get the prefixed title with spaces, plus any fragment
592 * (part beginning with '#')
593 * @return \type{\string} the prefixed title, with spaces and
594 * the fragment, including '#'
595 */
596 public function getFullText() {
597 $text = $this->getPrefixedText();
598 if( '' != $this->mFragment ) {
599 $text .= '#' . $this->mFragment;
600 }
601 return $text;
602 }
603
604 /**
605 * Get the base name, i.e. the leftmost parts before the /
606 * @return \type{\string} Base name
607 */
608 public function getBaseText() {
609 if( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
610 return $this->getText();
611 }
612
613 $parts = explode( '/', $this->getText() );
614 # Don't discard the real title if there's no subpage involved
615 if( count( $parts ) > 1 )
616 unset( $parts[ count( $parts ) - 1 ] );
617 return implode( '/', $parts );
618 }
619
620 /**
621 * Get the lowest-level subpage name, i.e. the rightmost part after /
622 * @return \type{\string} Subpage name
623 */
624 public function getSubpageText() {
625 if( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
626 return( $this->mTextform );
627 }
628 $parts = explode( '/', $this->mTextform );
629 return( $parts[ count( $parts ) - 1 ] );
630 }
631
632 /**
633 * Get a URL-encoded form of the subpage text
634 * @return \type{\string} URL-encoded subpage name
635 */
636 public function getSubpageUrlForm() {
637 $text = $this->getSubpageText();
638 $text = wfUrlencode( str_replace( ' ', '_', $text ) );
639 $text = str_replace( '%28', '(', str_replace( '%29', ')', $text ) ); # Clean up the URL; per below, this might not be safe
640 return( $text );
641 }
642
643 /**
644 * Get a URL-encoded title (not an actual URL) including interwiki
645 * @return \type{\string} the URL-encoded form
646 */
647 public function getPrefixedURL() {
648 $s = $this->prefix( $this->mDbkeyform );
649 $s = str_replace( ' ', '_', $s );
650
651 $s = wfUrlencode ( $s ) ;
652
653 # Cleaning up URL to make it look nice -- is this safe?
654 $s = str_replace( '%28', '(', $s );
655 $s = str_replace( '%29', ')', $s );
656
657 return $s;
658 }
659
660 /**
661 * Get a real URL referring to this title, with interwiki link and
662 * fragment
663 *
664 * @param $query \twotypes{\string,\array} an optional query string, not used for interwiki
665 * links. Can be specified as an associative array as well, e.g.,
666 * array( 'action' => 'edit' ) (keys and values will be URL-escaped).
667 * @param $variant \type{\string} language variant of url (for sr, zh..)
668 * @return \type{\string} the URL
669 */
670 public function getFullURL( $query = '', $variant = false ) {
671 global $wgContLang, $wgServer, $wgRequest;
672
673 if( is_array( $query ) ) {
674 $query = wfArrayToCGI( $query );
675 }
676
677 if ( '' == $this->mInterwiki ) {
678 $url = $this->getLocalUrl( $query, $variant );
679
680 // Ugly quick hack to avoid duplicate prefixes (bug 4571 etc)
681 // Correct fix would be to move the prepending elsewhere.
682 if ($wgRequest->getVal('action') != 'render') {
683 $url = $wgServer . $url;
684 }
685 } else {
686 $baseUrl = Interwiki::fetch( $this->mInterwiki )->getURL( );
687
688 $namespace = wfUrlencode( $this->getNsText() );
689 if ( '' != $namespace ) {
690 # Can this actually happen? Interwikis shouldn't be parsed.
691 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
692 $namespace .= ':';
693 }
694 $url = str_replace( '$1', $namespace . $this->mUrlform, $baseUrl );
695 $url = wfAppendQuery( $url, $query );
696 }
697
698 # Finally, add the fragment.
699 $url .= $this->getFragmentForURL();
700
701 wfRunHooks( 'GetFullURL', array( &$this, &$url, $query ) );
702 return $url;
703 }
704
705 /**
706 * Get a URL with no fragment or server name. If this page is generated
707 * with action=render, $wgServer is prepended.
708 * @param mixed $query an optional query string; if not specified,
709 * $wgArticlePath will be used. Can be specified as an associative array
710 * as well, e.g., array( 'action' => 'edit' ) (keys and values will be
711 * URL-escaped).
712 * @param $variant \type{\string} language variant of url (for sr, zh..)
713 * @return \type{\string} the URL
714 */
715 public function getLocalURL( $query = '', $variant = false ) {
716 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
717 global $wgVariantArticlePath, $wgContLang, $wgUser;
718
719 if( is_array( $query ) ) {
720 $query = wfArrayToCGI( $query );
721 }
722
723 // internal links should point to same variant as current page (only anonymous users)
724 if($variant == false && $wgContLang->hasVariants() && !$wgUser->isLoggedIn()){
725 $pref = $wgContLang->getPreferredVariant(false);
726 if($pref != $wgContLang->getCode())
727 $variant = $pref;
728 }
729
730 if ( $this->isExternal() ) {
731 $url = $this->getFullURL();
732 if ( $query ) {
733 // This is currently only used for edit section links in the
734 // context of interwiki transclusion. In theory we should
735 // append the query to the end of any existing query string,
736 // but interwiki transclusion is already broken in that case.
737 $url .= "?$query";
738 }
739 } else {
740 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
741 if ( $query == '' ) {
742 if( $variant != false && $wgContLang->hasVariants() ) {
743 if( $wgVariantArticlePath == false ) {
744 $variantArticlePath = "$wgScript?title=$1&variant=$2"; // default
745 } else {
746 $variantArticlePath = $wgVariantArticlePath;
747 }
748 $url = str_replace( '$2', urlencode( $variant ), $variantArticlePath );
749 $url = str_replace( '$1', $dbkey, $url );
750 } else {
751 $url = str_replace( '$1', $dbkey, $wgArticlePath );
752 }
753 } else {
754 global $wgActionPaths;
755 $url = false;
756 $matches = array();
757 if( !empty( $wgActionPaths ) &&
758 preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches ) )
759 {
760 $action = urldecode( $matches[2] );
761 if( isset( $wgActionPaths[$action] ) ) {
762 $query = $matches[1];
763 if( isset( $matches[4] ) ) $query .= $matches[4];
764 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
765 if( $query != '' ) $url .= '?' . $query;
766 }
767 }
768 if ( $url === false ) {
769 if ( $query == '-' ) {
770 $query = '';
771 }
772 $url = "{$wgScript}?title={$dbkey}&{$query}";
773 }
774 }
775
776 // FIXME: this causes breakage in various places when we
777 // actually expected a local URL and end up with dupe prefixes.
778 if ($wgRequest->getVal('action') == 'render') {
779 $url = $wgServer . $url;
780 }
781 }
782 wfRunHooks( 'GetLocalURL', array( &$this, &$url, $query ) );
783 return $url;
784 }
785
786 /**
787 * Get a URL that's the simplest URL that will be valid to link, locally,
788 * to the current Title. It includes the fragment, but does not include
789 * the server unless action=render is used (or the link is external). If
790 * there's a fragment but the prefixed text is empty, we just return a link
791 * to the fragment.
792 *
793 * @param $query \type{\arrayof{\string}} An associative array of key => value pairs for the
794 * query string. Keys and values will be escaped.
795 * @param $variant \type{\string} Language variant of URL (for sr, zh..). Ignored
796 * for external links. Default is "false" (same variant as current page,
797 * for anonymous users).
798 * @return \type{\string} the URL
799 */
800 public function getLinkUrl( $query = array(), $variant = false ) {
801 if( !is_array( $query ) ) {
802 throw new MWException( 'Title::getLinkUrl passed a non-array for '.
803 '$query' );
804 }
805 if( $this->isExternal() ) {
806 return $this->getFullURL( $query );
807 } elseif( $this->getPrefixedText() === ''
808 and $this->getFragment() !== '' ) {
809 return $this->getFragmentForURL();
810 } else {
811 return $this->getLocalURL( $query, $variant )
812 . $this->getFragmentForURL();
813 }
814 }
815
816 /**
817 * Get an HTML-escaped version of the URL form, suitable for
818 * using in a link, without a server name or fragment
819 * @param $query \type{\string} an optional query string
820 * @return \type{\string} the URL
821 */
822 public function escapeLocalURL( $query = '' ) {
823 return htmlspecialchars( $this->getLocalURL( $query ) );
824 }
825
826 /**
827 * Get an HTML-escaped version of the URL form, suitable for
828 * using in a link, including the server name and fragment
829 *
830 * @param $query \type{\string} an optional query string
831 * @return \type{\string} the URL
832 */
833 public function escapeFullURL( $query = '' ) {
834 return htmlspecialchars( $this->getFullURL( $query ) );
835 }
836
837 /**
838 * Get the URL form for an internal link.
839 * - Used in various Squid-related code, in case we have a different
840 * internal hostname for the server from the exposed one.
841 *
842 * @param $query \type{\string} an optional query string
843 * @param $variant \type{\string} language variant of url (for sr, zh..)
844 * @return \type{\string} the URL
845 */
846 public function getInternalURL( $query = '', $variant = false ) {
847 global $wgInternalServer;
848 $url = $wgInternalServer . $this->getLocalURL( $query, $variant );
849 wfRunHooks( 'GetInternalURL', array( &$this, &$url, $query ) );
850 return $url;
851 }
852
853 /**
854 * Get the edit URL for this Title
855 * @return \type{\string} the URL, or a null string if this is an
856 * interwiki link
857 */
858 public function getEditURL() {
859 if ( '' != $this->mInterwiki ) { return ''; }
860 $s = $this->getLocalURL( 'action=edit' );
861
862 return $s;
863 }
864
865 /**
866 * Get the HTML-escaped displayable text form.
867 * Used for the title field in <a> tags.
868 * @return \type{\string} the text, including any prefixes
869 */
870 public function getEscapedText() {
871 return htmlspecialchars( $this->getPrefixedText() );
872 }
873
874 /**
875 * Is this Title interwiki?
876 * @return \type{\bool}
877 */
878 public function isExternal() { return ( '' != $this->mInterwiki ); }
879
880 /**
881 * Is this page "semi-protected" - the *only* protection is autoconfirm?
882 *
883 * @param @action \type{\string} Action to check (default: edit)
884 * @return \type{\bool}
885 */
886 public function isSemiProtected( $action = 'edit' ) {
887 if( $this->exists() ) {
888 $restrictions = $this->getRestrictions( $action );
889 if( count( $restrictions ) > 0 ) {
890 foreach( $restrictions as $restriction ) {
891 if( strtolower( $restriction ) != 'autoconfirmed' )
892 return false;
893 }
894 } else {
895 # Not protected
896 return false;
897 }
898 return true;
899 } else {
900 # If it doesn't exist, it can't be protected
901 return false;
902 }
903 }
904
905 /**
906 * Does the title correspond to a protected article?
907 * @param $what \type{\string} the action the page is protected from,
908 * by default checks move and edit
909 * @return \type{\bool}
910 */
911 public function isProtected( $action = '' ) {
912 global $wgRestrictionLevels, $wgRestrictionTypes;
913
914 # Special pages have inherent protection
915 if( $this->getNamespace() == NS_SPECIAL )
916 return true;
917
918 # Check regular protection levels
919 foreach( $wgRestrictionTypes as $type ){
920 if( $action == $type || $action == '' ) {
921 $r = $this->getRestrictions( $type );
922 foreach( $wgRestrictionLevels as $level ) {
923 if( in_array( $level, $r ) && $level != '' ) {
924 return true;
925 }
926 }
927 }
928 }
929
930 return false;
931 }
932
933 /**
934 * Is $wgUser watching this page?
935 * @return \type{\bool}
936 */
937 public function userIsWatching() {
938 global $wgUser;
939
940 if ( is_null( $this->mWatched ) ) {
941 if ( NS_SPECIAL == $this->mNamespace || !$wgUser->isLoggedIn()) {
942 $this->mWatched = false;
943 } else {
944 $this->mWatched = $wgUser->isWatched( $this );
945 }
946 }
947 return $this->mWatched;
948 }
949
950 /**
951 * Can $wgUser perform $action on this page?
952 * This skips potentially expensive cascading permission checks.
953 *
954 * Suitable for use for nonessential UI controls in common cases, but
955 * _not_ for functional access control.
956 *
957 * May provide false positives, but should never provide a false negative.
958 *
959 * @param $action \type{\string} action that permission needs to be checked for
960 * @return \type{\bool}
961 */
962 public function quickUserCan( $action ) {
963 return $this->userCan( $action, false );
964 }
965
966 /**
967 * Determines if $wgUser is unable to edit this page because it has been protected
968 * by $wgNamespaceProtection.
969 *
970 * @return \type{\bool}
971 */
972 public function isNamespaceProtected() {
973 global $wgNamespaceProtection, $wgUser;
974 if( isset( $wgNamespaceProtection[ $this->mNamespace ] ) ) {
975 foreach( (array)$wgNamespaceProtection[ $this->mNamespace ] as $right ) {
976 if( $right != '' && !$wgUser->isAllowed( $right ) )
977 return true;
978 }
979 }
980 return false;
981 }
982
983 /**
984 * Can $wgUser perform $action on this page?
985 * @param $action \type{\string} action that permission needs to be checked for
986 * @param $doExpensiveQueries \type{\bool} Set this to false to avoid doing unnecessary queries.
987 * @return \type{\bool}
988 */
989 public function userCan( $action, $doExpensiveQueries = true ) {
990 global $wgUser;
991 return ( $this->getUserPermissionsErrorsInternal( $action, $wgUser, $doExpensiveQueries ) === array());
992 }
993
994 /**
995 * Can $user perform $action on this page?
996 *
997 * FIXME: This *does not* check throttles (User::pingLimiter()).
998 *
999 * @param $action \type{\string}action that permission needs to be checked for
1000 * @param $user \type{User} user to check
1001 * @param $doExpensiveQueries \type{\bool} Set this to false to avoid doing unnecessary queries.
1002 * @param $ignoreErrors \type{\arrayof{\string}} Set this to a list of message keys whose corresponding errors may be ignored.
1003 * @return \type{\array} Array of arrays of the arguments to wfMsg to explain permissions problems.
1004 */
1005 public function getUserPermissionsErrors( $action, $user, $doExpensiveQueries = true, $ignoreErrors = array() ) {
1006 if( !StubObject::isRealObject( $user ) ) {
1007 //Since StubObject is always used on globals, we can unstub $wgUser here and set $user = $wgUser
1008 global $wgUser;
1009 $wgUser->_unstub( '', 5 );
1010 $user = $wgUser;
1011 }
1012 $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries );
1013
1014 global $wgContLang;
1015 global $wgLang;
1016 global $wgEmailConfirmToEdit;
1017
1018 if ( $wgEmailConfirmToEdit && !$user->isEmailConfirmed() && $action != 'createaccount' ) {
1019 $errors[] = array( 'confirmedittext' );
1020 }
1021
1022 // Edit blocks should not affect reading. Account creation blocks handled at userlogin.
1023 if ( $user->isBlockedFrom( $this ) && $action != 'read' && $action != 'createaccount' ) {
1024 $block = $user->mBlock;
1025
1026 // This is from OutputPage::blockedPage
1027 // Copied at r23888 by werdna
1028
1029 $id = $user->blockedBy();
1030 $reason = $user->blockedFor();
1031 if( $reason == '' ) {
1032 $reason = wfMsg( 'blockednoreason' );
1033 }
1034 $ip = wfGetIP();
1035
1036 if ( is_numeric( $id ) ) {
1037 $name = User::whoIs( $id );
1038 } else {
1039 $name = $id;
1040 }
1041
1042 $link = '[[' . $wgContLang->getNsText( NS_USER ) . ":{$name}|{$name}]]";
1043 $blockid = $block->mId;
1044 $blockExpiry = $user->mBlock->mExpiry;
1045 $blockTimestamp = $wgLang->timeanddate( wfTimestamp( TS_MW, $user->mBlock->mTimestamp ), true );
1046
1047 if ( $blockExpiry == 'infinity' ) {
1048 // Entry in database (table ipblocks) is 'infinity' but 'ipboptions' uses 'infinite' or 'indefinite'
1049 $scBlockExpiryOptions = wfMsg( 'ipboptions' );
1050
1051 foreach ( explode( ',', $scBlockExpiryOptions ) as $option ) {
1052 if ( strpos( $option, ':' ) == false )
1053 continue;
1054
1055 list ($show, $value) = explode( ":", $option );
1056
1057 if ( $value == 'infinite' || $value == 'indefinite' ) {
1058 $blockExpiry = $show;
1059 break;
1060 }
1061 }
1062 } else {
1063 $blockExpiry = $wgLang->timeanddate( wfTimestamp( TS_MW, $blockExpiry ), true );
1064 }
1065
1066 $intended = $user->mBlock->mAddress;
1067
1068 $errors[] = array( ($block->mAuto ? 'autoblockedtext' : 'blockedtext'), $link, $reason, $ip, $name,
1069 $blockid, $blockExpiry, $intended, $blockTimestamp );
1070 }
1071
1072 // Remove the errors being ignored.
1073
1074 foreach( $errors as $index => $error ) {
1075 $error_key = is_array($error) ? $error[0] : $error;
1076
1077 if (in_array( $error_key, $ignoreErrors )) {
1078 unset($errors[$index]);
1079 }
1080 }
1081
1082 return $errors;
1083 }
1084
1085 /**
1086 * Can $user perform $action on this page? This is an internal function,
1087 * which checks ONLY that previously checked by userCan (i.e. it leaves out
1088 * checks on wfReadOnly() and blocks)
1089 *
1090 * @param $action \type{\string} action that permission needs to be checked for
1091 * @param $user \type{User} user to check
1092 * @param $doExpensiveQueries \type{\bool} Set this to false to avoid doing unnecessary queries.
1093 * @return \type{\array} Array of arrays of the arguments to wfMsg to explain permissions problems.
1094 */
1095 private function getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries = true ) {
1096 wfProfileIn( __METHOD__ );
1097
1098 $errors = array();
1099
1100 // Use getUserPermissionsErrors instead
1101 if ( !wfRunHooks( 'userCan', array( &$this, &$user, $action, &$result ) ) ) {
1102 wfProfileOut( __METHOD__ );
1103 return $result ? array() : array( array( 'badaccess-group0' ) );
1104 }
1105
1106 if (!wfRunHooks( 'getUserPermissionsErrors', array( &$this, &$user, $action, &$result ) ) ) {
1107 if ($result != array() && is_array($result) && !is_array($result[0]))
1108 $errors[] = $result; # A single array representing an error
1109 else if (is_array($result) && is_array($result[0]))
1110 $errors = array_merge( $errors, $result ); # A nested array representing multiple errors
1111 else if ($result != '' && $result != null && $result !== true && $result !== false)
1112 $errors[] = array($result); # A string representing a message-id
1113 else if ($result === false )
1114 $errors[] = array('badaccess-group0'); # a generic "We don't want them to do that"
1115 }
1116 if ($doExpensiveQueries && !wfRunHooks( 'getUserPermissionsErrorsExpensive', array( &$this, &$user, $action, &$result ) ) ) {
1117 if ($result != array() && is_array($result) && !is_array($result[0]))
1118 $errors[] = $result; # A single array representing an error
1119 else if (is_array($result) && is_array($result[0]))
1120 $errors = array_merge( $errors, $result ); # A nested array representing multiple errors
1121 else if ($result != '' && $result != null && $result !== true && $result !== false)
1122 $errors[] = array($result); # A string representing a message-id
1123 else if ($result === false )
1124 $errors[] = array('badaccess-group0'); # a generic "We don't want them to do that"
1125 }
1126
1127 $specialOKActions = array( 'createaccount', 'execute' );
1128 if( NS_SPECIAL == $this->mNamespace && !in_array( $action, $specialOKActions) ) {
1129 $errors[] = array('ns-specialprotected');
1130 }
1131
1132 if ( $this->isNamespaceProtected() ) {
1133 $ns = $this->getNamespace() == NS_MAIN
1134 ? wfMsg( 'nstab-main' )
1135 : $this->getNsText();
1136 $errors[] = (NS_MEDIAWIKI == $this->mNamespace
1137 ? array('protectedinterface')
1138 : array( 'namespaceprotected', $ns ) );
1139 }
1140
1141 if( $this->mDbkeyform == '_' ) {
1142 # FIXME: Is this necessary? Shouldn't be allowed anyway...
1143 $errors[] = array('badaccess-group0');
1144 }
1145
1146 # protect css/js subpages of user pages
1147 # XXX: this might be better using restrictions
1148 # XXX: Find a way to work around the php bug that prevents using $this->userCanEditCssJsSubpage() from working
1149 if( $this->isCssJsSubpage()
1150 && !$user->isAllowed('editusercssjs')
1151 && !preg_match('/^'.preg_quote($user->getName(), '/').'\//', $this->mTextform) ) {
1152 $errors[] = array('customcssjsprotected');
1153 }
1154
1155 if ( $doExpensiveQueries && !$this->isCssJsSubpage() ) {
1156 # We /could/ use the protection level on the source page, but it's fairly ugly
1157 # as we have to establish a precedence hierarchy for pages included by multiple
1158 # cascade-protected pages. So just restrict it to people with 'protect' permission,
1159 # as they could remove the protection anyway.
1160 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
1161 # Cascading protection depends on more than this page...
1162 # Several cascading protected pages may include this page...
1163 # Check each cascading level
1164 # This is only for protection restrictions, not for all actions
1165 if( $cascadingSources > 0 && isset($restrictions[$action]) ) {
1166 foreach( $restrictions[$action] as $right ) {
1167 $right = ( $right == 'sysop' ) ? 'protect' : $right;
1168 if( '' != $right && !$user->isAllowed( $right ) ) {
1169 $pages = '';
1170 foreach( $cascadingSources as $page )
1171 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
1172 $errors[] = array( 'cascadeprotected', count( $cascadingSources ), $pages );
1173 }
1174 }
1175 }
1176 }
1177
1178 foreach( $this->getRestrictions($action) as $right ) {
1179 // Backwards compatibility, rewrite sysop -> protect
1180 if ( $right == 'sysop' ) {
1181 $right = 'protect';
1182 }
1183 if( '' != $right && !$user->isAllowed( $right ) ) {
1184 //Users with 'editprotected' permission can edit protected pages
1185 if( $action=='edit' && $user->isAllowed( 'editprotected' ) ) {
1186 //Users with 'editprotected' permission cannot edit protected pages
1187 //with cascading option turned on.
1188 if($this->mCascadeRestriction) {
1189 $errors[] = array( 'protectedpagetext', $right );
1190 } else {
1191 //Nothing, user can edit!
1192 }
1193 } else {
1194 $errors[] = array( 'protectedpagetext', $right );
1195 }
1196 }
1197 }
1198
1199 if ($action == 'protect') {
1200 if ($this->getUserPermissionsErrors('edit', $user) != array()) {
1201 $errors[] = array( 'protect-cantedit' ); // If they can't edit, they shouldn't protect.
1202 }
1203 }
1204
1205 if ($action == 'create') {
1206 $title_protection = $this->getTitleProtection();
1207
1208 if (is_array($title_protection)) {
1209 extract($title_protection);
1210
1211 if ($pt_create_perm == 'sysop')
1212 $pt_create_perm = 'protect';
1213
1214 if ($pt_create_perm == '' || !$user->isAllowed($pt_create_perm)) {
1215 $errors[] = array ( 'titleprotected', User::whoIs($pt_user), $pt_reason );
1216 }
1217 }
1218
1219 if( ( $this->isTalkPage() && !$user->isAllowed( 'createtalk' ) ) ||
1220 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage' ) ) ) {
1221 $errors[] = $user->isAnon() ? array ('nocreatetext') : array ('nocreate-loggedin');
1222 }
1223 } elseif( $action == 'move' && !( $this->isMovable() && $user->isAllowed( 'move' ) ) ) {
1224 $errors[] = $user->isAnon() ? array ( 'movenologintext' ) : array ('movenotallowed');
1225 } elseif ( !$user->isAllowed( $action ) ) {
1226 $return = null;
1227 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
1228 User::getGroupsWithPermission( $action ) );
1229 if ( $groups ) {
1230 $return = array( 'badaccess-groups',
1231 array(
1232 implode( ', ', $groups ),
1233 count( $groups ) ) );
1234 }
1235 else {
1236 $return = array( "badaccess-group0" );
1237 }
1238 $errors[] = $return;
1239 }
1240
1241 wfProfileOut( __METHOD__ );
1242 return $errors;
1243 }
1244
1245 /**
1246 * Is this title subject to title protection?
1247 * @return \type{\mixed} An associative array representing any existent title
1248 * protection, or false if there's none.
1249 */
1250 private function getTitleProtection() {
1251 // Can't protect pages in special namespaces
1252 if ( $this->getNamespace() < 0 ) {
1253 return false;
1254 }
1255
1256 $dbr = wfGetDB( DB_SLAVE );
1257 $res = $dbr->select( 'protected_titles', '*',
1258 array ('pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey()) );
1259
1260 if ($row = $dbr->fetchRow( $res )) {
1261 return $row;
1262 } else {
1263 return false;
1264 }
1265 }
1266
1267 /**
1268 * Update the title protection status
1269 * @param $create_perm \type{\string} Permission required for creation
1270 * @param $reason \type{\string} Reason for protection
1271 * @param $expiry \type{\string} Expiry timestamp
1272 */
1273 public function updateTitleProtection( $create_perm, $reason, $expiry ) {
1274 global $wgUser,$wgContLang;
1275
1276 if ($create_perm == implode(',',$this->getRestrictions('create'))
1277 && $expiry == $this->mRestrictionsExpiry['create']) {
1278 // No change
1279 return true;
1280 }
1281
1282 list ($namespace, $title) = array( $this->getNamespace(), $this->getDBkey() );
1283
1284 $dbw = wfGetDB( DB_MASTER );
1285
1286 $encodedExpiry = Block::encodeExpiry($expiry, $dbw );
1287
1288 $expiry_description = '';
1289 if ( $encodedExpiry != 'infinity' ) {
1290 $expiry_description = ' (' . wfMsgForContent( 'protect-expiring', $wgContLang->timeanddate( $expiry ) ).')';
1291 }
1292 else {
1293 $expiry_description .= ' (' . wfMsgForContent( 'protect-expiry-indefinite' ).')';
1294 }
1295
1296 # Update protection table
1297 if ($create_perm != '' ) {
1298 $dbw->replace( 'protected_titles', array(array('pt_namespace', 'pt_title')),
1299 array( 'pt_namespace' => $namespace, 'pt_title' => $title
1300 , 'pt_create_perm' => $create_perm
1301 , 'pt_timestamp' => Block::encodeExpiry(wfTimestampNow(), $dbw)
1302 , 'pt_expiry' => $encodedExpiry
1303 , 'pt_user' => $wgUser->getId(), 'pt_reason' => $reason ), __METHOD__ );
1304 } else {
1305 $dbw->delete( 'protected_titles', array( 'pt_namespace' => $namespace,
1306 'pt_title' => $title ), __METHOD__ );
1307 }
1308 # Update the protection log
1309 $log = new LogPage( 'protect' );
1310
1311 if( $create_perm ) {
1312 $params = array("[create=$create_perm] $expiry_description",'');
1313 $log->addEntry( $this->mRestrictions['create'] ? 'modify' : 'protect', $this, trim( $reason ), $params );
1314 } else {
1315 $log->addEntry( 'unprotect', $this, $reason );
1316 }
1317
1318 return true;
1319 }
1320
1321 /**
1322 * Remove any title protection due to page existing
1323 */
1324 public function deleteTitleProtection() {
1325 $dbw = wfGetDB( DB_MASTER );
1326
1327 $dbw->delete( 'protected_titles',
1328 array ('pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey()), __METHOD__ );
1329 }
1330
1331 /**
1332 * Can $wgUser edit this page?
1333 * @return \type{\bool} TRUE or FALSE
1334 * @deprecated use userCan('edit')
1335 */
1336 public function userCanEdit( $doExpensiveQueries = true ) {
1337 return $this->userCan( 'edit', $doExpensiveQueries );
1338 }
1339
1340 /**
1341 * Can $wgUser create this page?
1342 * @return \type{\bool} TRUE or FALSE
1343 * @deprecated use userCan('create')
1344 */
1345 public function userCanCreate( $doExpensiveQueries = true ) {
1346 return $this->userCan( 'create', $doExpensiveQueries );
1347 }
1348
1349 /**
1350 * Can $wgUser move this page?
1351 * @return \type{\bool} TRUE or FALSE
1352 * @deprecated use userCan('move')
1353 */
1354 public function userCanMove( $doExpensiveQueries = true ) {
1355 return $this->userCan( 'move', $doExpensiveQueries );
1356 }
1357
1358 /**
1359 * Would anybody with sufficient privileges be able to move this page?
1360 * Some pages just aren't movable.
1361 *
1362 * @return \type{\bool} TRUE or FALSE
1363 */
1364 public function isMovable() {
1365 return MWNamespace::isMovable( $this->getNamespace() )
1366 && $this->getInterwiki() == '';
1367 }
1368
1369 /**
1370 * Can $wgUser read this page?
1371 * @return \type{\bool} TRUE or FALSE
1372 * @todo fold these checks into userCan()
1373 */
1374 public function userCanRead() {
1375 global $wgUser, $wgGroupPermissions;
1376
1377 $result = null;
1378 wfRunHooks( 'userCan', array( &$this, &$wgUser, 'read', &$result ) );
1379 if ( $result !== null ) {
1380 return $result;
1381 }
1382
1383 # Shortcut for public wikis, allows skipping quite a bit of code
1384 if ($wgGroupPermissions['*']['read'])
1385 return true;
1386
1387 if( $wgUser->isAllowed( 'read' ) ) {
1388 return true;
1389 } else {
1390 global $wgWhitelistRead;
1391
1392 /**
1393 * Always grant access to the login page.
1394 * Even anons need to be able to log in.
1395 */
1396 if( $this->isSpecial( 'Userlogin' ) || $this->isSpecial( 'Resetpass' ) ) {
1397 return true;
1398 }
1399
1400 /**
1401 * Bail out if there isn't whitelist
1402 */
1403 if( !is_array($wgWhitelistRead) ) {
1404 return false;
1405 }
1406
1407 /**
1408 * Check for explicit whitelisting
1409 */
1410 $name = $this->getPrefixedText();
1411 $dbName = $this->getPrefixedDBKey();
1412 // Check with and without underscores
1413 if( in_array($name,$wgWhitelistRead,true) || in_array($dbName,$wgWhitelistRead,true) )
1414 return true;
1415
1416 /**
1417 * Old settings might have the title prefixed with
1418 * a colon for main-namespace pages
1419 */
1420 if( $this->getNamespace() == NS_MAIN ) {
1421 if( in_array( ':' . $name, $wgWhitelistRead ) )
1422 return true;
1423 }
1424
1425 /**
1426 * If it's a special page, ditch the subpage bit
1427 * and check again
1428 */
1429 if( $this->getNamespace() == NS_SPECIAL ) {
1430 $name = $this->getDBkey();
1431 list( $name, /* $subpage */) = SpecialPage::resolveAliasWithSubpage( $name );
1432 if ( $name === false ) {
1433 # Invalid special page, but we show standard login required message
1434 return false;
1435 }
1436
1437 $pure = SpecialPage::getTitleFor( $name )->getPrefixedText();
1438 if( in_array( $pure, $wgWhitelistRead, true ) )
1439 return true;
1440 }
1441
1442 }
1443 return false;
1444 }
1445
1446 /**
1447 * Is this a talk page of some sort?
1448 * @return \type{\bool} TRUE or FALSE
1449 */
1450 public function isTalkPage() {
1451 return MWNamespace::isTalk( $this->getNamespace() );
1452 }
1453
1454 /**
1455 * Is this a subpage?
1456 * @return \type{\bool} TRUE or FALSE
1457 */
1458 public function isSubpage() {
1459 return MWNamespace::hasSubpages( $this->mNamespace )
1460 ? strpos( $this->getText(), '/' ) !== false
1461 : false;
1462 }
1463
1464 /**
1465 * Does this have subpages? (Warning, usually requires an extra DB query.)
1466 * @return \type{\bool} TRUE or FALSE
1467 */
1468 public function hasSubpages() {
1469 if( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
1470 # Duh
1471 return false;
1472 }
1473
1474 # We dynamically add a member variable for the purpose of this method
1475 # alone to cache the result. There's no point in having it hanging
1476 # around uninitialized in every Title object; therefore we only add it
1477 # if needed and don't declare it statically.
1478 if( isset( $this->mHasSubpages ) ) {
1479 return $this->mHasSubpages;
1480 }
1481
1482 $db = wfGetDB( DB_SLAVE );
1483 return $this->mHasSubpages = (bool)$db->selectField( 'page', '1',
1484 "page_namespace = {$this->mNamespace} AND page_title LIKE '"
1485 . $db->escapeLike( $this->mDbkeyform ) . "/%'",
1486 __METHOD__
1487 );
1488 }
1489
1490 /**
1491 * Could this page contain custom CSS or JavaScript, based
1492 * on the title?
1493 *
1494 * @return \type{\bool} TRUE or FALSE
1495 */
1496 public function isCssOrJsPage() {
1497 return $this->mNamespace == NS_MEDIAWIKI
1498 && preg_match( '!\.(?:css|js)$!u', $this->mTextform ) > 0;
1499 }
1500
1501 /**
1502 * Is this a .css or .js subpage of a user page?
1503 * @return \type{\bool} TRUE or FALSE
1504 */
1505 public function isCssJsSubpage() {
1506 return ( NS_USER == $this->mNamespace and preg_match("/\\/.*\\.(?:css|js)$/", $this->mTextform ) );
1507 }
1508 /**
1509 * Is this a *valid* .css or .js subpage of a user page?
1510 * Check that the corresponding skin exists
1511 * @return \type{\bool} TRUE or FALSE
1512 */
1513 public function isValidCssJsSubpage() {
1514 if ( $this->isCssJsSubpage() ) {
1515 $skinNames = Skin::getSkinNames();
1516 return array_key_exists( $this->getSkinFromCssJsSubpage(), $skinNames );
1517 } else {
1518 return false;
1519 }
1520 }
1521 /**
1522 * Trim down a .css or .js subpage title to get the corresponding skin name
1523 */
1524 public function getSkinFromCssJsSubpage() {
1525 $subpage = explode( '/', $this->mTextform );
1526 $subpage = $subpage[ count( $subpage ) - 1 ];
1527 return( str_replace( array( '.css', '.js' ), array( '', '' ), $subpage ) );
1528 }
1529 /**
1530 * Is this a .css subpage of a user page?
1531 * @return \type{\bool} TRUE or FALSE
1532 */
1533 public function isCssSubpage() {
1534 return ( NS_USER == $this->mNamespace && preg_match("/\\/.*\\.css$/", $this->mTextform ) );
1535 }
1536 /**
1537 * Is this a .js subpage of a user page?
1538 * @return \type{\bool} TRUE or FALSE
1539 */
1540 public function isJsSubpage() {
1541 return ( NS_USER == $this->mNamespace && preg_match("/\\/.*\\.js$/", $this->mTextform ) );
1542 }
1543 /**
1544 * Protect css/js subpages of user pages: can $wgUser edit
1545 * this page?
1546 *
1547 * @return \type{\bool} TRUE or FALSE
1548 * @todo XXX: this might be better using restrictions
1549 */
1550 public function userCanEditCssJsSubpage() {
1551 global $wgUser;
1552 return ( $wgUser->isAllowed('editusercssjs') || preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform) );
1553 }
1554
1555 /**
1556 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
1557 *
1558 * @return \type{\bool} If the page is subject to cascading restrictions.
1559 */
1560 public function isCascadeProtected() {
1561 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
1562 return ( $sources > 0 );
1563 }
1564
1565 /**
1566 * Cascading protection: Get the source of any cascading restrictions on this page.
1567 *
1568 * @param $get_pages \type{\bool} Whether or not to retrieve the actual pages that the restrictions have come from.
1569 * @return \type{\arrayof{mixed title array, restriction array}} Array of the Title objects of the pages from
1570 * which cascading restrictions have come, false for none, or true if such restrictions exist, but $get_pages was not set.
1571 * The restriction array is an array of each type, each of which contains an array of unique groups.
1572 */
1573 public function getCascadeProtectionSources( $get_pages = true ) {
1574 global $wgRestrictionTypes;
1575
1576 # Define our dimension of restrictions types
1577 $pagerestrictions = array();
1578 foreach( $wgRestrictionTypes as $action )
1579 $pagerestrictions[$action] = array();
1580
1581 if ( isset( $this->mCascadeSources ) && $get_pages ) {
1582 return array( $this->mCascadeSources, $this->mCascadingRestrictions );
1583 } else if ( isset( $this->mHasCascadingRestrictions ) && !$get_pages ) {
1584 return array( $this->mHasCascadingRestrictions, $pagerestrictions );
1585 }
1586
1587 wfProfileIn( __METHOD__ );
1588
1589 $dbr = wfGetDb( DB_SLAVE );
1590
1591 if ( $this->getNamespace() == NS_IMAGE ) {
1592 $tables = array ('imagelinks', 'page_restrictions');
1593 $where_clauses = array(
1594 'il_to' => $this->getDBkey(),
1595 'il_from=pr_page',
1596 'pr_cascade' => 1 );
1597 } else {
1598 $tables = array ('templatelinks', 'page_restrictions');
1599 $where_clauses = array(
1600 'tl_namespace' => $this->getNamespace(),
1601 'tl_title' => $this->getDBkey(),
1602 'tl_from=pr_page',
1603 'pr_cascade' => 1 );
1604 }
1605
1606 if ( $get_pages ) {
1607 $cols = array('pr_page', 'page_namespace', 'page_title', 'pr_expiry', 'pr_type', 'pr_level' );
1608 $where_clauses[] = 'page_id=pr_page';
1609 $tables[] = 'page';
1610 } else {
1611 $cols = array( 'pr_expiry' );
1612 }
1613
1614 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__ );
1615
1616 $sources = $get_pages ? array() : false;
1617 $now = wfTimestampNow();
1618 $purgeExpired = false;
1619
1620 foreach( $res as $row ) {
1621 $expiry = Block::decodeExpiry( $row->pr_expiry );
1622 if( $expiry > $now ) {
1623 if ($get_pages) {
1624 $page_id = $row->pr_page;
1625 $page_ns = $row->page_namespace;
1626 $page_title = $row->page_title;
1627 $sources[$page_id] = Title::makeTitle($page_ns, $page_title);
1628 # Add groups needed for each restriction type if its not already there
1629 # Make sure this restriction type still exists
1630 if ( isset($pagerestrictions[$row->pr_type]) && !in_array($row->pr_level, $pagerestrictions[$row->pr_type]) ) {
1631 $pagerestrictions[$row->pr_type][]=$row->pr_level;
1632 }
1633 } else {
1634 $sources = true;
1635 }
1636 } else {
1637 // Trigger lazy purge of expired restrictions from the db
1638 $purgeExpired = true;
1639 }
1640 }
1641 if( $purgeExpired ) {
1642 Title::purgeExpiredRestrictions();
1643 }
1644
1645 wfProfileOut( __METHOD__ );
1646
1647 if ( $get_pages ) {
1648 $this->mCascadeSources = $sources;
1649 $this->mCascadingRestrictions = $pagerestrictions;
1650 } else {
1651 $this->mHasCascadingRestrictions = $sources;
1652 }
1653 return array( $sources, $pagerestrictions );
1654 }
1655
1656 function areRestrictionsCascading() {
1657 if (!$this->mRestrictionsLoaded) {
1658 $this->loadRestrictions();
1659 }
1660
1661 return $this->mCascadeRestriction;
1662 }
1663
1664 /**
1665 * Loads a string into mRestrictions array
1666 * @param $res \type{Resource} restrictions as an SQL result.
1667 */
1668 private function loadRestrictionsFromRow( $res, $oldFashionedRestrictions = NULL ) {
1669 global $wgRestrictionTypes;
1670 $dbr = wfGetDB( DB_SLAVE );
1671
1672 foreach( $wgRestrictionTypes as $type ){
1673 $this->mRestrictions[$type] = array();
1674 $this->mRestrictionsExpiry[$type] = Block::decodeExpiry('');
1675 }
1676
1677 $this->mCascadeRestriction = false;
1678
1679 # Backwards-compatibility: also load the restrictions from the page record (old format).
1680
1681 if ( $oldFashionedRestrictions === NULL ) {
1682 $oldFashionedRestrictions = $dbr->selectField( 'page', 'page_restrictions',
1683 array( 'page_id' => $this->getArticleId() ), __METHOD__ );
1684 }
1685
1686 if ($oldFashionedRestrictions != '') {
1687
1688 foreach( explode( ':', trim( $oldFashionedRestrictions ) ) as $restrict ) {
1689 $temp = explode( '=', trim( $restrict ) );
1690 if(count($temp) == 1) {
1691 // old old format should be treated as edit/move restriction
1692 $this->mRestrictions['edit'] = explode( ',', trim( $temp[0] ) );
1693 $this->mRestrictions['move'] = explode( ',', trim( $temp[0] ) );
1694 } else {
1695 $this->mRestrictions[$temp[0]] = explode( ',', trim( $temp[1] ) );
1696 }
1697 }
1698
1699 $this->mOldRestrictions = true;
1700
1701 }
1702
1703 if( $dbr->numRows( $res ) ) {
1704 # Current system - load second to make them override.
1705 $now = wfTimestampNow();
1706 $purgeExpired = false;
1707
1708 foreach( $res as $row ) {
1709 # Cycle through all the restrictions.
1710
1711 // Don't take care of restrictions types that aren't in $wgRestrictionTypes
1712 if( !in_array( $row->pr_type, $wgRestrictionTypes ) )
1713 continue;
1714
1715 // This code should be refactored, now that it's being used more generally,
1716 // But I don't really see any harm in leaving it in Block for now -werdna
1717 $expiry = Block::decodeExpiry( $row->pr_expiry );
1718
1719 // Only apply the restrictions if they haven't expired!
1720 if ( !$expiry || $expiry > $now ) {
1721 $this->mRestrictionsExpiry[$row->pr_type] = $expiry;
1722 $this->mRestrictions[$row->pr_type] = explode( ',', trim( $row->pr_level ) );
1723
1724 $this->mCascadeRestriction |= $row->pr_cascade;
1725 } else {
1726 // Trigger a lazy purge of expired restrictions
1727 $purgeExpired = true;
1728 }
1729 }
1730
1731 if( $purgeExpired ) {
1732 Title::purgeExpiredRestrictions();
1733 }
1734 }
1735
1736 $this->mRestrictionsLoaded = true;
1737 }
1738
1739 /**
1740 * Load restrictions from the page_restrictions table
1741 */
1742 public function loadRestrictions( $oldFashionedRestrictions = NULL ) {
1743 if( !$this->mRestrictionsLoaded ) {
1744 if ($this->exists()) {
1745 $dbr = wfGetDB( DB_SLAVE );
1746
1747 $res = $dbr->select( 'page_restrictions', '*',
1748 array ( 'pr_page' => $this->getArticleId() ), __METHOD__ );
1749
1750 $this->loadRestrictionsFromRow( $res, $oldFashionedRestrictions );
1751 } else {
1752 $title_protection = $this->getTitleProtection();
1753
1754 if (is_array($title_protection)) {
1755 extract($title_protection);
1756
1757 $now = wfTimestampNow();
1758 $expiry = Block::decodeExpiry($pt_expiry);
1759
1760 if (!$expiry || $expiry > $now) {
1761 // Apply the restrictions
1762 $this->mRestrictionsExpiry['create'] = $expiry;
1763 $this->mRestrictions['create'] = explode(',', trim($pt_create_perm) );
1764 } else { // Get rid of the old restrictions
1765 Title::purgeExpiredRestrictions();
1766 }
1767 } else {
1768 $this->mRestrictionsExpiry['create'] = Block::decodeExpiry('');
1769 }
1770 $this->mRestrictionsLoaded = true;
1771 }
1772 }
1773 }
1774
1775 /**
1776 * Purge expired restrictions from the page_restrictions table
1777 */
1778 static function purgeExpiredRestrictions() {
1779 $dbw = wfGetDB( DB_MASTER );
1780 $dbw->delete( 'page_restrictions',
1781 array( 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
1782 __METHOD__ );
1783
1784 $dbw->delete( 'protected_titles',
1785 array( 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
1786 __METHOD__ );
1787 }
1788
1789 /**
1790 * Accessor/initialisation for mRestrictions
1791 *
1792 * @param $action \type{\string} action that permission needs to be checked for
1793 * @return \type{\arrayof{\string}} the array of groups allowed to edit this article
1794 */
1795 public function getRestrictions( $action ) {
1796 if( !$this->mRestrictionsLoaded ) {
1797 $this->loadRestrictions();
1798 }
1799 return isset( $this->mRestrictions[$action] )
1800 ? $this->mRestrictions[$action]
1801 : array();
1802 }
1803
1804 /**
1805 * Get the expiry time for the restriction against a given action
1806 * @return 14-char timestamp, or 'infinity' if the page is protected forever
1807 * or not protected at all, or false if the action is not recognised.
1808 */
1809 public function getRestrictionExpiry( $action ) {
1810 if( !$this->mRestrictionsLoaded ) {
1811 $this->loadRestrictions();
1812 }
1813 return isset( $this->mRestrictionsExpiry[$action] ) ? $this->mRestrictionsExpiry[$action] : false;
1814 }
1815
1816 /**
1817 * Is there a version of this page in the deletion archive?
1818 * @return \type{\int} the number of archived revisions
1819 */
1820 public function isDeleted() {
1821 $fname = 'Title::isDeleted';
1822 if ( $this->getNamespace() < 0 ) {
1823 $n = 0;
1824 } else {
1825 $dbr = wfGetDB( DB_SLAVE );
1826 $n = $dbr->selectField( 'archive', 'COUNT(*)', array( 'ar_namespace' => $this->getNamespace(),
1827 'ar_title' => $this->getDBkey() ), $fname );
1828 if( $this->getNamespace() == NS_IMAGE ) {
1829 $n += $dbr->selectField( 'filearchive', 'COUNT(*)',
1830 array( 'fa_name' => $this->getDBkey() ), $fname );
1831 }
1832 }
1833 return (int)$n;
1834 }
1835
1836 /**
1837 * Get the article ID for this Title from the link cache,
1838 * adding it if necessary
1839 * @param $flags \type{\int} a bit field; may be GAID_FOR_UPDATE to select
1840 * for update
1841 * @return \type{\int} the ID
1842 */
1843 public function getArticleID( $flags = 0 ) {
1844 $linkCache = LinkCache::singleton();
1845 if( $flags & GAID_FOR_UPDATE ) {
1846 $oldUpdate = $linkCache->forUpdate( true );
1847 $linkCache->clearLink( $this );
1848 $this->mArticleID = $linkCache->addLinkObj( $this );
1849 $linkCache->forUpdate( $oldUpdate );
1850 } else {
1851 if( -1 == $this->mArticleID ) {
1852 $this->mArticleID = $linkCache->addLinkObj( $this );
1853 }
1854 }
1855 return $this->mArticleID;
1856 }
1857
1858 /**
1859 * Is this an article that is a redirect page?
1860 * Uses link cache, adding it if necessary
1861 * @param $flags \type{\int} a bit field; may be GAID_FOR_UPDATE to select for update
1862 * @return \type{\bool}
1863 */
1864 public function isRedirect( $flags = 0 ) {
1865 if( !is_null($this->mRedirect) )
1866 return $this->mRedirect;
1867 # Zero for special pages.
1868 # Also, calling getArticleID() loads the field from cache!
1869 if( !$this->getArticleID($flags) || $this->getNamespace() == NS_SPECIAL ) {
1870 return false;
1871 }
1872 $linkCache = LinkCache::singleton();
1873 $this->mRedirect = (bool)$linkCache->getGoodLinkFieldObj( $this, 'redirect' );
1874
1875 return $this->mRedirect;
1876 }
1877
1878 /**
1879 * What is the length of this page?
1880 * Uses link cache, adding it if necessary
1881 * @param $flags \type{\int} a bit field; may be GAID_FOR_UPDATE to select for update
1882 * @return \type{\bool}
1883 */
1884 public function getLength( $flags = 0 ) {
1885 if( $this->mLength != -1 )
1886 return $this->mLength;
1887 # Zero for special pages.
1888 # Also, calling getArticleID() loads the field from cache!
1889 if( !$this->getArticleID($flags) || $this->getNamespace() == NS_SPECIAL ) {
1890 return 0;
1891 }
1892 $linkCache = LinkCache::singleton();
1893 $this->mLength = intval( $linkCache->getGoodLinkFieldObj( $this, 'length' ) );
1894
1895 return $this->mLength;
1896 }
1897
1898 /**
1899 * What is the page_latest field for this page?
1900 * @param $flags \type{\int} a bit field; may be GAID_FOR_UPDATE to select for update
1901 * @return \type{\int}
1902 */
1903 public function getLatestRevID( $flags = 0 ) {
1904 if( $this->mLatestID !== false )
1905 return $this->mLatestID;
1906
1907 $db = ($flags & GAID_FOR_UPDATE) ? wfGetDB(DB_MASTER) : wfGetDB(DB_SLAVE);
1908 $this->mLatestID = $db->selectField( 'page', 'page_latest',
1909 array( 'page_namespace' => $this->getNamespace(), 'page_title' => $this->getDBKey() ),
1910 __METHOD__ );
1911 return $this->mLatestID;
1912 }
1913
1914 /**
1915 * This clears some fields in this object, and clears any associated
1916 * keys in the "bad links" section of the link cache.
1917 *
1918 * - This is called from Article::insertNewArticle() to allow
1919 * loading of the new page_id. It's also called from
1920 * Article::doDeleteArticle()
1921 *
1922 * @param $newid \type{\int} the new Article ID
1923 */
1924 public function resetArticleID( $newid ) {
1925 $linkCache = LinkCache::singleton();
1926 $linkCache->clearBadLink( $this->getPrefixedDBkey() );
1927
1928 if ( 0 == $newid ) { $this->mArticleID = -1; }
1929 else { $this->mArticleID = $newid; }
1930 $this->mRestrictionsLoaded = false;
1931 $this->mRestrictions = array();
1932 }
1933
1934 /**
1935 * Updates page_touched for this page; called from LinksUpdate.php
1936 * @return \type{\bool} true if the update succeded
1937 */
1938 public function invalidateCache() {
1939 global $wgUseFileCache;
1940
1941 if ( wfReadOnly() ) {
1942 return;
1943 }
1944
1945 $dbw = wfGetDB( DB_MASTER );
1946 $success = $dbw->update( 'page',
1947 array( /* SET */
1948 'page_touched' => $dbw->timestamp()
1949 ), array( /* WHERE */
1950 'page_namespace' => $this->getNamespace() ,
1951 'page_title' => $this->getDBkey()
1952 ), 'Title::invalidateCache'
1953 );
1954
1955 if ($wgUseFileCache) {
1956 $cache = new HTMLFileCache($this);
1957 @unlink($cache->fileCacheName());
1958 }
1959
1960 return $success;
1961 }
1962
1963 /**
1964 * Prefix some arbitrary text with the namespace or interwiki prefix
1965 * of this object
1966 *
1967 * @param $name \type{\string} the text
1968 * @return \type{\string} the prefixed text
1969 * @private
1970 */
1971 /* private */ function prefix( $name ) {
1972 $p = '';
1973 if ( '' != $this->mInterwiki ) {
1974 $p = $this->mInterwiki . ':';
1975 }
1976 if ( 0 != $this->mNamespace ) {
1977 $p .= $this->getNsText() . ':';
1978 }
1979 return $p . $name;
1980 }
1981
1982 /**
1983 * Secure and split - main initialisation function for this object
1984 *
1985 * Assumes that mDbkeyform has been set, and is urldecoded
1986 * and uses underscores, but not otherwise munged. This function
1987 * removes illegal characters, splits off the interwiki and
1988 * namespace prefixes, sets the other forms, and canonicalizes
1989 * everything.
1990 * @return \type{\bool} true on success
1991 */
1992 private function secureAndSplit() {
1993 global $wgContLang, $wgLocalInterwiki, $wgCapitalLinks;
1994
1995 # Initialisation
1996 static $rxTc = false;
1997 if( !$rxTc ) {
1998 # Matching titles will be held as illegal.
1999 $rxTc = '/' .
2000 # Any character not allowed is forbidden...
2001 '[^' . Title::legalChars() . ']' .
2002 # URL percent encoding sequences interfere with the ability
2003 # to round-trip titles -- you can't link to them consistently.
2004 '|%[0-9A-Fa-f]{2}' .
2005 # XML/HTML character references produce similar issues.
2006 '|&[A-Za-z0-9\x80-\xff]+;' .
2007 '|&#[0-9]+;' .
2008 '|&#x[0-9A-Fa-f]+;' .
2009 '/S';
2010 }
2011
2012 $this->mInterwiki = $this->mFragment = '';
2013 $this->mNamespace = $this->mDefaultNamespace; # Usually NS_MAIN
2014
2015 $dbkey = $this->mDbkeyform;
2016
2017 # Strip Unicode bidi override characters.
2018 # Sometimes they slip into cut-n-pasted page titles, where the
2019 # override chars get included in list displays.
2020 $dbkey = str_replace( "\xE2\x80\x8E", '', $dbkey ); // 200E LEFT-TO-RIGHT MARK
2021 $dbkey = str_replace( "\xE2\x80\x8F", '', $dbkey ); // 200F RIGHT-TO-LEFT MARK
2022
2023 # Clean up whitespace
2024 #
2025 $dbkey = preg_replace( '/[ _]+/', '_', $dbkey );
2026 $dbkey = trim( $dbkey, '_' );
2027
2028 if ( '' == $dbkey ) {
2029 return false;
2030 }
2031
2032 if( false !== strpos( $dbkey, UTF8_REPLACEMENT ) ) {
2033 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
2034 return false;
2035 }
2036
2037 $this->mDbkeyform = $dbkey;
2038
2039 # Initial colon indicates main namespace rather than specified default
2040 # but should not create invalid {ns,title} pairs such as {0,Project:Foo}
2041 if ( ':' == $dbkey{0} ) {
2042 $this->mNamespace = NS_MAIN;
2043 $dbkey = substr( $dbkey, 1 ); # remove the colon but continue processing
2044 $dbkey = trim( $dbkey, '_' ); # remove any subsequent whitespace
2045 }
2046
2047 # Namespace or interwiki prefix
2048 $firstPass = true;
2049 do {
2050 $m = array();
2051 if ( preg_match( "/^(.+?)_*:_*(.*)$/S", $dbkey, $m ) ) {
2052 $p = $m[1];
2053 if ( $ns = $wgContLang->getNsIndex( $p )) {
2054 # Ordinary namespace
2055 $dbkey = $m[2];
2056 $this->mNamespace = $ns;
2057 } elseif( Interwiki::fetch( $p ) ) {
2058 if( !$firstPass ) {
2059 # Can't make a local interwiki link to an interwiki link.
2060 # That's just crazy!
2061 return false;
2062 }
2063
2064 # Interwiki link
2065 $dbkey = $m[2];
2066 $this->mInterwiki = $wgContLang->lc( $p );
2067
2068 # Redundant interwiki prefix to the local wiki
2069 if ( 0 == strcasecmp( $this->mInterwiki, $wgLocalInterwiki ) ) {
2070 if( $dbkey == '' ) {
2071 # Can't have an empty self-link
2072 return false;
2073 }
2074 $this->mInterwiki = '';
2075 $firstPass = false;
2076 # Do another namespace split...
2077 continue;
2078 }
2079
2080 # If there's an initial colon after the interwiki, that also
2081 # resets the default namespace
2082 if ( $dbkey !== '' && $dbkey[0] == ':' ) {
2083 $this->mNamespace = NS_MAIN;
2084 $dbkey = substr( $dbkey, 1 );
2085 }
2086 }
2087 # If there's no recognized interwiki or namespace,
2088 # then let the colon expression be part of the title.
2089 }
2090 break;
2091 } while( true );
2092
2093 # We already know that some pages won't be in the database!
2094 #
2095 if ( '' != $this->mInterwiki || NS_SPECIAL == $this->mNamespace ) {
2096 $this->mArticleID = 0;
2097 }
2098 $fragment = strstr( $dbkey, '#' );
2099 if ( false !== $fragment ) {
2100 $this->setFragment( $fragment );
2101 $dbkey = substr( $dbkey, 0, strlen( $dbkey ) - strlen( $fragment ) );
2102 # remove whitespace again: prevents "Foo_bar_#"
2103 # becoming "Foo_bar_"
2104 $dbkey = preg_replace( '/_*$/', '', $dbkey );
2105 }
2106
2107 # Reject illegal characters.
2108 #
2109 if( preg_match( $rxTc, $dbkey ) ) {
2110 return false;
2111 }
2112
2113 /**
2114 * Pages with "/./" or "/../" appearing in the URLs will often be un-
2115 * reachable due to the way web browsers deal with 'relative' URLs.
2116 * Also, they conflict with subpage syntax. Forbid them explicitly.
2117 */
2118 if ( strpos( $dbkey, '.' ) !== false &&
2119 ( $dbkey === '.' || $dbkey === '..' ||
2120 strpos( $dbkey, './' ) === 0 ||
2121 strpos( $dbkey, '../' ) === 0 ||
2122 strpos( $dbkey, '/./' ) !== false ||
2123 strpos( $dbkey, '/../' ) !== false ||
2124 substr( $dbkey, -2 ) == '/.' ||
2125 substr( $dbkey, -3 ) == '/..' ) )
2126 {
2127 return false;
2128 }
2129
2130 /**
2131 * Magic tilde sequences? Nu-uh!
2132 */
2133 if( strpos( $dbkey, '~~~' ) !== false ) {
2134 return false;
2135 }
2136
2137 /**
2138 * Limit the size of titles to 255 bytes.
2139 * This is typically the size of the underlying database field.
2140 * We make an exception for special pages, which don't need to be stored
2141 * in the database, and may edge over 255 bytes due to subpage syntax
2142 * for long titles, e.g. [[Special:Block/Long name]]
2143 */
2144 if ( ( $this->mNamespace != NS_SPECIAL && strlen( $dbkey ) > 255 ) ||
2145 strlen( $dbkey ) > 512 )
2146 {
2147 return false;
2148 }
2149
2150 /**
2151 * Normally, all wiki links are forced to have
2152 * an initial capital letter so [[foo]] and [[Foo]]
2153 * point to the same place.
2154 *
2155 * Don't force it for interwikis, since the other
2156 * site might be case-sensitive.
2157 */
2158 $this->mUserCaseDBKey = $dbkey;
2159 if( $wgCapitalLinks && $this->mInterwiki == '') {
2160 $dbkey = $wgContLang->ucfirst( $dbkey );
2161 }
2162
2163 /**
2164 * Can't make a link to a namespace alone...
2165 * "empty" local links can only be self-links
2166 * with a fragment identifier.
2167 */
2168 if( $dbkey == '' &&
2169 $this->mInterwiki == '' &&
2170 $this->mNamespace != NS_MAIN ) {
2171 return false;
2172 }
2173 // Allow IPv6 usernames to start with '::' by canonicalizing IPv6 titles.
2174 // IP names are not allowed for accounts, and can only be referring to
2175 // edits from the IP. Given '::' abbreviations and caps/lowercaps,
2176 // there are numerous ways to present the same IP. Having sp:contribs scan
2177 // them all is silly and having some show the edits and others not is
2178 // inconsistent. Same for talk/userpages. Keep them normalized instead.
2179 $dbkey = ($this->mNamespace == NS_USER || $this->mNamespace == NS_USER_TALK) ?
2180 IP::sanitizeIP( $dbkey ) : $dbkey;
2181 // Any remaining initial :s are illegal.
2182 if ( $dbkey !== '' && ':' == $dbkey{0} ) {
2183 return false;
2184 }
2185
2186 # Fill fields
2187 $this->mDbkeyform = $dbkey;
2188 $this->mUrlform = wfUrlencode( $dbkey );
2189
2190 $this->mTextform = str_replace( '_', ' ', $dbkey );
2191
2192 return true;
2193 }
2194
2195 /**
2196 * Set the fragment for this title. Removes the first character from the
2197 * specified fragment before setting, so it assumes you're passing it with
2198 * an initial "#".
2199 *
2200 * Deprecated for public use, use Title::makeTitle() with fragment parameter.
2201 * Still in active use privately.
2202 *
2203 * @param $fragment \type{\string} text
2204 */
2205 public function setFragment( $fragment ) {
2206 $this->mFragment = str_replace( '_', ' ', substr( $fragment, 1 ) );
2207 }
2208
2209 /**
2210 * Get a Title object associated with the talk page of this article
2211 * @return \type{Title} the object for the talk page
2212 */
2213 public function getTalkPage() {
2214 return Title::makeTitle( MWNamespace::getTalk( $this->getNamespace() ), $this->getDBkey() );
2215 }
2216
2217 /**
2218 * Get a title object associated with the subject page of this
2219 * talk page
2220 *
2221 * @return \type{Title} the object for the subject page
2222 */
2223 public function getSubjectPage() {
2224 return Title::makeTitle( MWNamespace::getSubject( $this->getNamespace() ), $this->getDBkey() );
2225 }
2226
2227 /**
2228 * Get an array of Title objects linking to this Title
2229 * Also stores the IDs in the link cache.
2230 *
2231 * WARNING: do not use this function on arbitrary user-supplied titles!
2232 * On heavily-used templates it will max out the memory.
2233 *
2234 * @param $options \type{\string} may be FOR UPDATE
2235 * @return \type{\arrayof{Title}} the Title objects linking here
2236 */
2237 public function getLinksTo( $options = '', $table = 'pagelinks', $prefix = 'pl' ) {
2238 $linkCache = LinkCache::singleton();
2239
2240 if ( $options ) {
2241 $db = wfGetDB( DB_MASTER );
2242 } else {
2243 $db = wfGetDB( DB_SLAVE );
2244 }
2245
2246 $res = $db->select( array( 'page', $table ),
2247 array( 'page_namespace', 'page_title', 'page_id', 'page_len', 'page_is_redirect' ),
2248 array(
2249 "{$prefix}_from=page_id",
2250 "{$prefix}_namespace" => $this->getNamespace(),
2251 "{$prefix}_title" => $this->getDBkey() ),
2252 __METHOD__,
2253 $options );
2254
2255 $retVal = array();
2256 if ( $db->numRows( $res ) ) {
2257 foreach( $res as $row ) {
2258 if ( $titleObj = Title::makeTitle( $row->page_namespace, $row->page_title ) ) {
2259 $linkCache->addGoodLinkObj( $row->page_id, $titleObj, $row->page_len, $row->page_is_redirect );
2260 $retVal[] = $titleObj;
2261 }
2262 }
2263 }
2264 $db->freeResult( $res );
2265 return $retVal;
2266 }
2267
2268 /**
2269 * Get an array of Title objects using this Title as a template
2270 * Also stores the IDs in the link cache.
2271 *
2272 * WARNING: do not use this function on arbitrary user-supplied titles!
2273 * On heavily-used templates it will max out the memory.
2274 *
2275 * @param $options \type{\string} may be FOR UPDATE
2276 * @return \type{\arrayof{Title}} the Title objects linking here
2277 */
2278 public function getTemplateLinksTo( $options = '' ) {
2279 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
2280 }
2281
2282 /**
2283 * Get an array of Title objects referring to non-existent articles linked from this page
2284 *
2285 * @todo check if needed (used only in SpecialBrokenRedirects.php, and should use redirect table in this case)
2286 * @param $options \type{\string} may be FOR UPDATE
2287 * @return \type{\arrayof{Title}} the Title objects
2288 */
2289 public function getBrokenLinksFrom( $options = '' ) {
2290 if ( $this->getArticleId() == 0 ) {
2291 # All links from article ID 0 are false positives
2292 return array();
2293 }
2294
2295 if ( $options ) {
2296 $db = wfGetDB( DB_MASTER );
2297 } else {
2298 $db = wfGetDB( DB_SLAVE );
2299 }
2300
2301 $res = $db->safeQuery(
2302 "SELECT pl_namespace, pl_title
2303 FROM !
2304 LEFT JOIN !
2305 ON pl_namespace=page_namespace
2306 AND pl_title=page_title
2307 WHERE pl_from=?
2308 AND page_namespace IS NULL
2309 !",
2310 $db->tableName( 'pagelinks' ),
2311 $db->tableName( 'page' ),
2312 $this->getArticleId(),
2313 $options );
2314
2315 $retVal = array();
2316 if ( $db->numRows( $res ) ) {
2317 foreach( $res as $row ) {
2318 $retVal[] = Title::makeTitle( $row->pl_namespace, $row->pl_title );
2319 }
2320 }
2321 $db->freeResult( $res );
2322 return $retVal;
2323 }
2324
2325
2326 /**
2327 * Get a list of URLs to purge from the Squid cache when this
2328 * page changes
2329 *
2330 * @return \type{\arrayof{\string}} the URLs
2331 */
2332 public function getSquidURLs() {
2333 global $wgContLang;
2334
2335 $urls = array(
2336 $this->getInternalURL(),
2337 $this->getInternalURL( 'action=history' )
2338 );
2339
2340 // purge variant urls as well
2341 if($wgContLang->hasVariants()){
2342 $variants = $wgContLang->getVariants();
2343 foreach($variants as $vCode){
2344 if($vCode==$wgContLang->getCode()) continue; // we don't want default variant
2345 $urls[] = $this->getInternalURL('',$vCode);
2346 }
2347 }
2348
2349 return $urls;
2350 }
2351
2352 /**
2353 * Purge all applicable Squid URLs
2354 */
2355 public function purgeSquid() {
2356 global $wgUseSquid;
2357 if ( $wgUseSquid ) {
2358 $urls = $this->getSquidURLs();
2359 $u = new SquidUpdate( $urls );
2360 $u->doUpdate();
2361 }
2362 }
2363
2364 /**
2365 * Move this page without authentication
2366 * @param &$nt \type{Title} the new page Title
2367 */
2368 public function moveNoAuth( &$nt ) {
2369 return $this->moveTo( $nt, false );
2370 }
2371
2372 /**
2373 * Check whether a given move operation would be valid.
2374 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
2375 * @param &$nt \type{Title} the new title
2376 * @param $auth \type{\bool} indicates whether $wgUser's permissions
2377 * should be checked
2378 * @param $reason \type{\string} is the log summary of the move, used for spam checking
2379 * @return \type{\mixed} True on success, getUserPermissionsErrors()-like array on failure
2380 */
2381 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
2382 global $wgUser;
2383
2384 $errors = array();
2385 if( !$nt ) {
2386 // Normally we'd add this to $errors, but we'll get
2387 // lots of syntax errors if $nt is not an object
2388 return array(array('badtitletext'));
2389 }
2390 if( $this->equals( $nt ) ) {
2391 $errors[] = array('selfmove');
2392 }
2393 if( !$this->isMovable() || !$nt->isMovable() ) {
2394 $errors[] = array('immobile_namespace');
2395 }
2396
2397 $oldid = $this->getArticleID();
2398 $newid = $nt->getArticleID();
2399
2400 if ( strlen( $nt->getDBkey() ) < 1 ) {
2401 $errors[] = array('articleexists');
2402 }
2403 if ( ( '' == $this->getDBkey() ) ||
2404 ( !$oldid ) ||
2405 ( '' == $nt->getDBkey() ) ) {
2406 $errors[] = array('badarticleerror');
2407 }
2408
2409 // Image-specific checks
2410 if( $this->getNamespace() == NS_IMAGE ) {
2411 $file = wfLocalFile( $this );
2412 if( $file->exists() ) {
2413 if( $nt->getNamespace() != NS_IMAGE ) {
2414 $errors[] = array('imagenocrossnamespace');
2415 }
2416 if( $nt->getText() != wfStripIllegalFilenameChars( $nt->getText() ) ) {
2417 $errors[] = array('imageinvalidfilename');
2418 }
2419 if( !File::checkExtensionCompatibility( $file, $nt->getDbKey() ) ) {
2420 $errors[] = array('imagetypemismatch');
2421 }
2422 }
2423 }
2424
2425 if ( $auth ) {
2426 $errors = wfArrayMerge($errors,
2427 $this->getUserPermissionsErrors('move', $wgUser),
2428 $this->getUserPermissionsErrors('edit', $wgUser),
2429 $nt->getUserPermissionsErrors('move', $wgUser),
2430 $nt->getUserPermissionsErrors('edit', $wgUser));
2431
2432 # Root userpage ?
2433 if ( $nt->getNamespace() == NS_USER && !$nt->isSubpage() && !$wgUser->isAllowed('move-rootuserpages') ) {
2434 $errors[] = array('moverootuserpagesnotallowed');
2435 }
2436 }
2437
2438 $match = EditPage::matchSpamRegex( $reason );
2439 if( $match !== false ) {
2440 // This is kind of lame, won't display nice
2441 $errors[] = array('spamprotectiontext');
2442 }
2443
2444 $err = null;
2445 if( !wfRunHooks( 'AbortMove', array( $this, $nt, $wgUser, &$err, $reason ) ) ) {
2446 $errors[] = array('hookaborted', $err);
2447 }
2448
2449 # The move is allowed only if (1) the target doesn't exist, or
2450 # (2) the target is a redirect to the source, and has no history
2451 # (so we can undo bad moves right after they're done).
2452
2453 if ( 0 != $newid ) { # Target exists; check for validity
2454 if ( ! $this->isValidMoveTarget( $nt ) ) {
2455 $errors[] = array('articleexists');
2456 }
2457 } else {
2458 $tp = $nt->getTitleProtection();
2459 $right = ( $tp['pt_create_perm'] == 'sysop' ) ? 'protect' : $tp['pt_create_perm'];
2460 if ( $tp and !$wgUser->isAllowed( $right ) ) {
2461 $errors[] = array('cantmove-titleprotected');
2462 }
2463 }
2464 if(empty($errors))
2465 return true;
2466 return $errors;
2467 }
2468
2469 /**
2470 * Move a title to a new location
2471 * @param &$nt \type{Title} the new title
2472 * @param $auth \type{\bool} indicates whether $wgUser's permissions
2473 * should be checked
2474 * @param $reason \type{\string} The reason for the move
2475 * @param $createRedirect \type{\bool} Whether to create a redirect from the old title to the new title.
2476 * Ignored if the user doesn't have the suppressredirect right.
2477 * @return \type{\mixed} true on success, getUserPermissionsErrors()-like array on failure
2478 */
2479 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true ) {
2480 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
2481 if( is_array( $err ) ) {
2482 return $err;
2483 }
2484
2485 $pageid = $this->getArticleID();
2486 $protected = $this->isProtected();
2487 if( $nt->exists() ) {
2488 $err = $this->moveOverExistingRedirect( $nt, $reason, $createRedirect );
2489 $pageCountChange = ($createRedirect ? 0 : -1);
2490 } else { # Target didn't exist, do normal move.
2491 $err = $this->moveToNewTitle( $nt, $reason, $createRedirect );
2492 $pageCountChange = ($createRedirect ? 1 : 0);
2493 }
2494
2495 if( is_array( $err ) ) {
2496 return $err;
2497 }
2498 $redirid = $this->getArticleID();
2499
2500 // Category memberships include a sort key which may be customized.
2501 // If it's left as the default (the page title), we need to update
2502 // the sort key to match the new title.
2503 //
2504 // Be careful to avoid resetting cl_timestamp, which may disturb
2505 // time-based lists on some sites.
2506 //
2507 // Warning -- if the sort key is *explicitly* set to the old title,
2508 // we can't actually distinguish it from a default here, and it'll
2509 // be set to the new title even though it really shouldn't.
2510 // It'll get corrected on the next edit, but resetting cl_timestamp.
2511 $dbw = wfGetDB( DB_MASTER );
2512 $dbw->update( 'categorylinks',
2513 array(
2514 'cl_sortkey' => $nt->getPrefixedText(),
2515 'cl_timestamp=cl_timestamp' ),
2516 array(
2517 'cl_from' => $pageid,
2518 'cl_sortkey' => $this->getPrefixedText() ),
2519 __METHOD__ );
2520
2521 if( $protected ) {
2522 # Protect the redirect title as the title used to be...
2523 $dbw->insertSelect( 'page_restrictions', 'page_restrictions',
2524 array(
2525 'pr_page' => $redirid,
2526 'pr_type' => 'pr_type',
2527 'pr_level' => 'pr_level',
2528 'pr_cascade' => 'pr_cascade',
2529 'pr_user' => 'pr_user',
2530 'pr_expiry' => 'pr_expiry'
2531 ),
2532 array( 'pr_page' => $pageid ),
2533 __METHOD__,
2534 array( 'IGNORE' )
2535 );
2536 # Update the protection log
2537 $log = new LogPage( 'protect' );
2538 $comment = wfMsgForContent('prot_1movedto2',$this->getPrefixedText(), $nt->getPrefixedText() );
2539 if( $reason ) $comment .= ': ' . $reason;
2540 $log->addEntry( 'move_prot', $nt, $comment, array($this->getPrefixedText()) ); // FIXME: $params?
2541 }
2542
2543 # Update watchlists
2544 $oldnamespace = $this->getNamespace() & ~1;
2545 $newnamespace = $nt->getNamespace() & ~1;
2546 $oldtitle = $this->getDBkey();
2547 $newtitle = $nt->getDBkey();
2548
2549 if( $oldnamespace != $newnamespace || $oldtitle != $newtitle ) {
2550 WatchedItem::duplicateEntries( $this, $nt );
2551 }
2552
2553 # Update search engine
2554 $u = new SearchUpdate( $pageid, $nt->getPrefixedDBkey() );
2555 $u->doUpdate();
2556 $u = new SearchUpdate( $redirid, $this->getPrefixedDBkey(), '' );
2557 $u->doUpdate();
2558
2559 # Update site_stats
2560 if( $this->isContentPage() && !$nt->isContentPage() ) {
2561 # No longer a content page
2562 # Not viewed, edited, removing
2563 $u = new SiteStatsUpdate( 0, 1, -1, $pageCountChange );
2564 } elseif( !$this->isContentPage() && $nt->isContentPage() ) {
2565 # Now a content page
2566 # Not viewed, edited, adding
2567 $u = new SiteStatsUpdate( 0, 1, +1, $pageCountChange );
2568 } elseif( $pageCountChange ) {
2569 # Redirect added
2570 $u = new SiteStatsUpdate( 0, 0, 0, 1 );
2571 } else {
2572 # Nothing special
2573 $u = false;
2574 }
2575 if( $u )
2576 $u->doUpdate();
2577 # Update message cache for interface messages
2578 if( $nt->getNamespace() == NS_MEDIAWIKI ) {
2579 global $wgMessageCache;
2580 $oldarticle = new Article( $this );
2581 $wgMessageCache->replace( $this->getDBkey(), $oldarticle->getContent() );
2582 $newarticle = new Article( $nt );
2583 $wgMessageCache->replace( $nt->getDBkey(), $newarticle->getContent() );
2584 }
2585
2586 global $wgUser;
2587 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) );
2588 return true;
2589 }
2590
2591 /**
2592 * Move page to a title which is at present a redirect to the
2593 * source page
2594 *
2595 * @param &$nt \type{Title} the page to move to, which should currently
2596 * be a redirect
2597 * @param $reason \type{\string} The reason for the move
2598 * @param $createRedirect \type{\bool} Whether to leave a redirect at the old title.
2599 * Ignored if the user doesn't have the suppressredirect right
2600 */
2601 private function moveOverExistingRedirect( &$nt, $reason = '', $createRedirect = true ) {
2602 global $wgUseSquid, $wgUser;
2603 $fname = 'Title::moveOverExistingRedirect';
2604 $comment = wfMsgForContent( '1movedto2_redir', $this->getPrefixedText(), $nt->getPrefixedText() );
2605
2606 if ( $reason ) {
2607 $comment .= ": $reason";
2608 }
2609
2610 $now = wfTimestampNow();
2611 $newid = $nt->getArticleID();
2612 $oldid = $this->getArticleID();
2613 $latest = $this->getLatestRevID();
2614
2615 $dbw = wfGetDB( DB_MASTER );
2616
2617 # Delete the old redirect. We don't save it to history since
2618 # by definition if we've got here it's rather uninteresting.
2619 # We have to remove it so that the next step doesn't trigger
2620 # a conflict on the unique namespace+title index...
2621 $dbw->delete( 'page', array( 'page_id' => $newid ), $fname );
2622 if ( !$dbw->cascadingDeletes() ) {
2623 $dbw->delete( 'revision', array( 'rev_page' => $newid ), __METHOD__ );
2624 global $wgUseTrackbacks;
2625 if ($wgUseTrackbacks)
2626 $dbw->delete( 'trackbacks', array( 'tb_page' => $newid ), __METHOD__ );
2627 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), __METHOD__ );
2628 $dbw->delete( 'imagelinks', array( 'il_from' => $newid ), __METHOD__ );
2629 $dbw->delete( 'categorylinks', array( 'cl_from' => $newid ), __METHOD__ );
2630 $dbw->delete( 'templatelinks', array( 'tl_from' => $newid ), __METHOD__ );
2631 $dbw->delete( 'externallinks', array( 'el_from' => $newid ), __METHOD__ );
2632 $dbw->delete( 'langlinks', array( 'll_from' => $newid ), __METHOD__ );
2633 $dbw->delete( 'redirect', array( 'rd_from' => $newid ), __METHOD__ );
2634 }
2635
2636 # Save a null revision in the page's history notifying of the move
2637 $nullRevision = Revision::newNullRevision( $dbw, $oldid, $comment, true );
2638 $nullRevId = $nullRevision->insertOn( $dbw );
2639
2640 $article = new Article( $this );
2641 wfRunHooks( 'NewRevisionFromEditComplete', array($article, $nullRevision, $latest) );
2642
2643 # Change the name of the target page:
2644 $dbw->update( 'page',
2645 /* SET */ array(
2646 'page_touched' => $dbw->timestamp($now),
2647 'page_namespace' => $nt->getNamespace(),
2648 'page_title' => $nt->getDBkey(),
2649 'page_latest' => $nullRevId,
2650 ),
2651 /* WHERE */ array( 'page_id' => $oldid ),
2652 $fname
2653 );
2654 $nt->resetArticleID( $oldid );
2655
2656 # Recreate the redirect, this time in the other direction.
2657 if( $createRedirect || !$wgUser->isAllowed('suppressredirect') ) {
2658 $mwRedir = MagicWord::get( 'redirect' );
2659 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
2660 $redirectArticle = new Article( $this );
2661 $newid = $redirectArticle->insertOn( $dbw );
2662 $redirectRevision = new Revision( array(
2663 'page' => $newid,
2664 'comment' => $comment,
2665 'text' => $redirectText ) );
2666 $redirectRevision->insertOn( $dbw );
2667 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
2668
2669 wfRunHooks( 'NewRevisionFromEditComplete', array($redirectArticle, $redirectRevision, false) );
2670
2671 # Now, we record the link from the redirect to the new title.
2672 # It should have no other outgoing links...
2673 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), $fname );
2674 $dbw->insert( 'pagelinks',
2675 array(
2676 'pl_from' => $newid,
2677 'pl_namespace' => $nt->getNamespace(),
2678 'pl_title' => $nt->getDBkey() ),
2679 $fname );
2680 } else {
2681 $this->resetArticleID( 0 );
2682 }
2683
2684 # Move an image if this is a file
2685 if( $this->getNamespace() == NS_IMAGE ) {
2686 $file = wfLocalFile( $this );
2687 if( $file->exists() ) {
2688 $status = $file->move( $nt );
2689 if( !$status->isOk() ) {
2690 $dbw->rollback();
2691 return $status->getErrorsArray();
2692 }
2693 }
2694 }
2695
2696 # Log the move
2697 $log = new LogPage( 'move' );
2698 $log->addEntry( 'move_redir', $this, $reason, array( 1 => $nt->getPrefixedText() ) );
2699
2700 # Purge squid
2701 if ( $wgUseSquid ) {
2702 $urls = array_merge( $nt->getSquidURLs(), $this->getSquidURLs() );
2703 $u = new SquidUpdate( $urls );
2704 $u->doUpdate();
2705 }
2706
2707 }
2708
2709 /**
2710 * Move page to non-existing title.
2711 * @param &$nt \type{Title} the new Title
2712 * @param $reason \type{\string} The reason for the move
2713 * @param $createRedirect \type{\bool} Whether to create a redirect from the old title to the new title
2714 * Ignored if the user doesn't have the suppressredirect right
2715 */
2716 private function moveToNewTitle( &$nt, $reason = '', $createRedirect = true ) {
2717 global $wgUseSquid, $wgUser;
2718 $fname = 'MovePageForm::moveToNewTitle';
2719 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
2720 if ( $reason ) {
2721 $comment .= wfMsgExt( 'colon-separator',
2722 array( 'escapenoentities', 'content' ) );
2723 $comment .= $reason;
2724 }
2725
2726 $newid = $nt->getArticleID();
2727 $oldid = $this->getArticleID();
2728 $latest = $this->getLatestRevId();
2729
2730 $dbw = wfGetDB( DB_MASTER );
2731 $now = $dbw->timestamp();
2732
2733 # Save a null revision in the page's history notifying of the move
2734 $nullRevision = Revision::newNullRevision( $dbw, $oldid, $comment, true );
2735 $nullRevId = $nullRevision->insertOn( $dbw );
2736
2737 $article = new Article( $this );
2738 wfRunHooks( 'NewRevisionFromEditComplete', array($article, $nullRevision, $latest) );
2739
2740 # Rename page entry
2741 $dbw->update( 'page',
2742 /* SET */ array(
2743 'page_touched' => $now,
2744 'page_namespace' => $nt->getNamespace(),
2745 'page_title' => $nt->getDBkey(),
2746 'page_latest' => $nullRevId,
2747 ),
2748 /* WHERE */ array( 'page_id' => $oldid ),
2749 $fname
2750 );
2751 $nt->resetArticleID( $oldid );
2752
2753 if( $createRedirect || !$wgUser->isAllowed('suppressredirect') ) {
2754 # Insert redirect
2755 $mwRedir = MagicWord::get( 'redirect' );
2756 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
2757 $redirectArticle = new Article( $this );
2758 $newid = $redirectArticle->insertOn( $dbw );
2759 $redirectRevision = new Revision( array(
2760 'page' => $newid,
2761 'comment' => $comment,
2762 'text' => $redirectText ) );
2763 $redirectRevision->insertOn( $dbw );
2764 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
2765
2766 wfRunHooks( 'NewRevisionFromEditComplete', array($redirectArticle, $redirectRevision, false) );
2767
2768 # Record the just-created redirect's linking to the page
2769 $dbw->insert( 'pagelinks',
2770 array(
2771 'pl_from' => $newid,
2772 'pl_namespace' => $nt->getNamespace(),
2773 'pl_title' => $nt->getDBkey() ),
2774 $fname );
2775 } else {
2776 $this->resetArticleID( 0 );
2777 }
2778
2779 # Move an image if this is a file
2780 if( $this->getNamespace() == NS_IMAGE ) {
2781 $file = wfLocalFile( $this );
2782 if( $file->exists() ) {
2783 $status = $file->move( $nt );
2784 if( !$status->isOk() ) {
2785 $dbw->rollback();
2786 return $status->getErrorsArray();
2787 }
2788 }
2789 }
2790
2791 # Log the move
2792 $log = new LogPage( 'move' );
2793 $log->addEntry( 'move', $this, $reason, array( 1 => $nt->getPrefixedText()) );
2794
2795 # Purge caches as per article creation
2796 Article::onArticleCreate( $nt );
2797
2798 # Purge old title from squid
2799 # The new title, and links to the new title, are purged in Article::onArticleCreate()
2800 $this->purgeSquid();
2801
2802 }
2803
2804 /**
2805 * Checks if $this can be moved to a given Title
2806 * - Selects for update, so don't call it unless you mean business
2807 *
2808 * @param &$nt \type{Title} the new title to check
2809 * @return \type{\bool} TRUE or FALSE
2810 */
2811 public function isValidMoveTarget( $nt ) {
2812
2813 $fname = 'Title::isValidMoveTarget';
2814 $dbw = wfGetDB( DB_MASTER );
2815
2816 # Is it an existsing file?
2817 if( $nt->getNamespace() == NS_IMAGE ) {
2818 $file = wfLocalFile( $nt );
2819 if( $file->exists() ) {
2820 wfDebug( __METHOD__ . ": file exists\n" );
2821 return false;
2822 }
2823 }
2824
2825 # Is it a redirect?
2826 $id = $nt->getArticleID();
2827 $obj = $dbw->selectRow( array( 'page', 'revision', 'text'),
2828 array( 'page_is_redirect','old_text','old_flags' ),
2829 array( 'page_id' => $id, 'page_latest=rev_id', 'rev_text_id=old_id' ),
2830 $fname, 'FOR UPDATE' );
2831
2832 if ( !$obj || 0 == $obj->page_is_redirect ) {
2833 # Not a redirect
2834 wfDebug( __METHOD__ . ": not a redirect\n" );
2835 return false;
2836 }
2837 $text = Revision::getRevisionText( $obj );
2838
2839 # Does the redirect point to the source?
2840 # Or is it a broken self-redirect, usually caused by namespace collisions?
2841 $m = array();
2842 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $text, $m ) ) {
2843 $redirTitle = Title::newFromText( $m[1] );
2844 if( !is_object( $redirTitle ) ||
2845 ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
2846 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) ) {
2847 wfDebug( __METHOD__ . ": redirect points to other page\n" );
2848 return false;
2849 }
2850 } else {
2851 # Fail safe
2852 wfDebug( __METHOD__ . ": failsafe\n" );
2853 return false;
2854 }
2855
2856 # Does the article have a history?
2857 $row = $dbw->selectRow( array( 'page', 'revision'),
2858 array( 'rev_id' ),
2859 array( 'page_namespace' => $nt->getNamespace(),
2860 'page_title' => $nt->getDBkey(),
2861 'page_id=rev_page AND page_latest != rev_id'
2862 ), $fname, 'FOR UPDATE'
2863 );
2864
2865 # Return true if there was no history
2866 return $row === false;
2867 }
2868
2869 /**
2870 * Can this title be added to a user's watchlist?
2871 *
2872 * @return \type{\bool} TRUE or FALSE
2873 */
2874 public function isWatchable() {
2875 return !$this->isExternal()
2876 && MWNamespace::isWatchable( $this->getNamespace() );
2877 }
2878
2879 /**
2880 * Get categories to which this Title belongs and return an array of
2881 * categories' names.
2882 *
2883 * @return \type{\array} array an array of parents in the form:
2884 * $parent => $currentarticle
2885 */
2886 public function getParentCategories() {
2887 global $wgContLang;
2888
2889 $titlekey = $this->getArticleId();
2890 $dbr = wfGetDB( DB_SLAVE );
2891 $categorylinks = $dbr->tableName( 'categorylinks' );
2892
2893 # NEW SQL
2894 $sql = "SELECT * FROM $categorylinks"
2895 ." WHERE cl_from='$titlekey'"
2896 ." AND cl_from <> '0'"
2897 ." ORDER BY cl_sortkey";
2898
2899 $res = $dbr->query( $sql );
2900
2901 if( $dbr->numRows( $res ) > 0 ) {
2902 foreach( $res as $row )
2903 //$data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$row->cl_to);
2904 $data[$wgContLang->getNSText( NS_CATEGORY ).':'.$row->cl_to] = $this->getFullText();
2905 $dbr->freeResult( $res );
2906 } else {
2907 $data = array();
2908 }
2909 return $data;
2910 }
2911
2912 /**
2913 * Get a tree of parent categories
2914 * @param $children \type{\array} an array with the children in the keys, to check for circular refs
2915 * @return \type{\array} Tree of parent categories
2916 */
2917 public function getParentCategoryTree( $children = array() ) {
2918 $stack = array();
2919 $parents = $this->getParentCategories();
2920
2921 if( $parents ) {
2922 foreach( $parents as $parent => $current ) {
2923 if ( array_key_exists( $parent, $children ) ) {
2924 # Circular reference
2925 $stack[$parent] = array();
2926 } else {
2927 $nt = Title::newFromText($parent);
2928 if ( $nt ) {
2929 $stack[$parent] = $nt->getParentCategoryTree( $children + array($parent => 1) );
2930 }
2931 }
2932 }
2933 return $stack;
2934 } else {
2935 return array();
2936 }
2937 }
2938
2939
2940 /**
2941 * Get an associative array for selecting this title from
2942 * the "page" table
2943 *
2944 * @return \type{\array} Selection array
2945 */
2946 public function pageCond() {
2947 return array( 'page_namespace' => $this->mNamespace, 'page_title' => $this->mDbkeyform );
2948 }
2949
2950 /**
2951 * Get the revision ID of the previous revision
2952 *
2953 * @param $revId \type{\int} Revision ID. Get the revision that was before this one.
2954 * @param $flags \type{\int} GAID_FOR_UPDATE
2955 * @return \twotypes{\int,\bool} Old revision ID, or FALSE if none exists
2956 */
2957 public function getPreviousRevisionID( $revId, $flags=0 ) {
2958 $db = ($flags & GAID_FOR_UPDATE) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
2959 return $db->selectField( 'revision', 'rev_id',
2960 array(
2961 'rev_page' => $this->getArticleId($flags),
2962 'rev_id < ' . intval( $revId )
2963 ),
2964 __METHOD__,
2965 array( 'ORDER BY' => 'rev_id DESC' )
2966 );
2967 }
2968
2969 /**
2970 * Get the revision ID of the next revision
2971 *
2972 * @param $revId \type{\int} Revision ID. Get the revision that was after this one.
2973 * @param $flags \type{\int} GAID_FOR_UPDATE
2974 * @return \twotypes{\int,\bool} Next revision ID, or FALSE if none exists
2975 */
2976 public function getNextRevisionID( $revId, $flags=0 ) {
2977 $db = ($flags & GAID_FOR_UPDATE) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
2978 return $db->selectField( 'revision', 'rev_id',
2979 array(
2980 'rev_page' => $this->getArticleId($flags),
2981 'rev_id > ' . intval( $revId )
2982 ),
2983 __METHOD__,
2984 array( 'ORDER BY' => 'rev_id' )
2985 );
2986 }
2987
2988 /**
2989 * Get the number of revisions between the given revision IDs.
2990 * Used for diffs and other things that really need it.
2991 *
2992 * @param $old \type{\int} Revision ID.
2993 * @param $new \type{\int} Revision ID.
2994 * @return \type{\int} Number of revisions between these IDs.
2995 */
2996 public function countRevisionsBetween( $old, $new ) {
2997 $dbr = wfGetDB( DB_SLAVE );
2998 return $dbr->selectField( 'revision', 'count(*)',
2999 'rev_page = ' . intval( $this->getArticleId() ) .
3000 ' AND rev_id > ' . intval( $old ) .
3001 ' AND rev_id < ' . intval( $new ),
3002 __METHOD__,
3003 array( 'USE INDEX' => 'PRIMARY' ) );
3004 }
3005
3006 /**
3007 * Compare with another title.
3008 *
3009 * @param \type{Title} $title
3010 * @return \type{\bool} TRUE or FALSE
3011 */
3012 public function equals( Title $title ) {
3013 // Note: === is necessary for proper matching of number-like titles.
3014 return $this->getInterwiki() === $title->getInterwiki()
3015 && $this->getNamespace() == $title->getNamespace()
3016 && $this->getDBkey() === $title->getDBkey();
3017 }
3018
3019 /**
3020 * Callback for usort() to do title sorts by (namespace, title)
3021 */
3022 static function compare( $a, $b ) {
3023 if( $a->getNamespace() == $b->getNamespace() ) {
3024 return strcmp( $a->getText(), $b->getText() );
3025 } else {
3026 return $a->getNamespace() - $b->getNamespace();
3027 }
3028 }
3029
3030 /**
3031 * Return a string representation of this title
3032 *
3033 * @return \type{\string} String representation of this title
3034 */
3035 public function __toString() {
3036 return $this->getPrefixedText();
3037 }
3038
3039 /**
3040 * Check if page exists
3041 * @return \type{\bool} TRUE or FALSE
3042 */
3043 public function exists() {
3044 return $this->getArticleId() != 0;
3045 }
3046
3047 /**
3048 * Do we know that this title definitely exists, or should we otherwise
3049 * consider that it exists?
3050 *
3051 * @return \type{\bool} TRUE or FALSE
3052 */
3053 public function isAlwaysKnown() {
3054 // If the page is form Mediawiki:message/lang, calling wfMsgWeirdKey causes
3055 // the full l10n of that language to be loaded. That takes much memory and
3056 // isn't needed. So we strip the language part away.
3057 // Also, extension messages which are not loaded, are shown as red, because
3058 // we don't call MessageCache::loadAllMessages.
3059 list( $basename, /* rest */ ) = explode( '/', $this->mDbkeyform, 2 );
3060 return $this->isExternal()
3061 || ( $this->mNamespace == NS_MAIN && $this->mDbkeyform == '' )
3062 || ( $this->mNamespace == NS_MEDIAWIKI && wfMsgWeirdKey( $basename ) );
3063 }
3064
3065 /**
3066 * Update page_touched timestamps and send squid purge messages for
3067 * pages linking to this title. May be sent to the job queue depending
3068 * on the number of links. Typically called on create and delete.
3069 */
3070 public function touchLinks() {
3071 $u = new HTMLCacheUpdate( $this, 'pagelinks' );
3072 $u->doUpdate();
3073
3074 if ( $this->getNamespace() == NS_CATEGORY ) {
3075 $u = new HTMLCacheUpdate( $this, 'categorylinks' );
3076 $u->doUpdate();
3077 }
3078 }
3079
3080 /**
3081 * Get the last touched timestamp
3082 * @param Database $db, optional db
3083 * @return \type{\string} Last touched timestamp
3084 */
3085 public function getTouched( $db = NULL ) {
3086 $db = isset($db) ? $db : wfGetDB( DB_SLAVE );
3087 $touched = $db->selectField( 'page', 'page_touched',
3088 array(
3089 'page_namespace' => $this->getNamespace(),
3090 'page_title' => $this->getDBkey()
3091 ), __METHOD__
3092 );
3093 return $touched;
3094 }
3095
3096 /**
3097 * Get the trackback URL for this page
3098 * @return \type{\string} Trackback URL
3099 */
3100 public function trackbackURL() {
3101 global $wgScriptPath, $wgServer;
3102
3103 return "$wgServer$wgScriptPath/trackback.php?article="
3104 . htmlspecialchars(urlencode($this->getPrefixedDBkey()));
3105 }
3106
3107 /**
3108 * Get the trackback RDF for this page
3109 * @return \type{\string} Trackback RDF
3110 */
3111 public function trackbackRDF() {
3112 $url = htmlspecialchars($this->getFullURL());
3113 $title = htmlspecialchars($this->getText());
3114 $tburl = $this->trackbackURL();
3115
3116 // Autodiscovery RDF is placed in comments so HTML validator
3117 // won't barf. This is a rather icky workaround, but seems
3118 // frequently used by this kind of RDF thingy.
3119 //
3120 // Spec: http://www.sixapart.com/pronet/docs/trackback_spec
3121 return "<!--
3122 <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"
3123 xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
3124 xmlns:trackback=\"http://madskills.com/public/xml/rss/module/trackback/\">
3125 <rdf:Description
3126 rdf:about=\"$url\"
3127 dc:identifier=\"$url\"
3128 dc:title=\"$title\"
3129 trackback:ping=\"$tburl\" />
3130 </rdf:RDF>
3131 -->";
3132 }
3133
3134 /**
3135 * Generate strings used for xml 'id' names in monobook tabs
3136 * @return \type{\string} XML 'id' name
3137 */
3138 public function getNamespaceKey() {
3139 global $wgContLang;
3140 switch ($this->getNamespace()) {
3141 case NS_MAIN:
3142 case NS_TALK:
3143 return 'nstab-main';
3144 case NS_USER:
3145 case NS_USER_TALK:
3146 return 'nstab-user';
3147 case NS_MEDIA:
3148 return 'nstab-media';
3149 case NS_SPECIAL:
3150 return 'nstab-special';
3151 case NS_PROJECT:
3152 case NS_PROJECT_TALK:
3153 return 'nstab-project';
3154 case NS_IMAGE:
3155 case NS_IMAGE_TALK:
3156 return 'nstab-image';
3157 case NS_MEDIAWIKI:
3158 case NS_MEDIAWIKI_TALK:
3159 return 'nstab-mediawiki';
3160 case NS_TEMPLATE:
3161 case NS_TEMPLATE_TALK:
3162 return 'nstab-template';
3163 case NS_HELP:
3164 case NS_HELP_TALK:
3165 return 'nstab-help';
3166 case NS_CATEGORY:
3167 case NS_CATEGORY_TALK:
3168 return 'nstab-category';
3169 default:
3170 return 'nstab-' . $wgContLang->lc( $this->getSubjectNsText() );
3171 }
3172 }
3173
3174 /**
3175 * Returns true if this title resolves to the named special page
3176 * @param $name \type{\string} The special page name
3177 */
3178 public function isSpecial( $name ) {
3179 if ( $this->getNamespace() == NS_SPECIAL ) {
3180 list( $thisName, /* $subpage */ ) = SpecialPage::resolveAliasWithSubpage( $this->getDBkey() );
3181 if ( $name == $thisName ) {
3182 return true;
3183 }
3184 }
3185 return false;
3186 }
3187
3188 /**
3189 * If the Title refers to a special page alias which is not the local default,
3190 * @return \type{Title} A new Title which points to the local default. Otherwise, returns $this.
3191 */
3192 public function fixSpecialName() {
3193 if ( $this->getNamespace() == NS_SPECIAL ) {
3194 $canonicalName = SpecialPage::resolveAlias( $this->mDbkeyform );
3195 if ( $canonicalName ) {
3196 $localName = SpecialPage::getLocalNameFor( $canonicalName );
3197 if ( $localName != $this->mDbkeyform ) {
3198 return Title::makeTitle( NS_SPECIAL, $localName );
3199 }
3200 }
3201 }
3202 return $this;
3203 }
3204
3205 /**
3206 * Is this Title in a namespace which contains content?
3207 * In other words, is this a content page, for the purposes of calculating
3208 * statistics, etc?
3209 *
3210 * @return \type{\bool} TRUE or FALSE
3211 */
3212 public function isContentPage() {
3213 return MWNamespace::isContent( $this->getNamespace() );
3214 }
3215
3216 /**
3217 * Get all extant redirects to this Title
3218 *
3219 * @param $ns \twotypes{\int,\null} Single namespace to consider;
3220 * NULL to consider all namespaces
3221 * @return \type{\arrayof{Title}} Redirects to this title
3222 */
3223 public function getRedirectsHere( $ns = null ) {
3224 $redirs = array();
3225
3226 $dbr = wfGetDB( DB_SLAVE );
3227 $where = array(
3228 'rd_namespace' => $this->getNamespace(),
3229 'rd_title' => $this->getDBkey(),
3230 'rd_from = page_id'
3231 );
3232 if ( !is_null($ns) ) $where['page_namespace'] = $ns;
3233
3234 $res = $dbr->select(
3235 array( 'redirect', 'page' ),
3236 array( 'page_namespace', 'page_title' ),
3237 $where,
3238 __METHOD__
3239 );
3240
3241
3242 foreach( $res as $row ) {
3243 $redirs[] = self::newFromRow( $row );
3244 }
3245 return $redirs;
3246 }
3247 }