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