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