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