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