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