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