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