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