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