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