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