Make sure a member var is declared.
[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( is_array($title_protection) ) {
1439 extract($title_protection); // is this extract() really needed?
1440
1441 if( $pt_create_perm == 'sysop' ) {
1442 $pt_create_perm = 'protect'; // B/C
1443 }
1444 if( $pt_create_perm == '' || !$user->isAllowed($pt_create_perm) ) {
1445 $errors[] = array( 'titleprotected', User::whoIs($pt_user), $pt_reason );
1446 }
1447 }
1448 } elseif( $action == 'move' ) {
1449 // Check for immobile pages
1450 if( !MWNamespace::isMovable( $this->getNamespace() ) ) {
1451 // Specific message for this case
1452 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
1453 } elseif( !$this->isMovable() ) {
1454 // Less specific message for rarer cases
1455 $errors[] = array( 'immobile-page' );
1456 }
1457 } elseif( $action == 'move-target' ) {
1458 if( !MWNamespace::isMovable( $this->getNamespace() ) ) {
1459 $errors[] = array( 'immobile-target-namespace', $this->getNsText() );
1460 } elseif( !$this->isMovable() ) {
1461 $errors[] = array( 'immobile-target-page' );
1462 }
1463 }
1464
1465 wfProfileOut( __METHOD__ );
1466 return $errors;
1467 }
1468
1469 /**
1470 * Is this title subject to title protection?
1471 *
1472 * @return \type{\mixed} An associative array representing any existent title
1473 * protection, or false if there's none.
1474 */
1475 private function getTitleProtection() {
1476 // Can't protect pages in special namespaces
1477 if ( $this->getNamespace() < 0 ) {
1478 return false;
1479 }
1480
1481 // Can't protect pages that exist.
1482 if ($this->exists()) {
1483 return false;
1484 }
1485
1486 $dbr = wfGetDB( DB_SLAVE );
1487 $res = $dbr->select( 'protected_titles', '*',
1488 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
1489 __METHOD__ );
1490
1491 if ($row = $dbr->fetchRow( $res )) {
1492 return $row;
1493 } else {
1494 return false;
1495 }
1496 }
1497
1498 /**
1499 * Update the title protection status
1500 *
1501 * @param $create_perm \type{\string} Permission required for creation
1502 * @param $reason \type{\string} Reason for protection
1503 * @param $expiry \type{\string} Expiry timestamp
1504 * @return boolean true
1505 */
1506 public function updateTitleProtection( $create_perm, $reason, $expiry ) {
1507 global $wgUser,$wgContLang;
1508
1509 if ($create_perm == implode(',',$this->getRestrictions('create'))
1510 && $expiry == $this->mRestrictionsExpiry['create']) {
1511 // No change
1512 return true;
1513 }
1514
1515 list ($namespace, $title) = array( $this->getNamespace(), $this->getDBkey() );
1516
1517 $dbw = wfGetDB( DB_MASTER );
1518
1519 $encodedExpiry = Block::encodeExpiry($expiry, $dbw );
1520
1521 $expiry_description = '';
1522 if ( $encodedExpiry != 'infinity' ) {
1523 $expiry_description = ' (' . wfMsgForContent( 'protect-expiring',$wgContLang->timeanddate( $expiry ),
1524 $wgContLang->date( $expiry ) , $wgContLang->time( $expiry ) ).')';
1525 }
1526 else {
1527 $expiry_description .= ' (' . wfMsgForContent( 'protect-expiry-indefinite' ).')';
1528 }
1529
1530 # Update protection table
1531 if ($create_perm != '' ) {
1532 $dbw->replace( 'protected_titles', array(array('pt_namespace', 'pt_title')),
1533 array(
1534 'pt_namespace' => $namespace,
1535 'pt_title' => $title,
1536 'pt_create_perm' => $create_perm,
1537 'pt_timestamp' => Block::encodeExpiry(wfTimestampNow(), $dbw),
1538 'pt_expiry' => $encodedExpiry,
1539 'pt_user' => $wgUser->getId(),
1540 'pt_reason' => $reason,
1541 ), __METHOD__
1542 );
1543 } else {
1544 $dbw->delete( 'protected_titles', array( 'pt_namespace' => $namespace,
1545 'pt_title' => $title ), __METHOD__ );
1546 }
1547 # Update the protection log
1548 if( $dbw->affectedRows() ) {
1549 $log = new LogPage( 'protect' );
1550
1551 if( $create_perm ) {
1552 $params = array("[create=$create_perm] $expiry_description",'');
1553 $log->addEntry( ( isset( $this->mRestrictions['create'] ) && $this->mRestrictions['create'] ) ? 'modify' : 'protect', $this, trim( $reason ), $params );
1554 } else {
1555 $log->addEntry( 'unprotect', $this, $reason );
1556 }
1557 }
1558
1559 return true;
1560 }
1561
1562 /**
1563 * Remove any title protection due to page existing
1564 */
1565 public function deleteTitleProtection() {
1566 $dbw = wfGetDB( DB_MASTER );
1567
1568 $dbw->delete( 'protected_titles',
1569 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
1570 __METHOD__ );
1571 }
1572
1573 /**
1574 * Would anybody with sufficient privileges be able to move this page?
1575 * Some pages just aren't movable.
1576 *
1577 * @return \type{\bool} TRUE or FALSE
1578 */
1579 public function isMovable() {
1580 return MWNamespace::isMovable( $this->getNamespace() ) && $this->getInterwiki() == '';
1581 }
1582
1583 /**
1584 * Can $wgUser read this page?
1585 *
1586 * @return \type{\bool}
1587 * @todo fold these checks into userCan()
1588 */
1589 public function userCanRead() {
1590 global $wgUser, $wgGroupPermissions;
1591
1592 static $useShortcut = null;
1593
1594 # Initialize the $useShortcut boolean, to determine if we can skip quite a bit of code below
1595 if( is_null( $useShortcut ) ) {
1596 global $wgRevokePermissions;
1597 $useShortcut = true;
1598 if( empty( $wgGroupPermissions['*']['read'] ) ) {
1599 # Not a public wiki, so no shortcut
1600 $useShortcut = false;
1601 } elseif( !empty( $wgRevokePermissions ) ) {
1602 /*
1603 * Iterate through each group with permissions being revoked (key not included since we don't care
1604 * what the group name is), then check if the read permission is being revoked. If it is, then
1605 * we don't use the shortcut below since the user might not be able to read, even though anon
1606 * reading is allowed.
1607 */
1608 foreach( $wgRevokePermissions as $perms ) {
1609 if( !empty( $perms['read'] ) ) {
1610 # We might be removing the read right from the user, so no shortcut
1611 $useShortcut = false;
1612 break;
1613 }
1614 }
1615 }
1616 }
1617
1618 $result = null;
1619 wfRunHooks( 'userCan', array( &$this, &$wgUser, 'read', &$result ) );
1620 if ( $result !== null ) {
1621 return $result;
1622 }
1623
1624 # Shortcut for public wikis, allows skipping quite a bit of code
1625 if ( $useShortcut )
1626 return true;
1627
1628 if( $wgUser->isAllowed( 'read' ) ) {
1629 return true;
1630 } else {
1631 global $wgWhitelistRead;
1632
1633 /**
1634 * Always grant access to the login page.
1635 * Even anons need to be able to log in.
1636 */
1637 if( $this->isSpecial( 'Userlogin' ) || $this->isSpecial( 'Resetpass' ) ) {
1638 return true;
1639 }
1640
1641 /**
1642 * Bail out if there isn't whitelist
1643 */
1644 if( !is_array($wgWhitelistRead) ) {
1645 return false;
1646 }
1647
1648 /**
1649 * Check for explicit whitelisting
1650 */
1651 $name = $this->getPrefixedText();
1652 $dbName = $this->getPrefixedDBKey();
1653 // Check with and without underscores
1654 if( in_array($name,$wgWhitelistRead,true) || in_array($dbName,$wgWhitelistRead,true) )
1655 return true;
1656
1657 /**
1658 * Old settings might have the title prefixed with
1659 * a colon for main-namespace pages
1660 */
1661 if( $this->getNamespace() == NS_MAIN ) {
1662 if( in_array( ':' . $name, $wgWhitelistRead ) )
1663 return true;
1664 }
1665
1666 /**
1667 * If it's a special page, ditch the subpage bit
1668 * and check again
1669 */
1670 if( $this->getNamespace() == NS_SPECIAL ) {
1671 $name = $this->getDBkey();
1672 list( $name, /* $subpage */) = SpecialPage::resolveAliasWithSubpage( $name );
1673 if ( $name === false ) {
1674 # Invalid special page, but we show standard login required message
1675 return false;
1676 }
1677
1678 $pure = SpecialPage::getTitleFor( $name )->getPrefixedText();
1679 if( in_array( $pure, $wgWhitelistRead, true ) )
1680 return true;
1681 }
1682
1683 }
1684 return false;
1685 }
1686
1687 /**
1688 * Is this a talk page of some sort?
1689 *
1690 * @return \type{\bool}
1691 */
1692 public function isTalkPage() {
1693 return MWNamespace::isTalk( $this->getNamespace() );
1694 }
1695
1696 /**
1697 * Is this a subpage?
1698 *
1699 * @return \type{\bool}
1700 */
1701 public function isSubpage() {
1702 return MWNamespace::hasSubpages( $this->mNamespace )
1703 ? strpos( $this->getText(), '/' ) !== false
1704 : false;
1705 }
1706
1707 /**
1708 * Does this have subpages? (Warning, usually requires an extra DB query.)
1709 *
1710 * @return \type{\bool}
1711 */
1712 public function hasSubpages() {
1713 if( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
1714 # Duh
1715 return false;
1716 }
1717
1718 # We dynamically add a member variable for the purpose of this method
1719 # alone to cache the result. There's no point in having it hanging
1720 # around uninitialized in every Title object; therefore we only add it
1721 # if needed and don't declare it statically.
1722 if( isset( $this->mHasSubpages ) ) {
1723 return $this->mHasSubpages;
1724 }
1725
1726 $subpages = $this->getSubpages( 1 );
1727 if( $subpages instanceof TitleArray )
1728 return $this->mHasSubpages = (bool)$subpages->count();
1729 return $this->mHasSubpages = false;
1730 }
1731
1732 /**
1733 * Get all subpages of this page.
1734 *
1735 * @param $limit Maximum number of subpages to fetch; -1 for no limit
1736 * @return mixed TitleArray, or empty array if this page's namespace
1737 * doesn't allow subpages
1738 */
1739 public function getSubpages( $limit = -1 ) {
1740 if( !MWNamespace::hasSubpages( $this->getNamespace() ) )
1741 return array();
1742
1743 $dbr = wfGetDB( DB_SLAVE );
1744 $conds['page_namespace'] = $this->getNamespace();
1745 $conds[] = 'page_title ' . $dbr->buildLike( $this->getDBkey() . '/', $dbr->anyString() );
1746 $options = array();
1747 if( $limit > -1 )
1748 $options['LIMIT'] = $limit;
1749 return $this->mSubpages = TitleArray::newFromResult(
1750 $dbr->select( 'page',
1751 array( 'page_id', 'page_namespace', 'page_title', 'page_is_redirect' ),
1752 $conds,
1753 __METHOD__,
1754 $options
1755 )
1756 );
1757 }
1758
1759 /**
1760 * Could this page contain custom CSS or JavaScript, based
1761 * on the title?
1762 *
1763 * @return \type{\bool}
1764 */
1765 public function isCssOrJsPage() {
1766 return $this->mNamespace == NS_MEDIAWIKI
1767 && preg_match( '!\.(?:css|js)$!u', $this->mTextform ) > 0;
1768 }
1769
1770 /**
1771 * Is this a .css or .js subpage of a user page?
1772 * @return \type{\bool}
1773 */
1774 public function isCssJsSubpage() {
1775 return ( NS_USER == $this->mNamespace and preg_match("/\\/.*\\.(?:css|js)$/", $this->mTextform ) );
1776 }
1777
1778 /**
1779 * Is this a *valid* .css or .js subpage of a user page?
1780 * Check that the corresponding skin exists
1781 *
1782 * @return \type{\bool}
1783 */
1784 public function isValidCssJsSubpage() {
1785 if ( $this->isCssJsSubpage() ) {
1786 $name = $this->getSkinFromCssJsSubpage();
1787 if ( $name == 'common' ) return true;
1788 $skinNames = Skin::getSkinNames();
1789 return array_key_exists( $name, $skinNames );
1790 } else {
1791 return false;
1792 }
1793 }
1794
1795 /**
1796 * Trim down a .css or .js subpage title to get the corresponding skin name
1797 *
1798 * @return string containing skin name from .css or .js subpage title
1799 */
1800 public function getSkinFromCssJsSubpage() {
1801 $subpage = explode( '/', $this->mTextform );
1802 $subpage = $subpage[ count( $subpage ) - 1 ];
1803 return( str_replace( array( '.css', '.js' ), array( '', '' ), $subpage ) );
1804 }
1805
1806 /**
1807 * Is this a .css subpage of a user page?
1808 *
1809 * @return \type{\bool}
1810 */
1811 public function isCssSubpage() {
1812 return ( NS_USER == $this->mNamespace && preg_match("/\\/.*\\.css$/", $this->mTextform ) );
1813 }
1814
1815 /**
1816 * Is this a .js subpage of a user page?
1817 *
1818 * @return \type{\bool}
1819 */
1820 public function isJsSubpage() {
1821 return ( NS_USER == $this->mNamespace && preg_match("/\\/.*\\.js$/", $this->mTextform ) );
1822 }
1823
1824 /**
1825 * Protect css subpages of user pages: can $wgUser edit
1826 * this page?
1827 *
1828 * @return \type{\bool}
1829 * @todo XXX: this might be better using restrictions
1830 */
1831 public function userCanEditCssSubpage() {
1832 global $wgUser;
1833 return ( ( $wgUser->isAllowed('editusercssjs') && $wgUser->isAllowed('editusercss') )
1834 || preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform) );
1835 }
1836 /**
1837 * Protect js subpages of user pages: can $wgUser edit
1838 * this page?
1839 *
1840 * @return \type{\bool}
1841 * @todo XXX: this might be better using restrictions
1842 */
1843 public function userCanEditJsSubpage() {
1844 global $wgUser;
1845 return ( ( $wgUser->isAllowed('editusercssjs') && $wgUser->isAllowed('edituserjs') )
1846 || preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform) );
1847 }
1848
1849 /**
1850 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
1851 *
1852 * @return \type{\bool} If the page is subject to cascading restrictions.
1853 */
1854 public function isCascadeProtected() {
1855 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
1856 return ( $sources > 0 );
1857 }
1858
1859 /**
1860 * Cascading protection: Get the source of any cascading restrictions on this page.
1861 *
1862 * @param $get_pages \type{\bool} Whether or not to retrieve the actual pages
1863 * that the restrictions have come from.
1864 * @return \type{\arrayof{mixed title array, restriction array}} Array of the Title
1865 * objects of the pages from which cascading restrictions have come,
1866 * false for none, or true if such restrictions exist, but $get_pages was not set.
1867 * The restriction array is an array of each type, each of which contains a
1868 * array of unique groups.
1869 */
1870 public function getCascadeProtectionSources( $get_pages = true ) {
1871 $pagerestrictions = array();
1872
1873 if ( isset( $this->mCascadeSources ) && $get_pages ) {
1874 return array( $this->mCascadeSources, $this->mCascadingRestrictions );
1875 } else if ( isset( $this->mHasCascadingRestrictions ) && !$get_pages ) {
1876 return array( $this->mHasCascadingRestrictions, $pagerestrictions );
1877 }
1878
1879 wfProfileIn( __METHOD__ );
1880
1881 $dbr = wfGetDB( DB_SLAVE );
1882
1883 if ( $this->getNamespace() == NS_FILE ) {
1884 $tables = array ('imagelinks', 'page_restrictions');
1885 $where_clauses = array(
1886 'il_to' => $this->getDBkey(),
1887 'il_from=pr_page',
1888 'pr_cascade' => 1 );
1889 } else {
1890 $tables = array ('templatelinks', 'page_restrictions');
1891 $where_clauses = array(
1892 'tl_namespace' => $this->getNamespace(),
1893 'tl_title' => $this->getDBkey(),
1894 'tl_from=pr_page',
1895 'pr_cascade' => 1 );
1896 }
1897
1898 if ( $get_pages ) {
1899 $cols = array('pr_page', 'page_namespace', 'page_title', 'pr_expiry', 'pr_type', 'pr_level' );
1900 $where_clauses[] = 'page_id=pr_page';
1901 $tables[] = 'page';
1902 } else {
1903 $cols = array( 'pr_expiry' );
1904 }
1905
1906 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__ );
1907
1908 $sources = $get_pages ? array() : false;
1909 $now = wfTimestampNow();
1910 $purgeExpired = false;
1911
1912 foreach( $res as $row ) {
1913 $expiry = Block::decodeExpiry( $row->pr_expiry );
1914 if( $expiry > $now ) {
1915 if ($get_pages) {
1916 $page_id = $row->pr_page;
1917 $page_ns = $row->page_namespace;
1918 $page_title = $row->page_title;
1919 $sources[$page_id] = Title::makeTitle($page_ns, $page_title);
1920 # Add groups needed for each restriction type if its not already there
1921 # Make sure this restriction type still exists
1922
1923 if ( !isset( $pagerestrictions[$row->pr_type] ) ) {
1924 $pagerestrictions[$row->pr_type] = array();
1925 }
1926
1927 if ( isset($pagerestrictions[$row->pr_type]) &&
1928 !in_array($row->pr_level, $pagerestrictions[$row->pr_type]) ) {
1929 $pagerestrictions[$row->pr_type][]=$row->pr_level;
1930 }
1931 } else {
1932 $sources = true;
1933 }
1934 } else {
1935 // Trigger lazy purge of expired restrictions from the db
1936 $purgeExpired = true;
1937 }
1938 }
1939 if( $purgeExpired ) {
1940 Title::purgeExpiredRestrictions();
1941 }
1942
1943 wfProfileOut( __METHOD__ );
1944
1945 if ( $get_pages ) {
1946 $this->mCascadeSources = $sources;
1947 $this->mCascadingRestrictions = $pagerestrictions;
1948 } else {
1949 $this->mHasCascadingRestrictions = $sources;
1950 }
1951 return array( $sources, $pagerestrictions );
1952 }
1953
1954 /**
1955 * Returns cascading restrictions for the current article
1956 *
1957 * @return Boolean
1958 */
1959 function areRestrictionsCascading() {
1960 if (!$this->mRestrictionsLoaded) {
1961 $this->loadRestrictions();
1962 }
1963
1964 return $this->mCascadeRestriction;
1965 }
1966
1967 /**
1968 * Loads a string into mRestrictions array
1969 *
1970 * @param $res \type{Resource} restrictions as an SQL result.
1971 * @param $oldFashionedRestrictions string comma-separated list of page
1972 * restrictions from page table (pre 1.10)
1973 */
1974 private function loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions = null ) {
1975 $rows = array();
1976 $dbr = wfGetDB( DB_SLAVE );
1977
1978 while( $row = $dbr->fetchObject( $res ) ) {
1979 $rows[] = $row;
1980 }
1981
1982 $this->loadRestrictionsFromRows( $rows, $oldFashionedRestrictions );
1983 }
1984
1985 /**
1986 * Compiles list of active page restrictions from both page table (pre 1.10)
1987 * and page_restrictions table
1988 *
1989 * @param $rows array of db result objects
1990 * @param $oldFashionedRestrictions string comma-separated list of page
1991 * restrictions from page table (pre 1.10)
1992 */
1993 public function loadRestrictionsFromRows( $rows, $oldFashionedRestrictions = null ) {
1994 $dbr = wfGetDB( DB_SLAVE );
1995
1996 $restrictionTypes = $this->getRestrictionTypes();
1997
1998 foreach( $restrictionTypes as $type ){
1999 $this->mRestrictions[$type] = array();
2000 $this->mRestrictionsExpiry[$type] = Block::decodeExpiry('');
2001 }
2002
2003 $this->mCascadeRestriction = false;
2004
2005 # Backwards-compatibility: also load the restrictions from the page record (old format).
2006
2007 if ( $oldFashionedRestrictions === null ) {
2008 $oldFashionedRestrictions = $dbr->selectField( 'page', 'page_restrictions',
2009 array( 'page_id' => $this->getArticleId() ), __METHOD__ );
2010 }
2011
2012 if ($oldFashionedRestrictions != '') {
2013
2014 foreach( explode( ':', trim( $oldFashionedRestrictions ) ) as $restrict ) {
2015 $temp = explode( '=', trim( $restrict ) );
2016 if(count($temp) == 1) {
2017 // old old format should be treated as edit/move restriction
2018 $this->mRestrictions['edit'] = explode( ',', trim( $temp[0] ) );
2019 $this->mRestrictions['move'] = explode( ',', trim( $temp[0] ) );
2020 } else {
2021 $this->mRestrictions[$temp[0]] = explode( ',', trim( $temp[1] ) );
2022 }
2023 }
2024
2025 $this->mOldRestrictions = true;
2026
2027 }
2028
2029 if( count($rows) ) {
2030 # Current system - load second to make them override.
2031 $now = wfTimestampNow();
2032 $purgeExpired = false;
2033
2034 foreach( $rows as $row ) {
2035 # Cycle through all the restrictions.
2036
2037 // Don't take care of restrictions types that aren't allowed
2038
2039 if( !in_array( $row->pr_type, $restrictionTypes ) )
2040 continue;
2041
2042 // This code should be refactored, now that it's being used more generally,
2043 // But I don't really see any harm in leaving it in Block for now -werdna
2044 $expiry = Block::decodeExpiry( $row->pr_expiry );
2045
2046 // Only apply the restrictions if they haven't expired!
2047 if ( !$expiry || $expiry > $now ) {
2048 $this->mRestrictionsExpiry[$row->pr_type] = $expiry;
2049 $this->mRestrictions[$row->pr_type] = explode( ',', trim( $row->pr_level ) );
2050
2051 $this->mCascadeRestriction |= $row->pr_cascade;
2052 } else {
2053 // Trigger a lazy purge of expired restrictions
2054 $purgeExpired = true;
2055 }
2056 }
2057
2058 if( $purgeExpired ) {
2059 Title::purgeExpiredRestrictions();
2060 }
2061 }
2062
2063 $this->mRestrictionsLoaded = true;
2064 }
2065
2066 /**
2067 * Load restrictions from the page_restrictions table
2068 *
2069 * @param $oldFashionedRestrictions string comma-separated list of page
2070 * restrictions from page table (pre 1.10)
2071 */
2072 public function loadRestrictions( $oldFashionedRestrictions = null ) {
2073 if( !$this->mRestrictionsLoaded ) {
2074 if ($this->exists()) {
2075 $dbr = wfGetDB( DB_SLAVE );
2076
2077 $res = $dbr->select( 'page_restrictions', '*',
2078 array ( 'pr_page' => $this->getArticleId() ), __METHOD__ );
2079
2080 $this->loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions );
2081 } else {
2082 $title_protection = $this->getTitleProtection();
2083
2084 if (is_array($title_protection)) {
2085 extract($title_protection);
2086
2087 $now = wfTimestampNow();
2088 $expiry = Block::decodeExpiry($pt_expiry);
2089
2090 if (!$expiry || $expiry > $now) {
2091 // Apply the restrictions
2092 $this->mRestrictionsExpiry['create'] = $expiry;
2093 $this->mRestrictions['create'] = explode(',', trim($pt_create_perm) );
2094 } else { // Get rid of the old restrictions
2095 Title::purgeExpiredRestrictions();
2096 }
2097 } else {
2098 $this->mRestrictionsExpiry['create'] = Block::decodeExpiry('');
2099 }
2100 $this->mRestrictionsLoaded = true;
2101 }
2102 }
2103 }
2104
2105 /**
2106 * Purge expired restrictions from the page_restrictions table
2107 */
2108 static function purgeExpiredRestrictions() {
2109 $dbw = wfGetDB( DB_MASTER );
2110 $dbw->delete( 'page_restrictions',
2111 array( 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
2112 __METHOD__ );
2113
2114 $dbw->delete( 'protected_titles',
2115 array( 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
2116 __METHOD__ );
2117 }
2118
2119 /**
2120 * Accessor/initialisation for mRestrictions
2121 *
2122 * @param $action \type{\string} action that permission needs to be checked for
2123 * @return \type{\arrayof{\string}} the array of groups allowed to edit this article
2124 */
2125 public function getRestrictions( $action ) {
2126 if( !$this->mRestrictionsLoaded ) {
2127 $this->loadRestrictions();
2128 }
2129 return isset( $this->mRestrictions[$action] )
2130 ? $this->mRestrictions[$action]
2131 : array();
2132 }
2133
2134 /**
2135 * Get the expiry time for the restriction against a given action
2136 *
2137 * @return 14-char timestamp, or 'infinity' if the page is protected forever
2138 * or not protected at all, or false if the action is not recognised.
2139 */
2140 public function getRestrictionExpiry( $action ) {
2141 if( !$this->mRestrictionsLoaded ) {
2142 $this->loadRestrictions();
2143 }
2144 return isset( $this->mRestrictionsExpiry[$action] ) ? $this->mRestrictionsExpiry[$action] : false;
2145 }
2146
2147 /**
2148 * Is there a version of this page in the deletion archive?
2149 *
2150 * @return \type{\int} the number of archived revisions
2151 */
2152 public function isDeleted() {
2153 if( $this->getNamespace() < 0 ) {
2154 $n = 0;
2155 } else {
2156 $dbr = wfGetDB( DB_SLAVE );
2157 $n = $dbr->selectField( 'archive', 'COUNT(*)',
2158 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
2159 __METHOD__
2160 );
2161 if( $this->getNamespace() == NS_FILE ) {
2162 $n += $dbr->selectField( 'filearchive', 'COUNT(*)',
2163 array( 'fa_name' => $this->getDBkey() ),
2164 __METHOD__
2165 );
2166 }
2167 }
2168 return (int)$n;
2169 }
2170
2171 /**
2172 * Is there a version of this page in the deletion archive?
2173 *
2174 * @return Boolean
2175 */
2176 public function isDeletedQuick() {
2177 if( $this->getNamespace() < 0 ) {
2178 return false;
2179 }
2180 $dbr = wfGetDB( DB_SLAVE );
2181 $deleted = (bool)$dbr->selectField( 'archive', '1',
2182 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
2183 __METHOD__
2184 );
2185 if( !$deleted && $this->getNamespace() == NS_FILE ) {
2186 $deleted = (bool)$dbr->selectField( 'filearchive', '1',
2187 array( 'fa_name' => $this->getDBkey() ),
2188 __METHOD__
2189 );
2190 }
2191 return $deleted;
2192 }
2193
2194 /**
2195 * Get the article ID for this Title from the link cache,
2196 * adding it if necessary
2197 *
2198 * @param $flags \type{\int} a bit field; may be GAID_FOR_UPDATE to select
2199 * for update
2200 * @return \type{\int} the ID
2201 */
2202 public function getArticleID( $flags = 0 ) {
2203 if( $this->getNamespace() < 0 ) {
2204 return $this->mArticleID = 0;
2205 }
2206 $linkCache = LinkCache::singleton();
2207 if( $flags & GAID_FOR_UPDATE ) {
2208 $oldUpdate = $linkCache->forUpdate( true );
2209 $linkCache->clearLink( $this );
2210 $this->mArticleID = $linkCache->addLinkObj( $this );
2211 $linkCache->forUpdate( $oldUpdate );
2212 } else {
2213 if( -1 == $this->mArticleID ) {
2214 $this->mArticleID = $linkCache->addLinkObj( $this );
2215 }
2216 }
2217 return $this->mArticleID;
2218 }
2219
2220 /**
2221 * Is this an article that is a redirect page?
2222 * Uses link cache, adding it if necessary
2223 *
2224 * @param $flags \type{\int} a bit field; may be GAID_FOR_UPDATE to select for update
2225 * @return \type{\bool}
2226 */
2227 public function isRedirect( $flags = 0 ) {
2228 if( !is_null($this->mRedirect) )
2229 return $this->mRedirect;
2230 # Calling getArticleID() loads the field from cache as needed
2231 if( !$this->getArticleID($flags) ) {
2232 return $this->mRedirect = false;
2233 }
2234 $linkCache = LinkCache::singleton();
2235 $this->mRedirect = (bool)$linkCache->getGoodLinkFieldObj( $this, 'redirect' );
2236
2237 return $this->mRedirect;
2238 }
2239
2240 /**
2241 * What is the length of this page?
2242 * Uses link cache, adding it if necessary
2243 *
2244 * @param $flags \type{\int} a bit field; may be GAID_FOR_UPDATE to select for update
2245 * @return \type{\bool}
2246 */
2247 public function getLength( $flags = 0 ) {
2248 if( $this->mLength != -1 )
2249 return $this->mLength;
2250 # Calling getArticleID() loads the field from cache as needed
2251 if( !$this->getArticleID($flags) ) {
2252 return $this->mLength = 0;
2253 }
2254 $linkCache = LinkCache::singleton();
2255 $this->mLength = intval( $linkCache->getGoodLinkFieldObj( $this, 'length' ) );
2256
2257 return $this->mLength;
2258 }
2259
2260 /**
2261 * What is the page_latest field for this page?
2262 *
2263 * @param $flags \type{\int} a bit field; may be GAID_FOR_UPDATE to select for update
2264 * @return \type{\int} or false if the page doesn't exist
2265 */
2266 public function getLatestRevID( $flags = 0 ) {
2267 if( $this->mLatestID !== false )
2268 return $this->mLatestID;
2269
2270 $db = ($flags & GAID_FOR_UPDATE) ? wfGetDB(DB_MASTER) : wfGetDB(DB_SLAVE);
2271 $this->mLatestID = (int)$db->selectField(
2272 'page', 'page_latest', $this->pageCond(), __METHOD__ );
2273 return $this->mLatestID;
2274 }
2275
2276 /**
2277 * This clears some fields in this object, and clears any associated
2278 * keys in the "bad links" section of the link cache.
2279 *
2280 * - This is called from Article::insertNewArticle() to allow
2281 * loading of the new page_id. It's also called from
2282 * Article::doDeleteArticle()
2283 *
2284 * @param $newid \type{\int} the new Article ID
2285 */
2286 public function resetArticleID( $newid ) {
2287 $linkCache = LinkCache::singleton();
2288 $linkCache->clearBadLink( $this->getPrefixedDBkey() );
2289
2290 if ( $newid === false ) {
2291 $this->mArticleID = -1;
2292 } else {
2293 $this->mArticleID = intval( $newid );
2294 }
2295 $this->mRestrictionsLoaded = false;
2296 $this->mRestrictions = array();
2297 $this->mRedirect = null;
2298 $this->mLength = -1;
2299 $this->mLatestID = false;
2300 }
2301
2302 /**
2303 * Updates page_touched for this page; called from LinksUpdate.php
2304 *
2305 * @return \type{\bool} true if the update succeded
2306 */
2307 public function invalidateCache() {
2308 if( wfReadOnly() ) {
2309 return;
2310 }
2311 $dbw = wfGetDB( DB_MASTER );
2312 $success = $dbw->update( 'page',
2313 array( 'page_touched' => $dbw->timestamp() ),
2314 $this->pageCond(),
2315 __METHOD__
2316 );
2317 HTMLFileCache::clearFileCache( $this );
2318 return $success;
2319 }
2320
2321 /**
2322 * Prefix some arbitrary text with the namespace or interwiki prefix
2323 * of this object
2324 *
2325 * @param $name \type{\string} the text
2326 * @return \type{\string} the prefixed text
2327 * @private
2328 */
2329 /* private */ function prefix( $name ) {
2330 $p = '';
2331 if ( $this->mInterwiki != '' ) {
2332 $p = $this->mInterwiki . ':';
2333 }
2334 if ( 0 != $this->mNamespace ) {
2335 $p .= $this->getNsText() . ':';
2336 }
2337 return $p . $name;
2338 }
2339
2340 /**
2341 * Returns a simple regex that will match on characters and sequences invalid in titles.
2342 * Note that this doesn't pick up many things that could be wrong with titles, but that
2343 * replacing this regex with something valid will make many titles valid.
2344 *
2345 * @return string regex string
2346 */
2347 static function getTitleInvalidRegex() {
2348 static $rxTc = false;
2349 if( !$rxTc ) {
2350 # Matching titles will be held as illegal.
2351 $rxTc = '/' .
2352 # Any character not allowed is forbidden...
2353 '[^' . Title::legalChars() . ']' .
2354 # URL percent encoding sequences interfere with the ability
2355 # to round-trip titles -- you can't link to them consistently.
2356 '|%[0-9A-Fa-f]{2}' .
2357 # XML/HTML character references produce similar issues.
2358 '|&[A-Za-z0-9\x80-\xff]+;' .
2359 '|&#[0-9]+;' .
2360 '|&#x[0-9A-Fa-f]+;' .
2361 '/S';
2362 }
2363
2364 return $rxTc;
2365 }
2366
2367 /**
2368 * Capitalize a text string for a title if it belongs to a namespace that capitalizes
2369 *
2370 * @param $text string containing title to capitalize
2371 * @param $ns int namespace index, defaults to NS_MAIN
2372 * @return String containing capitalized title
2373 */
2374 public static function capitalize( $text, $ns = NS_MAIN ) {
2375 global $wgContLang;
2376
2377 if ( MWNamespace::isCapitalized( $ns ) )
2378 return $wgContLang->ucfirst( $text );
2379 else
2380 return $text;
2381 }
2382
2383 /**
2384 * Secure and split - main initialisation function for this object
2385 *
2386 * Assumes that mDbkeyform has been set, and is urldecoded
2387 * and uses underscores, but not otherwise munged. This function
2388 * removes illegal characters, splits off the interwiki and
2389 * namespace prefixes, sets the other forms, and canonicalizes
2390 * everything.
2391 *
2392 * @return \type{\bool} true on success
2393 */
2394 private function secureAndSplit() {
2395 global $wgContLang, $wgLocalInterwiki;
2396
2397 # Initialisation
2398 $rxTc = self::getTitleInvalidRegex();
2399
2400 $this->mInterwiki = $this->mFragment = '';
2401 $this->mNamespace = $this->mDefaultNamespace; # Usually NS_MAIN
2402
2403 $dbkey = $this->mDbkeyform;
2404
2405 # Strip Unicode bidi override characters.
2406 # Sometimes they slip into cut-n-pasted page titles, where the
2407 # override chars get included in list displays.
2408 $dbkey = preg_replace( '/\xE2\x80[\x8E\x8F\xAA-\xAE]/S', '', $dbkey );
2409
2410 # Clean up whitespace
2411 # Note: use of the /u option on preg_replace here will cause
2412 # input with invalid UTF-8 sequences to be nullified out in PHP 5.2.x,
2413 # conveniently disabling them.
2414 #
2415 $dbkey = preg_replace( '/[ _\xA0\x{1680}\x{180E}\x{2000}-\x{200A}\x{2028}\x{2029}\x{202F}\x{205F}\x{3000}]+/u', '_', $dbkey );
2416 $dbkey = trim( $dbkey, '_' );
2417
2418 if ( $dbkey == '' ) {
2419 return false;
2420 }
2421
2422 if( false !== strpos( $dbkey, UTF8_REPLACEMENT ) ) {
2423 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
2424 return false;
2425 }
2426
2427 $this->mDbkeyform = $dbkey;
2428
2429 # Initial colon indicates main namespace rather than specified default
2430 # but should not create invalid {ns,title} pairs such as {0,Project:Foo}
2431 if ( ':' == $dbkey{0} ) {
2432 $this->mNamespace = NS_MAIN;
2433 $dbkey = substr( $dbkey, 1 ); # remove the colon but continue processing
2434 $dbkey = trim( $dbkey, '_' ); # remove any subsequent whitespace
2435 }
2436
2437 # Namespace or interwiki prefix
2438 $firstPass = true;
2439 $prefixRegexp = "/^(.+?)_*:_*(.*)$/S";
2440 do {
2441 $m = array();
2442 if ( preg_match( $prefixRegexp, $dbkey, $m ) ) {
2443 $p = $m[1];
2444 if ( ( $ns = $wgContLang->getNsIndex( $p ) ) !== false ) {
2445 # Ordinary namespace
2446 $dbkey = $m[2];
2447 $this->mNamespace = $ns;
2448 # For Talk:X pages, check if X has a "namespace" prefix
2449 if( $ns == NS_TALK && preg_match( $prefixRegexp, $dbkey, $x ) ) {
2450 if( $wgContLang->getNsIndex( $x[1] ) )
2451 return false; # Disallow Talk:File:x type titles...
2452 else if( Interwiki::isValidInterwiki( $x[1] ) )
2453 return false; # Disallow Talk:Interwiki:x type titles...
2454 }
2455 } elseif( Interwiki::isValidInterwiki( $p ) ) {
2456 if( !$firstPass ) {
2457 # Can't make a local interwiki link to an interwiki link.
2458 # That's just crazy!
2459 return false;
2460 }
2461
2462 # Interwiki link
2463 $dbkey = $m[2];
2464 $this->mInterwiki = $wgContLang->lc( $p );
2465
2466 # Redundant interwiki prefix to the local wiki
2467 if ( 0 == strcasecmp( $this->mInterwiki, $wgLocalInterwiki ) ) {
2468 if( $dbkey == '' ) {
2469 # Can't have an empty self-link
2470 return false;
2471 }
2472 $this->mInterwiki = '';
2473 $firstPass = false;
2474 # Do another namespace split...
2475 continue;
2476 }
2477
2478 # If there's an initial colon after the interwiki, that also
2479 # resets the default namespace
2480 if ( $dbkey !== '' && $dbkey[0] == ':' ) {
2481 $this->mNamespace = NS_MAIN;
2482 $dbkey = substr( $dbkey, 1 );
2483 }
2484 }
2485 # If there's no recognized interwiki or namespace,
2486 # then let the colon expression be part of the title.
2487 }
2488 break;
2489 } while( true );
2490
2491 # We already know that some pages won't be in the database!
2492 #
2493 if ( $this->mInterwiki != '' || NS_SPECIAL == $this->mNamespace ) {
2494 $this->mArticleID = 0;
2495 }
2496 $fragment = strstr( $dbkey, '#' );
2497 if ( false !== $fragment ) {
2498 $this->setFragment( $fragment );
2499 $dbkey = substr( $dbkey, 0, strlen( $dbkey ) - strlen( $fragment ) );
2500 # remove whitespace again: prevents "Foo_bar_#"
2501 # becoming "Foo_bar_"
2502 $dbkey = preg_replace( '/_*$/', '', $dbkey );
2503 }
2504
2505 # Reject illegal characters.
2506 #
2507 if( preg_match( $rxTc, $dbkey ) ) {
2508 return false;
2509 }
2510
2511 /**
2512 * Pages with "/./" or "/../" appearing in the URLs will often be un-
2513 * reachable due to the way web browsers deal with 'relative' URLs.
2514 * Also, they conflict with subpage syntax. Forbid them explicitly.
2515 */
2516 if ( strpos( $dbkey, '.' ) !== false &&
2517 ( $dbkey === '.' || $dbkey === '..' ||
2518 strpos( $dbkey, './' ) === 0 ||
2519 strpos( $dbkey, '../' ) === 0 ||
2520 strpos( $dbkey, '/./' ) !== false ||
2521 strpos( $dbkey, '/../' ) !== false ||
2522 substr( $dbkey, -2 ) == '/.' ||
2523 substr( $dbkey, -3 ) == '/..' ) )
2524 {
2525 return false;
2526 }
2527
2528 /**
2529 * Magic tilde sequences? Nu-uh!
2530 */
2531 if( strpos( $dbkey, '~~~' ) !== false ) {
2532 return false;
2533 }
2534
2535 /**
2536 * Limit the size of titles to 255 bytes.
2537 * This is typically the size of the underlying database field.
2538 * We make an exception for special pages, which don't need to be stored
2539 * in the database, and may edge over 255 bytes due to subpage syntax
2540 * for long titles, e.g. [[Special:Block/Long name]]
2541 */
2542 if ( ( $this->mNamespace != NS_SPECIAL && strlen( $dbkey ) > 255 ) ||
2543 strlen( $dbkey ) > 512 )
2544 {
2545 return false;
2546 }
2547
2548 /**
2549 * Normally, all wiki links are forced to have
2550 * an initial capital letter so [[foo]] and [[Foo]]
2551 * point to the same place.
2552 *
2553 * Don't force it for interwikis, since the other
2554 * site might be case-sensitive.
2555 */
2556 $this->mUserCaseDBKey = $dbkey;
2557 if( $this->mInterwiki == '') {
2558 $dbkey = self::capitalize( $dbkey, $this->mNamespace );
2559 }
2560
2561 /**
2562 * Can't make a link to a namespace alone...
2563 * "empty" local links can only be self-links
2564 * with a fragment identifier.
2565 */
2566 if( $dbkey == '' &&
2567 $this->mInterwiki == '' &&
2568 $this->mNamespace != NS_MAIN ) {
2569 return false;
2570 }
2571 // Allow IPv6 usernames to start with '::' by canonicalizing IPv6 titles.
2572 // IP names are not allowed for accounts, and can only be referring to
2573 // edits from the IP. Given '::' abbreviations and caps/lowercaps,
2574 // there are numerous ways to present the same IP. Having sp:contribs scan
2575 // them all is silly and having some show the edits and others not is
2576 // inconsistent. Same for talk/userpages. Keep them normalized instead.
2577 $dbkey = ($this->mNamespace == NS_USER || $this->mNamespace == NS_USER_TALK) ?
2578 IP::sanitizeIP( $dbkey ) : $dbkey;
2579 // Any remaining initial :s are illegal.
2580 if ( $dbkey !== '' && ':' == $dbkey{0} ) {
2581 return false;
2582 }
2583
2584 # Fill fields
2585 $this->mDbkeyform = $dbkey;
2586 $this->mUrlform = wfUrlencode( $dbkey );
2587
2588 $this->mTextform = str_replace( '_', ' ', $dbkey );
2589
2590 return true;
2591 }
2592
2593 /**
2594 * Set the fragment for this title. Removes the first character from the
2595 * specified fragment before setting, so it assumes you're passing it with
2596 * an initial "#".
2597 *
2598 * Deprecated for public use, use Title::makeTitle() with fragment parameter.
2599 * Still in active use privately.
2600 *
2601 * @param $fragment \type{\string} text
2602 */
2603 public function setFragment( $fragment ) {
2604 $this->mFragment = str_replace( '_', ' ', substr( $fragment, 1 ) );
2605 }
2606
2607 /**
2608 * Get a Title object associated with the talk page of this article
2609 *
2610 * @return \type{Title} the object for the talk page
2611 */
2612 public function getTalkPage() {
2613 return Title::makeTitle( MWNamespace::getTalk( $this->getNamespace() ), $this->getDBkey() );
2614 }
2615
2616 /**
2617 * Get a title object associated with the subject page of this
2618 * talk page
2619 *
2620 * @return \type{Title} the object for the subject page
2621 */
2622 public function getSubjectPage() {
2623 // Is this the same title?
2624 $subjectNS = MWNamespace::getSubject( $this->getNamespace() );
2625 if( $this->getNamespace() == $subjectNS ) {
2626 return $this;
2627 }
2628 return Title::makeTitle( $subjectNS, $this->getDBkey() );
2629 }
2630
2631 /**
2632 * Get an array of Title objects linking to this Title
2633 * Also stores the IDs in the link cache.
2634 *
2635 * WARNING: do not use this function on arbitrary user-supplied titles!
2636 * On heavily-used templates it will max out the memory.
2637 *
2638 * @param $options Array: may be FOR UPDATE
2639 * @param $table String: table name
2640 * @param $prefix String: fields prefix
2641 * @return \type{\arrayof{Title}} the Title objects linking here
2642 */
2643 public function getLinksTo( $options = array(), $table = 'pagelinks', $prefix = 'pl' ) {
2644 $linkCache = LinkCache::singleton();
2645
2646 if ( count( $options ) > 0 ) {
2647 $db = wfGetDB( DB_MASTER );
2648 } else {
2649 $db = wfGetDB( DB_SLAVE );
2650 }
2651
2652 $res = $db->select( array( 'page', $table ),
2653 array( 'page_namespace', 'page_title', 'page_id', 'page_len', 'page_is_redirect' ),
2654 array(
2655 "{$prefix}_from=page_id",
2656 "{$prefix}_namespace" => $this->getNamespace(),
2657 "{$prefix}_title" => $this->getDBkey() ),
2658 __METHOD__,
2659 $options );
2660
2661 $retVal = array();
2662 if ( $db->numRows( $res ) ) {
2663 foreach( $res as $row ) {
2664 if ( $titleObj = Title::makeTitle( $row->page_namespace, $row->page_title ) ) {
2665 $linkCache->addGoodLinkObj( $row->page_id, $titleObj, $row->page_len, $row->page_is_redirect );
2666 $retVal[] = $titleObj;
2667 }
2668 }
2669 }
2670 $db->freeResult( $res );
2671 return $retVal;
2672 }
2673
2674 /**
2675 * Get an array of Title objects using this Title as a template
2676 * Also stores the IDs in the link cache.
2677 *
2678 * WARNING: do not use this function on arbitrary user-supplied titles!
2679 * On heavily-used templates it will max out the memory.
2680 *
2681 * @param $options Array: may be FOR UPDATE
2682 * @return \type{\arrayof{Title}} the Title objects linking here
2683 */
2684 public function getTemplateLinksTo( $options = array() ) {
2685 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
2686 }
2687
2688 /**
2689 * Get an array of Title objects referring to non-existent articles linked from this page
2690 *
2691 * @todo check if needed (used only in SpecialBrokenRedirects.php, and should use redirect table in this case)
2692 * @return \type{\arrayof{Title}} the Title objects
2693 */
2694 public function getBrokenLinksFrom() {
2695 if ( $this->getArticleId() == 0 ) {
2696 # All links from article ID 0 are false positives
2697 return array();
2698 }
2699
2700 $dbr = wfGetDB( DB_SLAVE );
2701 $res = $dbr->select(
2702 array( 'page', 'pagelinks' ),
2703 array( 'pl_namespace', 'pl_title' ),
2704 array(
2705 'pl_from' => $this->getArticleId(),
2706 'page_namespace IS NULL'
2707 ),
2708 __METHOD__, array(),
2709 array(
2710 'page' => array(
2711 'LEFT JOIN',
2712 array( 'pl_namespace=page_namespace', 'pl_title=page_title' )
2713 )
2714 )
2715 );
2716
2717 $retVal = array();
2718 foreach( $res as $row ) {
2719 $retVal[] = Title::makeTitle( $row->pl_namespace, $row->pl_title );
2720 }
2721 return $retVal;
2722 }
2723
2724
2725 /**
2726 * Get a list of URLs to purge from the Squid cache when this
2727 * page changes
2728 *
2729 * @return \type{\arrayof{\string}} the URLs
2730 */
2731 public function getSquidURLs() {
2732 global $wgContLang;
2733
2734 $urls = array(
2735 $this->getInternalURL(),
2736 $this->getInternalURL( 'action=history' )
2737 );
2738
2739 // purge variant urls as well
2740 if($wgContLang->hasVariants()){
2741 $variants = $wgContLang->getVariants();
2742 foreach($variants as $vCode){
2743 if($vCode==$wgContLang->getCode()) continue; // we don't want default variant
2744 $urls[] = $this->getInternalURL('',$vCode);
2745 }
2746 }
2747
2748 return $urls;
2749 }
2750
2751 /**
2752 * Purge all applicable Squid URLs
2753 */
2754 public function purgeSquid() {
2755 global $wgUseSquid;
2756 if ( $wgUseSquid ) {
2757 $urls = $this->getSquidURLs();
2758 $u = new SquidUpdate( $urls );
2759 $u->doUpdate();
2760 }
2761 }
2762
2763 /**
2764 * Move this page without authentication
2765 *
2766 * @param $nt \type{Title} the new page Title
2767 * @return \type{\mixed} true on success, getUserPermissionsErrors()-like array on failure
2768 */
2769 public function moveNoAuth( &$nt ) {
2770 return $this->moveTo( $nt, false );
2771 }
2772
2773 /**
2774 * Check whether a given move operation would be valid.
2775 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
2776 *
2777 * @param $nt \type{Title} the new title
2778 * @param $auth \type{\bool} indicates whether $wgUser's permissions
2779 * should be checked
2780 * @param $reason \type{\string} is the log summary of the move, used for spam checking
2781 * @return \type{\mixed} True on success, getUserPermissionsErrors()-like array on failure
2782 */
2783 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
2784 global $wgUser;
2785
2786 $errors = array();
2787 if( !$nt ) {
2788 // Normally we'd add this to $errors, but we'll get
2789 // lots of syntax errors if $nt is not an object
2790 return array(array('badtitletext'));
2791 }
2792 if( $this->equals( $nt ) ) {
2793 $errors[] = array('selfmove');
2794 }
2795 if( !$this->isMovable() ) {
2796 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
2797 }
2798 if ( $nt->getInterwiki() != '' ) {
2799 $errors[] = array( 'immobile-target-namespace-iw' );
2800 }
2801 if ( !$nt->isMovable() ) {
2802 $errors[] = array('immobile-target-namespace', $nt->getNsText() );
2803 }
2804
2805 $oldid = $this->getArticleID();
2806 $newid = $nt->getArticleID();
2807
2808 if ( strlen( $nt->getDBkey() ) < 1 ) {
2809 $errors[] = array('articleexists');
2810 }
2811 if ( ( $this->getDBkey() == '' ) ||
2812 ( !$oldid ) ||
2813 ( $nt->getDBkey() == '' ) ) {
2814 $errors[] = array('badarticleerror');
2815 }
2816
2817 // Image-specific checks
2818 if( $this->getNamespace() == NS_FILE ) {
2819 $file = wfLocalFile( $this );
2820 if( $file->exists() ) {
2821 if( $nt->getNamespace() != NS_FILE ) {
2822 $errors[] = array('imagenocrossnamespace');
2823 }
2824 if( $nt->getText() != wfStripIllegalFilenameChars( $nt->getText() ) ) {
2825 $errors[] = array('imageinvalidfilename');
2826 }
2827 if( !File::checkExtensionCompatibility( $file, $nt->getDBkey() ) ) {
2828 $errors[] = array('imagetypemismatch');
2829 }
2830 }
2831 $destfile = wfLocalFile( $nt );
2832 if( !$wgUser->isAllowed( 'reupload-shared' ) && !$destfile->exists() && wfFindFile( $nt ) ) {
2833 $errors[] = array( 'file-exists-sharedrepo' );
2834 }
2835
2836 }
2837
2838 if ( $auth ) {
2839 $errors = wfMergeErrorArrays( $errors,
2840 $this->getUserPermissionsErrors('move', $wgUser),
2841 $this->getUserPermissionsErrors('edit', $wgUser),
2842 $nt->getUserPermissionsErrors('move-target', $wgUser),
2843 $nt->getUserPermissionsErrors('edit', $wgUser) );
2844 }
2845
2846 $match = EditPage::matchSummarySpamRegex( $reason );
2847 if( $match !== false ) {
2848 // This is kind of lame, won't display nice
2849 $errors[] = array('spamprotectiontext');
2850 }
2851
2852 $err = null;
2853 if( !wfRunHooks( 'AbortMove', array( $this, $nt, $wgUser, &$err, $reason ) ) ) {
2854 $errors[] = array('hookaborted', $err);
2855 }
2856
2857 # The move is allowed only if (1) the target doesn't exist, or
2858 # (2) the target is a redirect to the source, and has no history
2859 # (so we can undo bad moves right after they're done).
2860
2861 if ( 0 != $newid ) { # Target exists; check for validity
2862 if ( ! $this->isValidMoveTarget( $nt ) ) {
2863 $errors[] = array('articleexists');
2864 }
2865 } else {
2866 $tp = $nt->getTitleProtection();
2867 $right = ( $tp['pt_create_perm'] == 'sysop' ) ? 'protect' : $tp['pt_create_perm'];
2868 if ( $tp and !$wgUser->isAllowed( $right ) ) {
2869 $errors[] = array('cantmove-titleprotected');
2870 }
2871 }
2872 if(empty($errors))
2873 return true;
2874 return $errors;
2875 }
2876
2877 /**
2878 * Move a title to a new location
2879 *
2880 * @param $nt \type{Title} the new title
2881 * @param $auth \type{\bool} indicates whether $wgUser's permissions
2882 * should be checked
2883 * @param $reason \type{\string} The reason for the move
2884 * @param $createRedirect \type{\bool} Whether to create a redirect from the old title to the new title.
2885 * Ignored if the user doesn't have the suppressredirect right.
2886 * @return \type{\mixed} true on success, getUserPermissionsErrors()-like array on failure
2887 */
2888 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true ) {
2889 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
2890 if( is_array( $err ) ) {
2891 return $err;
2892 }
2893
2894 // If it is a file, move it first. It is done before all other moving stuff is done because it's hard to revert
2895 $dbw = wfGetDB( DB_MASTER );
2896 if( $this->getNamespace() == NS_FILE ) {
2897 $file = wfLocalFile( $this );
2898 if( $file->exists() ) {
2899 $status = $file->move( $nt );
2900 if( !$status->isOk() ) {
2901 return $status->getErrorsArray();
2902 }
2903 }
2904 }
2905
2906 $pageid = $this->getArticleID();
2907 $protected = $this->isProtected();
2908 if( $nt->exists() ) {
2909 $err = $this->moveOverExistingRedirect( $nt, $reason, $createRedirect );
2910 $pageCountChange = ($createRedirect ? 0 : -1);
2911 } else { # Target didn't exist, do normal move.
2912 $err = $this->moveToNewTitle( $nt, $reason, $createRedirect );
2913 $pageCountChange = ($createRedirect ? 1 : 0);
2914 }
2915
2916 if( is_array( $err ) ) {
2917 return $err;
2918 }
2919 $redirid = $this->getArticleID();
2920
2921 // Category memberships include a sort key which may be customized.
2922 // If it's left as the default (the page title), we need to update
2923 // the sort key to match the new title.
2924 //
2925 // Be careful to avoid resetting cl_timestamp, which may disturb
2926 // time-based lists on some sites.
2927 //
2928 // Warning -- if the sort key is *explicitly* set to the old title,
2929 // we can't actually distinguish it from a default here, and it'll
2930 // be set to the new title even though it really shouldn't.
2931 // It'll get corrected on the next edit, but resetting cl_timestamp.
2932 $dbw->update( 'categorylinks',
2933 array(
2934 'cl_sortkey' => $nt->getPrefixedText(),
2935 'cl_timestamp=cl_timestamp' ),
2936 array(
2937 'cl_from' => $pageid,
2938 'cl_sortkey' => $this->getPrefixedText() ),
2939 __METHOD__ );
2940
2941 if( $protected ) {
2942 # Protect the redirect title as the title used to be...
2943 $dbw->insertSelect( 'page_restrictions', 'page_restrictions',
2944 array(
2945 'pr_page' => $redirid,
2946 'pr_type' => 'pr_type',
2947 'pr_level' => 'pr_level',
2948 'pr_cascade' => 'pr_cascade',
2949 'pr_user' => 'pr_user',
2950 'pr_expiry' => 'pr_expiry'
2951 ),
2952 array( 'pr_page' => $pageid ),
2953 __METHOD__,
2954 array( 'IGNORE' )
2955 );
2956 # Update the protection log
2957 $log = new LogPage( 'protect' );
2958 $comment = wfMsgForContent( 'prot_1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
2959 if( $reason ) $comment .= wfMsgForContent( 'colon-separator' ) . $reason;
2960 $log->addEntry( 'move_prot', $nt, $comment, array($this->getPrefixedText()) ); // FIXME: $params?
2961 }
2962
2963 # Update watchlists
2964 $oldnamespace = $this->getNamespace() & ~1;
2965 $newnamespace = $nt->getNamespace() & ~1;
2966 $oldtitle = $this->getDBkey();
2967 $newtitle = $nt->getDBkey();
2968
2969 if( $oldnamespace != $newnamespace || $oldtitle != $newtitle ) {
2970 WatchedItem::duplicateEntries( $this, $nt );
2971 }
2972
2973 # Update search engine
2974 $u = new SearchUpdate( $pageid, $nt->getPrefixedDBkey() );
2975 $u->doUpdate();
2976 $u = new SearchUpdate( $redirid, $this->getPrefixedDBkey(), '' );
2977 $u->doUpdate();
2978
2979 # Update site_stats
2980 if( $this->isContentPage() && !$nt->isContentPage() ) {
2981 # No longer a content page
2982 # Not viewed, edited, removing
2983 $u = new SiteStatsUpdate( 0, 1, -1, $pageCountChange );
2984 } elseif( !$this->isContentPage() && $nt->isContentPage() ) {
2985 # Now a content page
2986 # Not viewed, edited, adding
2987 $u = new SiteStatsUpdate( 0, 1, +1, $pageCountChange );
2988 } elseif( $pageCountChange ) {
2989 # Redirect added
2990 $u = new SiteStatsUpdate( 0, 0, 0, 1 );
2991 } else {
2992 # Nothing special
2993 $u = false;
2994 }
2995 if( $u )
2996 $u->doUpdate();
2997 # Update message cache for interface messages
2998 if( $nt->getNamespace() == NS_MEDIAWIKI ) {
2999 global $wgMessageCache;
3000
3001 # @bug 17860: old article can be deleted, if this the case,
3002 # delete it from message cache
3003 if ( $this->getArticleID() === 0 ) {
3004 $wgMessageCache->replace( $this->getDBkey(), false );
3005 } else {
3006 $oldarticle = new Article( $this );
3007 $wgMessageCache->replace( $this->getDBkey(), $oldarticle->getContent() );
3008 }
3009
3010 $newarticle = new Article( $nt );
3011 $wgMessageCache->replace( $nt->getDBkey(), $newarticle->getContent() );
3012 }
3013
3014 global $wgUser;
3015 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) );
3016 return true;
3017 }
3018
3019 /**
3020 * Move page to a title which is at present a redirect to the
3021 * source page
3022 *
3023 * @param $nt \type{Title} the page to move to, which should currently
3024 * be a redirect
3025 * @param $reason \type{\string} The reason for the move
3026 * @param $createRedirect \type{\bool} Whether to leave a redirect at the old title.
3027 * Ignored if the user doesn't have the suppressredirect right
3028 */
3029 private function moveOverExistingRedirect( &$nt, $reason = '', $createRedirect = true ) {
3030 global $wgUseSquid, $wgUser, $wgContLang;
3031
3032 $comment = wfMsgForContent( '1movedto2_redir', $this->getPrefixedText(), $nt->getPrefixedText() );
3033
3034 if ( $reason ) {
3035 $comment .= wfMsgForContent( 'colon-separator' ) . $reason;
3036 }
3037 # Truncate for whole multibyte characters. +5 bytes for ellipsis
3038 $comment = $wgContLang->truncate( $comment, 250 );
3039
3040 $now = wfTimestampNow();
3041 $newid = $nt->getArticleID();
3042 $oldid = $this->getArticleID();
3043 $latest = $this->getLatestRevID();
3044
3045 $dbw = wfGetDB( DB_MASTER );
3046
3047 $rcts = $dbw->timestamp( $nt->getEarliestRevTime() );
3048 $newns = $nt->getNamespace();
3049 $newdbk = $nt->getDBkey();
3050
3051 # Delete the old redirect. We don't save it to history since
3052 # by definition if we've got here it's rather uninteresting.
3053 # We have to remove it so that the next step doesn't trigger
3054 # a conflict on the unique namespace+title index...
3055 $dbw->delete( 'page', array( 'page_id' => $newid ), __METHOD__ );
3056 if ( !$dbw->cascadingDeletes() ) {
3057 $dbw->delete( 'revision', array( 'rev_page' => $newid ), __METHOD__ );
3058 global $wgUseTrackbacks;
3059 if ($wgUseTrackbacks)
3060 $dbw->delete( 'trackbacks', array( 'tb_page' => $newid ), __METHOD__ );
3061 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), __METHOD__ );
3062 $dbw->delete( 'imagelinks', array( 'il_from' => $newid ), __METHOD__ );
3063 $dbw->delete( 'categorylinks', array( 'cl_from' => $newid ), __METHOD__ );
3064 $dbw->delete( 'templatelinks', array( 'tl_from' => $newid ), __METHOD__ );
3065 $dbw->delete( 'externallinks', array( 'el_from' => $newid ), __METHOD__ );
3066 $dbw->delete( 'langlinks', array( 'll_from' => $newid ), __METHOD__ );
3067 $dbw->delete( 'redirect', array( 'rd_from' => $newid ), __METHOD__ );
3068 }
3069 // If the redirect was recently created, it may have an entry in recentchanges still
3070 $dbw->delete( 'recentchanges',
3071 array( 'rc_timestamp' => $rcts, 'rc_namespace' => $newns, 'rc_title' => $newdbk, 'rc_new' => 1 ),
3072 __METHOD__
3073 );
3074
3075 # Save a null revision in the page's history notifying of the move
3076 $nullRevision = Revision::newNullRevision( $dbw, $oldid, $comment, true );
3077 $nullRevId = $nullRevision->insertOn( $dbw );
3078
3079 $article = new Article( $this );
3080 wfRunHooks( 'NewRevisionFromEditComplete', array($article, $nullRevision, $latest, $wgUser) );
3081
3082 # Change the name of the target page:
3083 $dbw->update( 'page',
3084 /* SET */ array(
3085 'page_touched' => $dbw->timestamp($now),
3086 'page_namespace' => $nt->getNamespace(),
3087 'page_title' => $nt->getDBkey(),
3088 'page_latest' => $nullRevId,
3089 ),
3090 /* WHERE */ array( 'page_id' => $oldid ),
3091 __METHOD__
3092 );
3093 $nt->resetArticleID( $oldid );
3094
3095 # Recreate the redirect, this time in the other direction.
3096 if( $createRedirect || !$wgUser->isAllowed('suppressredirect') ) {
3097 $mwRedir = MagicWord::get( 'redirect' );
3098 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
3099 $redirectArticle = new Article( $this );
3100 $newid = $redirectArticle->insertOn( $dbw );
3101 $redirectRevision = new Revision( array(
3102 'page' => $newid,
3103 'comment' => $comment,
3104 'text' => $redirectText ) );
3105 $redirectRevision->insertOn( $dbw );
3106 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
3107
3108 wfRunHooks( 'NewRevisionFromEditComplete', array($redirectArticle, $redirectRevision, false, $wgUser) );
3109
3110 # Now, we record the link from the redirect to the new title.
3111 # It should have no other outgoing links...
3112 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), __METHOD__ );
3113 $dbw->insert( 'pagelinks',
3114 array(
3115 'pl_from' => $newid,
3116 'pl_namespace' => $nt->getNamespace(),
3117 'pl_title' => $nt->getDBkey() ),
3118 __METHOD__ );
3119 $redirectSuppressed = false;
3120 } else {
3121 $this->resetArticleID( 0 );
3122 $redirectSuppressed = true;
3123 }
3124
3125 # Log the move
3126 $log = new LogPage( 'move' );
3127 $log->addEntry( 'move_redir', $this, $reason, array( 1 => $nt->getPrefixedText(), 2 => $redirectSuppressed ) );
3128
3129 # Purge squid
3130 if ( $wgUseSquid ) {
3131 $urls = array_merge( $nt->getSquidURLs(), $this->getSquidURLs() );
3132 $u = new SquidUpdate( $urls );
3133 $u->doUpdate();
3134 }
3135
3136 }
3137
3138 /**
3139 * Move page to non-existing title.
3140 *
3141 * @param $nt \type{Title} the new Title
3142 * @param $reason \type{\string} The reason for the move
3143 * @param $createRedirect \type{\bool} Whether to create a redirect from the old title to the new title
3144 * Ignored if the user doesn't have the suppressredirect right
3145 */
3146 private function moveToNewTitle( &$nt, $reason = '', $createRedirect = true ) {
3147 global $wgUseSquid, $wgUser, $wgContLang;
3148
3149 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
3150 if ( $reason ) {
3151 $comment .= wfMsgExt( 'colon-separator',
3152 array( 'escapenoentities', 'content' ) );
3153 $comment .= $reason;
3154 }
3155 # Truncate for whole multibyte characters. +5 bytes for ellipsis
3156 $comment = $wgContLang->truncate( $comment, 250 );
3157
3158 $newid = $nt->getArticleID();
3159 $oldid = $this->getArticleID();
3160 $latest = $this->getLatestRevId();
3161
3162 $dbw = wfGetDB( DB_MASTER );
3163 $now = $dbw->timestamp();
3164
3165 # Save a null revision in the page's history notifying of the move
3166 $nullRevision = Revision::newNullRevision( $dbw, $oldid, $comment, true );
3167 if ( !is_object( $nullRevision ) ) {
3168 throw new MWException( 'No valid null revision produced in ' . __METHOD__ );
3169 }
3170 $nullRevId = $nullRevision->insertOn( $dbw );
3171
3172 $article = new Article( $this );
3173 wfRunHooks( 'NewRevisionFromEditComplete', array($article, $nullRevision, $latest, $wgUser) );
3174
3175 # Rename page entry
3176 $dbw->update( 'page',
3177 /* SET */ array(
3178 'page_touched' => $now,
3179 'page_namespace' => $nt->getNamespace(),
3180 'page_title' => $nt->getDBkey(),
3181 'page_latest' => $nullRevId,
3182 ),
3183 /* WHERE */ array( 'page_id' => $oldid ),
3184 __METHOD__
3185 );
3186 $nt->resetArticleID( $oldid );
3187
3188 if( $createRedirect || !$wgUser->isAllowed('suppressredirect') ) {
3189 # Insert redirect
3190 $mwRedir = MagicWord::get( 'redirect' );
3191 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
3192 $redirectArticle = new Article( $this );
3193 $newid = $redirectArticle->insertOn( $dbw );
3194 $redirectRevision = new Revision( array(
3195 'page' => $newid,
3196 'comment' => $comment,
3197 'text' => $redirectText ) );
3198 $redirectRevision->insertOn( $dbw );
3199 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
3200
3201 wfRunHooks( 'NewRevisionFromEditComplete', array($redirectArticle, $redirectRevision, false, $wgUser) );
3202
3203 # Record the just-created redirect's linking to the page
3204 $dbw->insert( 'pagelinks',
3205 array(
3206 'pl_from' => $newid,
3207 'pl_namespace' => $nt->getNamespace(),
3208 'pl_title' => $nt->getDBkey() ),
3209 __METHOD__ );
3210 $redirectSuppressed = false;
3211 } else {
3212 $this->resetArticleID( 0 );
3213 $redirectSuppressed = true;
3214 }
3215
3216 # Log the move
3217 $log = new LogPage( 'move' );
3218 $log->addEntry( 'move', $this, $reason, array( 1 => $nt->getPrefixedText(), 2 => $redirectSuppressed ) );
3219
3220 # Purge caches as per article creation
3221 Article::onArticleCreate( $nt );
3222
3223 # Purge old title from squid
3224 # The new title, and links to the new title, are purged in Article::onArticleCreate()
3225 $this->purgeSquid();
3226
3227 }
3228
3229 /**
3230 * Move this page's subpages to be subpages of $nt
3231 *
3232 * @param $nt Title Move target
3233 * @param $auth bool Whether $wgUser's permissions should be checked
3234 * @param $reason string The reason for the move
3235 * @param $createRedirect bool Whether to create redirects from the old subpages to the new ones
3236 * Ignored if the user doesn't have the 'suppressredirect' right
3237 * @return mixed array with old page titles as keys, and strings (new page titles) or
3238 * arrays (errors) as values, or an error array with numeric indices if no pages were moved
3239 */
3240 public function moveSubpages( $nt, $auth = true, $reason = '', $createRedirect = true ) {
3241 global $wgMaximumMovedPages;
3242 // Check permissions
3243 if( !$this->userCan( 'move-subpages' ) )
3244 return array( 'cant-move-subpages' );
3245 // Do the source and target namespaces support subpages?
3246 if( !MWNamespace::hasSubpages( $this->getNamespace() ) )
3247 return array( 'namespace-nosubpages',
3248 MWNamespace::getCanonicalName( $this->getNamespace() ) );
3249 if( !MWNamespace::hasSubpages( $nt->getNamespace() ) )
3250 return array( 'namespace-nosubpages',
3251 MWNamespace::getCanonicalName( $nt->getNamespace() ) );
3252
3253 $subpages = $this->getSubpages($wgMaximumMovedPages + 1);
3254 $retval = array();
3255 $count = 0;
3256 foreach( $subpages as $oldSubpage ) {
3257 $count++;
3258 if( $count > $wgMaximumMovedPages ) {
3259 $retval[$oldSubpage->getPrefixedTitle()] =
3260 array( 'movepage-max-pages',
3261 $wgMaximumMovedPages );
3262 break;
3263 }
3264
3265 // We don't know whether this function was called before
3266 // or after moving the root page, so check both
3267 // $this and $nt
3268 if( $oldSubpage->getArticleId() == $this->getArticleId() ||
3269 $oldSubpage->getArticleID() == $nt->getArticleId() )
3270 // When moving a page to a subpage of itself,
3271 // don't move it twice
3272 continue;
3273 $newPageName = preg_replace(
3274 '#^'.preg_quote( $this->getDBkey(), '#' ).'#',
3275 StringUtils::escapeRegexReplacement( $nt->getDBkey() ), # bug 21234
3276 $oldSubpage->getDBkey() );
3277 if( $oldSubpage->isTalkPage() ) {
3278 $newNs = $nt->getTalkPage()->getNamespace();
3279 } else {
3280 $newNs = $nt->getSubjectPage()->getNamespace();
3281 }
3282 # Bug 14385: we need makeTitleSafe because the new page names may
3283 # be longer than 255 characters.
3284 $newSubpage = Title::makeTitleSafe( $newNs, $newPageName );
3285
3286 $success = $oldSubpage->moveTo( $newSubpage, $auth, $reason, $createRedirect );
3287 if( $success === true ) {
3288 $retval[$oldSubpage->getPrefixedText()] = $newSubpage->getPrefixedText();
3289 } else {
3290 $retval[$oldSubpage->getPrefixedText()] = $success;
3291 }
3292 }
3293 return $retval;
3294 }
3295
3296 /**
3297 * Checks if this page is just a one-rev redirect.
3298 * Adds lock, so don't use just for light purposes.
3299 *
3300 * @return \type{\bool}
3301 */
3302 public function isSingleRevRedirect() {
3303 $dbw = wfGetDB( DB_MASTER );
3304 # Is it a redirect?
3305 $row = $dbw->selectRow( 'page',
3306 array( 'page_is_redirect', 'page_latest', 'page_id' ),
3307 $this->pageCond(),
3308 __METHOD__,
3309 array( 'FOR UPDATE' )
3310 );
3311 # Cache some fields we may want
3312 $this->mArticleID = $row ? intval($row->page_id) : 0;
3313 $this->mRedirect = $row ? (bool)$row->page_is_redirect : false;
3314 $this->mLatestID = $row ? intval($row->page_latest) : false;
3315 if( !$this->mRedirect ) {
3316 return false;
3317 }
3318 # Does the article have a history?
3319 $row = $dbw->selectField( array( 'page', 'revision'),
3320 'rev_id',
3321 array( 'page_namespace' => $this->getNamespace(),
3322 'page_title' => $this->getDBkey(),
3323 'page_id=rev_page',
3324 'page_latest != rev_id'
3325 ),
3326 __METHOD__,
3327 array( 'FOR UPDATE' )
3328 );
3329 # Return true if there was no history
3330 return ($row === false);
3331 }
3332
3333 /**
3334 * Checks if $this can be moved to a given Title
3335 * - Selects for update, so don't call it unless you mean business
3336 *
3337 * @param $nt \type{Title} the new title to check
3338 * @return \type{\bool} TRUE or FALSE
3339 */
3340 public function isValidMoveTarget( $nt ) {
3341 $dbw = wfGetDB( DB_MASTER );
3342 # Is it an existsing file?
3343 if( $nt->getNamespace() == NS_FILE ) {
3344 $file = wfLocalFile( $nt );
3345 if( $file->exists() ) {
3346 wfDebug( __METHOD__ . ": file exists\n" );
3347 return false;
3348 }
3349 }
3350 # Is it a redirect with no history?
3351 if( !$nt->isSingleRevRedirect() ) {
3352 wfDebug( __METHOD__ . ": not a one-rev redirect\n" );
3353 return false;
3354 }
3355 # Get the article text
3356 $rev = Revision::newFromTitle( $nt );
3357 $text = $rev->getText();
3358 # Does the redirect point to the source?
3359 # Or is it a broken self-redirect, usually caused by namespace collisions?
3360 $m = array();
3361 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $text, $m ) ) {
3362 $redirTitle = Title::newFromText( $m[1] );
3363 if( !is_object( $redirTitle ) ||
3364 ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
3365 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) ) {
3366 wfDebug( __METHOD__ . ": redirect points to other page\n" );
3367 return false;
3368 }
3369 } else {
3370 # Fail safe
3371 wfDebug( __METHOD__ . ": failsafe\n" );
3372 return false;
3373 }
3374 return true;
3375 }
3376
3377 /**
3378 * Can this title be added to a user's watchlist?
3379 *
3380 * @return \type{\bool} TRUE or FALSE
3381 */
3382 public function isWatchable() {
3383 return !$this->isExternal() && MWNamespace::isWatchable( $this->getNamespace() );
3384 }
3385
3386 /**
3387 * Get categories to which this Title belongs and return an array of
3388 * categories' names.
3389 *
3390 * @return \type{\array} array an array of parents in the form:
3391 * $parent => $currentarticle
3392 */
3393 public function getParentCategories() {
3394 global $wgContLang;
3395
3396 $titlekey = $this->getArticleId();
3397 $dbr = wfGetDB( DB_SLAVE );
3398 $categorylinks = $dbr->tableName( 'categorylinks' );
3399
3400 # NEW SQL
3401 $sql = "SELECT * FROM $categorylinks"
3402 ." WHERE cl_from='$titlekey'"
3403 ." AND cl_from <> '0'"
3404 ." ORDER BY cl_sortkey";
3405
3406 $res = $dbr->query( $sql );
3407
3408 if( $dbr->numRows( $res ) > 0 ) {
3409 foreach( $res as $row )
3410 //$data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$row->cl_to);
3411 $data[$wgContLang->getNSText( NS_CATEGORY ).':'.$row->cl_to] = $this->getFullText();
3412 $dbr->freeResult( $res );
3413 } else {
3414 $data = array();
3415 }
3416 return $data;
3417 }
3418
3419 /**
3420 * Get a tree of parent categories
3421 *
3422 * @param $children \type{\array} an array with the children in the keys, to check for circular refs
3423 * @return \type{\array} Tree of parent categories
3424 */
3425 public function getParentCategoryTree( $children = array() ) {
3426 $stack = array();
3427 $parents = $this->getParentCategories();
3428
3429 if( $parents ) {
3430 foreach( $parents as $parent => $current ) {
3431 if ( array_key_exists( $parent, $children ) ) {
3432 # Circular reference
3433 $stack[$parent] = array();
3434 } else {
3435 $nt = Title::newFromText($parent);
3436 if ( $nt ) {
3437 $stack[$parent] = $nt->getParentCategoryTree( $children + array($parent => 1) );
3438 }
3439 }
3440 }
3441 return $stack;
3442 } else {
3443 return array();
3444 }
3445 }
3446
3447
3448 /**
3449 * Get an associative array for selecting this title from
3450 * the "page" table
3451 *
3452 * @return \type{\array} Selection array
3453 */
3454 public function pageCond() {
3455 if( $this->mArticleID > 0 ) {
3456 // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs
3457 return array( 'page_id' => $this->mArticleID );
3458 } else {
3459 return array( 'page_namespace' => $this->mNamespace, 'page_title' => $this->mDbkeyform );
3460 }
3461 }
3462
3463 /**
3464 * Get the revision ID of the previous revision
3465 *
3466 * @param $revId \type{\int} Revision ID. Get the revision that was before this one.
3467 * @param $flags \type{\int} GAID_FOR_UPDATE
3468 * @return \twotypes{\int,\bool} Old revision ID, or FALSE if none exists
3469 */
3470 public function getPreviousRevisionID( $revId, $flags=0 ) {
3471 $db = ($flags & GAID_FOR_UPDATE) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
3472 return $db->selectField( 'revision', 'rev_id',
3473 array(
3474 'rev_page' => $this->getArticleId($flags),
3475 'rev_id < ' . intval( $revId )
3476 ),
3477 __METHOD__,
3478 array( 'ORDER BY' => 'rev_id DESC' )
3479 );
3480 }
3481
3482 /**
3483 * Get the revision ID of the next revision
3484 *
3485 * @param $revId \type{\int} Revision ID. Get the revision that was after this one.
3486 * @param $flags \type{\int} GAID_FOR_UPDATE
3487 * @return \twotypes{\int,\bool} Next revision ID, or FALSE if none exists
3488 */
3489 public function getNextRevisionID( $revId, $flags=0 ) {
3490 $db = ($flags & GAID_FOR_UPDATE) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
3491 return $db->selectField( 'revision', 'rev_id',
3492 array(
3493 'rev_page' => $this->getArticleId($flags),
3494 'rev_id > ' . intval( $revId )
3495 ),
3496 __METHOD__,
3497 array( 'ORDER BY' => 'rev_id' )
3498 );
3499 }
3500
3501 /**
3502 * Get the first revision of the page
3503 *
3504 * @param $flags \type{\int} GAID_FOR_UPDATE
3505 * @return Revision (or NULL if page doesn't exist)
3506 */
3507 public function getFirstRevision( $flags=0 ) {
3508 $db = ($flags & GAID_FOR_UPDATE) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
3509 $pageId = $this->getArticleId($flags);
3510 if( !$pageId ) return null;
3511 $row = $db->selectRow( 'revision', '*',
3512 array( 'rev_page' => $pageId ),
3513 __METHOD__,
3514 array( 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 1 )
3515 );
3516 if( !$row ) {
3517 return null;
3518 } else {
3519 return new Revision( $row );
3520 }
3521 }
3522
3523 /**
3524 * Check if this is a new page
3525 *
3526 * @return bool
3527 */
3528 public function isNewPage() {
3529 $dbr = wfGetDB( DB_SLAVE );
3530 return (bool)$dbr->selectField( 'page', 'page_is_new', $this->pageCond(), __METHOD__ );
3531 }
3532
3533 /**
3534 * Get the oldest revision timestamp of this page
3535 *
3536 * @return String: MW timestamp
3537 */
3538 public function getEarliestRevTime() {
3539 $dbr = wfGetDB( DB_SLAVE );
3540 if( $this->exists() ) {
3541 $min = $dbr->selectField( 'revision',
3542 'MIN(rev_timestamp)',
3543 array( 'rev_page' => $this->getArticleId() ),
3544 __METHOD__ );
3545 return wfTimestampOrNull( TS_MW, $min );
3546 }
3547 return null;
3548 }
3549
3550 /**
3551 * Get the number of revisions between the given revision IDs.
3552 * Used for diffs and other things that really need it.
3553 *
3554 * @param $old \type{\int} Revision ID.
3555 * @param $new \type{\int} Revision ID.
3556 * @return \type{\int} Number of revisions between these IDs.
3557 */
3558 public function countRevisionsBetween( $old, $new ) {
3559 $dbr = wfGetDB( DB_SLAVE );
3560 return (int)$dbr->selectField( 'revision', 'count(*)',
3561 'rev_page = ' . intval( $this->getArticleId() ) .
3562 ' AND rev_id > ' . intval( $old ) .
3563 ' AND rev_id < ' . intval( $new ),
3564 __METHOD__
3565 );
3566 }
3567
3568 /**
3569 * Compare with another title.
3570 *
3571 * @param $title \type{Title}
3572 * @return \type{\bool} TRUE or FALSE
3573 */
3574 public function equals( Title $title ) {
3575 // Note: === is necessary for proper matching of number-like titles.
3576 return $this->getInterwiki() === $title->getInterwiki()
3577 && $this->getNamespace() == $title->getNamespace()
3578 && $this->getDBkey() === $title->getDBkey();
3579 }
3580
3581 /**
3582 * Callback for usort() to do title sorts by (namespace, title)
3583 *
3584 * @return Integer: result of string comparison, or namespace comparison
3585 */
3586 public static function compare( $a, $b ) {
3587 if( $a->getNamespace() == $b->getNamespace() ) {
3588 return strcmp( $a->getText(), $b->getText() );
3589 } else {
3590 return $a->getNamespace() - $b->getNamespace();
3591 }
3592 }
3593
3594 /**
3595 * Return a string representation of this title
3596 *
3597 * @return \type{\string} String representation of this title
3598 */
3599 public function __toString() {
3600 return $this->getPrefixedText();
3601 }
3602
3603 /**
3604 * Check if page exists. For historical reasons, this function simply
3605 * checks for the existence of the title in the page table, and will
3606 * thus return false for interwiki links, special pages and the like.
3607 * If you want to know if a title can be meaningfully viewed, you should
3608 * probably call the isKnown() method instead.
3609 *
3610 * @return \type{\bool}
3611 */
3612 public function exists() {
3613 return $this->getArticleId() != 0;
3614 }
3615
3616 /**
3617 * Should links to this title be shown as potentially viewable (i.e. as
3618 * "bluelinks"), even if there's no record by this title in the page
3619 * table?
3620 *
3621 * This function is semi-deprecated for public use, as well as somewhat
3622 * misleadingly named. You probably just want to call isKnown(), which
3623 * calls this function internally.
3624 *
3625 * (ISSUE: Most of these checks are cheap, but the file existence check
3626 * can potentially be quite expensive. Including it here fixes a lot of
3627 * existing code, but we might want to add an optional parameter to skip
3628 * it and any other expensive checks.)
3629 *
3630 * @return \type{\bool}
3631 */
3632 public function isAlwaysKnown() {
3633 if( $this->mInterwiki != '' ) {
3634 return true; // any interwiki link might be viewable, for all we know
3635 }
3636 switch( $this->mNamespace ) {
3637 case NS_MEDIA:
3638 case NS_FILE:
3639 return wfFindFile( $this ); // file exists, possibly in a foreign repo
3640 case NS_SPECIAL:
3641 return SpecialPage::exists( $this->getDBkey() ); // valid special page
3642 case NS_MAIN:
3643 return $this->mDbkeyform == ''; // selflink, possibly with fragment
3644 case NS_MEDIAWIKI:
3645 // If the page is form Mediawiki:message/lang, calling wfMsgWeirdKey causes
3646 // the full l10n of that language to be loaded. That takes much memory and
3647 // isn't needed. So we strip the language part away.
3648 list( $basename, /* rest */ ) = explode( '/', $this->mDbkeyform, 2 );
3649 return (bool)wfMsgWeirdKey( $basename ); // known system message
3650 default:
3651 return false;
3652 }
3653 }
3654
3655 /**
3656 * Does this title refer to a page that can (or might) be meaningfully
3657 * viewed? In particular, this function may be used to determine if
3658 * links to the title should be rendered as "bluelinks" (as opposed to
3659 * "redlinks" to non-existent pages).
3660 *
3661 * @return \type{\bool}
3662 */
3663 public function isKnown() {
3664 return $this->exists() || $this->isAlwaysKnown();
3665 }
3666
3667 /**
3668 * Does this page have source text?
3669 *
3670 * @return Boolean
3671 */
3672 public function hasSourceText() {
3673 if ( $this->exists() )
3674 return true;
3675
3676 if ( $this->mNamespace == NS_MEDIAWIKI ) {
3677 // If the page doesn't exist but is a known system message, default
3678 // message content will be displayed, same for language subpages
3679 // Also, if the page is form Mediawiki:message/lang, calling wfMsgWeirdKey
3680 // causes the full l10n of that language to be loaded. That takes much
3681 // memory and isn't needed. So we strip the language part away.
3682 list( $basename, /* rest */ ) = explode( '/', $this->mDbkeyform, 2 );
3683 return (bool)wfMsgWeirdKey( $basename );
3684 }
3685
3686 return false;
3687 }
3688
3689 /**
3690 * Is this in a namespace that allows actual pages?
3691 *
3692 * @return \type{\bool}
3693 * @internal note -- uses hardcoded namespace index instead of constants
3694 */
3695 public function canExist() {
3696 return $this->mNamespace >=0 && $this->mNamespace != NS_MEDIA;
3697 }
3698
3699 /**
3700 * Update page_touched timestamps and send squid purge messages for
3701 * pages linking to this title. May be sent to the job queue depending
3702 * on the number of links. Typically called on create and delete.
3703 */
3704 public function touchLinks() {
3705 $u = new HTMLCacheUpdate( $this, 'pagelinks' );
3706 $u->doUpdate();
3707
3708 if ( $this->getNamespace() == NS_CATEGORY ) {
3709 $u = new HTMLCacheUpdate( $this, 'categorylinks' );
3710 $u->doUpdate();
3711 }
3712 }
3713
3714 /**
3715 * Get the last touched timestamp
3716 *
3717 * @param $db DatabaseBase: optional db
3718 * @return \type{\string} Last touched timestamp
3719 */
3720 public function getTouched( $db = null ) {
3721 $db = isset($db) ? $db : wfGetDB( DB_SLAVE );
3722 $touched = $db->selectField( 'page', 'page_touched', $this->pageCond(), __METHOD__ );
3723 return $touched;
3724 }
3725
3726 /**
3727 * Get the timestamp when this page was updated since the user last saw it.
3728 *
3729 * @param $user User
3730 * @return Mixed: string/null
3731 */
3732 public function getNotificationTimestamp( $user = null ) {
3733 global $wgUser, $wgShowUpdatedMarker;
3734 // Assume current user if none given
3735 if( !$user ) $user = $wgUser;
3736 // Check cache first
3737 $uid = $user->getId();
3738 if( isset($this->mNotificationTimestamp[$uid]) ) {
3739 return $this->mNotificationTimestamp[$uid];
3740 }
3741 if( !$uid || !$wgShowUpdatedMarker ) {
3742 return $this->mNotificationTimestamp[$uid] = false;
3743 }
3744 // Don't cache too much!
3745 if( count($this->mNotificationTimestamp) >= self::CACHE_MAX ) {
3746 $this->mNotificationTimestamp = array();
3747 }
3748 $dbr = wfGetDB( DB_SLAVE );
3749 $this->mNotificationTimestamp[$uid] = $dbr->selectField( 'watchlist',
3750 'wl_notificationtimestamp',
3751 array( 'wl_namespace' => $this->getNamespace(),
3752 'wl_title' => $this->getDBkey(),
3753 'wl_user' => $user->getId()
3754 ),
3755 __METHOD__
3756 );
3757 return $this->mNotificationTimestamp[$uid];
3758 }
3759
3760 /**
3761 * Get the trackback URL for this page
3762 *
3763 * @return \type{\string} Trackback URL
3764 */
3765 public function trackbackURL() {
3766 global $wgScriptPath, $wgServer, $wgScriptExtension;
3767
3768 return "$wgServer$wgScriptPath/trackback$wgScriptExtension?article="
3769 . htmlspecialchars(urlencode($this->getPrefixedDBkey()));
3770 }
3771
3772 /**
3773 * Get the trackback RDF for this page
3774 *
3775 * @return \type{\string} Trackback RDF
3776 */
3777 public function trackbackRDF() {
3778 $url = htmlspecialchars($this->getFullURL());
3779 $title = htmlspecialchars($this->getText());
3780 $tburl = $this->trackbackURL();
3781
3782 // Autodiscovery RDF is placed in comments so HTML validator
3783 // won't barf. This is a rather icky workaround, but seems
3784 // frequently used by this kind of RDF thingy.
3785 //
3786 // Spec: http://www.sixapart.com/pronet/docs/trackback_spec
3787 return "<!--
3788 <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"
3789 xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
3790 xmlns:trackback=\"http://madskills.com/public/xml/rss/module/trackback/\">
3791 <rdf:Description
3792 rdf:about=\"$url\"
3793 dc:identifier=\"$url\"
3794 dc:title=\"$title\"
3795 trackback:ping=\"$tburl\" />
3796 </rdf:RDF>
3797 -->";
3798 }
3799
3800 /**
3801 * Generate strings used for xml 'id' names in monobook tabs
3802 *
3803 * @param $prepend string defaults to 'nstab-'
3804 * @return \type{\string} XML 'id' name
3805 */
3806 public function getNamespaceKey( $prepend = 'nstab-' ) {
3807 global $wgContLang;
3808 // Gets the subject namespace if this title
3809 $namespace = MWNamespace::getSubject( $this->getNamespace() );
3810 // Checks if cononical namespace name exists for namespace
3811 if ( MWNamespace::exists( $this->getNamespace() ) ) {
3812 // Uses canonical namespace name
3813 $namespaceKey = MWNamespace::getCanonicalName( $namespace );
3814 } else {
3815 // Uses text of namespace
3816 $namespaceKey = $this->getSubjectNsText();
3817 }
3818 // Makes namespace key lowercase
3819 $namespaceKey = $wgContLang->lc( $namespaceKey );
3820 // Uses main
3821 if ( $namespaceKey == '' ) {
3822 $namespaceKey = 'main';
3823 }
3824 // Changes file to image for backwards compatibility
3825 if ( $namespaceKey == 'file' ) {
3826 $namespaceKey = 'image';
3827 }
3828 return $prepend . $namespaceKey;
3829 }
3830
3831 /**
3832 * Returns true if this is a special page.
3833 *
3834 * @return boolean
3835 */
3836 public function isSpecialPage( ) {
3837 return $this->getNamespace() == NS_SPECIAL;
3838 }
3839
3840 /**
3841 * Returns true if this title resolves to the named special page
3842 *
3843 * @param $name \type{\string} The special page name
3844 * @return boolean
3845 */
3846 public function isSpecial( $name ) {
3847 if ( $this->getNamespace() == NS_SPECIAL ) {
3848 list( $thisName, /* $subpage */ ) = SpecialPage::resolveAliasWithSubpage( $this->getDBkey() );
3849 if ( $name == $thisName ) {
3850 return true;
3851 }
3852 }
3853 return false;
3854 }
3855
3856 /**
3857 * If the Title refers to a special page alias which is not the local default,
3858 *
3859 * @return \type{Title} A new Title which points to the local default.
3860 * Otherwise, returns $this.
3861 */
3862 public function fixSpecialName() {
3863 if ( $this->getNamespace() == NS_SPECIAL ) {
3864 $canonicalName = SpecialPage::resolveAlias( $this->mDbkeyform );
3865 if ( $canonicalName ) {
3866 $localName = SpecialPage::getLocalNameFor( $canonicalName );
3867 if ( $localName != $this->mDbkeyform ) {
3868 return Title::makeTitle( NS_SPECIAL, $localName );
3869 }
3870 }
3871 }
3872 return $this;
3873 }
3874
3875 /**
3876 * Is this Title in a namespace which contains content?
3877 * In other words, is this a content page, for the purposes of calculating
3878 * statistics, etc?
3879 *
3880 * @return \type{\bool}
3881 */
3882 public function isContentPage() {
3883 return MWNamespace::isContent( $this->getNamespace() );
3884 }
3885
3886 /**
3887 * Get all extant redirects to this Title
3888 *
3889 * @param $ns \twotypes{\int,\null} Single namespace to consider;
3890 * NULL to consider all namespaces
3891 * @return \type{\arrayof{Title}} Redirects to this title
3892 */
3893 public function getRedirectsHere( $ns = null ) {
3894 $redirs = array();
3895
3896 $dbr = wfGetDB( DB_SLAVE );
3897 $where = array(
3898 'rd_namespace' => $this->getNamespace(),
3899 'rd_title' => $this->getDBkey(),
3900 'rd_from = page_id'
3901 );
3902 if ( !is_null($ns) ) $where['page_namespace'] = $ns;
3903
3904 $res = $dbr->select(
3905 array( 'redirect', 'page' ),
3906 array( 'page_namespace', 'page_title' ),
3907 $where,
3908 __METHOD__
3909 );
3910
3911
3912 foreach( $res as $row ) {
3913 $redirs[] = self::newFromRow( $row );
3914 }
3915 return $redirs;
3916 }
3917
3918 /**
3919 * Check if this Title is a valid redirect target
3920 *
3921 * @return \type{\bool}
3922 */
3923 public function isValidRedirectTarget() {
3924 global $wgInvalidRedirectTargets;
3925
3926 // invalid redirect targets are stored in a global array, but explicity disallow Userlogout here
3927 if( $this->isSpecial( 'Userlogout' ) ) {
3928 return false;
3929 }
3930
3931 foreach( $wgInvalidRedirectTargets as $target ) {
3932 if( $this->isSpecial( $target ) ) {
3933 return false;
3934 }
3935 }
3936
3937 return true;
3938 }
3939
3940 /**
3941 * Get a backlink cache object
3942 *
3943 * @return object BacklinkCache
3944 */
3945 function getBacklinkCache() {
3946 if ( is_null( $this->mBacklinkCache ) ) {
3947 $this->mBacklinkCache = new BacklinkCache( $this );
3948 }
3949 return $this->mBacklinkCache;
3950 }
3951
3952 /**
3953 * Whether the magic words __INDEX__ and __NOINDEX__ function for
3954 * this page.
3955 *
3956 * @return Boolean
3957 */
3958 public function canUseNoindex(){
3959 global $wgArticleRobotPolicies, $wgContentNamespaces,
3960 $wgExemptFromUserRobotsControl;
3961
3962 $bannedNamespaces = is_null( $wgExemptFromUserRobotsControl )
3963 ? $wgContentNamespaces
3964 : $wgExemptFromUserRobotsControl;
3965
3966 return !in_array( $this->mNamespace, $bannedNamespaces );
3967
3968 }
3969
3970 /**
3971 * Returns restriction types for the current Title
3972 *
3973 * @return array applicable restriction types
3974 */
3975 public function getRestrictionTypes() {
3976 global $wgRestrictionTypes;
3977 $types = $this->exists() ? $wgRestrictionTypes : array('create');
3978
3979 if ( $this->getNamespace() == NS_FILE ) {
3980 $types[] = 'upload';
3981 }
3982
3983 wfRunHooks( 'TitleGetRestrictionTypes', array( $this, &$types ) );
3984
3985 return $types;
3986 }
3987 }