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