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