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