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