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