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