Merge "Revert "Follow-up ee320648fd1: output mw-content-{ltr,rtl} unconditionally""
[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 wfWarn( __METHOD__ . ': $text must be a string. This will throw an InvalidArgumentException in future.', 2 );
269 }
270
271 try {
272 return Title::newFromTextThrow( $text, $defaultNamespace );
273 } catch ( MalformedTitleException $ex ) {
274 return null;
275 }
276 }
277
278 /**
279 * Like Title::newFromText(), but throws MalformedTitleException when the title is invalid,
280 * rather than returning null.
281 *
282 * The exception subclasses encode detailed information about why the title is invalid.
283 *
284 * @see Title::newFromText
285 *
286 * @since 1.25
287 * @param string $text Title text to check
288 * @param int $defaultNamespace
289 * @throws MalformedTitleException If the title is invalid
290 * @return Title
291 */
292 public static function newFromTextThrow( $text, $defaultNamespace = NS_MAIN ) {
293 if ( is_object( $text ) ) {
294 throw new MWException( 'Title::newFromTextThrow given an object' );
295 }
296
297 $cache = self::getTitleCache();
298
299 /**
300 * Wiki pages often contain multiple links to the same page.
301 * Title normalization and parsing can become expensive on
302 * pages with many links, so we can save a little time by
303 * caching them.
304 *
305 * In theory these are value objects and won't get changed...
306 */
307 if ( $defaultNamespace == NS_MAIN && $cache->has( $text ) ) {
308 return $cache->get( $text );
309 }
310
311 # Convert things like &eacute; &#257; or &#x3017; into normalized (bug 14952) text
312 $filteredText = Sanitizer::decodeCharReferencesAndNormalize( $text );
313
314 $t = new Title();
315 $t->mDbkeyform = str_replace( ' ', '_', $filteredText );
316 $t->mDefaultNamespace = intval( $defaultNamespace );
317
318 $t->secureAndSplit();
319 if ( $defaultNamespace == NS_MAIN ) {
320 $cache->set( $text, $t );
321 }
322 return $t;
323 }
324
325 /**
326 * THIS IS NOT THE FUNCTION YOU WANT. Use Title::newFromText().
327 *
328 * Example of wrong and broken code:
329 * $title = Title::newFromURL( $wgRequest->getVal( 'title' ) );
330 *
331 * Example of right code:
332 * $title = Title::newFromText( $wgRequest->getVal( 'title' ) );
333 *
334 * Create a new Title from URL-encoded text. Ensures that
335 * the given title's length does not exceed the maximum.
336 *
337 * @param string $url The title, as might be taken from a URL
338 * @return Title|null The new object, or null on an error
339 */
340 public static function newFromURL( $url ) {
341 $t = new Title();
342
343 # For compatibility with old buggy URLs. "+" is usually not valid in titles,
344 # but some URLs used it as a space replacement and they still come
345 # from some external search tools.
346 if ( strpos( self::legalChars(), '+' ) === false ) {
347 $url = str_replace( '+', ' ', $url );
348 }
349
350 $t->mDbkeyform = str_replace( ' ', '_', $url );
351
352 try {
353 $t->secureAndSplit();
354 return $t;
355 } catch ( MalformedTitleException $ex ) {
356 return null;
357 }
358 }
359
360 /**
361 * @return MapCacheLRU
362 */
363 private static function getTitleCache() {
364 if ( self::$titleCache == null ) {
365 self::$titleCache = new MapCacheLRU( self::CACHE_MAX );
366 }
367 return self::$titleCache;
368 }
369
370 /**
371 * Returns a list of fields that are to be selected for initializing Title
372 * objects or LinkCache entries. Uses $wgContentHandlerUseDB to determine
373 * whether to include page_content_model.
374 *
375 * @return array
376 */
377 protected static function getSelectFields() {
378 global $wgContentHandlerUseDB;
379
380 $fields = array(
381 'page_namespace', 'page_title', 'page_id',
382 'page_len', 'page_is_redirect', 'page_latest',
383 );
384
385 if ( $wgContentHandlerUseDB ) {
386 $fields[] = 'page_content_model';
387 }
388
389 return $fields;
390 }
391
392 /**
393 * Create a new Title from an article ID
394 *
395 * @param int $id The page_id corresponding to the Title to create
396 * @param int $flags Use Title::GAID_FOR_UPDATE to use master
397 * @return Title|null The new object, or null on an error
398 */
399 public static function newFromID( $id, $flags = 0 ) {
400 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
401 $row = $db->selectRow(
402 'page',
403 self::getSelectFields(),
404 array( 'page_id' => $id ),
405 __METHOD__
406 );
407 if ( $row !== false ) {
408 $title = Title::newFromRow( $row );
409 } else {
410 $title = null;
411 }
412 return $title;
413 }
414
415 /**
416 * Make an array of titles from an array of IDs
417 *
418 * @param int[] $ids Array of IDs
419 * @return Title[] Array of Titles
420 */
421 public static function newFromIDs( $ids ) {
422 if ( !count( $ids ) ) {
423 return array();
424 }
425 $dbr = wfGetDB( DB_SLAVE );
426
427 $res = $dbr->select(
428 'page',
429 self::getSelectFields(),
430 array( 'page_id' => $ids ),
431 __METHOD__
432 );
433
434 $titles = array();
435 foreach ( $res as $row ) {
436 $titles[] = Title::newFromRow( $row );
437 }
438 return $titles;
439 }
440
441 /**
442 * Make a Title object from a DB row
443 *
444 * @param stdClass $row Object database row (needs at least page_title,page_namespace)
445 * @return Title Corresponding Title
446 */
447 public static function newFromRow( $row ) {
448 $t = self::makeTitle( $row->page_namespace, $row->page_title );
449 $t->loadFromRow( $row );
450 return $t;
451 }
452
453 /**
454 * Load Title object fields from a DB row.
455 * If false is given, the title will be treated as non-existing.
456 *
457 * @param stdClass|bool $row Database row
458 */
459 public function loadFromRow( $row ) {
460 if ( $row ) { // page found
461 if ( isset( $row->page_id ) ) {
462 $this->mArticleID = (int)$row->page_id;
463 }
464 if ( isset( $row->page_len ) ) {
465 $this->mLength = (int)$row->page_len;
466 }
467 if ( isset( $row->page_is_redirect ) ) {
468 $this->mRedirect = (bool)$row->page_is_redirect;
469 }
470 if ( isset( $row->page_latest ) ) {
471 $this->mLatestID = (int)$row->page_latest;
472 }
473 if ( isset( $row->page_content_model ) ) {
474 $this->mContentModel = strval( $row->page_content_model );
475 } else {
476 $this->mContentModel = false; # initialized lazily in getContentModel()
477 }
478 if ( isset( $row->page_lang ) ) {
479 $this->mDbPageLanguage = (string)$row->page_lang;
480 }
481 if ( isset( $row->page_restrictions ) ) {
482 $this->mOldRestrictions = $row->page_restrictions;
483 }
484 } else { // page not found
485 $this->mArticleID = 0;
486 $this->mLength = 0;
487 $this->mRedirect = false;
488 $this->mLatestID = 0;
489 $this->mContentModel = false; # initialized lazily in getContentModel()
490 }
491 }
492
493 /**
494 * Create a new Title from a namespace index and a DB key.
495 * It's assumed that $ns and $title are *valid*, for instance when
496 * they came directly from the database or a special page name.
497 * For convenience, spaces are converted to underscores so that
498 * eg user_text fields can be used directly.
499 *
500 * @param int $ns The namespace of the article
501 * @param string $title The unprefixed database key form
502 * @param string $fragment The link fragment (after the "#")
503 * @param string $interwiki The interwiki prefix
504 * @return Title The new object
505 */
506 public static function &makeTitle( $ns, $title, $fragment = '', $interwiki = '' ) {
507 $t = new Title();
508 $t->mInterwiki = $interwiki;
509 $t->mFragment = $fragment;
510 $t->mNamespace = $ns = intval( $ns );
511 $t->mDbkeyform = str_replace( ' ', '_', $title );
512 $t->mArticleID = ( $ns >= 0 ) ? -1 : 0;
513 $t->mUrlform = wfUrlencode( $t->mDbkeyform );
514 $t->mTextform = str_replace( '_', ' ', $title );
515 $t->mContentModel = false; # initialized lazily in getContentModel()
516 return $t;
517 }
518
519 /**
520 * Create a new Title from a namespace index and a DB key.
521 * The parameters will be checked for validity, which is a bit slower
522 * than makeTitle() but safer for user-provided data.
523 *
524 * @param int $ns The namespace of the article
525 * @param string $title Database key form
526 * @param string $fragment The link fragment (after the "#")
527 * @param string $interwiki Interwiki prefix
528 * @return Title The new object, or null on an error
529 */
530 public static function makeTitleSafe( $ns, $title, $fragment = '', $interwiki = '' ) {
531 if ( !MWNamespace::exists( $ns ) ) {
532 return null;
533 }
534
535 $t = new Title();
536 $t->mDbkeyform = Title::makeName( $ns, $title, $fragment, $interwiki, true );
537
538 try {
539 $t->secureAndSplit();
540 return $t;
541 } catch ( MalformedTitleException $ex ) {
542 return null;
543 }
544 }
545
546 /**
547 * Create a new Title for the Main Page
548 *
549 * @return Title The new object
550 */
551 public static function newMainPage() {
552 $title = Title::newFromText( wfMessage( 'mainpage' )->inContentLanguage()->text() );
553 // Don't give fatal errors if the message is broken
554 if ( !$title ) {
555 $title = Title::newFromText( 'Main Page' );
556 }
557 return $title;
558 }
559
560 /**
561 * Extract a redirect destination from a string and return the
562 * Title, or null if the text doesn't contain a valid redirect
563 * This will only return the very next target, useful for
564 * the redirect table and other checks that don't need full recursion
565 *
566 * @param string $text Text with possible redirect
567 * @return Title The corresponding Title
568 * @deprecated since 1.21, use Content::getRedirectTarget instead.
569 */
570 public static function newFromRedirect( $text ) {
571 ContentHandler::deprecated( __METHOD__, '1.21' );
572
573 $content = ContentHandler::makeContent( $text, null, CONTENT_MODEL_WIKITEXT );
574 return $content->getRedirectTarget();
575 }
576
577 /**
578 * Extract a redirect destination from a string and return the
579 * Title, or null if the text doesn't contain a valid redirect
580 * This will recurse down $wgMaxRedirects times or until a non-redirect target is hit
581 * in order to provide (hopefully) the Title of the final destination instead of another redirect
582 *
583 * @param string $text Text with possible redirect
584 * @return Title
585 * @deprecated since 1.21, use Content::getUltimateRedirectTarget instead.
586 */
587 public static function newFromRedirectRecurse( $text ) {
588 ContentHandler::deprecated( __METHOD__, '1.21' );
589
590 $content = ContentHandler::makeContent( $text, null, CONTENT_MODEL_WIKITEXT );
591 return $content->getUltimateRedirectTarget();
592 }
593
594 /**
595 * Extract a redirect destination from a string and return an
596 * array of Titles, or null if the text doesn't contain a valid redirect
597 * The last element in the array is the final destination after all redirects
598 * have been resolved (up to $wgMaxRedirects times)
599 *
600 * @param string $text Text with possible redirect
601 * @return Title[] Array of Titles, with the destination last
602 * @deprecated since 1.21, use Content::getRedirectChain instead.
603 */
604 public static function newFromRedirectArray( $text ) {
605 ContentHandler::deprecated( __METHOD__, '1.21' );
606
607 $content = ContentHandler::makeContent( $text, null, CONTENT_MODEL_WIKITEXT );
608 return $content->getRedirectChain();
609 }
610
611 /**
612 * Get the prefixed DB key associated with an ID
613 *
614 * @param int $id The page_id of the article
615 * @return Title|null An object representing the article, or null if no such article was found
616 */
617 public static function nameOf( $id ) {
618 $dbr = wfGetDB( DB_SLAVE );
619
620 $s = $dbr->selectRow(
621 'page',
622 array( 'page_namespace', 'page_title' ),
623 array( 'page_id' => $id ),
624 __METHOD__
625 );
626 if ( $s === false ) {
627 return null;
628 }
629
630 $n = self::makeName( $s->page_namespace, $s->page_title );
631 return $n;
632 }
633
634 /**
635 * Get a regex character class describing the legal characters in a link
636 *
637 * @return string The list of characters, not delimited
638 */
639 public static function legalChars() {
640 global $wgLegalTitleChars;
641 return $wgLegalTitleChars;
642 }
643
644 /**
645 * Returns a simple regex that will match on characters and sequences invalid in titles.
646 * Note that this doesn't pick up many things that could be wrong with titles, but that
647 * replacing this regex with something valid will make many titles valid.
648 *
649 * @deprecated since 1.25, use MediaWikiTitleCodec::getTitleInvalidRegex() instead
650 *
651 * @return string Regex string
652 */
653 static function getTitleInvalidRegex() {
654 wfDeprecated( __METHOD__, '1.25' );
655 return MediaWikiTitleCodec::getTitleInvalidRegex();
656 }
657
658 /**
659 * Utility method for converting a character sequence from bytes to Unicode.
660 *
661 * Primary usecase being converting $wgLegalTitleChars to a sequence usable in
662 * javascript, as PHP uses UTF-8 bytes where javascript uses Unicode code units.
663 *
664 * @param string $byteClass
665 * @return string
666 */
667 public static function convertByteClassToUnicodeClass( $byteClass ) {
668 $length = strlen( $byteClass );
669 // Input token queue
670 $x0 = $x1 = $x2 = '';
671 // Decoded queue
672 $d0 = $d1 = $d2 = '';
673 // Decoded integer codepoints
674 $ord0 = $ord1 = $ord2 = 0;
675 // Re-encoded queue
676 $r0 = $r1 = $r2 = '';
677 // Output
678 $out = '';
679 // Flags
680 $allowUnicode = false;
681 for ( $pos = 0; $pos < $length; $pos++ ) {
682 // Shift the queues down
683 $x2 = $x1;
684 $x1 = $x0;
685 $d2 = $d1;
686 $d1 = $d0;
687 $ord2 = $ord1;
688 $ord1 = $ord0;
689 $r2 = $r1;
690 $r1 = $r0;
691 // Load the current input token and decoded values
692 $inChar = $byteClass[$pos];
693 if ( $inChar == '\\' ) {
694 if ( preg_match( '/x([0-9a-fA-F]{2})/A', $byteClass, $m, 0, $pos + 1 ) ) {
695 $x0 = $inChar . $m[0];
696 $d0 = chr( hexdec( $m[1] ) );
697 $pos += strlen( $m[0] );
698 } elseif ( preg_match( '/[0-7]{3}/A', $byteClass, $m, 0, $pos + 1 ) ) {
699 $x0 = $inChar . $m[0];
700 $d0 = chr( octdec( $m[0] ) );
701 $pos += strlen( $m[0] );
702 } elseif ( $pos + 1 >= $length ) {
703 $x0 = $d0 = '\\';
704 } else {
705 $d0 = $byteClass[$pos + 1];
706 $x0 = $inChar . $d0;
707 $pos += 1;
708 }
709 } else {
710 $x0 = $d0 = $inChar;
711 }
712 $ord0 = ord( $d0 );
713 // Load the current re-encoded value
714 if ( $ord0 < 32 || $ord0 == 0x7f ) {
715 $r0 = sprintf( '\x%02x', $ord0 );
716 } elseif ( $ord0 >= 0x80 ) {
717 // Allow unicode if a single high-bit character appears
718 $r0 = sprintf( '\x%02x', $ord0 );
719 $allowUnicode = true;
720 } elseif ( strpos( '-\\[]^', $d0 ) !== false ) {
721 $r0 = '\\' . $d0;
722 } else {
723 $r0 = $d0;
724 }
725 // Do the output
726 if ( $x0 !== '' && $x1 === '-' && $x2 !== '' ) {
727 // Range
728 if ( $ord2 > $ord0 ) {
729 // Empty range
730 } elseif ( $ord0 >= 0x80 ) {
731 // Unicode range
732 $allowUnicode = true;
733 if ( $ord2 < 0x80 ) {
734 // Keep the non-unicode section of the range
735 $out .= "$r2-\\x7F";
736 }
737 } else {
738 // Normal range
739 $out .= "$r2-$r0";
740 }
741 // Reset state to the initial value
742 $x0 = $x1 = $d0 = $d1 = $r0 = $r1 = '';
743 } elseif ( $ord2 < 0x80 ) {
744 // ASCII character
745 $out .= $r2;
746 }
747 }
748 if ( $ord1 < 0x80 ) {
749 $out .= $r1;
750 }
751 if ( $ord0 < 0x80 ) {
752 $out .= $r0;
753 }
754 if ( $allowUnicode ) {
755 $out .= '\u0080-\uFFFF';
756 }
757 return $out;
758 }
759
760 /**
761 * Make a prefixed DB key from a DB key and a namespace index
762 *
763 * @param int $ns Numerical representation of the namespace
764 * @param string $title The DB key form the title
765 * @param string $fragment The link fragment (after the "#")
766 * @param string $interwiki The interwiki prefix
767 * @param bool $canoncialNamespace If true, use the canonical name for
768 * $ns instead of the localized version.
769 * @return string The prefixed form of the title
770 */
771 public static function makeName( $ns, $title, $fragment = '', $interwiki = '',
772 $canoncialNamespace = false
773 ) {
774 global $wgContLang;
775
776 if ( $canoncialNamespace ) {
777 $namespace = MWNamespace::getCanonicalName( $ns );
778 } else {
779 $namespace = $wgContLang->getNsText( $ns );
780 }
781 $name = $namespace == '' ? $title : "$namespace:$title";
782 if ( strval( $interwiki ) != '' ) {
783 $name = "$interwiki:$name";
784 }
785 if ( strval( $fragment ) != '' ) {
786 $name .= '#' . $fragment;
787 }
788 return $name;
789 }
790
791 /**
792 * Escape a text fragment, say from a link, for a URL
793 *
794 * @param string $fragment Containing a URL or link fragment (after the "#")
795 * @return string Escaped string
796 */
797 static function escapeFragmentForURL( $fragment ) {
798 # Note that we don't urlencode the fragment. urlencoded Unicode
799 # fragments appear not to work in IE (at least up to 7) or in at least
800 # one version of Opera 9.x. The W3C validator, for one, doesn't seem
801 # to care if they aren't encoded.
802 return Sanitizer::escapeId( $fragment, 'noninitial' );
803 }
804
805 /**
806 * Callback for usort() to do title sorts by (namespace, title)
807 *
808 * @param Title $a
809 * @param Title $b
810 *
811 * @return int Result of string comparison, or namespace comparison
812 */
813 public static function compare( $a, $b ) {
814 if ( $a->getNamespace() == $b->getNamespace() ) {
815 return strcmp( $a->getText(), $b->getText() );
816 } else {
817 return $a->getNamespace() - $b->getNamespace();
818 }
819 }
820
821 /**
822 * Determine whether the object refers to a page within
823 * this project (either this wiki or a wiki with a local
824 * interwiki, see https://www.mediawiki.org/wiki/Manual:Interwiki_table#iw_local )
825 *
826 * @return bool True if this is an in-project interwiki link or a wikilink, false otherwise
827 */
828 public function isLocal() {
829 if ( $this->isExternal() ) {
830 $iw = Interwiki::fetch( $this->mInterwiki );
831 if ( $iw ) {
832 return $iw->isLocal();
833 }
834 }
835 return true;
836 }
837
838 /**
839 * Is this Title interwiki?
840 *
841 * @return bool
842 */
843 public function isExternal() {
844 return $this->mInterwiki !== '';
845 }
846
847 /**
848 * Get the interwiki prefix
849 *
850 * Use Title::isExternal to check if a interwiki is set
851 *
852 * @return string Interwiki prefix
853 */
854 public function getInterwiki() {
855 return $this->mInterwiki;
856 }
857
858 /**
859 * Was this a local interwiki link?
860 *
861 * @return bool
862 */
863 public function wasLocalInterwiki() {
864 return $this->mLocalInterwiki;
865 }
866
867 /**
868 * Determine whether the object refers to a page within
869 * this project and is transcludable.
870 *
871 * @return bool True if this is transcludable
872 */
873 public function isTrans() {
874 if ( !$this->isExternal() ) {
875 return false;
876 }
877
878 return Interwiki::fetch( $this->mInterwiki )->isTranscludable();
879 }
880
881 /**
882 * Returns the DB name of the distant wiki which owns the object.
883 *
884 * @return string The DB name
885 */
886 public function getTransWikiID() {
887 if ( !$this->isExternal() ) {
888 return false;
889 }
890
891 return Interwiki::fetch( $this->mInterwiki )->getWikiID();
892 }
893
894 /**
895 * Get a TitleValue object representing this Title.
896 *
897 * @note Not all valid Titles have a corresponding valid TitleValue
898 * (e.g. TitleValues cannot represent page-local links that have a
899 * fragment but no title text).
900 *
901 * @return TitleValue|null
902 */
903 public function getTitleValue() {
904 if ( $this->mTitleValue === null ) {
905 try {
906 $this->mTitleValue = new TitleValue(
907 $this->getNamespace(),
908 $this->getDBkey(),
909 $this->getFragment() );
910 } catch ( InvalidArgumentException $ex ) {
911 wfDebug( __METHOD__ . ': Can\'t create a TitleValue for [[' .
912 $this->getPrefixedText() . ']]: ' . $ex->getMessage() . "\n" );
913 }
914 }
915
916 return $this->mTitleValue;
917 }
918
919 /**
920 * Get the text form (spaces not underscores) of the main part
921 *
922 * @return string Main part of the title
923 */
924 public function getText() {
925 return $this->mTextform;
926 }
927
928 /**
929 * Get the URL-encoded form of the main part
930 *
931 * @return string Main part of the title, URL-encoded
932 */
933 public function getPartialURL() {
934 return $this->mUrlform;
935 }
936
937 /**
938 * Get the main part with underscores
939 *
940 * @return string Main part of the title, with underscores
941 */
942 public function getDBkey() {
943 return $this->mDbkeyform;
944 }
945
946 /**
947 * Get the DB key with the initial letter case as specified by the user
948 *
949 * @return string DB key
950 */
951 function getUserCaseDBKey() {
952 if ( !is_null( $this->mUserCaseDBKey ) ) {
953 return $this->mUserCaseDBKey;
954 } else {
955 // If created via makeTitle(), $this->mUserCaseDBKey is not set.
956 return $this->mDbkeyform;
957 }
958 }
959
960 /**
961 * Get the namespace index, i.e. one of the NS_xxxx constants.
962 *
963 * @return int Namespace index
964 */
965 public function getNamespace() {
966 return $this->mNamespace;
967 }
968
969 /**
970 * Get the page's content model id, see the CONTENT_MODEL_XXX constants.
971 *
972 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
973 * @return string Content model id
974 */
975 public function getContentModel( $flags = 0 ) {
976 if ( !$this->mContentModel && $this->getArticleID( $flags ) ) {
977 $linkCache = LinkCache::singleton();
978 $linkCache->addLinkObj( $this ); # in case we already had an article ID
979 $this->mContentModel = $linkCache->getGoodLinkFieldObj( $this, 'model' );
980 }
981
982 if ( !$this->mContentModel ) {
983 $this->mContentModel = ContentHandler::getDefaultModelFor( $this );
984 }
985
986 return $this->mContentModel;
987 }
988
989 /**
990 * Convenience method for checking a title's content model name
991 *
992 * @param string $id The content model ID (use the CONTENT_MODEL_XXX constants).
993 * @return bool True if $this->getContentModel() == $id
994 */
995 public function hasContentModel( $id ) {
996 return $this->getContentModel() == $id;
997 }
998
999 /**
1000 * Get the namespace text
1001 *
1002 * @return string Namespace text
1003 */
1004 public function getNsText() {
1005 if ( $this->isExternal() ) {
1006 // This probably shouldn't even happen. ohh man, oh yuck.
1007 // But for interwiki transclusion it sometimes does.
1008 // Shit. Shit shit shit.
1009 //
1010 // Use the canonical namespaces if possible to try to
1011 // resolve a foreign namespace.
1012 if ( MWNamespace::exists( $this->mNamespace ) ) {
1013 return MWNamespace::getCanonicalName( $this->mNamespace );
1014 }
1015 }
1016
1017 try {
1018 $formatter = self::getTitleFormatter();
1019 return $formatter->getNamespaceName( $this->mNamespace, $this->mDbkeyform );
1020 } catch ( InvalidArgumentException $ex ) {
1021 wfDebug( __METHOD__ . ': ' . $ex->getMessage() . "\n" );
1022 return false;
1023 }
1024 }
1025
1026 /**
1027 * Get the namespace text of the subject (rather than talk) page
1028 *
1029 * @return string Namespace text
1030 */
1031 public function getSubjectNsText() {
1032 global $wgContLang;
1033 return $wgContLang->getNsText( MWNamespace::getSubject( $this->mNamespace ) );
1034 }
1035
1036 /**
1037 * Get the namespace text of the talk page
1038 *
1039 * @return string Namespace text
1040 */
1041 public function getTalkNsText() {
1042 global $wgContLang;
1043 return $wgContLang->getNsText( MWNamespace::getTalk( $this->mNamespace ) );
1044 }
1045
1046 /**
1047 * Could this title have a corresponding talk page?
1048 *
1049 * @return bool
1050 */
1051 public function canTalk() {
1052 return MWNamespace::canTalk( $this->mNamespace );
1053 }
1054
1055 /**
1056 * Is this in a namespace that allows actual pages?
1057 *
1058 * @return bool
1059 */
1060 public function canExist() {
1061 return $this->mNamespace >= NS_MAIN;
1062 }
1063
1064 /**
1065 * Can this title be added to a user's watchlist?
1066 *
1067 * @return bool
1068 */
1069 public function isWatchable() {
1070 return !$this->isExternal() && MWNamespace::isWatchable( $this->getNamespace() );
1071 }
1072
1073 /**
1074 * Returns true if this is a special page.
1075 *
1076 * @return bool
1077 */
1078 public function isSpecialPage() {
1079 return $this->getNamespace() == NS_SPECIAL;
1080 }
1081
1082 /**
1083 * Returns true if this title resolves to the named special page
1084 *
1085 * @param string $name The special page name
1086 * @return bool
1087 */
1088 public function isSpecial( $name ) {
1089 if ( $this->isSpecialPage() ) {
1090 list( $thisName, /* $subpage */ ) = SpecialPageFactory::resolveAlias( $this->getDBkey() );
1091 if ( $name == $thisName ) {
1092 return true;
1093 }
1094 }
1095 return false;
1096 }
1097
1098 /**
1099 * If the Title refers to a special page alias which is not the local default, resolve
1100 * the alias, and localise the name as necessary. Otherwise, return $this
1101 *
1102 * @return Title
1103 */
1104 public function fixSpecialName() {
1105 if ( $this->isSpecialPage() ) {
1106 list( $canonicalName, $par ) = SpecialPageFactory::resolveAlias( $this->mDbkeyform );
1107 if ( $canonicalName ) {
1108 $localName = SpecialPageFactory::getLocalNameFor( $canonicalName, $par );
1109 if ( $localName != $this->mDbkeyform ) {
1110 return Title::makeTitle( NS_SPECIAL, $localName );
1111 }
1112 }
1113 }
1114 return $this;
1115 }
1116
1117 /**
1118 * Returns true if the title is inside the specified namespace.
1119 *
1120 * Please make use of this instead of comparing to getNamespace()
1121 * This function is much more resistant to changes we may make
1122 * to namespaces than code that makes direct comparisons.
1123 * @param int $ns The namespace
1124 * @return bool
1125 * @since 1.19
1126 */
1127 public function inNamespace( $ns ) {
1128 return MWNamespace::equals( $this->getNamespace(), $ns );
1129 }
1130
1131 /**
1132 * Returns true if the title is inside one of the specified namespaces.
1133 *
1134 * @param int $namespaces,... The namespaces to check for
1135 * @return bool
1136 * @since 1.19
1137 */
1138 public function inNamespaces( /* ... */ ) {
1139 $namespaces = func_get_args();
1140 if ( count( $namespaces ) > 0 && is_array( $namespaces[0] ) ) {
1141 $namespaces = $namespaces[0];
1142 }
1143
1144 foreach ( $namespaces as $ns ) {
1145 if ( $this->inNamespace( $ns ) ) {
1146 return true;
1147 }
1148 }
1149
1150 return false;
1151 }
1152
1153 /**
1154 * Returns true if the title has the same subject namespace as the
1155 * namespace specified.
1156 * For example this method will take NS_USER and return true if namespace
1157 * is either NS_USER or NS_USER_TALK since both of them have NS_USER
1158 * as their subject namespace.
1159 *
1160 * This is MUCH simpler than individually testing for equivalence
1161 * against both NS_USER and NS_USER_TALK, and is also forward compatible.
1162 * @since 1.19
1163 * @param int $ns
1164 * @return bool
1165 */
1166 public function hasSubjectNamespace( $ns ) {
1167 return MWNamespace::subjectEquals( $this->getNamespace(), $ns );
1168 }
1169
1170 /**
1171 * Is this Title in a namespace which contains content?
1172 * In other words, is this a content page, for the purposes of calculating
1173 * statistics, etc?
1174 *
1175 * @return bool
1176 */
1177 public function isContentPage() {
1178 return MWNamespace::isContent( $this->getNamespace() );
1179 }
1180
1181 /**
1182 * Would anybody with sufficient privileges be able to move this page?
1183 * Some pages just aren't movable.
1184 *
1185 * @return bool
1186 */
1187 public function isMovable() {
1188 if ( !MWNamespace::isMovable( $this->getNamespace() ) || $this->isExternal() ) {
1189 // Interwiki title or immovable namespace. Hooks don't get to override here
1190 return false;
1191 }
1192
1193 $result = true;
1194 Hooks::run( 'TitleIsMovable', array( $this, &$result ) );
1195 return $result;
1196 }
1197
1198 /**
1199 * Is this the mainpage?
1200 * @note Title::newFromText seems to be sufficiently optimized by the title
1201 * cache that we don't need to over-optimize by doing direct comparisons and
1202 * accidentally creating new bugs where $title->equals( Title::newFromText() )
1203 * ends up reporting something differently than $title->isMainPage();
1204 *
1205 * @since 1.18
1206 * @return bool
1207 */
1208 public function isMainPage() {
1209 return $this->equals( Title::newMainPage() );
1210 }
1211
1212 /**
1213 * Is this a subpage?
1214 *
1215 * @return bool
1216 */
1217 public function isSubpage() {
1218 return MWNamespace::hasSubpages( $this->mNamespace )
1219 ? strpos( $this->getText(), '/' ) !== false
1220 : false;
1221 }
1222
1223 /**
1224 * Is this a conversion table for the LanguageConverter?
1225 *
1226 * @return bool
1227 */
1228 public function isConversionTable() {
1229 // @todo ConversionTable should become a separate content model.
1230
1231 return $this->getNamespace() == NS_MEDIAWIKI &&
1232 strpos( $this->getText(), 'Conversiontable/' ) === 0;
1233 }
1234
1235 /**
1236 * Does that page contain wikitext, or it is JS, CSS or whatever?
1237 *
1238 * @return bool
1239 */
1240 public function isWikitextPage() {
1241 return $this->hasContentModel( CONTENT_MODEL_WIKITEXT );
1242 }
1243
1244 /**
1245 * Could this page contain custom CSS or JavaScript for the global UI.
1246 * This is generally true for pages in the MediaWiki namespace having CONTENT_MODEL_CSS
1247 * or CONTENT_MODEL_JAVASCRIPT.
1248 *
1249 * This method does *not* return true for per-user JS/CSS. Use isCssJsSubpage()
1250 * for that!
1251 *
1252 * Note that this method should not return true for pages that contain and
1253 * show "inactive" CSS or JS.
1254 *
1255 * @return bool
1256 */
1257 public function isCssOrJsPage() {
1258 $isCssOrJsPage = NS_MEDIAWIKI == $this->mNamespace
1259 && ( $this->hasContentModel( CONTENT_MODEL_CSS )
1260 || $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT ) );
1261
1262 # @note This hook is also called in ContentHandler::getDefaultModel.
1263 # It's called here again to make sure hook functions can force this
1264 # method to return true even outside the MediaWiki namespace.
1265
1266 Hooks::run( 'TitleIsCssOrJsPage', array( $this, &$isCssOrJsPage ), '1.25' );
1267
1268 return $isCssOrJsPage;
1269 }
1270
1271 /**
1272 * Is this a .css or .js subpage of a user page?
1273 * @return bool
1274 */
1275 public function isCssJsSubpage() {
1276 return ( NS_USER == $this->mNamespace && $this->isSubpage()
1277 && ( $this->hasContentModel( CONTENT_MODEL_CSS )
1278 || $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT ) ) );
1279 }
1280
1281 /**
1282 * Trim down a .css or .js subpage title to get the corresponding skin name
1283 *
1284 * @return string Containing skin name from .css or .js subpage title
1285 */
1286 public function getSkinFromCssJsSubpage() {
1287 $subpage = explode( '/', $this->mTextform );
1288 $subpage = $subpage[count( $subpage ) - 1];
1289 $lastdot = strrpos( $subpage, '.' );
1290 if ( $lastdot === false ) {
1291 return $subpage; # Never happens: only called for names ending in '.css' or '.js'
1292 }
1293 return substr( $subpage, 0, $lastdot );
1294 }
1295
1296 /**
1297 * Is this a .css subpage of a user page?
1298 *
1299 * @return bool
1300 */
1301 public function isCssSubpage() {
1302 return ( NS_USER == $this->mNamespace && $this->isSubpage()
1303 && $this->hasContentModel( CONTENT_MODEL_CSS ) );
1304 }
1305
1306 /**
1307 * Is this a .js subpage of a user page?
1308 *
1309 * @return bool
1310 */
1311 public function isJsSubpage() {
1312 return ( NS_USER == $this->mNamespace && $this->isSubpage()
1313 && $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT ) );
1314 }
1315
1316 /**
1317 * Is this a talk page of some sort?
1318 *
1319 * @return bool
1320 */
1321 public function isTalkPage() {
1322 return MWNamespace::isTalk( $this->getNamespace() );
1323 }
1324
1325 /**
1326 * Get a Title object associated with the talk page of this article
1327 *
1328 * @return Title The object for the talk page
1329 */
1330 public function getTalkPage() {
1331 return Title::makeTitle( MWNamespace::getTalk( $this->getNamespace() ), $this->getDBkey() );
1332 }
1333
1334 /**
1335 * Get a title object associated with the subject page of this
1336 * talk page
1337 *
1338 * @return Title The object for the subject page
1339 */
1340 public function getSubjectPage() {
1341 // Is this the same title?
1342 $subjectNS = MWNamespace::getSubject( $this->getNamespace() );
1343 if ( $this->getNamespace() == $subjectNS ) {
1344 return $this;
1345 }
1346 return Title::makeTitle( $subjectNS, $this->getDBkey() );
1347 }
1348
1349 /**
1350 * Get the other title for this page, if this is a subject page
1351 * get the talk page, if it is a subject page get the talk page
1352 *
1353 * @since 1.25
1354 * @throws MWException
1355 * @return Title
1356 */
1357 public function getOtherPage() {
1358 if ( $this->isSpecialPage() ) {
1359 throw new MWException( 'Special pages cannot have other pages' );
1360 }
1361 if ( $this->isTalkPage() ) {
1362 return $this->getSubjectPage();
1363 } else {
1364 return $this->getTalkPage();
1365 }
1366 }
1367
1368 /**
1369 * Get the default namespace index, for when there is no namespace
1370 *
1371 * @return int Default namespace index
1372 */
1373 public function getDefaultNamespace() {
1374 return $this->mDefaultNamespace;
1375 }
1376
1377 /**
1378 * Get the Title fragment (i.e.\ the bit after the #) in text form
1379 *
1380 * Use Title::hasFragment to check for a fragment
1381 *
1382 * @return string Title fragment
1383 */
1384 public function getFragment() {
1385 return $this->mFragment;
1386 }
1387
1388 /**
1389 * Check if a Title fragment is set
1390 *
1391 * @return bool
1392 * @since 1.23
1393 */
1394 public function hasFragment() {
1395 return $this->mFragment !== '';
1396 }
1397
1398 /**
1399 * Get the fragment in URL form, including the "#" character if there is one
1400 * @return string Fragment in URL form
1401 */
1402 public function getFragmentForURL() {
1403 if ( !$this->hasFragment() ) {
1404 return '';
1405 } else {
1406 return '#' . Title::escapeFragmentForURL( $this->getFragment() );
1407 }
1408 }
1409
1410 /**
1411 * Set the fragment for this title. Removes the first character from the
1412 * specified fragment before setting, so it assumes you're passing it with
1413 * an initial "#".
1414 *
1415 * Deprecated for public use, use Title::makeTitle() with fragment parameter.
1416 * Still in active use privately.
1417 *
1418 * @param string $fragment Text
1419 */
1420 public function setFragment( $fragment ) {
1421 $this->mFragment = str_replace( '_', ' ', substr( $fragment, 1 ) );
1422 }
1423
1424 /**
1425 * Prefix some arbitrary text with the namespace or interwiki prefix
1426 * of this object
1427 *
1428 * @param string $name The text
1429 * @return string The prefixed text
1430 */
1431 private function prefix( $name ) {
1432 $p = '';
1433 if ( $this->isExternal() ) {
1434 $p = $this->mInterwiki . ':';
1435 }
1436
1437 if ( 0 != $this->mNamespace ) {
1438 $p .= $this->getNsText() . ':';
1439 }
1440 return $p . $name;
1441 }
1442
1443 /**
1444 * Get the prefixed database key form
1445 *
1446 * @return string The prefixed title, with underscores and
1447 * any interwiki and namespace prefixes
1448 */
1449 public function getPrefixedDBkey() {
1450 $s = $this->prefix( $this->mDbkeyform );
1451 $s = str_replace( ' ', '_', $s );
1452 return $s;
1453 }
1454
1455 /**
1456 * Get the prefixed title with spaces.
1457 * This is the form usually used for display
1458 *
1459 * @return string The prefixed title, with spaces
1460 */
1461 public function getPrefixedText() {
1462 if ( $this->mPrefixedText === null ) {
1463 $s = $this->prefix( $this->mTextform );
1464 $s = str_replace( '_', ' ', $s );
1465 $this->mPrefixedText = $s;
1466 }
1467 return $this->mPrefixedText;
1468 }
1469
1470 /**
1471 * Return a string representation of this title
1472 *
1473 * @return string Representation of this title
1474 */
1475 public function __toString() {
1476 return $this->getPrefixedText();
1477 }
1478
1479 /**
1480 * Get the prefixed title with spaces, plus any fragment
1481 * (part beginning with '#')
1482 *
1483 * @return string The prefixed title, with spaces and the fragment, including '#'
1484 */
1485 public function getFullText() {
1486 $text = $this->getPrefixedText();
1487 if ( $this->hasFragment() ) {
1488 $text .= '#' . $this->getFragment();
1489 }
1490 return $text;
1491 }
1492
1493 /**
1494 * Get the root page name text without a namespace, i.e. the leftmost part before any slashes
1495 *
1496 * @par Example:
1497 * @code
1498 * Title::newFromText('User:Foo/Bar/Baz')->getRootText();
1499 * # returns: 'Foo'
1500 * @endcode
1501 *
1502 * @return string Root name
1503 * @since 1.20
1504 */
1505 public function getRootText() {
1506 if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
1507 return $this->getText();
1508 }
1509
1510 return strtok( $this->getText(), '/' );
1511 }
1512
1513 /**
1514 * Get the root page name title, i.e. the leftmost part before any slashes
1515 *
1516 * @par Example:
1517 * @code
1518 * Title::newFromText('User:Foo/Bar/Baz')->getRootTitle();
1519 * # returns: Title{User:Foo}
1520 * @endcode
1521 *
1522 * @return Title Root title
1523 * @since 1.20
1524 */
1525 public function getRootTitle() {
1526 return Title::makeTitle( $this->getNamespace(), $this->getRootText() );
1527 }
1528
1529 /**
1530 * Get the base page name without a namespace, i.e. the part before the subpage name
1531 *
1532 * @par Example:
1533 * @code
1534 * Title::newFromText('User:Foo/Bar/Baz')->getBaseText();
1535 * # returns: 'Foo/Bar'
1536 * @endcode
1537 *
1538 * @return string Base name
1539 */
1540 public function getBaseText() {
1541 if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
1542 return $this->getText();
1543 }
1544
1545 $parts = explode( '/', $this->getText() );
1546 # Don't discard the real title if there's no subpage involved
1547 if ( count( $parts ) > 1 ) {
1548 unset( $parts[count( $parts ) - 1] );
1549 }
1550 return implode( '/', $parts );
1551 }
1552
1553 /**
1554 * Get the base page name title, i.e. the part before the subpage name
1555 *
1556 * @par Example:
1557 * @code
1558 * Title::newFromText('User:Foo/Bar/Baz')->getBaseTitle();
1559 * # returns: Title{User:Foo/Bar}
1560 * @endcode
1561 *
1562 * @return Title Base title
1563 * @since 1.20
1564 */
1565 public function getBaseTitle() {
1566 return Title::makeTitle( $this->getNamespace(), $this->getBaseText() );
1567 }
1568
1569 /**
1570 * Get the lowest-level subpage name, i.e. the rightmost part after any slashes
1571 *
1572 * @par Example:
1573 * @code
1574 * Title::newFromText('User:Foo/Bar/Baz')->getSubpageText();
1575 * # returns: "Baz"
1576 * @endcode
1577 *
1578 * @return string Subpage name
1579 */
1580 public function getSubpageText() {
1581 if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
1582 return $this->mTextform;
1583 }
1584 $parts = explode( '/', $this->mTextform );
1585 return $parts[count( $parts ) - 1];
1586 }
1587
1588 /**
1589 * Get the title for a subpage of the current page
1590 *
1591 * @par Example:
1592 * @code
1593 * Title::newFromText('User:Foo/Bar/Baz')->getSubpage("Asdf");
1594 * # returns: Title{User:Foo/Bar/Baz/Asdf}
1595 * @endcode
1596 *
1597 * @param string $text The subpage name to add to the title
1598 * @return Title Subpage title
1599 * @since 1.20
1600 */
1601 public function getSubpage( $text ) {
1602 return Title::makeTitleSafe( $this->getNamespace(), $this->getText() . '/' . $text );
1603 }
1604
1605 /**
1606 * Get a URL-encoded form of the subpage text
1607 *
1608 * @return string URL-encoded subpage name
1609 */
1610 public function getSubpageUrlForm() {
1611 $text = $this->getSubpageText();
1612 $text = wfUrlencode( str_replace( ' ', '_', $text ) );
1613 return $text;
1614 }
1615
1616 /**
1617 * Get a URL-encoded title (not an actual URL) including interwiki
1618 *
1619 * @return string The URL-encoded form
1620 */
1621 public function getPrefixedURL() {
1622 $s = $this->prefix( $this->mDbkeyform );
1623 $s = wfUrlencode( str_replace( ' ', '_', $s ) );
1624 return $s;
1625 }
1626
1627 /**
1628 * Helper to fix up the get{Canonical,Full,Link,Local,Internal}URL args
1629 * get{Canonical,Full,Link,Local,Internal}URL methods accepted an optional
1630 * second argument named variant. This was deprecated in favor
1631 * of passing an array of option with a "variant" key
1632 * Once $query2 is removed for good, this helper can be dropped
1633 * and the wfArrayToCgi moved to getLocalURL();
1634 *
1635 * @since 1.19 (r105919)
1636 * @param array|string $query
1637 * @param bool $query2
1638 * @return string
1639 */
1640 private static function fixUrlQueryArgs( $query, $query2 = false ) {
1641 if ( $query2 !== false ) {
1642 wfDeprecated( "Title::get{Canonical,Full,Link,Local,Internal}URL " .
1643 "method called with a second parameter is deprecated. Add your " .
1644 "parameter to an array passed as the first parameter.", "1.19" );
1645 }
1646 if ( is_array( $query ) ) {
1647 $query = wfArrayToCgi( $query );
1648 }
1649 if ( $query2 ) {
1650 if ( is_string( $query2 ) ) {
1651 // $query2 is a string, we will consider this to be
1652 // a deprecated $variant argument and add it to the query
1653 $query2 = wfArrayToCgi( array( 'variant' => $query2 ) );
1654 } else {
1655 $query2 = wfArrayToCgi( $query2 );
1656 }
1657 // If we have $query content add a & to it first
1658 if ( $query ) {
1659 $query .= '&';
1660 }
1661 // Now append the queries together
1662 $query .= $query2;
1663 }
1664 return $query;
1665 }
1666
1667 /**
1668 * Get a real URL referring to this title, with interwiki link and
1669 * fragment
1670 *
1671 * @see self::getLocalURL for the arguments.
1672 * @see wfExpandUrl
1673 * @param array|string $query
1674 * @param bool $query2
1675 * @param string $proto Protocol type to use in URL
1676 * @return string The URL
1677 */
1678 public function getFullURL( $query = '', $query2 = false, $proto = PROTO_RELATIVE ) {
1679 $query = self::fixUrlQueryArgs( $query, $query2 );
1680
1681 # Hand off all the decisions on urls to getLocalURL
1682 $url = $this->getLocalURL( $query );
1683
1684 # Expand the url to make it a full url. Note that getLocalURL has the
1685 # potential to output full urls for a variety of reasons, so we use
1686 # wfExpandUrl instead of simply prepending $wgServer
1687 $url = wfExpandUrl( $url, $proto );
1688
1689 # Finally, add the fragment.
1690 $url .= $this->getFragmentForURL();
1691
1692 Hooks::run( 'GetFullURL', array( &$this, &$url, $query ) );
1693 return $url;
1694 }
1695
1696 /**
1697 * Get a URL with no fragment or server name (relative URL) from a Title object.
1698 * If this page is generated with action=render, however,
1699 * $wgServer is prepended to make an absolute URL.
1700 *
1701 * @see self::getFullURL to always get an absolute URL.
1702 * @see self::getLinkURL to always get a URL that's the simplest URL that will be
1703 * valid to link, locally, to the current Title.
1704 * @see self::newFromText to produce a Title object.
1705 *
1706 * @param string|array $query An optional query string,
1707 * not used for interwiki links. Can be specified as an associative array as well,
1708 * e.g., array( 'action' => 'edit' ) (keys and values will be URL-escaped).
1709 * Some query patterns will trigger various shorturl path replacements.
1710 * @param array $query2 An optional secondary query array. This one MUST
1711 * be an array. If a string is passed it will be interpreted as a deprecated
1712 * variant argument and urlencoded into a variant= argument.
1713 * This second query argument will be added to the $query
1714 * The second parameter is deprecated since 1.19. Pass it as a key,value
1715 * pair in the first parameter array instead.
1716 *
1717 * @return string String of the URL.
1718 */
1719 public function getLocalURL( $query = '', $query2 = false ) {
1720 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
1721
1722 $query = self::fixUrlQueryArgs( $query, $query2 );
1723
1724 $interwiki = Interwiki::fetch( $this->mInterwiki );
1725 if ( $interwiki ) {
1726 $namespace = $this->getNsText();
1727 if ( $namespace != '' ) {
1728 # Can this actually happen? Interwikis shouldn't be parsed.
1729 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
1730 $namespace .= ':';
1731 }
1732 $url = $interwiki->getURL( $namespace . $this->getDBkey() );
1733 $url = wfAppendQuery( $url, $query );
1734 } else {
1735 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
1736 if ( $query == '' ) {
1737 $url = str_replace( '$1', $dbkey, $wgArticlePath );
1738 Hooks::run( 'GetLocalURL::Article', array( &$this, &$url ) );
1739 } else {
1740 global $wgVariantArticlePath, $wgActionPaths, $wgContLang;
1741 $url = false;
1742 $matches = array();
1743
1744 if ( !empty( $wgActionPaths )
1745 && preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches )
1746 ) {
1747 $action = urldecode( $matches[2] );
1748 if ( isset( $wgActionPaths[$action] ) ) {
1749 $query = $matches[1];
1750 if ( isset( $matches[4] ) ) {
1751 $query .= $matches[4];
1752 }
1753 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
1754 if ( $query != '' ) {
1755 $url = wfAppendQuery( $url, $query );
1756 }
1757 }
1758 }
1759
1760 if ( $url === false
1761 && $wgVariantArticlePath
1762 && $wgContLang->getCode() === $this->getPageLanguage()->getCode()
1763 && $this->getPageLanguage()->hasVariants()
1764 && preg_match( '/^variant=([^&]*)$/', $query, $matches )
1765 ) {
1766 $variant = urldecode( $matches[1] );
1767 if ( $this->getPageLanguage()->hasVariant( $variant ) ) {
1768 // Only do the variant replacement if the given variant is a valid
1769 // variant for the page's language.
1770 $url = str_replace( '$2', urlencode( $variant ), $wgVariantArticlePath );
1771 $url = str_replace( '$1', $dbkey, $url );
1772 }
1773 }
1774
1775 if ( $url === false ) {
1776 if ( $query == '-' ) {
1777 $query = '';
1778 }
1779 $url = "{$wgScript}?title={$dbkey}&{$query}";
1780 }
1781 }
1782
1783 Hooks::run( 'GetLocalURL::Internal', array( &$this, &$url, $query ) );
1784
1785 // @todo FIXME: This causes breakage in various places when we
1786 // actually expected a local URL and end up with dupe prefixes.
1787 if ( $wgRequest->getVal( 'action' ) == 'render' ) {
1788 $url = $wgServer . $url;
1789 }
1790 }
1791 Hooks::run( 'GetLocalURL', array( &$this, &$url, $query ) );
1792 return $url;
1793 }
1794
1795 /**
1796 * Get a URL that's the simplest URL that will be valid to link, locally,
1797 * to the current Title. It includes the fragment, but does not include
1798 * the server unless action=render is used (or the link is external). If
1799 * there's a fragment but the prefixed text is empty, we just return a link
1800 * to the fragment.
1801 *
1802 * The result obviously should not be URL-escaped, but does need to be
1803 * HTML-escaped if it's being output in HTML.
1804 *
1805 * @param array $query
1806 * @param bool $query2
1807 * @param string $proto Protocol to use; setting this will cause a full URL to be used
1808 * @see self::getLocalURL for the arguments.
1809 * @return string The URL
1810 */
1811 public function getLinkURL( $query = '', $query2 = false, $proto = PROTO_RELATIVE ) {
1812 if ( $this->isExternal() || $proto !== PROTO_RELATIVE ) {
1813 $ret = $this->getFullURL( $query, $query2, $proto );
1814 } elseif ( $this->getPrefixedText() === '' && $this->hasFragment() ) {
1815 $ret = $this->getFragmentForURL();
1816 } else {
1817 $ret = $this->getLocalURL( $query, $query2 ) . $this->getFragmentForURL();
1818 }
1819 return $ret;
1820 }
1821
1822 /**
1823 * Get the URL form for an internal link.
1824 * - Used in various Squid-related code, in case we have a different
1825 * internal hostname for the server from the exposed one.
1826 *
1827 * This uses $wgInternalServer to qualify the path, or $wgServer
1828 * if $wgInternalServer is not set. If the server variable used is
1829 * protocol-relative, the URL will be expanded to http://
1830 *
1831 * @see self::getLocalURL for the arguments.
1832 * @return string The URL
1833 */
1834 public function getInternalURL( $query = '', $query2 = false ) {
1835 global $wgInternalServer, $wgServer;
1836 $query = self::fixUrlQueryArgs( $query, $query2 );
1837 $server = $wgInternalServer !== false ? $wgInternalServer : $wgServer;
1838 $url = wfExpandUrl( $server . $this->getLocalURL( $query ), PROTO_HTTP );
1839 Hooks::run( 'GetInternalURL', array( &$this, &$url, $query ) );
1840 return $url;
1841 }
1842
1843 /**
1844 * Get the URL for a canonical link, for use in things like IRC and
1845 * e-mail notifications. Uses $wgCanonicalServer and the
1846 * GetCanonicalURL hook.
1847 *
1848 * NOTE: Unlike getInternalURL(), the canonical URL includes the fragment
1849 *
1850 * @see self::getLocalURL for the arguments.
1851 * @return string The URL
1852 * @since 1.18
1853 */
1854 public function getCanonicalURL( $query = '', $query2 = false ) {
1855 $query = self::fixUrlQueryArgs( $query, $query2 );
1856 $url = wfExpandUrl( $this->getLocalURL( $query ) . $this->getFragmentForURL(), PROTO_CANONICAL );
1857 Hooks::run( 'GetCanonicalURL', array( &$this, &$url, $query ) );
1858 return $url;
1859 }
1860
1861 /**
1862 * Get the edit URL for this Title
1863 *
1864 * @return string The URL, or a null string if this is an interwiki link
1865 */
1866 public function getEditURL() {
1867 if ( $this->isExternal() ) {
1868 return '';
1869 }
1870 $s = $this->getLocalURL( 'action=edit' );
1871
1872 return $s;
1873 }
1874
1875 /**
1876 * Is $wgUser watching this page?
1877 *
1878 * @deprecated since 1.20; use User::isWatched() instead.
1879 * @return bool
1880 */
1881 public function userIsWatching() {
1882 global $wgUser;
1883
1884 if ( is_null( $this->mWatched ) ) {
1885 if ( NS_SPECIAL == $this->mNamespace || !$wgUser->isLoggedIn() ) {
1886 $this->mWatched = false;
1887 } else {
1888 $this->mWatched = $wgUser->isWatched( $this );
1889 }
1890 }
1891 return $this->mWatched;
1892 }
1893
1894 /**
1895 * Can $user perform $action on this page?
1896 * This skips potentially expensive cascading permission checks
1897 * as well as avoids expensive error formatting
1898 *
1899 * Suitable for use for nonessential UI controls in common cases, but
1900 * _not_ for functional access control.
1901 *
1902 * May provide false positives, but should never provide a false negative.
1903 *
1904 * @param string $action Action that permission needs to be checked for
1905 * @param User $user User to check (since 1.19); $wgUser will be used if not provided.
1906 * @return bool
1907 */
1908 public function quickUserCan( $action, $user = null ) {
1909 return $this->userCan( $action, $user, false );
1910 }
1911
1912 /**
1913 * Can $user perform $action on this page?
1914 *
1915 * @param string $action Action that permission needs to be checked for
1916 * @param User $user User to check (since 1.19); $wgUser will be used if not
1917 * provided.
1918 * @param string $rigor Same format as Title::getUserPermissionsErrors()
1919 * @return bool
1920 */
1921 public function userCan( $action, $user = null, $rigor = 'secure' ) {
1922 if ( !$user instanceof User ) {
1923 global $wgUser;
1924 $user = $wgUser;
1925 }
1926
1927 return !count( $this->getUserPermissionsErrorsInternal( $action, $user, $rigor, true ) );
1928 }
1929
1930 /**
1931 * Can $user perform $action on this page?
1932 *
1933 * @todo FIXME: This *does not* check throttles (User::pingLimiter()).
1934 *
1935 * @param string $action Action that permission needs to be checked for
1936 * @param User $user User to check
1937 * @param string $rigor One of (quick,full,secure)
1938 * - quick : does cheap permission checks from slaves (usable for GUI creation)
1939 * - full : does cheap and expensive checks possibly from a slave
1940 * - secure : does cheap and expensive checks, using the master as needed
1941 * @param bool $short Set this to true to stop after the first permission error.
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 /**
3312 * Capitalize a text string for a title if it belongs to a namespace that capitalizes
3313 *
3314 * @param string $text Containing title to capitalize
3315 * @param int $ns Namespace index, defaults to NS_MAIN
3316 * @return string Containing capitalized title
3317 */
3318 public static function capitalize( $text, $ns = NS_MAIN ) {
3319 global $wgContLang;
3320
3321 if ( MWNamespace::isCapitalized( $ns ) ) {
3322 return $wgContLang->ucfirst( $text );
3323 } else {
3324 return $text;
3325 }
3326 }
3327
3328 /**
3329 * Secure and split - main initialisation function for this object
3330 *
3331 * Assumes that mDbkeyform has been set, and is urldecoded
3332 * and uses underscores, but not otherwise munged. This function
3333 * removes illegal characters, splits off the interwiki and
3334 * namespace prefixes, sets the other forms, and canonicalizes
3335 * everything.
3336 *
3337 * @throws MalformedTitleException On invalid titles
3338 * @return bool True on success
3339 */
3340 private function secureAndSplit() {
3341 # Initialisation
3342 $this->mInterwiki = '';
3343 $this->mFragment = '';
3344 $this->mNamespace = $this->mDefaultNamespace; # Usually NS_MAIN
3345
3346 $dbkey = $this->mDbkeyform;
3347
3348 // @note: splitTitleString() is a temporary hack to allow MediaWikiTitleCodec to share
3349 // the parsing code with Title, while avoiding massive refactoring.
3350 // @todo: get rid of secureAndSplit, refactor parsing code.
3351 $titleParser = self::getTitleParser();
3352 // MalformedTitleException can be thrown here
3353 $parts = $titleParser->splitTitleString( $dbkey, $this->getDefaultNamespace() );
3354
3355 # Fill fields
3356 $this->setFragment( '#' . $parts['fragment'] );
3357 $this->mInterwiki = $parts['interwiki'];
3358 $this->mLocalInterwiki = $parts['local_interwiki'];
3359 $this->mNamespace = $parts['namespace'];
3360 $this->mUserCaseDBKey = $parts['user_case_dbkey'];
3361
3362 $this->mDbkeyform = $parts['dbkey'];
3363 $this->mUrlform = wfUrlencode( $this->mDbkeyform );
3364 $this->mTextform = str_replace( '_', ' ', $this->mDbkeyform );
3365
3366 # We already know that some pages won't be in the database!
3367 if ( $this->isExternal() || $this->mNamespace == NS_SPECIAL ) {
3368 $this->mArticleID = 0;
3369 }
3370
3371 return true;
3372 }
3373
3374 /**
3375 * Get an array of Title objects linking to this Title
3376 * Also stores the IDs in the link cache.
3377 *
3378 * WARNING: do not use this function on arbitrary user-supplied titles!
3379 * On heavily-used templates it will max out the memory.
3380 *
3381 * @param array $options May be FOR UPDATE
3382 * @param string $table Table name
3383 * @param string $prefix Fields prefix
3384 * @return Title[] Array of Title objects linking here
3385 */
3386 public function getLinksTo( $options = array(), $table = 'pagelinks', $prefix = 'pl' ) {
3387 if ( count( $options ) > 0 ) {
3388 $db = wfGetDB( DB_MASTER );
3389 } else {
3390 $db = wfGetDB( DB_SLAVE );
3391 }
3392
3393 $res = $db->select(
3394 array( 'page', $table ),
3395 self::getSelectFields(),
3396 array(
3397 "{$prefix}_from=page_id",
3398 "{$prefix}_namespace" => $this->getNamespace(),
3399 "{$prefix}_title" => $this->getDBkey() ),
3400 __METHOD__,
3401 $options
3402 );
3403
3404 $retVal = array();
3405 if ( $res->numRows() ) {
3406 $linkCache = LinkCache::singleton();
3407 foreach ( $res as $row ) {
3408 $titleObj = Title::makeTitle( $row->page_namespace, $row->page_title );
3409 if ( $titleObj ) {
3410 $linkCache->addGoodLinkObjFromRow( $titleObj, $row );
3411 $retVal[] = $titleObj;
3412 }
3413 }
3414 }
3415 return $retVal;
3416 }
3417
3418 /**
3419 * Get an array of Title objects using this Title as a template
3420 * Also stores the IDs in the link cache.
3421 *
3422 * WARNING: do not use this function on arbitrary user-supplied titles!
3423 * On heavily-used templates it will max out the memory.
3424 *
3425 * @param array $options May be FOR UPDATE
3426 * @return Title[] Array of Title the Title objects linking here
3427 */
3428 public function getTemplateLinksTo( $options = array() ) {
3429 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
3430 }
3431
3432 /**
3433 * Get an array of Title objects linked from this Title
3434 * Also stores the IDs in the link cache.
3435 *
3436 * WARNING: do not use this function on arbitrary user-supplied titles!
3437 * On heavily-used templates it will max out the memory.
3438 *
3439 * @param array $options May be FOR UPDATE
3440 * @param string $table Table name
3441 * @param string $prefix Fields prefix
3442 * @return array Array of Title objects linking here
3443 */
3444 public function getLinksFrom( $options = array(), $table = 'pagelinks', $prefix = 'pl' ) {
3445 $id = $this->getArticleID();
3446
3447 # If the page doesn't exist; there can't be any link from this page
3448 if ( !$id ) {
3449 return array();
3450 }
3451
3452 if ( count( $options ) > 0 ) {
3453 $db = wfGetDB( DB_MASTER );
3454 } else {
3455 $db = wfGetDB( DB_SLAVE );
3456 }
3457
3458 $blNamespace = "{$prefix}_namespace";
3459 $blTitle = "{$prefix}_title";
3460
3461 $res = $db->select(
3462 array( $table, 'page' ),
3463 array_merge(
3464 array( $blNamespace, $blTitle ),
3465 WikiPage::selectFields()
3466 ),
3467 array( "{$prefix}_from" => $id ),
3468 __METHOD__,
3469 $options,
3470 array( 'page' => array(
3471 'LEFT JOIN',
3472 array( "page_namespace=$blNamespace", "page_title=$blTitle" )
3473 ) )
3474 );
3475
3476 $retVal = array();
3477 $linkCache = LinkCache::singleton();
3478 foreach ( $res as $row ) {
3479 if ( $row->page_id ) {
3480 $titleObj = Title::newFromRow( $row );
3481 } else {
3482 $titleObj = Title::makeTitle( $row->$blNamespace, $row->$blTitle );
3483 $linkCache->addBadLinkObj( $titleObj );
3484 }
3485 $retVal[] = $titleObj;
3486 }
3487
3488 return $retVal;
3489 }
3490
3491 /**
3492 * Get an array of Title objects used on this Title as a template
3493 * Also stores the IDs in the link cache.
3494 *
3495 * WARNING: do not use this function on arbitrary user-supplied titles!
3496 * On heavily-used templates it will max out the memory.
3497 *
3498 * @param array $options May be FOR UPDATE
3499 * @return Title[] Array of Title the Title objects used here
3500 */
3501 public function getTemplateLinksFrom( $options = array() ) {
3502 return $this->getLinksFrom( $options, 'templatelinks', 'tl' );
3503 }
3504
3505 /**
3506 * Get an array of Title objects referring to non-existent articles linked
3507 * from this page.
3508 *
3509 * @todo check if needed (used only in SpecialBrokenRedirects.php, and
3510 * should use redirect table in this case).
3511 * @return Title[] Array of Title the Title objects
3512 */
3513 public function getBrokenLinksFrom() {
3514 if ( $this->getArticleID() == 0 ) {
3515 # All links from article ID 0 are false positives
3516 return array();
3517 }
3518
3519 $dbr = wfGetDB( DB_SLAVE );
3520 $res = $dbr->select(
3521 array( 'page', 'pagelinks' ),
3522 array( 'pl_namespace', 'pl_title' ),
3523 array(
3524 'pl_from' => $this->getArticleID(),
3525 'page_namespace IS NULL'
3526 ),
3527 __METHOD__, array(),
3528 array(
3529 'page' => array(
3530 'LEFT JOIN',
3531 array( 'pl_namespace=page_namespace', 'pl_title=page_title' )
3532 )
3533 )
3534 );
3535
3536 $retVal = array();
3537 foreach ( $res as $row ) {
3538 $retVal[] = Title::makeTitle( $row->pl_namespace, $row->pl_title );
3539 }
3540 return $retVal;
3541 }
3542
3543 /**
3544 * Get a list of URLs to purge from the Squid cache when this
3545 * page changes
3546 *
3547 * @return string[] Array of String the URLs
3548 */
3549 public function getSquidURLs() {
3550 $urls = array(
3551 $this->getInternalURL(),
3552 $this->getInternalURL( 'action=history' )
3553 );
3554
3555 $pageLang = $this->getPageLanguage();
3556 if ( $pageLang->hasVariants() ) {
3557 $variants = $pageLang->getVariants();
3558 foreach ( $variants as $vCode ) {
3559 $urls[] = $this->getInternalURL( '', $vCode );
3560 }
3561 }
3562
3563 // If we are looking at a css/js user subpage, purge the action=raw.
3564 if ( $this->isJsSubpage() ) {
3565 $urls[] = $this->getInternalUrl( 'action=raw&ctype=text/javascript' );
3566 } elseif ( $this->isCssSubpage() ) {
3567 $urls[] = $this->getInternalUrl( 'action=raw&ctype=text/css' );
3568 }
3569
3570 Hooks::run( 'TitleSquidURLs', array( $this, &$urls ) );
3571 return $urls;
3572 }
3573
3574 /**
3575 * Purge all applicable Squid URLs
3576 */
3577 public function purgeSquid() {
3578 global $wgUseSquid;
3579 if ( $wgUseSquid ) {
3580 $urls = $this->getSquidURLs();
3581 $u = new SquidUpdate( $urls );
3582 $u->doUpdate();
3583 }
3584 }
3585
3586 /**
3587 * Move this page without authentication
3588 *
3589 * @deprecated since 1.25 use MovePage class instead
3590 * @param Title $nt The new page Title
3591 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
3592 */
3593 public function moveNoAuth( &$nt ) {
3594 wfDeprecated( __METHOD__, '1.25' );
3595 return $this->moveTo( $nt, false );
3596 }
3597
3598 /**
3599 * Check whether a given move operation would be valid.
3600 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
3601 *
3602 * @deprecated since 1.25, use MovePage's methods instead
3603 * @param Title $nt The new title
3604 * @param bool $auth Whether to check user permissions (uses $wgUser)
3605 * @param string $reason Is the log summary of the move, used for spam checking
3606 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
3607 */
3608 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
3609 global $wgUser;
3610
3611 if ( !( $nt instanceof Title ) ) {
3612 // Normally we'd add this to $errors, but we'll get
3613 // lots of syntax errors if $nt is not an object
3614 return array( array( 'badtitletext' ) );
3615 }
3616
3617 $mp = new MovePage( $this, $nt );
3618 $errors = $mp->isValidMove()->getErrorsArray();
3619 if ( $auth ) {
3620 $errors = wfMergeErrorArrays(
3621 $errors,
3622 $mp->checkPermissions( $wgUser, $reason )->getErrorsArray()
3623 );
3624 }
3625
3626 return $errors ? : true;
3627 }
3628
3629 /**
3630 * Check if the requested move target is a valid file move target
3631 * @todo move this to MovePage
3632 * @param Title $nt Target title
3633 * @return array List of errors
3634 */
3635 protected function validateFileMoveOperation( $nt ) {
3636 global $wgUser;
3637
3638 $errors = array();
3639
3640 $destFile = wfLocalFile( $nt );
3641 $destFile->load( File::READ_LATEST );
3642 if ( !$wgUser->isAllowed( 'reupload-shared' )
3643 && !$destFile->exists() && wfFindFile( $nt )
3644 ) {
3645 $errors[] = array( 'file-exists-sharedrepo' );
3646 }
3647
3648 return $errors;
3649 }
3650
3651 /**
3652 * Move a title to a new location
3653 *
3654 * @deprecated since 1.25, use the MovePage class instead
3655 * @param Title $nt The new title
3656 * @param bool $auth Indicates whether $wgUser's permissions
3657 * should be checked
3658 * @param string $reason The reason for the move
3659 * @param bool $createRedirect Whether to create a redirect from the old title to the new title.
3660 * Ignored if the user doesn't have the suppressredirect right.
3661 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
3662 */
3663 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true ) {
3664 global $wgUser;
3665 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
3666 if ( is_array( $err ) ) {
3667 // Auto-block user's IP if the account was "hard" blocked
3668 $wgUser->spreadAnyEditBlock();
3669 return $err;
3670 }
3671 // Check suppressredirect permission
3672 if ( $auth && !$wgUser->isAllowed( 'suppressredirect' ) ) {
3673 $createRedirect = true;
3674 }
3675
3676 $mp = new MovePage( $this, $nt );
3677 $status = $mp->move( $wgUser, $reason, $createRedirect );
3678 if ( $status->isOK() ) {
3679 return true;
3680 } else {
3681 return $status->getErrorsArray();
3682 }
3683 }
3684
3685 /**
3686 * Move this page's subpages to be subpages of $nt
3687 *
3688 * @param Title $nt Move target
3689 * @param bool $auth Whether $wgUser's permissions should be checked
3690 * @param string $reason The reason for the move
3691 * @param bool $createRedirect Whether to create redirects from the old subpages to
3692 * the new ones Ignored if the user doesn't have the 'suppressredirect' right
3693 * @return array Array with old page titles as keys, and strings (new page titles) or
3694 * arrays (errors) as values, or an error array with numeric indices if no pages
3695 * were moved
3696 */
3697 public function moveSubpages( $nt, $auth = true, $reason = '', $createRedirect = true ) {
3698 global $wgMaximumMovedPages;
3699 // Check permissions
3700 if ( !$this->userCan( 'move-subpages' ) ) {
3701 return array( 'cant-move-subpages' );
3702 }
3703 // Do the source and target namespaces support subpages?
3704 if ( !MWNamespace::hasSubpages( $this->getNamespace() ) ) {
3705 return array( 'namespace-nosubpages',
3706 MWNamespace::getCanonicalName( $this->getNamespace() ) );
3707 }
3708 if ( !MWNamespace::hasSubpages( $nt->getNamespace() ) ) {
3709 return array( 'namespace-nosubpages',
3710 MWNamespace::getCanonicalName( $nt->getNamespace() ) );
3711 }
3712
3713 $subpages = $this->getSubpages( $wgMaximumMovedPages + 1 );
3714 $retval = array();
3715 $count = 0;
3716 foreach ( $subpages as $oldSubpage ) {
3717 $count++;
3718 if ( $count > $wgMaximumMovedPages ) {
3719 $retval[$oldSubpage->getPrefixedText()] =
3720 array( 'movepage-max-pages',
3721 $wgMaximumMovedPages );
3722 break;
3723 }
3724
3725 // We don't know whether this function was called before
3726 // or after moving the root page, so check both
3727 // $this and $nt
3728 if ( $oldSubpage->getArticleID() == $this->getArticleID()
3729 || $oldSubpage->getArticleID() == $nt->getArticleID()
3730 ) {
3731 // When moving a page to a subpage of itself,
3732 // don't move it twice
3733 continue;
3734 }
3735 $newPageName = preg_replace(
3736 '#^' . preg_quote( $this->getDBkey(), '#' ) . '#',
3737 StringUtils::escapeRegexReplacement( $nt->getDBkey() ), # bug 21234
3738 $oldSubpage->getDBkey() );
3739 if ( $oldSubpage->isTalkPage() ) {
3740 $newNs = $nt->getTalkPage()->getNamespace();
3741 } else {
3742 $newNs = $nt->getSubjectPage()->getNamespace();
3743 }
3744 # Bug 14385: we need makeTitleSafe because the new page names may
3745 # be longer than 255 characters.
3746 $newSubpage = Title::makeTitleSafe( $newNs, $newPageName );
3747
3748 $success = $oldSubpage->moveTo( $newSubpage, $auth, $reason, $createRedirect );
3749 if ( $success === true ) {
3750 $retval[$oldSubpage->getPrefixedText()] = $newSubpage->getPrefixedText();
3751 } else {
3752 $retval[$oldSubpage->getPrefixedText()] = $success;
3753 }
3754 }
3755 return $retval;
3756 }
3757
3758 /**
3759 * Checks if this page is just a one-rev redirect.
3760 * Adds lock, so don't use just for light purposes.
3761 *
3762 * @return bool
3763 */
3764 public function isSingleRevRedirect() {
3765 global $wgContentHandlerUseDB;
3766
3767 $dbw = wfGetDB( DB_MASTER );
3768
3769 # Is it a redirect?
3770 $fields = array( 'page_is_redirect', 'page_latest', 'page_id' );
3771 if ( $wgContentHandlerUseDB ) {
3772 $fields[] = 'page_content_model';
3773 }
3774
3775 $row = $dbw->selectRow( 'page',
3776 $fields,
3777 $this->pageCond(),
3778 __METHOD__,
3779 array( 'FOR UPDATE' )
3780 );
3781 # Cache some fields we may want
3782 $this->mArticleID = $row ? intval( $row->page_id ) : 0;
3783 $this->mRedirect = $row ? (bool)$row->page_is_redirect : false;
3784 $this->mLatestID = $row ? intval( $row->page_latest ) : false;
3785 $this->mContentModel = $row && isset( $row->page_content_model )
3786 ? strval( $row->page_content_model )
3787 : false;
3788
3789 if ( !$this->mRedirect ) {
3790 return false;
3791 }
3792 # Does the article have a history?
3793 $row = $dbw->selectField( array( 'page', 'revision' ),
3794 'rev_id',
3795 array( 'page_namespace' => $this->getNamespace(),
3796 'page_title' => $this->getDBkey(),
3797 'page_id=rev_page',
3798 'page_latest != rev_id'
3799 ),
3800 __METHOD__,
3801 array( 'FOR UPDATE' )
3802 );
3803 # Return true if there was no history
3804 return ( $row === false );
3805 }
3806
3807 /**
3808 * Checks if $this can be moved to a given Title
3809 * - Selects for update, so don't call it unless you mean business
3810 *
3811 * @deprecated since 1.25, use MovePage's methods instead
3812 * @param Title $nt The new title to check
3813 * @return bool
3814 */
3815 public function isValidMoveTarget( $nt ) {
3816 # Is it an existing file?
3817 if ( $nt->getNamespace() == NS_FILE ) {
3818 $file = wfLocalFile( $nt );
3819 $file->load( File::READ_LATEST );
3820 if ( $file->exists() ) {
3821 wfDebug( __METHOD__ . ": file exists\n" );
3822 return false;
3823 }
3824 }
3825 # Is it a redirect with no history?
3826 if ( !$nt->isSingleRevRedirect() ) {
3827 wfDebug( __METHOD__ . ": not a one-rev redirect\n" );
3828 return false;
3829 }
3830 # Get the article text
3831 $rev = Revision::newFromTitle( $nt, false, Revision::READ_LATEST );
3832 if ( !is_object( $rev ) ) {
3833 return false;
3834 }
3835 $content = $rev->getContent();
3836 # Does the redirect point to the source?
3837 # Or is it a broken self-redirect, usually caused by namespace collisions?
3838 $redirTitle = $content ? $content->getRedirectTarget() : null;
3839
3840 if ( $redirTitle ) {
3841 if ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
3842 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) {
3843 wfDebug( __METHOD__ . ": redirect points to other page\n" );
3844 return false;
3845 } else {
3846 return true;
3847 }
3848 } else {
3849 # Fail safe (not a redirect after all. strange.)
3850 wfDebug( __METHOD__ . ": failsafe: database sais " . $nt->getPrefixedDBkey() .
3851 " is a redirect, but it doesn't contain a valid redirect.\n" );
3852 return false;
3853 }
3854 }
3855
3856 /**
3857 * Get categories to which this Title belongs and return an array of
3858 * categories' names.
3859 *
3860 * @return array Array of parents in the form:
3861 * $parent => $currentarticle
3862 */
3863 public function getParentCategories() {
3864 global $wgContLang;
3865
3866 $data = array();
3867
3868 $titleKey = $this->getArticleID();
3869
3870 if ( $titleKey === 0 ) {
3871 return $data;
3872 }
3873
3874 $dbr = wfGetDB( DB_SLAVE );
3875
3876 $res = $dbr->select(
3877 'categorylinks',
3878 'cl_to',
3879 array( 'cl_from' => $titleKey ),
3880 __METHOD__
3881 );
3882
3883 if ( $res->numRows() > 0 ) {
3884 foreach ( $res as $row ) {
3885 // $data[] = Title::newFromText($wgContLang->getNsText ( NS_CATEGORY ).':'.$row->cl_to);
3886 $data[$wgContLang->getNsText( NS_CATEGORY ) . ':' . $row->cl_to] = $this->getFullText();
3887 }
3888 }
3889 return $data;
3890 }
3891
3892 /**
3893 * Get a tree of parent categories
3894 *
3895 * @param array $children Array with the children in the keys, to check for circular refs
3896 * @return array Tree of parent categories
3897 */
3898 public function getParentCategoryTree( $children = array() ) {
3899 $stack = array();
3900 $parents = $this->getParentCategories();
3901
3902 if ( $parents ) {
3903 foreach ( $parents as $parent => $current ) {
3904 if ( array_key_exists( $parent, $children ) ) {
3905 # Circular reference
3906 $stack[$parent] = array();
3907 } else {
3908 $nt = Title::newFromText( $parent );
3909 if ( $nt ) {
3910 $stack[$parent] = $nt->getParentCategoryTree( $children + array( $parent => 1 ) );
3911 }
3912 }
3913 }
3914 }
3915
3916 return $stack;
3917 }
3918
3919 /**
3920 * Get an associative array for selecting this title from
3921 * the "page" table
3922 *
3923 * @return array Array suitable for the $where parameter of DB::select()
3924 */
3925 public function pageCond() {
3926 if ( $this->mArticleID > 0 ) {
3927 // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs
3928 return array( 'page_id' => $this->mArticleID );
3929 } else {
3930 return array( 'page_namespace' => $this->mNamespace, 'page_title' => $this->mDbkeyform );
3931 }
3932 }
3933
3934 /**
3935 * Get the revision ID of the previous revision
3936 *
3937 * @param int $revId Revision ID. Get the revision that was before this one.
3938 * @param int $flags Title::GAID_FOR_UPDATE
3939 * @return int|bool Old revision ID, or false if none exists
3940 */
3941 public function getPreviousRevisionID( $revId, $flags = 0 ) {
3942 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
3943 $revId = $db->selectField( 'revision', 'rev_id',
3944 array(
3945 'rev_page' => $this->getArticleID( $flags ),
3946 'rev_id < ' . intval( $revId )
3947 ),
3948 __METHOD__,
3949 array( 'ORDER BY' => 'rev_id DESC' )
3950 );
3951
3952 if ( $revId === false ) {
3953 return false;
3954 } else {
3955 return intval( $revId );
3956 }
3957 }
3958
3959 /**
3960 * Get the revision ID of the next revision
3961 *
3962 * @param int $revId Revision ID. Get the revision that was after this one.
3963 * @param int $flags Title::GAID_FOR_UPDATE
3964 * @return int|bool Next revision ID, or false if none exists
3965 */
3966 public function getNextRevisionID( $revId, $flags = 0 ) {
3967 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
3968 $revId = $db->selectField( 'revision', 'rev_id',
3969 array(
3970 'rev_page' => $this->getArticleID( $flags ),
3971 'rev_id > ' . intval( $revId )
3972 ),
3973 __METHOD__,
3974 array( 'ORDER BY' => 'rev_id' )
3975 );
3976
3977 if ( $revId === false ) {
3978 return false;
3979 } else {
3980 return intval( $revId );
3981 }
3982 }
3983
3984 /**
3985 * Get the first revision of the page
3986 *
3987 * @param int $flags Title::GAID_FOR_UPDATE
3988 * @return Revision|null If page doesn't exist
3989 */
3990 public function getFirstRevision( $flags = 0 ) {
3991 $pageId = $this->getArticleID( $flags );
3992 if ( $pageId ) {
3993 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
3994 $row = $db->selectRow( 'revision', Revision::selectFields(),
3995 array( 'rev_page' => $pageId ),
3996 __METHOD__,
3997 array( 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 1 )
3998 );
3999 if ( $row ) {
4000 return new Revision( $row );
4001 }
4002 }
4003 return null;
4004 }
4005
4006 /**
4007 * Get the oldest revision timestamp of this page
4008 *
4009 * @param int $flags Title::GAID_FOR_UPDATE
4010 * @return string MW timestamp
4011 */
4012 public function getEarliestRevTime( $flags = 0 ) {
4013 $rev = $this->getFirstRevision( $flags );
4014 return $rev ? $rev->getTimestamp() : null;
4015 }
4016
4017 /**
4018 * Check if this is a new page
4019 *
4020 * @return bool
4021 */
4022 public function isNewPage() {
4023 $dbr = wfGetDB( DB_SLAVE );
4024 return (bool)$dbr->selectField( 'page', 'page_is_new', $this->pageCond(), __METHOD__ );
4025 }
4026
4027 /**
4028 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
4029 *
4030 * @return bool
4031 */
4032 public function isBigDeletion() {
4033 global $wgDeleteRevisionsLimit;
4034
4035 if ( !$wgDeleteRevisionsLimit ) {
4036 return false;
4037 }
4038
4039 if ( $this->mIsBigDeletion === null ) {
4040 $dbr = wfGetDB( DB_SLAVE );
4041
4042 $revCount = $dbr->selectRowCount(
4043 'revision',
4044 '1',
4045 array( 'rev_page' => $this->getArticleID() ),
4046 __METHOD__,
4047 array( 'LIMIT' => $wgDeleteRevisionsLimit + 1 )
4048 );
4049
4050 $this->mIsBigDeletion = $revCount > $wgDeleteRevisionsLimit;
4051 }
4052
4053 return $this->mIsBigDeletion;
4054 }
4055
4056 /**
4057 * Get the approximate revision count of this page.
4058 *
4059 * @return int
4060 */
4061 public function estimateRevisionCount() {
4062 if ( !$this->exists() ) {
4063 return 0;
4064 }
4065
4066 if ( $this->mEstimateRevisions === null ) {
4067 $dbr = wfGetDB( DB_SLAVE );
4068 $this->mEstimateRevisions = $dbr->estimateRowCount( 'revision', '*',
4069 array( 'rev_page' => $this->getArticleID() ), __METHOD__ );
4070 }
4071
4072 return $this->mEstimateRevisions;
4073 }
4074
4075 /**
4076 * Get the number of revisions between the given revision.
4077 * Used for diffs and other things that really need it.
4078 *
4079 * @param int|Revision $old Old revision or rev ID (first before range)
4080 * @param int|Revision $new New revision or rev ID (first after range)
4081 * @param int|null $max Limit of Revisions to count, will be incremented to detect truncations
4082 * @return int Number of revisions between these revisions.
4083 */
4084 public function countRevisionsBetween( $old, $new, $max = null ) {
4085 if ( !( $old instanceof Revision ) ) {
4086 $old = Revision::newFromTitle( $this, (int)$old );
4087 }
4088 if ( !( $new instanceof Revision ) ) {
4089 $new = Revision::newFromTitle( $this, (int)$new );
4090 }
4091 if ( !$old || !$new ) {
4092 return 0; // nothing to compare
4093 }
4094 $dbr = wfGetDB( DB_SLAVE );
4095 $conds = array(
4096 'rev_page' => $this->getArticleID(),
4097 'rev_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4098 'rev_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4099 );
4100 if ( $max !== null ) {
4101 return $dbr->selectRowCount( 'revision', '1',
4102 $conds,
4103 __METHOD__,
4104 array( 'LIMIT' => $max + 1 ) // extra to detect truncation
4105 );
4106 } else {
4107 return (int)$dbr->selectField( 'revision', 'count(*)', $conds, __METHOD__ );
4108 }
4109 }
4110
4111 /**
4112 * Get the authors between the given revisions or revision IDs.
4113 * Used for diffs and other things that really need it.
4114 *
4115 * @since 1.23
4116 *
4117 * @param int|Revision $old Old revision or rev ID (first before range by default)
4118 * @param int|Revision $new New revision or rev ID (first after range by default)
4119 * @param int $limit Maximum number of authors
4120 * @param string|array $options (Optional): Single option, or an array of options:
4121 * 'include_old' Include $old in the range; $new is excluded.
4122 * 'include_new' Include $new in the range; $old is excluded.
4123 * 'include_both' Include both $old and $new in the range.
4124 * Unknown option values are ignored.
4125 * @return array|null Names of revision authors in the range; null if not both revisions exist
4126 */
4127 public function getAuthorsBetween( $old, $new, $limit, $options = array() ) {
4128 if ( !( $old instanceof Revision ) ) {
4129 $old = Revision::newFromTitle( $this, (int)$old );
4130 }
4131 if ( !( $new instanceof Revision ) ) {
4132 $new = Revision::newFromTitle( $this, (int)$new );
4133 }
4134 // XXX: what if Revision objects are passed in, but they don't refer to this title?
4135 // Add $old->getPage() != $new->getPage() || $old->getPage() != $this->getArticleID()
4136 // in the sanity check below?
4137 if ( !$old || !$new ) {
4138 return null; // nothing to compare
4139 }
4140 $authors = array();
4141 $old_cmp = '>';
4142 $new_cmp = '<';
4143 $options = (array)$options;
4144 if ( in_array( 'include_old', $options ) ) {
4145 $old_cmp = '>=';
4146 }
4147 if ( in_array( 'include_new', $options ) ) {
4148 $new_cmp = '<=';
4149 }
4150 if ( in_array( 'include_both', $options ) ) {
4151 $old_cmp = '>=';
4152 $new_cmp = '<=';
4153 }
4154 // No DB query needed if $old and $new are the same or successive revisions:
4155 if ( $old->getId() === $new->getId() ) {
4156 return ( $old_cmp === '>' && $new_cmp === '<' ) ?
4157 array() :
4158 array( $old->getUserText( Revision::RAW ) );
4159 } elseif ( $old->getId() === $new->getParentId() ) {
4160 if ( $old_cmp === '>=' && $new_cmp === '<=' ) {
4161 $authors[] = $old->getUserText( Revision::RAW );
4162 if ( $old->getUserText( Revision::RAW ) != $new->getUserText( Revision::RAW ) ) {
4163 $authors[] = $new->getUserText( Revision::RAW );
4164 }
4165 } elseif ( $old_cmp === '>=' ) {
4166 $authors[] = $old->getUserText( Revision::RAW );
4167 } elseif ( $new_cmp === '<=' ) {
4168 $authors[] = $new->getUserText( Revision::RAW );
4169 }
4170 return $authors;
4171 }
4172 $dbr = wfGetDB( DB_SLAVE );
4173 $res = $dbr->select( 'revision', 'DISTINCT rev_user_text',
4174 array(
4175 'rev_page' => $this->getArticleID(),
4176 "rev_timestamp $old_cmp " . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4177 "rev_timestamp $new_cmp " . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4178 ), __METHOD__,
4179 array( 'LIMIT' => $limit + 1 ) // add one so caller knows it was truncated
4180 );
4181 foreach ( $res as $row ) {
4182 $authors[] = $row->rev_user_text;
4183 }
4184 return $authors;
4185 }
4186
4187 /**
4188 * Get the number of authors between the given revisions or revision IDs.
4189 * Used for diffs and other things that really need it.
4190 *
4191 * @param int|Revision $old Old revision or rev ID (first before range by default)
4192 * @param int|Revision $new New revision or rev ID (first after range by default)
4193 * @param int $limit Maximum number of authors
4194 * @param string|array $options (Optional): Single option, or an array of options:
4195 * 'include_old' Include $old in the range; $new is excluded.
4196 * 'include_new' Include $new in the range; $old is excluded.
4197 * 'include_both' Include both $old and $new in the range.
4198 * Unknown option values are ignored.
4199 * @return int Number of revision authors in the range; zero if not both revisions exist
4200 */
4201 public function countAuthorsBetween( $old, $new, $limit, $options = array() ) {
4202 $authors = $this->getAuthorsBetween( $old, $new, $limit, $options );
4203 return $authors ? count( $authors ) : 0;
4204 }
4205
4206 /**
4207 * Compare with another title.
4208 *
4209 * @param Title $title
4210 * @return bool
4211 */
4212 public function equals( Title $title ) {
4213 // Note: === is necessary for proper matching of number-like titles.
4214 return $this->getInterwiki() === $title->getInterwiki()
4215 && $this->getNamespace() == $title->getNamespace()
4216 && $this->getDBkey() === $title->getDBkey();
4217 }
4218
4219 /**
4220 * Check if this title is a subpage of another title
4221 *
4222 * @param Title $title
4223 * @return bool
4224 */
4225 public function isSubpageOf( Title $title ) {
4226 return $this->getInterwiki() === $title->getInterwiki()
4227 && $this->getNamespace() == $title->getNamespace()
4228 && strpos( $this->getDBkey(), $title->getDBkey() . '/' ) === 0;
4229 }
4230
4231 /**
4232 * Check if page exists. For historical reasons, this function simply
4233 * checks for the existence of the title in the page table, and will
4234 * thus return false for interwiki links, special pages and the like.
4235 * If you want to know if a title can be meaningfully viewed, you should
4236 * probably call the isKnown() method instead.
4237 *
4238 * @param int $flags An optional bit field; may be Title::GAID_FOR_UPDATE to check
4239 * from master/for update
4240 * @return bool
4241 */
4242 public function exists( $flags = 0 ) {
4243 $exists = $this->getArticleID( $flags ) != 0;
4244 Hooks::run( 'TitleExists', array( $this, &$exists ) );
4245 return $exists;
4246 }
4247
4248 /**
4249 * Should links to this title be shown as potentially viewable (i.e. as
4250 * "bluelinks"), even if there's no record by this title in the page
4251 * table?
4252 *
4253 * This function is semi-deprecated for public use, as well as somewhat
4254 * misleadingly named. You probably just want to call isKnown(), which
4255 * calls this function internally.
4256 *
4257 * (ISSUE: Most of these checks are cheap, but the file existence check
4258 * can potentially be quite expensive. Including it here fixes a lot of
4259 * existing code, but we might want to add an optional parameter to skip
4260 * it and any other expensive checks.)
4261 *
4262 * @return bool
4263 */
4264 public function isAlwaysKnown() {
4265 $isKnown = null;
4266
4267 /**
4268 * Allows overriding default behavior for determining if a page exists.
4269 * If $isKnown is kept as null, regular checks happen. If it's
4270 * a boolean, this value is returned by the isKnown method.
4271 *
4272 * @since 1.20
4273 *
4274 * @param Title $title
4275 * @param bool|null $isKnown
4276 */
4277 Hooks::run( 'TitleIsAlwaysKnown', array( $this, &$isKnown ) );
4278
4279 if ( !is_null( $isKnown ) ) {
4280 return $isKnown;
4281 }
4282
4283 if ( $this->isExternal() ) {
4284 return true; // any interwiki link might be viewable, for all we know
4285 }
4286
4287 switch ( $this->mNamespace ) {
4288 case NS_MEDIA:
4289 case NS_FILE:
4290 // file exists, possibly in a foreign repo
4291 return (bool)wfFindFile( $this );
4292 case NS_SPECIAL:
4293 // valid special page
4294 return SpecialPageFactory::exists( $this->getDBkey() );
4295 case NS_MAIN:
4296 // selflink, possibly with fragment
4297 return $this->mDbkeyform == '';
4298 case NS_MEDIAWIKI:
4299 // known system message
4300 return $this->hasSourceText() !== false;
4301 default:
4302 return false;
4303 }
4304 }
4305
4306 /**
4307 * Does this title refer to a page that can (or might) be meaningfully
4308 * viewed? In particular, this function may be used to determine if
4309 * links to the title should be rendered as "bluelinks" (as opposed to
4310 * "redlinks" to non-existent pages).
4311 * Adding something else to this function will cause inconsistency
4312 * since LinkHolderArray calls isAlwaysKnown() and does its own
4313 * page existence check.
4314 *
4315 * @return bool
4316 */
4317 public function isKnown() {
4318 return $this->isAlwaysKnown() || $this->exists();
4319 }
4320
4321 /**
4322 * Does this page have source text?
4323 *
4324 * @return bool
4325 */
4326 public function hasSourceText() {
4327 if ( $this->exists() ) {
4328 return true;
4329 }
4330
4331 if ( $this->mNamespace == NS_MEDIAWIKI ) {
4332 // If the page doesn't exist but is a known system message, default
4333 // message content will be displayed, same for language subpages-
4334 // Use always content language to avoid loading hundreds of languages
4335 // to get the link color.
4336 global $wgContLang;
4337 list( $name, ) = MessageCache::singleton()->figureMessage(
4338 $wgContLang->lcfirst( $this->getText() )
4339 );
4340 $message = wfMessage( $name )->inLanguage( $wgContLang )->useDatabase( false );
4341 return $message->exists();
4342 }
4343
4344 return false;
4345 }
4346
4347 /**
4348 * Get the default message text or false if the message doesn't exist
4349 *
4350 * @return string|bool
4351 */
4352 public function getDefaultMessageText() {
4353 global $wgContLang;
4354
4355 if ( $this->getNamespace() != NS_MEDIAWIKI ) { // Just in case
4356 return false;
4357 }
4358
4359 list( $name, $lang ) = MessageCache::singleton()->figureMessage(
4360 $wgContLang->lcfirst( $this->getText() )
4361 );
4362 $message = wfMessage( $name )->inLanguage( $lang )->useDatabase( false );
4363
4364 if ( $message->exists() ) {
4365 return $message->plain();
4366 } else {
4367 return false;
4368 }
4369 }
4370
4371 /**
4372 * Updates page_touched for this page; called from LinksUpdate.php
4373 *
4374 * @return bool True if the update succeeded
4375 */
4376 public function invalidateCache() {
4377 if ( wfReadOnly() ) {
4378 return false;
4379 }
4380
4381 if ( $this->mArticleID === 0 ) {
4382 return true; // avoid gap locking if we know it's not there
4383 }
4384
4385 $method = __METHOD__;
4386 $dbw = wfGetDB( DB_MASTER );
4387 $conds = $this->pageCond();
4388 $dbw->onTransactionIdle( function () use ( $dbw, $conds, $method ) {
4389 $dbw->update(
4390 'page',
4391 array( 'page_touched' => $dbw->timestamp() ),
4392 $conds,
4393 $method
4394 );
4395 } );
4396
4397 return true;
4398 }
4399
4400 /**
4401 * Update page_touched timestamps and send squid purge messages for
4402 * pages linking to this title. May be sent to the job queue depending
4403 * on the number of links. Typically called on create and delete.
4404 */
4405 public function touchLinks() {
4406 $u = new HTMLCacheUpdate( $this, 'pagelinks' );
4407 $u->doUpdate();
4408
4409 if ( $this->getNamespace() == NS_CATEGORY ) {
4410 $u = new HTMLCacheUpdate( $this, 'categorylinks' );
4411 $u->doUpdate();
4412 }
4413 }
4414
4415 /**
4416 * Get the last touched timestamp
4417 *
4418 * @param DatabaseBase $db Optional db
4419 * @return string Last-touched timestamp
4420 */
4421 public function getTouched( $db = null ) {
4422 if ( $db === null ) {
4423 $db = wfGetDB( DB_SLAVE );
4424 }
4425 $touched = $db->selectField( 'page', 'page_touched', $this->pageCond(), __METHOD__ );
4426 return $touched;
4427 }
4428
4429 /**
4430 * Get the timestamp when this page was updated since the user last saw it.
4431 *
4432 * @param User $user
4433 * @return string|null
4434 */
4435 public function getNotificationTimestamp( $user = null ) {
4436 global $wgUser;
4437
4438 // Assume current user if none given
4439 if ( !$user ) {
4440 $user = $wgUser;
4441 }
4442 // Check cache first
4443 $uid = $user->getId();
4444 if ( !$uid ) {
4445 return false;
4446 }
4447 // avoid isset here, as it'll return false for null entries
4448 if ( array_key_exists( $uid, $this->mNotificationTimestamp ) ) {
4449 return $this->mNotificationTimestamp[$uid];
4450 }
4451 // Don't cache too much!
4452 if ( count( $this->mNotificationTimestamp ) >= self::CACHE_MAX ) {
4453 $this->mNotificationTimestamp = array();
4454 }
4455
4456 $watchedItem = WatchedItem::fromUserTitle( $user, $this );
4457 $this->mNotificationTimestamp[$uid] = $watchedItem->getNotificationTimestamp();
4458
4459 return $this->mNotificationTimestamp[$uid];
4460 }
4461
4462 /**
4463 * Generate strings used for xml 'id' names in monobook tabs
4464 *
4465 * @param string $prepend Defaults to 'nstab-'
4466 * @return string XML 'id' name
4467 */
4468 public function getNamespaceKey( $prepend = 'nstab-' ) {
4469 global $wgContLang;
4470 // Gets the subject namespace if this title
4471 $namespace = MWNamespace::getSubject( $this->getNamespace() );
4472 // Checks if canonical namespace name exists for namespace
4473 if ( MWNamespace::exists( $this->getNamespace() ) ) {
4474 // Uses canonical namespace name
4475 $namespaceKey = MWNamespace::getCanonicalName( $namespace );
4476 } else {
4477 // Uses text of namespace
4478 $namespaceKey = $this->getSubjectNsText();
4479 }
4480 // Makes namespace key lowercase
4481 $namespaceKey = $wgContLang->lc( $namespaceKey );
4482 // Uses main
4483 if ( $namespaceKey == '' ) {
4484 $namespaceKey = 'main';
4485 }
4486 // Changes file to image for backwards compatibility
4487 if ( $namespaceKey == 'file' ) {
4488 $namespaceKey = 'image';
4489 }
4490 return $prepend . $namespaceKey;
4491 }
4492
4493 /**
4494 * Get all extant redirects to this Title
4495 *
4496 * @param int|null $ns Single namespace to consider; null to consider all namespaces
4497 * @return Title[] Array of Title redirects to this title
4498 */
4499 public function getRedirectsHere( $ns = null ) {
4500 $redirs = array();
4501
4502 $dbr = wfGetDB( DB_SLAVE );
4503 $where = array(
4504 'rd_namespace' => $this->getNamespace(),
4505 'rd_title' => $this->getDBkey(),
4506 'rd_from = page_id'
4507 );
4508 if ( $this->isExternal() ) {
4509 $where['rd_interwiki'] = $this->getInterwiki();
4510 } else {
4511 $where[] = 'rd_interwiki = ' . $dbr->addQuotes( '' ) . ' OR rd_interwiki IS NULL';
4512 }
4513 if ( !is_null( $ns ) ) {
4514 $where['page_namespace'] = $ns;
4515 }
4516
4517 $res = $dbr->select(
4518 array( 'redirect', 'page' ),
4519 array( 'page_namespace', 'page_title' ),
4520 $where,
4521 __METHOD__
4522 );
4523
4524 foreach ( $res as $row ) {
4525 $redirs[] = self::newFromRow( $row );
4526 }
4527 return $redirs;
4528 }
4529
4530 /**
4531 * Check if this Title is a valid redirect target
4532 *
4533 * @return bool
4534 */
4535 public function isValidRedirectTarget() {
4536 global $wgInvalidRedirectTargets;
4537
4538 // invalid redirect targets are stored in a global array, but explicitly disallow Userlogout here
4539 if ( $this->isSpecial( 'Userlogout' ) ) {
4540 return false;
4541 }
4542
4543 foreach ( $wgInvalidRedirectTargets as $target ) {
4544 if ( $this->isSpecial( $target ) ) {
4545 return false;
4546 }
4547 }
4548
4549 return true;
4550 }
4551
4552 /**
4553 * Get a backlink cache object
4554 *
4555 * @return BacklinkCache
4556 */
4557 public function getBacklinkCache() {
4558 return BacklinkCache::get( $this );
4559 }
4560
4561 /**
4562 * Whether the magic words __INDEX__ and __NOINDEX__ function for this page.
4563 *
4564 * @return bool
4565 */
4566 public function canUseNoindex() {
4567 global $wgContentNamespaces, $wgExemptFromUserRobotsControl;
4568
4569 $bannedNamespaces = is_null( $wgExemptFromUserRobotsControl )
4570 ? $wgContentNamespaces
4571 : $wgExemptFromUserRobotsControl;
4572
4573 return !in_array( $this->mNamespace, $bannedNamespaces );
4574
4575 }
4576
4577 /**
4578 * Returns the raw sort key to be used for categories, with the specified
4579 * prefix. This will be fed to Collation::getSortKey() to get a
4580 * binary sortkey that can be used for actual sorting.
4581 *
4582 * @param string $prefix The prefix to be used, specified using
4583 * {{defaultsort:}} or like [[Category:Foo|prefix]]. Empty for no
4584 * prefix.
4585 * @return string
4586 */
4587 public function getCategorySortkey( $prefix = '' ) {
4588 $unprefixed = $this->getText();
4589
4590 // Anything that uses this hook should only depend
4591 // on the Title object passed in, and should probably
4592 // tell the users to run updateCollations.php --force
4593 // in order to re-sort existing category relations.
4594 Hooks::run( 'GetDefaultSortkey', array( $this, &$unprefixed ) );
4595 if ( $prefix !== '' ) {
4596 # Separate with a line feed, so the unprefixed part is only used as
4597 # a tiebreaker when two pages have the exact same prefix.
4598 # In UCA, tab is the only character that can sort above LF
4599 # so we strip both of them from the original prefix.
4600 $prefix = strtr( $prefix, "\n\t", ' ' );
4601 return "$prefix\n$unprefixed";
4602 }
4603 return $unprefixed;
4604 }
4605
4606 /**
4607 * Get the language in which the content of this page is written in
4608 * wikitext. Defaults to $wgContLang, but in certain cases it can be
4609 * e.g. $wgLang (such as special pages, which are in the user language).
4610 *
4611 * @since 1.18
4612 * @return Language
4613 */
4614 public function getPageLanguage() {
4615 global $wgLang, $wgLanguageCode;
4616 if ( $this->isSpecialPage() ) {
4617 // special pages are in the user language
4618 return $wgLang;
4619 }
4620
4621 // Checking if DB language is set
4622 if ( $this->mDbPageLanguage ) {
4623 return wfGetLangObj( $this->mDbPageLanguage );
4624 }
4625
4626 if ( !$this->mPageLanguage || $this->mPageLanguage[1] !== $wgLanguageCode ) {
4627 // Note that this may depend on user settings, so the cache should
4628 // be only per-request.
4629 // NOTE: ContentHandler::getPageLanguage() may need to load the
4630 // content to determine the page language!
4631 // Checking $wgLanguageCode hasn't changed for the benefit of unit
4632 // tests.
4633 $contentHandler = ContentHandler::getForTitle( $this );
4634 $langObj = wfGetLangObj( $contentHandler->getPageLanguage( $this ) );
4635 $this->mPageLanguage = array( $langObj->getCode(), $wgLanguageCode );
4636 } else {
4637 $langObj = wfGetLangObj( $this->mPageLanguage[0] );
4638 }
4639
4640 return $langObj;
4641 }
4642
4643 /**
4644 * Get the language in which the content of this page is written when
4645 * viewed by user. Defaults to $wgContLang, but in certain cases it can be
4646 * e.g. $wgLang (such as special pages, which are in the user language).
4647 *
4648 * @since 1.20
4649 * @return Language
4650 */
4651 public function getPageViewLanguage() {
4652 global $wgLang;
4653
4654 if ( $this->isSpecialPage() ) {
4655 // If the user chooses a variant, the content is actually
4656 // in a language whose code is the variant code.
4657 $variant = $wgLang->getPreferredVariant();
4658 if ( $wgLang->getCode() !== $variant ) {
4659 return Language::factory( $variant );
4660 }
4661
4662 return $wgLang;
4663 }
4664
4665 // @note Can't be cached persistently, depends on user settings.
4666 // @note ContentHandler::getPageViewLanguage() may need to load the
4667 // content to determine the page language!
4668 $contentHandler = ContentHandler::getForTitle( $this );
4669 $pageLang = $contentHandler->getPageViewLanguage( $this );
4670 return $pageLang;
4671 }
4672
4673 /**
4674 * Get a list of rendered edit notices for this page.
4675 *
4676 * Array is keyed by the original message key, and values are rendered using parseAsBlock, so
4677 * they will already be wrapped in paragraphs.
4678 *
4679 * @since 1.21
4680 * @param int $oldid Revision ID that's being edited
4681 * @return array
4682 */
4683 public function getEditNotices( $oldid = 0 ) {
4684 $notices = array();
4685
4686 // Optional notice for the entire namespace
4687 $editnotice_ns = 'editnotice-' . $this->getNamespace();
4688 $msg = wfMessage( $editnotice_ns );
4689 if ( $msg->exists() ) {
4690 $html = $msg->parseAsBlock();
4691 // Edit notices may have complex logic, but output nothing (T91715)
4692 if ( trim( $html ) !== '' ) {
4693 $notices[$editnotice_ns] = Html::rawElement(
4694 'div',
4695 array( 'class' => array(
4696 'mw-editnotice',
4697 'mw-editnotice-namespace',
4698 Sanitizer::escapeClass( "mw-$editnotice_ns" )
4699 ) ),
4700 $html
4701 );
4702 }
4703 }
4704
4705 if ( MWNamespace::hasSubpages( $this->getNamespace() ) ) {
4706 // Optional notice for page itself and any parent page
4707 $parts = explode( '/', $this->getDBkey() );
4708 $editnotice_base = $editnotice_ns;
4709 while ( count( $parts ) > 0 ) {
4710 $editnotice_base .= '-' . array_shift( $parts );
4711 $msg = wfMessage( $editnotice_base );
4712 if ( $msg->exists() ) {
4713 $html = $msg->parseAsBlock();
4714 if ( trim( $html ) !== '' ) {
4715 $notices[$editnotice_base] = Html::rawElement(
4716 'div',
4717 array( 'class' => array(
4718 'mw-editnotice',
4719 'mw-editnotice-base',
4720 Sanitizer::escapeClass( "mw-$editnotice_base" )
4721 ) ),
4722 $html
4723 );
4724 }
4725 }
4726 }
4727 } else {
4728 // Even if there are no subpages in namespace, we still don't want "/" in MediaWiki message keys
4729 $editnoticeText = $editnotice_ns . '-' . str_replace( '/', '-', $this->getDBkey() );
4730 $msg = wfMessage( $editnoticeText );
4731 if ( $msg->exists() ) {
4732 $html = $msg->parseAsBlock();
4733 if ( trim( $html ) !== '' ) {
4734 $notices[$editnoticeText] = Html::rawElement(
4735 'div',
4736 array( 'class' => array(
4737 'mw-editnotice',
4738 'mw-editnotice-page',
4739 Sanitizer::escapeClass( "mw-$editnoticeText" )
4740 ) ),
4741 $html
4742 );
4743 }
4744 }
4745 }
4746
4747 Hooks::run( 'TitleGetEditNotices', array( $this, $oldid, &$notices ) );
4748 return $notices;
4749 }
4750 }