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