Update oyejorge/less.php to 1.7.0.10
[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 May be FOR UPDATE
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 May be FOR UPDATE
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 if ( count( $options ) > 0 ) {
3458 $db = wfGetDB( DB_MASTER );
3459 } else {
3460 $db = wfGetDB( DB_SLAVE );
3461 }
3462
3463 $blNamespace = "{$prefix}_namespace";
3464 $blTitle = "{$prefix}_title";
3465
3466 $res = $db->select(
3467 array( $table, 'page' ),
3468 array_merge(
3469 array( $blNamespace, $blTitle ),
3470 WikiPage::selectFields()
3471 ),
3472 array( "{$prefix}_from" => $id ),
3473 __METHOD__,
3474 $options,
3475 array( 'page' => array(
3476 'LEFT JOIN',
3477 array( "page_namespace=$blNamespace", "page_title=$blTitle" )
3478 ) )
3479 );
3480
3481 $retVal = array();
3482 $linkCache = LinkCache::singleton();
3483 foreach ( $res as $row ) {
3484 if ( $row->page_id ) {
3485 $titleObj = Title::newFromRow( $row );
3486 } else {
3487 $titleObj = Title::makeTitle( $row->$blNamespace, $row->$blTitle );
3488 $linkCache->addBadLinkObj( $titleObj );
3489 }
3490 $retVal[] = $titleObj;
3491 }
3492
3493 return $retVal;
3494 }
3495
3496 /**
3497 * Get an array of Title objects used on this Title as a template
3498 * Also stores the IDs in the link cache.
3499 *
3500 * WARNING: do not use this function on arbitrary user-supplied titles!
3501 * On heavily-used templates it will max out the memory.
3502 *
3503 * @param array $options May be FOR UPDATE
3504 * @return Title[] Array of Title the Title objects used here
3505 */
3506 public function getTemplateLinksFrom( $options = array() ) {
3507 return $this->getLinksFrom( $options, 'templatelinks', 'tl' );
3508 }
3509
3510 /**
3511 * Get an array of Title objects referring to non-existent articles linked
3512 * from this page.
3513 *
3514 * @todo check if needed (used only in SpecialBrokenRedirects.php, and
3515 * should use redirect table in this case).
3516 * @return Title[] Array of Title the Title objects
3517 */
3518 public function getBrokenLinksFrom() {
3519 if ( $this->getArticleID() == 0 ) {
3520 # All links from article ID 0 are false positives
3521 return array();
3522 }
3523
3524 $dbr = wfGetDB( DB_SLAVE );
3525 $res = $dbr->select(
3526 array( 'page', 'pagelinks' ),
3527 array( 'pl_namespace', 'pl_title' ),
3528 array(
3529 'pl_from' => $this->getArticleID(),
3530 'page_namespace IS NULL'
3531 ),
3532 __METHOD__, array(),
3533 array(
3534 'page' => array(
3535 'LEFT JOIN',
3536 array( 'pl_namespace=page_namespace', 'pl_title=page_title' )
3537 )
3538 )
3539 );
3540
3541 $retVal = array();
3542 foreach ( $res as $row ) {
3543 $retVal[] = Title::makeTitle( $row->pl_namespace, $row->pl_title );
3544 }
3545 return $retVal;
3546 }
3547
3548 /**
3549 * Get a list of URLs to purge from the CDN cache when this
3550 * page changes
3551 *
3552 * @return string[] Array of String the URLs
3553 */
3554 public function getCdnUrls() {
3555 $urls = array(
3556 $this->getInternalURL(),
3557 $this->getInternalURL( 'action=history' )
3558 );
3559
3560 $pageLang = $this->getPageLanguage();
3561 if ( $pageLang->hasVariants() ) {
3562 $variants = $pageLang->getVariants();
3563 foreach ( $variants as $vCode ) {
3564 $urls[] = $this->getInternalURL( $vCode );
3565 }
3566 }
3567
3568 // If we are looking at a css/js user subpage, purge the action=raw.
3569 if ( $this->isJsSubpage() ) {
3570 $urls[] = $this->getInternalUrl( 'action=raw&ctype=text/javascript' );
3571 } elseif ( $this->isCssSubpage() ) {
3572 $urls[] = $this->getInternalUrl( 'action=raw&ctype=text/css' );
3573 }
3574
3575 Hooks::run( 'TitleSquidURLs', array( $this, &$urls ) );
3576 return $urls;
3577 }
3578
3579 /**
3580 * @deprecated since 1.27 use getCdnUrls()
3581 */
3582 public function getSquidURLs() {
3583 return $this->getCdnUrls();
3584 }
3585
3586 /**
3587 * Purge all applicable CDN URLs
3588 */
3589 public function purgeSquid() {
3590 DeferredUpdates::addUpdate(
3591 new CdnCacheUpdate( $this->getCdnUrls() ),
3592 DeferredUpdates::PRESEND
3593 );
3594 }
3595
3596 /**
3597 * Move this page without authentication
3598 *
3599 * @deprecated since 1.25 use MovePage class instead
3600 * @param Title $nt The new page Title
3601 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
3602 */
3603 public function moveNoAuth( &$nt ) {
3604 wfDeprecated( __METHOD__, '1.25' );
3605 return $this->moveTo( $nt, false );
3606 }
3607
3608 /**
3609 * Check whether a given move operation would be valid.
3610 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
3611 *
3612 * @deprecated since 1.25, use MovePage's methods instead
3613 * @param Title $nt The new title
3614 * @param bool $auth Whether to check user permissions (uses $wgUser)
3615 * @param string $reason Is the log summary of the move, used for spam checking
3616 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
3617 */
3618 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
3619 global $wgUser;
3620
3621 if ( !( $nt instanceof Title ) ) {
3622 // Normally we'd add this to $errors, but we'll get
3623 // lots of syntax errors if $nt is not an object
3624 return array( array( 'badtitletext' ) );
3625 }
3626
3627 $mp = new MovePage( $this, $nt );
3628 $errors = $mp->isValidMove()->getErrorsArray();
3629 if ( $auth ) {
3630 $errors = wfMergeErrorArrays(
3631 $errors,
3632 $mp->checkPermissions( $wgUser, $reason )->getErrorsArray()
3633 );
3634 }
3635
3636 return $errors ?: true;
3637 }
3638
3639 /**
3640 * Check if the requested move target is a valid file move target
3641 * @todo move this to MovePage
3642 * @param Title $nt Target title
3643 * @return array List of errors
3644 */
3645 protected function validateFileMoveOperation( $nt ) {
3646 global $wgUser;
3647
3648 $errors = array();
3649
3650 $destFile = wfLocalFile( $nt );
3651 $destFile->load( File::READ_LATEST );
3652 if ( !$wgUser->isAllowed( 'reupload-shared' )
3653 && !$destFile->exists() && wfFindFile( $nt )
3654 ) {
3655 $errors[] = array( 'file-exists-sharedrepo' );
3656 }
3657
3658 return $errors;
3659 }
3660
3661 /**
3662 * Move a title to a new location
3663 *
3664 * @deprecated since 1.25, use the MovePage class instead
3665 * @param Title $nt The new title
3666 * @param bool $auth Indicates whether $wgUser's permissions
3667 * should be checked
3668 * @param string $reason The reason for the move
3669 * @param bool $createRedirect Whether to create a redirect from the old title to the new title.
3670 * Ignored if the user doesn't have the suppressredirect right.
3671 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
3672 */
3673 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true ) {
3674 global $wgUser;
3675 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
3676 if ( is_array( $err ) ) {
3677 // Auto-block user's IP if the account was "hard" blocked
3678 $wgUser->spreadAnyEditBlock();
3679 return $err;
3680 }
3681 // Check suppressredirect permission
3682 if ( $auth && !$wgUser->isAllowed( 'suppressredirect' ) ) {
3683 $createRedirect = true;
3684 }
3685
3686 $mp = new MovePage( $this, $nt );
3687 $status = $mp->move( $wgUser, $reason, $createRedirect );
3688 if ( $status->isOK() ) {
3689 return true;
3690 } else {
3691 return $status->getErrorsArray();
3692 }
3693 }
3694
3695 /**
3696 * Move this page's subpages to be subpages of $nt
3697 *
3698 * @param Title $nt Move target
3699 * @param bool $auth Whether $wgUser's permissions should be checked
3700 * @param string $reason The reason for the move
3701 * @param bool $createRedirect Whether to create redirects from the old subpages to
3702 * the new ones Ignored if the user doesn't have the 'suppressredirect' right
3703 * @return array Array with old page titles as keys, and strings (new page titles) or
3704 * arrays (errors) as values, or an error array with numeric indices if no pages
3705 * were moved
3706 */
3707 public function moveSubpages( $nt, $auth = true, $reason = '', $createRedirect = true ) {
3708 global $wgMaximumMovedPages;
3709 // Check permissions
3710 if ( !$this->userCan( 'move-subpages' ) ) {
3711 return array( 'cant-move-subpages' );
3712 }
3713 // Do the source and target namespaces support subpages?
3714 if ( !MWNamespace::hasSubpages( $this->getNamespace() ) ) {
3715 return array( 'namespace-nosubpages',
3716 MWNamespace::getCanonicalName( $this->getNamespace() ) );
3717 }
3718 if ( !MWNamespace::hasSubpages( $nt->getNamespace() ) ) {
3719 return array( 'namespace-nosubpages',
3720 MWNamespace::getCanonicalName( $nt->getNamespace() ) );
3721 }
3722
3723 $subpages = $this->getSubpages( $wgMaximumMovedPages + 1 );
3724 $retval = array();
3725 $count = 0;
3726 foreach ( $subpages as $oldSubpage ) {
3727 $count++;
3728 if ( $count > $wgMaximumMovedPages ) {
3729 $retval[$oldSubpage->getPrefixedText()] =
3730 array( 'movepage-max-pages',
3731 $wgMaximumMovedPages );
3732 break;
3733 }
3734
3735 // We don't know whether this function was called before
3736 // or after moving the root page, so check both
3737 // $this and $nt
3738 if ( $oldSubpage->getArticleID() == $this->getArticleID()
3739 || $oldSubpage->getArticleID() == $nt->getArticleID()
3740 ) {
3741 // When moving a page to a subpage of itself,
3742 // don't move it twice
3743 continue;
3744 }
3745 $newPageName = preg_replace(
3746 '#^' . preg_quote( $this->getDBkey(), '#' ) . '#',
3747 StringUtils::escapeRegexReplacement( $nt->getDBkey() ), # bug 21234
3748 $oldSubpage->getDBkey() );
3749 if ( $oldSubpage->isTalkPage() ) {
3750 $newNs = $nt->getTalkPage()->getNamespace();
3751 } else {
3752 $newNs = $nt->getSubjectPage()->getNamespace();
3753 }
3754 # Bug 14385: we need makeTitleSafe because the new page names may
3755 # be longer than 255 characters.
3756 $newSubpage = Title::makeTitleSafe( $newNs, $newPageName );
3757
3758 $success = $oldSubpage->moveTo( $newSubpage, $auth, $reason, $createRedirect );
3759 if ( $success === true ) {
3760 $retval[$oldSubpage->getPrefixedText()] = $newSubpage->getPrefixedText();
3761 } else {
3762 $retval[$oldSubpage->getPrefixedText()] = $success;
3763 }
3764 }
3765 return $retval;
3766 }
3767
3768 /**
3769 * Checks if this page is just a one-rev redirect.
3770 * Adds lock, so don't use just for light purposes.
3771 *
3772 * @return bool
3773 */
3774 public function isSingleRevRedirect() {
3775 global $wgContentHandlerUseDB;
3776
3777 $dbw = wfGetDB( DB_MASTER );
3778
3779 # Is it a redirect?
3780 $fields = array( 'page_is_redirect', 'page_latest', 'page_id' );
3781 if ( $wgContentHandlerUseDB ) {
3782 $fields[] = 'page_content_model';
3783 }
3784
3785 $row = $dbw->selectRow( 'page',
3786 $fields,
3787 $this->pageCond(),
3788 __METHOD__,
3789 array( 'FOR UPDATE' )
3790 );
3791 # Cache some fields we may want
3792 $this->mArticleID = $row ? intval( $row->page_id ) : 0;
3793 $this->mRedirect = $row ? (bool)$row->page_is_redirect : false;
3794 $this->mLatestID = $row ? intval( $row->page_latest ) : false;
3795 $this->mContentModel = $row && isset( $row->page_content_model )
3796 ? strval( $row->page_content_model )
3797 : false;
3798
3799 if ( !$this->mRedirect ) {
3800 return false;
3801 }
3802 # Does the article have a history?
3803 $row = $dbw->selectField( array( 'page', 'revision' ),
3804 'rev_id',
3805 array( 'page_namespace' => $this->getNamespace(),
3806 'page_title' => $this->getDBkey(),
3807 'page_id=rev_page',
3808 'page_latest != rev_id'
3809 ),
3810 __METHOD__,
3811 array( 'FOR UPDATE' )
3812 );
3813 # Return true if there was no history
3814 return ( $row === false );
3815 }
3816
3817 /**
3818 * Checks if $this can be moved to a given Title
3819 * - Selects for update, so don't call it unless you mean business
3820 *
3821 * @deprecated since 1.25, use MovePage's methods instead
3822 * @param Title $nt The new title to check
3823 * @return bool
3824 */
3825 public function isValidMoveTarget( $nt ) {
3826 # Is it an existing file?
3827 if ( $nt->getNamespace() == NS_FILE ) {
3828 $file = wfLocalFile( $nt );
3829 $file->load( File::READ_LATEST );
3830 if ( $file->exists() ) {
3831 wfDebug( __METHOD__ . ": file exists\n" );
3832 return false;
3833 }
3834 }
3835 # Is it a redirect with no history?
3836 if ( !$nt->isSingleRevRedirect() ) {
3837 wfDebug( __METHOD__ . ": not a one-rev redirect\n" );
3838 return false;
3839 }
3840 # Get the article text
3841 $rev = Revision::newFromTitle( $nt, false, Revision::READ_LATEST );
3842 if ( !is_object( $rev ) ) {
3843 return false;
3844 }
3845 $content = $rev->getContent();
3846 # Does the redirect point to the source?
3847 # Or is it a broken self-redirect, usually caused by namespace collisions?
3848 $redirTitle = $content ? $content->getRedirectTarget() : null;
3849
3850 if ( $redirTitle ) {
3851 if ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
3852 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) {
3853 wfDebug( __METHOD__ . ": redirect points to other page\n" );
3854 return false;
3855 } else {
3856 return true;
3857 }
3858 } else {
3859 # Fail safe (not a redirect after all. strange.)
3860 wfDebug( __METHOD__ . ": failsafe: database sais " . $nt->getPrefixedDBkey() .
3861 " is a redirect, but it doesn't contain a valid redirect.\n" );
3862 return false;
3863 }
3864 }
3865
3866 /**
3867 * Get categories to which this Title belongs and return an array of
3868 * categories' names.
3869 *
3870 * @return array Array of parents in the form:
3871 * $parent => $currentarticle
3872 */
3873 public function getParentCategories() {
3874 global $wgContLang;
3875
3876 $data = array();
3877
3878 $titleKey = $this->getArticleID();
3879
3880 if ( $titleKey === 0 ) {
3881 return $data;
3882 }
3883
3884 $dbr = wfGetDB( DB_SLAVE );
3885
3886 $res = $dbr->select(
3887 'categorylinks',
3888 'cl_to',
3889 array( 'cl_from' => $titleKey ),
3890 __METHOD__
3891 );
3892
3893 if ( $res->numRows() > 0 ) {
3894 foreach ( $res as $row ) {
3895 // $data[] = Title::newFromText($wgContLang->getNsText ( NS_CATEGORY ).':'.$row->cl_to);
3896 $data[$wgContLang->getNsText( NS_CATEGORY ) . ':' . $row->cl_to] = $this->getFullText();
3897 }
3898 }
3899 return $data;
3900 }
3901
3902 /**
3903 * Get a tree of parent categories
3904 *
3905 * @param array $children Array with the children in the keys, to check for circular refs
3906 * @return array Tree of parent categories
3907 */
3908 public function getParentCategoryTree( $children = array() ) {
3909 $stack = array();
3910 $parents = $this->getParentCategories();
3911
3912 if ( $parents ) {
3913 foreach ( $parents as $parent => $current ) {
3914 if ( array_key_exists( $parent, $children ) ) {
3915 # Circular reference
3916 $stack[$parent] = array();
3917 } else {
3918 $nt = Title::newFromText( $parent );
3919 if ( $nt ) {
3920 $stack[$parent] = $nt->getParentCategoryTree( $children + array( $parent => 1 ) );
3921 }
3922 }
3923 }
3924 }
3925
3926 return $stack;
3927 }
3928
3929 /**
3930 * Get an associative array for selecting this title from
3931 * the "page" table
3932 *
3933 * @return array Array suitable for the $where parameter of DB::select()
3934 */
3935 public function pageCond() {
3936 if ( $this->mArticleID > 0 ) {
3937 // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs
3938 return array( 'page_id' => $this->mArticleID );
3939 } else {
3940 return array( 'page_namespace' => $this->mNamespace, 'page_title' => $this->mDbkeyform );
3941 }
3942 }
3943
3944 /**
3945 * Get the revision ID of the previous revision
3946 *
3947 * @param int $revId Revision ID. Get the revision that was before this one.
3948 * @param int $flags Title::GAID_FOR_UPDATE
3949 * @return int|bool Old revision ID, or false if none exists
3950 */
3951 public function getPreviousRevisionID( $revId, $flags = 0 ) {
3952 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
3953 $revId = $db->selectField( 'revision', 'rev_id',
3954 array(
3955 'rev_page' => $this->getArticleID( $flags ),
3956 'rev_id < ' . intval( $revId )
3957 ),
3958 __METHOD__,
3959 array( 'ORDER BY' => 'rev_id DESC' )
3960 );
3961
3962 if ( $revId === false ) {
3963 return false;
3964 } else {
3965 return intval( $revId );
3966 }
3967 }
3968
3969 /**
3970 * Get the revision ID of the next revision
3971 *
3972 * @param int $revId Revision ID. Get the revision that was after this one.
3973 * @param int $flags Title::GAID_FOR_UPDATE
3974 * @return int|bool Next revision ID, or false if none exists
3975 */
3976 public function getNextRevisionID( $revId, $flags = 0 ) {
3977 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
3978 $revId = $db->selectField( 'revision', 'rev_id',
3979 array(
3980 'rev_page' => $this->getArticleID( $flags ),
3981 'rev_id > ' . intval( $revId )
3982 ),
3983 __METHOD__,
3984 array( 'ORDER BY' => 'rev_id' )
3985 );
3986
3987 if ( $revId === false ) {
3988 return false;
3989 } else {
3990 return intval( $revId );
3991 }
3992 }
3993
3994 /**
3995 * Get the first revision of the page
3996 *
3997 * @param int $flags Title::GAID_FOR_UPDATE
3998 * @return Revision|null If page doesn't exist
3999 */
4000 public function getFirstRevision( $flags = 0 ) {
4001 $pageId = $this->getArticleID( $flags );
4002 if ( $pageId ) {
4003 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
4004 $row = $db->selectRow( 'revision', Revision::selectFields(),
4005 array( 'rev_page' => $pageId ),
4006 __METHOD__,
4007 array( 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 1 )
4008 );
4009 if ( $row ) {
4010 return new Revision( $row );
4011 }
4012 }
4013 return null;
4014 }
4015
4016 /**
4017 * Get the oldest revision timestamp of this page
4018 *
4019 * @param int $flags Title::GAID_FOR_UPDATE
4020 * @return string MW timestamp
4021 */
4022 public function getEarliestRevTime( $flags = 0 ) {
4023 $rev = $this->getFirstRevision( $flags );
4024 return $rev ? $rev->getTimestamp() : null;
4025 }
4026
4027 /**
4028 * Check if this is a new page
4029 *
4030 * @return bool
4031 */
4032 public function isNewPage() {
4033 $dbr = wfGetDB( DB_SLAVE );
4034 return (bool)$dbr->selectField( 'page', 'page_is_new', $this->pageCond(), __METHOD__ );
4035 }
4036
4037 /**
4038 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
4039 *
4040 * @return bool
4041 */
4042 public function isBigDeletion() {
4043 global $wgDeleteRevisionsLimit;
4044
4045 if ( !$wgDeleteRevisionsLimit ) {
4046 return false;
4047 }
4048
4049 if ( $this->mIsBigDeletion === null ) {
4050 $dbr = wfGetDB( DB_SLAVE );
4051
4052 $revCount = $dbr->selectRowCount(
4053 'revision',
4054 '1',
4055 array( 'rev_page' => $this->getArticleID() ),
4056 __METHOD__,
4057 array( 'LIMIT' => $wgDeleteRevisionsLimit + 1 )
4058 );
4059
4060 $this->mIsBigDeletion = $revCount > $wgDeleteRevisionsLimit;
4061 }
4062
4063 return $this->mIsBigDeletion;
4064 }
4065
4066 /**
4067 * Get the approximate revision count of this page.
4068 *
4069 * @return int
4070 */
4071 public function estimateRevisionCount() {
4072 if ( !$this->exists() ) {
4073 return 0;
4074 }
4075
4076 if ( $this->mEstimateRevisions === null ) {
4077 $dbr = wfGetDB( DB_SLAVE );
4078 $this->mEstimateRevisions = $dbr->estimateRowCount( 'revision', '*',
4079 array( 'rev_page' => $this->getArticleID() ), __METHOD__ );
4080 }
4081
4082 return $this->mEstimateRevisions;
4083 }
4084
4085 /**
4086 * Get the number of revisions between the given revision.
4087 * Used for diffs and other things that really need it.
4088 *
4089 * @param int|Revision $old Old revision or rev ID (first before range)
4090 * @param int|Revision $new New revision or rev ID (first after range)
4091 * @param int|null $max Limit of Revisions to count, will be incremented to detect truncations
4092 * @return int Number of revisions between these revisions.
4093 */
4094 public function countRevisionsBetween( $old, $new, $max = null ) {
4095 if ( !( $old instanceof Revision ) ) {
4096 $old = Revision::newFromTitle( $this, (int)$old );
4097 }
4098 if ( !( $new instanceof Revision ) ) {
4099 $new = Revision::newFromTitle( $this, (int)$new );
4100 }
4101 if ( !$old || !$new ) {
4102 return 0; // nothing to compare
4103 }
4104 $dbr = wfGetDB( DB_SLAVE );
4105 $conds = array(
4106 'rev_page' => $this->getArticleID(),
4107 'rev_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4108 'rev_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4109 );
4110 if ( $max !== null ) {
4111 return $dbr->selectRowCount( 'revision', '1',
4112 $conds,
4113 __METHOD__,
4114 array( 'LIMIT' => $max + 1 ) // extra to detect truncation
4115 );
4116 } else {
4117 return (int)$dbr->selectField( 'revision', 'count(*)', $conds, __METHOD__ );
4118 }
4119 }
4120
4121 /**
4122 * Get the authors between the given revisions or revision IDs.
4123 * Used for diffs and other things that really need it.
4124 *
4125 * @since 1.23
4126 *
4127 * @param int|Revision $old Old revision or rev ID (first before range by default)
4128 * @param int|Revision $new New revision or rev ID (first after range by default)
4129 * @param int $limit Maximum number of authors
4130 * @param string|array $options (Optional): Single option, or an array of options:
4131 * 'include_old' Include $old in the range; $new is excluded.
4132 * 'include_new' Include $new in the range; $old is excluded.
4133 * 'include_both' Include both $old and $new in the range.
4134 * Unknown option values are ignored.
4135 * @return array|null Names of revision authors in the range; null if not both revisions exist
4136 */
4137 public function getAuthorsBetween( $old, $new, $limit, $options = array() ) {
4138 if ( !( $old instanceof Revision ) ) {
4139 $old = Revision::newFromTitle( $this, (int)$old );
4140 }
4141 if ( !( $new instanceof Revision ) ) {
4142 $new = Revision::newFromTitle( $this, (int)$new );
4143 }
4144 // XXX: what if Revision objects are passed in, but they don't refer to this title?
4145 // Add $old->getPage() != $new->getPage() || $old->getPage() != $this->getArticleID()
4146 // in the sanity check below?
4147 if ( !$old || !$new ) {
4148 return null; // nothing to compare
4149 }
4150 $authors = array();
4151 $old_cmp = '>';
4152 $new_cmp = '<';
4153 $options = (array)$options;
4154 if ( in_array( 'include_old', $options ) ) {
4155 $old_cmp = '>=';
4156 }
4157 if ( in_array( 'include_new', $options ) ) {
4158 $new_cmp = '<=';
4159 }
4160 if ( in_array( 'include_both', $options ) ) {
4161 $old_cmp = '>=';
4162 $new_cmp = '<=';
4163 }
4164 // No DB query needed if $old and $new are the same or successive revisions:
4165 if ( $old->getId() === $new->getId() ) {
4166 return ( $old_cmp === '>' && $new_cmp === '<' ) ?
4167 array() :
4168 array( $old->getUserText( Revision::RAW ) );
4169 } elseif ( $old->getId() === $new->getParentId() ) {
4170 if ( $old_cmp === '>=' && $new_cmp === '<=' ) {
4171 $authors[] = $old->getUserText( Revision::RAW );
4172 if ( $old->getUserText( Revision::RAW ) != $new->getUserText( Revision::RAW ) ) {
4173 $authors[] = $new->getUserText( Revision::RAW );
4174 }
4175 } elseif ( $old_cmp === '>=' ) {
4176 $authors[] = $old->getUserText( Revision::RAW );
4177 } elseif ( $new_cmp === '<=' ) {
4178 $authors[] = $new->getUserText( Revision::RAW );
4179 }
4180 return $authors;
4181 }
4182 $dbr = wfGetDB( DB_SLAVE );
4183 $res = $dbr->select( 'revision', 'DISTINCT rev_user_text',
4184 array(
4185 'rev_page' => $this->getArticleID(),
4186 "rev_timestamp $old_cmp " . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4187 "rev_timestamp $new_cmp " . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4188 ), __METHOD__,
4189 array( 'LIMIT' => $limit + 1 ) // add one so caller knows it was truncated
4190 );
4191 foreach ( $res as $row ) {
4192 $authors[] = $row->rev_user_text;
4193 }
4194 return $authors;
4195 }
4196
4197 /**
4198 * Get the number of authors between the given revisions or revision IDs.
4199 * Used for diffs and other things that really need it.
4200 *
4201 * @param int|Revision $old Old revision or rev ID (first before range by default)
4202 * @param int|Revision $new New revision or rev ID (first after range by default)
4203 * @param int $limit Maximum number of authors
4204 * @param string|array $options (Optional): Single option, or an array of options:
4205 * 'include_old' Include $old in the range; $new is excluded.
4206 * 'include_new' Include $new in the range; $old is excluded.
4207 * 'include_both' Include both $old and $new in the range.
4208 * Unknown option values are ignored.
4209 * @return int Number of revision authors in the range; zero if not both revisions exist
4210 */
4211 public function countAuthorsBetween( $old, $new, $limit, $options = array() ) {
4212 $authors = $this->getAuthorsBetween( $old, $new, $limit, $options );
4213 return $authors ? count( $authors ) : 0;
4214 }
4215
4216 /**
4217 * Compare with another title.
4218 *
4219 * @param Title $title
4220 * @return bool
4221 */
4222 public function equals( Title $title ) {
4223 // Note: === is necessary for proper matching of number-like titles.
4224 return $this->getInterwiki() === $title->getInterwiki()
4225 && $this->getNamespace() == $title->getNamespace()
4226 && $this->getDBkey() === $title->getDBkey();
4227 }
4228
4229 /**
4230 * Check if this title is a subpage of another title
4231 *
4232 * @param Title $title
4233 * @return bool
4234 */
4235 public function isSubpageOf( Title $title ) {
4236 return $this->getInterwiki() === $title->getInterwiki()
4237 && $this->getNamespace() == $title->getNamespace()
4238 && strpos( $this->getDBkey(), $title->getDBkey() . '/' ) === 0;
4239 }
4240
4241 /**
4242 * Check if page exists. For historical reasons, this function simply
4243 * checks for the existence of the title in the page table, and will
4244 * thus return false for interwiki links, special pages and the like.
4245 * If you want to know if a title can be meaningfully viewed, you should
4246 * probably call the isKnown() method instead.
4247 *
4248 * @param int $flags An optional bit field; may be Title::GAID_FOR_UPDATE to check
4249 * from master/for update
4250 * @return bool
4251 */
4252 public function exists( $flags = 0 ) {
4253 $exists = $this->getArticleID( $flags ) != 0;
4254 Hooks::run( 'TitleExists', array( $this, &$exists ) );
4255 return $exists;
4256 }
4257
4258 /**
4259 * Should links to this title be shown as potentially viewable (i.e. as
4260 * "bluelinks"), even if there's no record by this title in the page
4261 * table?
4262 *
4263 * This function is semi-deprecated for public use, as well as somewhat
4264 * misleadingly named. You probably just want to call isKnown(), which
4265 * calls this function internally.
4266 *
4267 * (ISSUE: Most of these checks are cheap, but the file existence check
4268 * can potentially be quite expensive. Including it here fixes a lot of
4269 * existing code, but we might want to add an optional parameter to skip
4270 * it and any other expensive checks.)
4271 *
4272 * @return bool
4273 */
4274 public function isAlwaysKnown() {
4275 $isKnown = null;
4276
4277 /**
4278 * Allows overriding default behavior for determining if a page exists.
4279 * If $isKnown is kept as null, regular checks happen. If it's
4280 * a boolean, this value is returned by the isKnown method.
4281 *
4282 * @since 1.20
4283 *
4284 * @param Title $title
4285 * @param bool|null $isKnown
4286 */
4287 Hooks::run( 'TitleIsAlwaysKnown', array( $this, &$isKnown ) );
4288
4289 if ( !is_null( $isKnown ) ) {
4290 return $isKnown;
4291 }
4292
4293 if ( $this->isExternal() ) {
4294 return true; // any interwiki link might be viewable, for all we know
4295 }
4296
4297 switch ( $this->mNamespace ) {
4298 case NS_MEDIA:
4299 case NS_FILE:
4300 // file exists, possibly in a foreign repo
4301 return (bool)wfFindFile( $this );
4302 case NS_SPECIAL:
4303 // valid special page
4304 return SpecialPageFactory::exists( $this->getDBkey() );
4305 case NS_MAIN:
4306 // selflink, possibly with fragment
4307 return $this->mDbkeyform == '';
4308 case NS_MEDIAWIKI:
4309 // known system message
4310 return $this->hasSourceText() !== false;
4311 default:
4312 return false;
4313 }
4314 }
4315
4316 /**
4317 * Does this title refer to a page that can (or might) be meaningfully
4318 * viewed? In particular, this function may be used to determine if
4319 * links to the title should be rendered as "bluelinks" (as opposed to
4320 * "redlinks" to non-existent pages).
4321 * Adding something else to this function will cause inconsistency
4322 * since LinkHolderArray calls isAlwaysKnown() and does its own
4323 * page existence check.
4324 *
4325 * @return bool
4326 */
4327 public function isKnown() {
4328 return $this->isAlwaysKnown() || $this->exists();
4329 }
4330
4331 /**
4332 * Does this page have source text?
4333 *
4334 * @return bool
4335 */
4336 public function hasSourceText() {
4337 if ( $this->exists() ) {
4338 return true;
4339 }
4340
4341 if ( $this->mNamespace == NS_MEDIAWIKI ) {
4342 // If the page doesn't exist but is a known system message, default
4343 // message content will be displayed, same for language subpages-
4344 // Use always content language to avoid loading hundreds of languages
4345 // to get the link color.
4346 global $wgContLang;
4347 list( $name, ) = MessageCache::singleton()->figureMessage(
4348 $wgContLang->lcfirst( $this->getText() )
4349 );
4350 $message = wfMessage( $name )->inLanguage( $wgContLang )->useDatabase( false );
4351 return $message->exists();
4352 }
4353
4354 return false;
4355 }
4356
4357 /**
4358 * Get the default message text or false if the message doesn't exist
4359 *
4360 * @return string|bool
4361 */
4362 public function getDefaultMessageText() {
4363 global $wgContLang;
4364
4365 if ( $this->getNamespace() != NS_MEDIAWIKI ) { // Just in case
4366 return false;
4367 }
4368
4369 list( $name, $lang ) = MessageCache::singleton()->figureMessage(
4370 $wgContLang->lcfirst( $this->getText() )
4371 );
4372 $message = wfMessage( $name )->inLanguage( $lang )->useDatabase( false );
4373
4374 if ( $message->exists() ) {
4375 return $message->plain();
4376 } else {
4377 return false;
4378 }
4379 }
4380
4381 /**
4382 * Updates page_touched for this page; called from LinksUpdate.php
4383 *
4384 * @param string $purgeTime [optional] TS_MW timestamp
4385 * @return bool True if the update succeeded
4386 */
4387 public function invalidateCache( $purgeTime = null ) {
4388 if ( wfReadOnly() ) {
4389 return false;
4390 }
4391
4392 if ( $this->mArticleID === 0 ) {
4393 return true; // avoid gap locking if we know it's not there
4394 }
4395
4396 $method = __METHOD__;
4397 $dbw = wfGetDB( DB_MASTER );
4398 $conds = $this->pageCond();
4399 $dbw->onTransactionIdle( function () use ( $dbw, $conds, $method, $purgeTime ) {
4400 $dbTimestamp = $dbw->timestamp( $purgeTime ?: time() );
4401
4402 $dbw->update(
4403 'page',
4404 array( 'page_touched' => $dbTimestamp ),
4405 $conds + array( 'page_touched < ' . $dbw->addQuotes( $dbTimestamp ) ),
4406 $method
4407 );
4408 } );
4409
4410 return true;
4411 }
4412
4413 /**
4414 * Update page_touched timestamps and send CDN purge messages for
4415 * pages linking to this title. May be sent to the job queue depending
4416 * on the number of links. Typically called on create and delete.
4417 */
4418 public function touchLinks() {
4419 DeferredUpdates::addUpdate( new HTMLCacheUpdate( $this, 'pagelinks' ) );
4420 if ( $this->getNamespace() == NS_CATEGORY ) {
4421 DeferredUpdates::addUpdate( new HTMLCacheUpdate( $this, 'categorylinks' ) );
4422 }
4423 }
4424
4425 /**
4426 * Get the last touched timestamp
4427 *
4428 * @param IDatabase $db Optional db
4429 * @return string Last-touched timestamp
4430 */
4431 public function getTouched( $db = null ) {
4432 if ( $db === null ) {
4433 $db = wfGetDB( DB_SLAVE );
4434 }
4435 $touched = $db->selectField( 'page', 'page_touched', $this->pageCond(), __METHOD__ );
4436 return $touched;
4437 }
4438
4439 /**
4440 * Get the timestamp when this page was updated since the user last saw it.
4441 *
4442 * @param User $user
4443 * @return string|null
4444 */
4445 public function getNotificationTimestamp( $user = null ) {
4446 global $wgUser;
4447
4448 // Assume current user if none given
4449 if ( !$user ) {
4450 $user = $wgUser;
4451 }
4452 // Check cache first
4453 $uid = $user->getId();
4454 if ( !$uid ) {
4455 return false;
4456 }
4457 // avoid isset here, as it'll return false for null entries
4458 if ( array_key_exists( $uid, $this->mNotificationTimestamp ) ) {
4459 return $this->mNotificationTimestamp[$uid];
4460 }
4461 // Don't cache too much!
4462 if ( count( $this->mNotificationTimestamp ) >= self::CACHE_MAX ) {
4463 $this->mNotificationTimestamp = array();
4464 }
4465
4466 $watchedItem = WatchedItem::fromUserTitle( $user, $this );
4467 $this->mNotificationTimestamp[$uid] = $watchedItem->getNotificationTimestamp();
4468
4469 return $this->mNotificationTimestamp[$uid];
4470 }
4471
4472 /**
4473 * Generate strings used for xml 'id' names in monobook tabs
4474 *
4475 * @param string $prepend Defaults to 'nstab-'
4476 * @return string XML 'id' name
4477 */
4478 public function getNamespaceKey( $prepend = 'nstab-' ) {
4479 global $wgContLang;
4480 // Gets the subject namespace if this title
4481 $namespace = MWNamespace::getSubject( $this->getNamespace() );
4482 // Checks if canonical namespace name exists for namespace
4483 if ( MWNamespace::exists( $this->getNamespace() ) ) {
4484 // Uses canonical namespace name
4485 $namespaceKey = MWNamespace::getCanonicalName( $namespace );
4486 } else {
4487 // Uses text of namespace
4488 $namespaceKey = $this->getSubjectNsText();
4489 }
4490 // Makes namespace key lowercase
4491 $namespaceKey = $wgContLang->lc( $namespaceKey );
4492 // Uses main
4493 if ( $namespaceKey == '' ) {
4494 $namespaceKey = 'main';
4495 }
4496 // Changes file to image for backwards compatibility
4497 if ( $namespaceKey == 'file' ) {
4498 $namespaceKey = 'image';
4499 }
4500 return $prepend . $namespaceKey;
4501 }
4502
4503 /**
4504 * Get all extant redirects to this Title
4505 *
4506 * @param int|null $ns Single namespace to consider; null to consider all namespaces
4507 * @return Title[] Array of Title redirects to this title
4508 */
4509 public function getRedirectsHere( $ns = null ) {
4510 $redirs = array();
4511
4512 $dbr = wfGetDB( DB_SLAVE );
4513 $where = array(
4514 'rd_namespace' => $this->getNamespace(),
4515 'rd_title' => $this->getDBkey(),
4516 'rd_from = page_id'
4517 );
4518 if ( $this->isExternal() ) {
4519 $where['rd_interwiki'] = $this->getInterwiki();
4520 } else {
4521 $where[] = 'rd_interwiki = ' . $dbr->addQuotes( '' ) . ' OR rd_interwiki IS NULL';
4522 }
4523 if ( !is_null( $ns ) ) {
4524 $where['page_namespace'] = $ns;
4525 }
4526
4527 $res = $dbr->select(
4528 array( 'redirect', 'page' ),
4529 array( 'page_namespace', 'page_title' ),
4530 $where,
4531 __METHOD__
4532 );
4533
4534 foreach ( $res as $row ) {
4535 $redirs[] = self::newFromRow( $row );
4536 }
4537 return $redirs;
4538 }
4539
4540 /**
4541 * Check if this Title is a valid redirect target
4542 *
4543 * @return bool
4544 */
4545 public function isValidRedirectTarget() {
4546 global $wgInvalidRedirectTargets;
4547
4548 if ( $this->isSpecialPage() ) {
4549 // invalid redirect targets are stored in a global array, but explicitly disallow Userlogout here
4550 if ( $this->isSpecial( 'Userlogout' ) ) {
4551 return false;
4552 }
4553
4554 foreach ( $wgInvalidRedirectTargets as $target ) {
4555 if ( $this->isSpecial( $target ) ) {
4556 return false;
4557 }
4558 }
4559 }
4560
4561 return true;
4562 }
4563
4564 /**
4565 * Get a backlink cache object
4566 *
4567 * @return BacklinkCache
4568 */
4569 public function getBacklinkCache() {
4570 return BacklinkCache::get( $this );
4571 }
4572
4573 /**
4574 * Whether the magic words __INDEX__ and __NOINDEX__ function for this page.
4575 *
4576 * @return bool
4577 */
4578 public function canUseNoindex() {
4579 global $wgContentNamespaces, $wgExemptFromUserRobotsControl;
4580
4581 $bannedNamespaces = is_null( $wgExemptFromUserRobotsControl )
4582 ? $wgContentNamespaces
4583 : $wgExemptFromUserRobotsControl;
4584
4585 return !in_array( $this->mNamespace, $bannedNamespaces );
4586
4587 }
4588
4589 /**
4590 * Returns the raw sort key to be used for categories, with the specified
4591 * prefix. This will be fed to Collation::getSortKey() to get a
4592 * binary sortkey that can be used for actual sorting.
4593 *
4594 * @param string $prefix The prefix to be used, specified using
4595 * {{defaultsort:}} or like [[Category:Foo|prefix]]. Empty for no
4596 * prefix.
4597 * @return string
4598 */
4599 public function getCategorySortkey( $prefix = '' ) {
4600 $unprefixed = $this->getText();
4601
4602 // Anything that uses this hook should only depend
4603 // on the Title object passed in, and should probably
4604 // tell the users to run updateCollations.php --force
4605 // in order to re-sort existing category relations.
4606 Hooks::run( 'GetDefaultSortkey', array( $this, &$unprefixed ) );
4607 if ( $prefix !== '' ) {
4608 # Separate with a line feed, so the unprefixed part is only used as
4609 # a tiebreaker when two pages have the exact same prefix.
4610 # In UCA, tab is the only character that can sort above LF
4611 # so we strip both of them from the original prefix.
4612 $prefix = strtr( $prefix, "\n\t", ' ' );
4613 return "$prefix\n$unprefixed";
4614 }
4615 return $unprefixed;
4616 }
4617
4618 /**
4619 * Get the language in which the content of this page is written in
4620 * wikitext. Defaults to $wgContLang, but in certain cases it can be
4621 * e.g. $wgLang (such as special pages, which are in the user language).
4622 *
4623 * @since 1.18
4624 * @return Language
4625 */
4626 public function getPageLanguage() {
4627 global $wgLang, $wgLanguageCode;
4628 if ( $this->isSpecialPage() ) {
4629 // special pages are in the user language
4630 return $wgLang;
4631 }
4632
4633 // Checking if DB language is set
4634 if ( $this->mDbPageLanguage ) {
4635 return wfGetLangObj( $this->mDbPageLanguage );
4636 }
4637
4638 if ( !$this->mPageLanguage || $this->mPageLanguage[1] !== $wgLanguageCode ) {
4639 // Note that this may depend on user settings, so the cache should
4640 // be only per-request.
4641 // NOTE: ContentHandler::getPageLanguage() may need to load the
4642 // content to determine the page language!
4643 // Checking $wgLanguageCode hasn't changed for the benefit of unit
4644 // tests.
4645 $contentHandler = ContentHandler::getForTitle( $this );
4646 $langObj = $contentHandler->getPageLanguage( $this );
4647 $this->mPageLanguage = array( $langObj->getCode(), $wgLanguageCode );
4648 } else {
4649 $langObj = wfGetLangObj( $this->mPageLanguage[0] );
4650 }
4651
4652 return $langObj;
4653 }
4654
4655 /**
4656 * Get the language in which the content of this page is written when
4657 * viewed by user. Defaults to $wgContLang, but in certain cases it can be
4658 * e.g. $wgLang (such as special pages, which are in the user language).
4659 *
4660 * @since 1.20
4661 * @return Language
4662 */
4663 public function getPageViewLanguage() {
4664 global $wgLang;
4665
4666 if ( $this->isSpecialPage() ) {
4667 // If the user chooses a variant, the content is actually
4668 // in a language whose code is the variant code.
4669 $variant = $wgLang->getPreferredVariant();
4670 if ( $wgLang->getCode() !== $variant ) {
4671 return Language::factory( $variant );
4672 }
4673
4674 return $wgLang;
4675 }
4676
4677 // @note Can't be cached persistently, depends on user settings.
4678 // @note ContentHandler::getPageViewLanguage() may need to load the
4679 // content to determine the page language!
4680 $contentHandler = ContentHandler::getForTitle( $this );
4681 $pageLang = $contentHandler->getPageViewLanguage( $this );
4682 return $pageLang;
4683 }
4684
4685 /**
4686 * Get a list of rendered edit notices for this page.
4687 *
4688 * Array is keyed by the original message key, and values are rendered using parseAsBlock, so
4689 * they will already be wrapped in paragraphs.
4690 *
4691 * @since 1.21
4692 * @param int $oldid Revision ID that's being edited
4693 * @return array
4694 */
4695 public function getEditNotices( $oldid = 0 ) {
4696 $notices = array();
4697
4698 // Optional notice for the entire namespace
4699 $editnotice_ns = 'editnotice-' . $this->getNamespace();
4700 $msg = wfMessage( $editnotice_ns );
4701 if ( $msg->exists() ) {
4702 $html = $msg->parseAsBlock();
4703 // Edit notices may have complex logic, but output nothing (T91715)
4704 if ( trim( $html ) !== '' ) {
4705 $notices[$editnotice_ns] = Html::rawElement(
4706 'div',
4707 array( 'class' => array(
4708 'mw-editnotice',
4709 'mw-editnotice-namespace',
4710 Sanitizer::escapeClass( "mw-$editnotice_ns" )
4711 ) ),
4712 $html
4713 );
4714 }
4715 }
4716
4717 if ( MWNamespace::hasSubpages( $this->getNamespace() ) ) {
4718 // Optional notice for page itself and any parent page
4719 $parts = explode( '/', $this->getDBkey() );
4720 $editnotice_base = $editnotice_ns;
4721 while ( count( $parts ) > 0 ) {
4722 $editnotice_base .= '-' . array_shift( $parts );
4723 $msg = wfMessage( $editnotice_base );
4724 if ( $msg->exists() ) {
4725 $html = $msg->parseAsBlock();
4726 if ( trim( $html ) !== '' ) {
4727 $notices[$editnotice_base] = Html::rawElement(
4728 'div',
4729 array( 'class' => array(
4730 'mw-editnotice',
4731 'mw-editnotice-base',
4732 Sanitizer::escapeClass( "mw-$editnotice_base" )
4733 ) ),
4734 $html
4735 );
4736 }
4737 }
4738 }
4739 } else {
4740 // Even if there are no subpages in namespace, we still don't want "/" in MediaWiki message keys
4741 $editnoticeText = $editnotice_ns . '-' . strtr( $this->getDBkey(), '/', '-' );
4742 $msg = wfMessage( $editnoticeText );
4743 if ( $msg->exists() ) {
4744 $html = $msg->parseAsBlock();
4745 if ( trim( $html ) !== '' ) {
4746 $notices[$editnoticeText] = Html::rawElement(
4747 'div',
4748 array( 'class' => array(
4749 'mw-editnotice',
4750 'mw-editnotice-page',
4751 Sanitizer::escapeClass( "mw-$editnoticeText" )
4752 ) ),
4753 $html
4754 );
4755 }
4756 }
4757 }
4758
4759 Hooks::run( 'TitleGetEditNotices', array( $this, $oldid, &$notices ) );
4760 return $notices;
4761 }
4762
4763 /**
4764 * @return array
4765 */
4766 public function __sleep() {
4767 return array(
4768 'mNamespace',
4769 'mDbkeyform',
4770 'mFragment',
4771 'mInterwiki',
4772 'mLocalInterwiki',
4773 'mUserCaseDBKey',
4774 'mDefaultNamespace',
4775 );
4776 }
4777
4778 public function __wakeup() {
4779 $this->mArticleID = ( $this->mNamespace >= 0 ) ? -1 : 0;
4780 $this->mUrlform = wfUrlencode( $this->mDbkeyform );
4781 $this->mTextform = strtr( $this->mDbkeyform, '_', ' ' );
4782 }
4783
4784 }