Merge "TOC: Use padding instead of inline-block for space"
[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 MediaWikiTitleCodec
165 */
166 private static function getMediaWikiTitleCodec() {
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 getMediaWikiTitleCodec() returns a MediaWikiTitleCodec,
204 // which implements TitleFormatter.
205 return self::getMediaWikiTitleCodec();
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 * @todo FIXME: Rename to isSiteConfigPage() and remove deprecated hook
1265 */
1266 public function isCssOrJsPage() {
1267 $isCssOrJsPage = NS_MEDIAWIKI == $this->mNamespace
1268 && ( $this->hasContentModel( CONTENT_MODEL_CSS )
1269 || $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT ) );
1270
1271 # @note This hook is also called in ContentHandler::getDefaultModel.
1272 # It's called here again to make sure hook functions can force this
1273 # method to return true even outside the MediaWiki namespace.
1274
1275 Hooks::run( 'TitleIsCssOrJsPage', array( $this, &$isCssOrJsPage ), '1.25' );
1276
1277 return $isCssOrJsPage;
1278 }
1279
1280 /**
1281 * Is this a .css or .js subpage of a user page?
1282 * @return bool
1283 * @todo FIXME: Rename to isUserConfigPage()
1284 */
1285 public function isCssJsSubpage() {
1286 return ( NS_USER == $this->mNamespace && $this->isSubpage()
1287 && ( $this->hasContentModel( CONTENT_MODEL_CSS )
1288 || $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT ) ) );
1289 }
1290
1291 /**
1292 * Trim down a .css or .js subpage title to get the corresponding skin name
1293 *
1294 * @return string Containing skin name from .css or .js subpage title
1295 */
1296 public function getSkinFromCssJsSubpage() {
1297 $subpage = explode( '/', $this->mTextform );
1298 $subpage = $subpage[count( $subpage ) - 1];
1299 $lastdot = strrpos( $subpage, '.' );
1300 if ( $lastdot === false ) {
1301 return $subpage; # Never happens: only called for names ending in '.css' or '.js'
1302 }
1303 return substr( $subpage, 0, $lastdot );
1304 }
1305
1306 /**
1307 * Is this a .css subpage of a user page?
1308 *
1309 * @return bool
1310 */
1311 public function isCssSubpage() {
1312 return ( NS_USER == $this->mNamespace && $this->isSubpage()
1313 && $this->hasContentModel( CONTENT_MODEL_CSS ) );
1314 }
1315
1316 /**
1317 * Is this a .js subpage of a user page?
1318 *
1319 * @return bool
1320 */
1321 public function isJsSubpage() {
1322 return ( NS_USER == $this->mNamespace && $this->isSubpage()
1323 && $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT ) );
1324 }
1325
1326 /**
1327 * Is this a talk page of some sort?
1328 *
1329 * @return bool
1330 */
1331 public function isTalkPage() {
1332 return MWNamespace::isTalk( $this->getNamespace() );
1333 }
1334
1335 /**
1336 * Get a Title object associated with the talk page of this article
1337 *
1338 * @return Title The object for the talk page
1339 */
1340 public function getTalkPage() {
1341 return Title::makeTitle( MWNamespace::getTalk( $this->getNamespace() ), $this->getDBkey() );
1342 }
1343
1344 /**
1345 * Get a title object associated with the subject page of this
1346 * talk page
1347 *
1348 * @return Title The object for the subject page
1349 */
1350 public function getSubjectPage() {
1351 // Is this the same title?
1352 $subjectNS = MWNamespace::getSubject( $this->getNamespace() );
1353 if ( $this->getNamespace() == $subjectNS ) {
1354 return $this;
1355 }
1356 return Title::makeTitle( $subjectNS, $this->getDBkey() );
1357 }
1358
1359 /**
1360 * Get the other title for this page, if this is a subject page
1361 * get the talk page, if it is a subject page get the talk page
1362 *
1363 * @since 1.25
1364 * @throws MWException
1365 * @return Title
1366 */
1367 public function getOtherPage() {
1368 if ( $this->isSpecialPage() ) {
1369 throw new MWException( 'Special pages cannot have other pages' );
1370 }
1371 if ( $this->isTalkPage() ) {
1372 return $this->getSubjectPage();
1373 } else {
1374 return $this->getTalkPage();
1375 }
1376 }
1377
1378 /**
1379 * Get the default namespace index, for when there is no namespace
1380 *
1381 * @return int Default namespace index
1382 */
1383 public function getDefaultNamespace() {
1384 return $this->mDefaultNamespace;
1385 }
1386
1387 /**
1388 * Get the Title fragment (i.e.\ the bit after the #) in text form
1389 *
1390 * Use Title::hasFragment to check for a fragment
1391 *
1392 * @return string Title fragment
1393 */
1394 public function getFragment() {
1395 return $this->mFragment;
1396 }
1397
1398 /**
1399 * Check if a Title fragment is set
1400 *
1401 * @return bool
1402 * @since 1.23
1403 */
1404 public function hasFragment() {
1405 return $this->mFragment !== '';
1406 }
1407
1408 /**
1409 * Get the fragment in URL form, including the "#" character if there is one
1410 * @return string Fragment in URL form
1411 */
1412 public function getFragmentForURL() {
1413 if ( !$this->hasFragment() ) {
1414 return '';
1415 } else {
1416 return '#' . Title::escapeFragmentForURL( $this->getFragment() );
1417 }
1418 }
1419
1420 /**
1421 * Set the fragment for this title. Removes the first character from the
1422 * specified fragment before setting, so it assumes you're passing it with
1423 * an initial "#".
1424 *
1425 * Deprecated for public use, use Title::makeTitle() with fragment parameter.
1426 * Still in active use privately.
1427 *
1428 * @private
1429 * @param string $fragment Text
1430 */
1431 public function setFragment( $fragment ) {
1432 $this->mFragment = strtr( substr( $fragment, 1 ), '_', ' ' );
1433 }
1434
1435 /**
1436 * Prefix some arbitrary text with the namespace or interwiki prefix
1437 * of this object
1438 *
1439 * @param string $name The text
1440 * @return string The prefixed text
1441 */
1442 private function prefix( $name ) {
1443 $p = '';
1444 if ( $this->isExternal() ) {
1445 $p = $this->mInterwiki . ':';
1446 }
1447
1448 if ( 0 != $this->mNamespace ) {
1449 $p .= $this->getNsText() . ':';
1450 }
1451 return $p . $name;
1452 }
1453
1454 /**
1455 * Get the prefixed database key form
1456 *
1457 * @return string The prefixed title, with underscores and
1458 * any interwiki and namespace prefixes
1459 */
1460 public function getPrefixedDBkey() {
1461 $s = $this->prefix( $this->mDbkeyform );
1462 $s = strtr( $s, ' ', '_' );
1463 return $s;
1464 }
1465
1466 /**
1467 * Get the prefixed title with spaces.
1468 * This is the form usually used for display
1469 *
1470 * @return string The prefixed title, with spaces
1471 */
1472 public function getPrefixedText() {
1473 if ( $this->mPrefixedText === null ) {
1474 $s = $this->prefix( $this->mTextform );
1475 $s = strtr( $s, '_', ' ' );
1476 $this->mPrefixedText = $s;
1477 }
1478 return $this->mPrefixedText;
1479 }
1480
1481 /**
1482 * Return a string representation of this title
1483 *
1484 * @return string Representation of this title
1485 */
1486 public function __toString() {
1487 return $this->getPrefixedText();
1488 }
1489
1490 /**
1491 * Get the prefixed title with spaces, plus any fragment
1492 * (part beginning with '#')
1493 *
1494 * @return string The prefixed title, with spaces and the fragment, including '#'
1495 */
1496 public function getFullText() {
1497 $text = $this->getPrefixedText();
1498 if ( $this->hasFragment() ) {
1499 $text .= '#' . $this->getFragment();
1500 }
1501 return $text;
1502 }
1503
1504 /**
1505 * Get the root page name text without a namespace, i.e. the leftmost part before any slashes
1506 *
1507 * @par Example:
1508 * @code
1509 * Title::newFromText('User:Foo/Bar/Baz')->getRootText();
1510 * # returns: 'Foo'
1511 * @endcode
1512 *
1513 * @return string Root name
1514 * @since 1.20
1515 */
1516 public function getRootText() {
1517 if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
1518 return $this->getText();
1519 }
1520
1521 return strtok( $this->getText(), '/' );
1522 }
1523
1524 /**
1525 * Get the root page name title, i.e. the leftmost part before any slashes
1526 *
1527 * @par Example:
1528 * @code
1529 * Title::newFromText('User:Foo/Bar/Baz')->getRootTitle();
1530 * # returns: Title{User:Foo}
1531 * @endcode
1532 *
1533 * @return Title Root title
1534 * @since 1.20
1535 */
1536 public function getRootTitle() {
1537 return Title::makeTitle( $this->getNamespace(), $this->getRootText() );
1538 }
1539
1540 /**
1541 * Get the base page name without a namespace, i.e. the part before the subpage name
1542 *
1543 * @par Example:
1544 * @code
1545 * Title::newFromText('User:Foo/Bar/Baz')->getBaseText();
1546 * # returns: 'Foo/Bar'
1547 * @endcode
1548 *
1549 * @return string Base name
1550 */
1551 public function getBaseText() {
1552 if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
1553 return $this->getText();
1554 }
1555
1556 $parts = explode( '/', $this->getText() );
1557 # Don't discard the real title if there's no subpage involved
1558 if ( count( $parts ) > 1 ) {
1559 unset( $parts[count( $parts ) - 1] );
1560 }
1561 return implode( '/', $parts );
1562 }
1563
1564 /**
1565 * Get the base page name title, i.e. the part before the subpage name
1566 *
1567 * @par Example:
1568 * @code
1569 * Title::newFromText('User:Foo/Bar/Baz')->getBaseTitle();
1570 * # returns: Title{User:Foo/Bar}
1571 * @endcode
1572 *
1573 * @return Title Base title
1574 * @since 1.20
1575 */
1576 public function getBaseTitle() {
1577 return Title::makeTitle( $this->getNamespace(), $this->getBaseText() );
1578 }
1579
1580 /**
1581 * Get the lowest-level subpage name, i.e. the rightmost part after any slashes
1582 *
1583 * @par Example:
1584 * @code
1585 * Title::newFromText('User:Foo/Bar/Baz')->getSubpageText();
1586 * # returns: "Baz"
1587 * @endcode
1588 *
1589 * @return string Subpage name
1590 */
1591 public function getSubpageText() {
1592 if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
1593 return $this->mTextform;
1594 }
1595 $parts = explode( '/', $this->mTextform );
1596 return $parts[count( $parts ) - 1];
1597 }
1598
1599 /**
1600 * Get the title for a subpage of the current page
1601 *
1602 * @par Example:
1603 * @code
1604 * Title::newFromText('User:Foo/Bar/Baz')->getSubpage("Asdf");
1605 * # returns: Title{User:Foo/Bar/Baz/Asdf}
1606 * @endcode
1607 *
1608 * @param string $text The subpage name to add to the title
1609 * @return Title Subpage title
1610 * @since 1.20
1611 */
1612 public function getSubpage( $text ) {
1613 return Title::makeTitleSafe( $this->getNamespace(), $this->getText() . '/' . $text );
1614 }
1615
1616 /**
1617 * Get a URL-encoded form of the subpage text
1618 *
1619 * @return string URL-encoded subpage name
1620 */
1621 public function getSubpageUrlForm() {
1622 $text = $this->getSubpageText();
1623 $text = wfUrlencode( strtr( $text, ' ', '_' ) );
1624 return $text;
1625 }
1626
1627 /**
1628 * Get a URL-encoded title (not an actual URL) including interwiki
1629 *
1630 * @return string The URL-encoded form
1631 */
1632 public function getPrefixedURL() {
1633 $s = $this->prefix( $this->mDbkeyform );
1634 $s = wfUrlencode( strtr( $s, ' ', '_' ) );
1635 return $s;
1636 }
1637
1638 /**
1639 * Helper to fix up the get{Canonical,Full,Link,Local,Internal}URL args
1640 * get{Canonical,Full,Link,Local,Internal}URL methods accepted an optional
1641 * second argument named variant. This was deprecated in favor
1642 * of passing an array of option with a "variant" key
1643 * Once $query2 is removed for good, this helper can be dropped
1644 * and the wfArrayToCgi moved to getLocalURL();
1645 *
1646 * @since 1.19 (r105919)
1647 * @param array|string $query
1648 * @param bool $query2
1649 * @return string
1650 */
1651 private static function fixUrlQueryArgs( $query, $query2 = false ) {
1652 if ( $query2 !== false ) {
1653 wfDeprecated( "Title::get{Canonical,Full,Link,Local,Internal}URL " .
1654 "method called with a second parameter is deprecated. Add your " .
1655 "parameter to an array passed as the first parameter.", "1.19" );
1656 }
1657 if ( is_array( $query ) ) {
1658 $query = wfArrayToCgi( $query );
1659 }
1660 if ( $query2 ) {
1661 if ( is_string( $query2 ) ) {
1662 // $query2 is a string, we will consider this to be
1663 // a deprecated $variant argument and add it to the query
1664 $query2 = wfArrayToCgi( array( 'variant' => $query2 ) );
1665 } else {
1666 $query2 = wfArrayToCgi( $query2 );
1667 }
1668 // If we have $query content add a & to it first
1669 if ( $query ) {
1670 $query .= '&';
1671 }
1672 // Now append the queries together
1673 $query .= $query2;
1674 }
1675 return $query;
1676 }
1677
1678 /**
1679 * Get a real URL referring to this title, with interwiki link and
1680 * fragment
1681 *
1682 * @see self::getLocalURL for the arguments.
1683 * @see wfExpandUrl
1684 * @param array|string $query
1685 * @param bool $query2
1686 * @param string $proto Protocol type to use in URL
1687 * @return string The URL
1688 */
1689 public function getFullURL( $query = '', $query2 = false, $proto = PROTO_RELATIVE ) {
1690 $query = self::fixUrlQueryArgs( $query, $query2 );
1691
1692 # Hand off all the decisions on urls to getLocalURL
1693 $url = $this->getLocalURL( $query );
1694
1695 # Expand the url to make it a full url. Note that getLocalURL has the
1696 # potential to output full urls for a variety of reasons, so we use
1697 # wfExpandUrl instead of simply prepending $wgServer
1698 $url = wfExpandUrl( $url, $proto );
1699
1700 # Finally, add the fragment.
1701 $url .= $this->getFragmentForURL();
1702
1703 Hooks::run( 'GetFullURL', array( &$this, &$url, $query ) );
1704 return $url;
1705 }
1706
1707 /**
1708 * Get a URL with no fragment or server name (relative URL) from a Title object.
1709 * If this page is generated with action=render, however,
1710 * $wgServer is prepended to make an absolute URL.
1711 *
1712 * @see self::getFullURL to always get an absolute URL.
1713 * @see self::getLinkURL to always get a URL that's the simplest URL that will be
1714 * valid to link, locally, to the current Title.
1715 * @see self::newFromText to produce a Title object.
1716 *
1717 * @param string|array $query An optional query string,
1718 * not used for interwiki links. Can be specified as an associative array as well,
1719 * e.g., array( 'action' => 'edit' ) (keys and values will be URL-escaped).
1720 * Some query patterns will trigger various shorturl path replacements.
1721 * @param array $query2 An optional secondary query array. This one MUST
1722 * be an array. If a string is passed it will be interpreted as a deprecated
1723 * variant argument and urlencoded into a variant= argument.
1724 * This second query argument will be added to the $query
1725 * The second parameter is deprecated since 1.19. Pass it as a key,value
1726 * pair in the first parameter array instead.
1727 *
1728 * @return string String of the URL.
1729 */
1730 public function getLocalURL( $query = '', $query2 = false ) {
1731 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
1732
1733 $query = self::fixUrlQueryArgs( $query, $query2 );
1734
1735 $interwiki = Interwiki::fetch( $this->mInterwiki );
1736 if ( $interwiki ) {
1737 $namespace = $this->getNsText();
1738 if ( $namespace != '' ) {
1739 # Can this actually happen? Interwikis shouldn't be parsed.
1740 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
1741 $namespace .= ':';
1742 }
1743 $url = $interwiki->getURL( $namespace . $this->getDBkey() );
1744 $url = wfAppendQuery( $url, $query );
1745 } else {
1746 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
1747 if ( $query == '' ) {
1748 $url = str_replace( '$1', $dbkey, $wgArticlePath );
1749 Hooks::run( 'GetLocalURL::Article', array( &$this, &$url ) );
1750 } else {
1751 global $wgVariantArticlePath, $wgActionPaths, $wgContLang;
1752 $url = false;
1753 $matches = array();
1754
1755 if ( !empty( $wgActionPaths )
1756 && preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches )
1757 ) {
1758 $action = urldecode( $matches[2] );
1759 if ( isset( $wgActionPaths[$action] ) ) {
1760 $query = $matches[1];
1761 if ( isset( $matches[4] ) ) {
1762 $query .= $matches[4];
1763 }
1764 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
1765 if ( $query != '' ) {
1766 $url = wfAppendQuery( $url, $query );
1767 }
1768 }
1769 }
1770
1771 if ( $url === false
1772 && $wgVariantArticlePath
1773 && $wgContLang->getCode() === $this->getPageLanguage()->getCode()
1774 && $this->getPageLanguage()->hasVariants()
1775 && preg_match( '/^variant=([^&]*)$/', $query, $matches )
1776 ) {
1777 $variant = urldecode( $matches[1] );
1778 if ( $this->getPageLanguage()->hasVariant( $variant ) ) {
1779 // Only do the variant replacement if the given variant is a valid
1780 // variant for the page's language.
1781 $url = str_replace( '$2', urlencode( $variant ), $wgVariantArticlePath );
1782 $url = str_replace( '$1', $dbkey, $url );
1783 }
1784 }
1785
1786 if ( $url === false ) {
1787 if ( $query == '-' ) {
1788 $query = '';
1789 }
1790 $url = "{$wgScript}?title={$dbkey}&{$query}";
1791 }
1792 }
1793
1794 Hooks::run( 'GetLocalURL::Internal', array( &$this, &$url, $query ) );
1795
1796 // @todo FIXME: This causes breakage in various places when we
1797 // actually expected a local URL and end up with dupe prefixes.
1798 if ( $wgRequest->getVal( 'action' ) == 'render' ) {
1799 $url = $wgServer . $url;
1800 }
1801 }
1802 Hooks::run( 'GetLocalURL', array( &$this, &$url, $query ) );
1803 return $url;
1804 }
1805
1806 /**
1807 * Get a URL that's the simplest URL that will be valid to link, locally,
1808 * to the current Title. It includes the fragment, but does not include
1809 * the server unless action=render is used (or the link is external). If
1810 * there's a fragment but the prefixed text is empty, we just return a link
1811 * to the fragment.
1812 *
1813 * The result obviously should not be URL-escaped, but does need to be
1814 * HTML-escaped if it's being output in HTML.
1815 *
1816 * @param array $query
1817 * @param bool $query2
1818 * @param string $proto Protocol to use; setting this will cause a full URL to be used
1819 * @see self::getLocalURL for the arguments.
1820 * @return string The URL
1821 */
1822 public function getLinkURL( $query = '', $query2 = false, $proto = PROTO_RELATIVE ) {
1823 if ( $this->isExternal() || $proto !== PROTO_RELATIVE ) {
1824 $ret = $this->getFullURL( $query, $query2, $proto );
1825 } elseif ( $this->getPrefixedText() === '' && $this->hasFragment() ) {
1826 $ret = $this->getFragmentForURL();
1827 } else {
1828 $ret = $this->getLocalURL( $query, $query2 ) . $this->getFragmentForURL();
1829 }
1830 return $ret;
1831 }
1832
1833 /**
1834 * Get the URL form for an internal link.
1835 * - Used in various CDN-related code, in case we have a different
1836 * internal hostname for the server from the exposed one.
1837 *
1838 * This uses $wgInternalServer to qualify the path, or $wgServer
1839 * if $wgInternalServer is not set. If the server variable used is
1840 * protocol-relative, the URL will be expanded to http://
1841 *
1842 * @see self::getLocalURL for the arguments.
1843 * @return string The URL
1844 */
1845 public function getInternalURL( $query = '', $query2 = false ) {
1846 global $wgInternalServer, $wgServer;
1847 $query = self::fixUrlQueryArgs( $query, $query2 );
1848 $server = $wgInternalServer !== false ? $wgInternalServer : $wgServer;
1849 $url = wfExpandUrl( $server . $this->getLocalURL( $query ), PROTO_HTTP );
1850 Hooks::run( 'GetInternalURL', array( &$this, &$url, $query ) );
1851 return $url;
1852 }
1853
1854 /**
1855 * Get the URL for a canonical link, for use in things like IRC and
1856 * e-mail notifications. Uses $wgCanonicalServer and the
1857 * GetCanonicalURL hook.
1858 *
1859 * NOTE: Unlike getInternalURL(), the canonical URL includes the fragment
1860 *
1861 * @see self::getLocalURL for the arguments.
1862 * @return string The URL
1863 * @since 1.18
1864 */
1865 public function getCanonicalURL( $query = '', $query2 = false ) {
1866 $query = self::fixUrlQueryArgs( $query, $query2 );
1867 $url = wfExpandUrl( $this->getLocalURL( $query ) . $this->getFragmentForURL(), PROTO_CANONICAL );
1868 Hooks::run( 'GetCanonicalURL', array( &$this, &$url, $query ) );
1869 return $url;
1870 }
1871
1872 /**
1873 * Get the edit URL for this Title
1874 *
1875 * @return string The URL, or a null string if this is an interwiki link
1876 */
1877 public function getEditURL() {
1878 if ( $this->isExternal() ) {
1879 return '';
1880 }
1881 $s = $this->getLocalURL( 'action=edit' );
1882
1883 return $s;
1884 }
1885
1886 /**
1887 * Can $user perform $action on this page?
1888 * This skips potentially expensive cascading permission checks
1889 * as well as avoids expensive error formatting
1890 *
1891 * Suitable for use for nonessential UI controls in common cases, but
1892 * _not_ for functional access control.
1893 *
1894 * May provide false positives, but should never provide a false negative.
1895 *
1896 * @param string $action Action that permission needs to be checked for
1897 * @param User $user User to check (since 1.19); $wgUser will be used if not provided.
1898 * @return bool
1899 */
1900 public function quickUserCan( $action, $user = null ) {
1901 return $this->userCan( $action, $user, false );
1902 }
1903
1904 /**
1905 * Can $user perform $action on this page?
1906 *
1907 * @param string $action Action that permission needs to be checked for
1908 * @param User $user User to check (since 1.19); $wgUser will be used if not
1909 * provided.
1910 * @param string $rigor Same format as Title::getUserPermissionsErrors()
1911 * @return bool
1912 */
1913 public function userCan( $action, $user = null, $rigor = 'secure' ) {
1914 if ( !$user instanceof User ) {
1915 global $wgUser;
1916 $user = $wgUser;
1917 }
1918
1919 return !count( $this->getUserPermissionsErrorsInternal( $action, $user, $rigor, true ) );
1920 }
1921
1922 /**
1923 * Can $user perform $action on this page?
1924 *
1925 * @todo FIXME: This *does not* check throttles (User::pingLimiter()).
1926 *
1927 * @param string $action Action that permission needs to be checked for
1928 * @param User $user User to check
1929 * @param string $rigor One of (quick,full,secure)
1930 * - quick : does cheap permission checks from slaves (usable for GUI creation)
1931 * - full : does cheap and expensive checks possibly from a slave
1932 * - secure : does cheap and expensive checks, using the master as needed
1933 * @param array $ignoreErrors Array of Strings Set this to a list of message keys
1934 * whose corresponding errors may be ignored.
1935 * @return array Array of arrays of the arguments to wfMessage to explain permissions problems.
1936 */
1937 public function getUserPermissionsErrors(
1938 $action, $user, $rigor = 'secure', $ignoreErrors = array()
1939 ) {
1940 $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $rigor );
1941
1942 // Remove the errors being ignored.
1943 foreach ( $errors as $index => $error ) {
1944 $errKey = is_array( $error ) ? $error[0] : $error;
1945
1946 if ( in_array( $errKey, $ignoreErrors ) ) {
1947 unset( $errors[$index] );
1948 }
1949 if ( $errKey instanceof MessageSpecifier && in_array( $errKey->getKey(), $ignoreErrors ) ) {
1950 unset( $errors[$index] );
1951 }
1952 }
1953
1954 return $errors;
1955 }
1956
1957 /**
1958 * Permissions checks that fail most often, and which are easiest to test.
1959 *
1960 * @param string $action The action to check
1961 * @param User $user User to check
1962 * @param array $errors List of current errors
1963 * @param string $rigor Same format as Title::getUserPermissionsErrors()
1964 * @param bool $short Short circuit on first error
1965 *
1966 * @return array List of errors
1967 */
1968 private function checkQuickPermissions( $action, $user, $errors, $rigor, $short ) {
1969 if ( !Hooks::run( 'TitleQuickPermissions',
1970 array( $this, $user, $action, &$errors, ( $rigor !== 'quick' ), $short ) )
1971 ) {
1972 return $errors;
1973 }
1974
1975 if ( $action == 'create' ) {
1976 if (
1977 ( $this->isTalkPage() && !$user->isAllowed( 'createtalk' ) ) ||
1978 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage' ) )
1979 ) {
1980 $errors[] = $user->isAnon() ? array( 'nocreatetext' ) : array( 'nocreate-loggedin' );
1981 }
1982 } elseif ( $action == 'move' ) {
1983 if ( !$user->isAllowed( 'move-rootuserpages' )
1984 && $this->mNamespace == NS_USER && !$this->isSubpage() ) {
1985 // Show user page-specific message only if the user can move other pages
1986 $errors[] = array( 'cant-move-user-page' );
1987 }
1988
1989 // Check if user is allowed to move files if it's a file
1990 if ( $this->mNamespace == NS_FILE && !$user->isAllowed( 'movefile' ) ) {
1991 $errors[] = array( 'movenotallowedfile' );
1992 }
1993
1994 // Check if user is allowed to move category pages if it's a category page
1995 if ( $this->mNamespace == NS_CATEGORY && !$user->isAllowed( 'move-categorypages' ) ) {
1996 $errors[] = array( 'cant-move-category-page' );
1997 }
1998
1999 if ( !$user->isAllowed( 'move' ) ) {
2000 // User can't move anything
2001 $userCanMove = User::groupHasPermission( 'user', 'move' );
2002 $autoconfirmedCanMove = User::groupHasPermission( 'autoconfirmed', 'move' );
2003 if ( $user->isAnon() && ( $userCanMove || $autoconfirmedCanMove ) ) {
2004 // custom message if logged-in users without any special rights can move
2005 $errors[] = array( 'movenologintext' );
2006 } else {
2007 $errors[] = array( 'movenotallowed' );
2008 }
2009 }
2010 } elseif ( $action == 'move-target' ) {
2011 if ( !$user->isAllowed( 'move' ) ) {
2012 // User can't move anything
2013 $errors[] = array( 'movenotallowed' );
2014 } elseif ( !$user->isAllowed( 'move-rootuserpages' )
2015 && $this->mNamespace == NS_USER && !$this->isSubpage() ) {
2016 // Show user page-specific message only if the user can move other pages
2017 $errors[] = array( 'cant-move-to-user-page' );
2018 } elseif ( !$user->isAllowed( 'move-categorypages' )
2019 && $this->mNamespace == NS_CATEGORY ) {
2020 // Show category page-specific message only if the user can move other pages
2021 $errors[] = array( 'cant-move-to-category-page' );
2022 }
2023 } elseif ( !$user->isAllowed( $action ) ) {
2024 $errors[] = $this->missingPermissionError( $action, $short );
2025 }
2026
2027 return $errors;
2028 }
2029
2030 /**
2031 * Add the resulting error code to the errors array
2032 *
2033 * @param array $errors List of current errors
2034 * @param array $result Result of errors
2035 *
2036 * @return array List of errors
2037 */
2038 private function resultToError( $errors, $result ) {
2039 if ( is_array( $result ) && count( $result ) && !is_array( $result[0] ) ) {
2040 // A single array representing an error
2041 $errors[] = $result;
2042 } elseif ( is_array( $result ) && is_array( $result[0] ) ) {
2043 // A nested array representing multiple errors
2044 $errors = array_merge( $errors, $result );
2045 } elseif ( $result !== '' && is_string( $result ) ) {
2046 // A string representing a message-id
2047 $errors[] = array( $result );
2048 } elseif ( $result instanceof MessageSpecifier ) {
2049 // A message specifier representing an error
2050 $errors[] = array( $result );
2051 } elseif ( $result === false ) {
2052 // a generic "We don't want them to do that"
2053 $errors[] = array( 'badaccess-group0' );
2054 }
2055 return $errors;
2056 }
2057
2058 /**
2059 * Check various permission hooks
2060 *
2061 * @param string $action The action to check
2062 * @param User $user User to check
2063 * @param array $errors List of current errors
2064 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2065 * @param bool $short Short circuit on first error
2066 *
2067 * @return array List of errors
2068 */
2069 private function checkPermissionHooks( $action, $user, $errors, $rigor, $short ) {
2070 // Use getUserPermissionsErrors instead
2071 $result = '';
2072 if ( !Hooks::run( 'userCan', array( &$this, &$user, $action, &$result ) ) ) {
2073 return $result ? array() : array( array( 'badaccess-group0' ) );
2074 }
2075 // Check getUserPermissionsErrors hook
2076 if ( !Hooks::run( 'getUserPermissionsErrors', array( &$this, &$user, $action, &$result ) ) ) {
2077 $errors = $this->resultToError( $errors, $result );
2078 }
2079 // Check getUserPermissionsErrorsExpensive hook
2080 if (
2081 $rigor !== 'quick'
2082 && !( $short && count( $errors ) > 0 )
2083 && !Hooks::run( 'getUserPermissionsErrorsExpensive', array( &$this, &$user, $action, &$result ) )
2084 ) {
2085 $errors = $this->resultToError( $errors, $result );
2086 }
2087
2088 return $errors;
2089 }
2090
2091 /**
2092 * Check permissions on special pages & namespaces
2093 *
2094 * @param string $action The action to check
2095 * @param User $user User to check
2096 * @param array $errors List of current errors
2097 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2098 * @param bool $short Short circuit on first error
2099 *
2100 * @return array List of errors
2101 */
2102 private function checkSpecialsAndNSPermissions( $action, $user, $errors, $rigor, $short ) {
2103 # Only 'createaccount' can be performed on special pages,
2104 # which don't actually exist in the DB.
2105 if ( NS_SPECIAL == $this->mNamespace && $action !== 'createaccount' ) {
2106 $errors[] = array( 'ns-specialprotected' );
2107 }
2108
2109 # Check $wgNamespaceProtection for restricted namespaces
2110 if ( $this->isNamespaceProtected( $user ) ) {
2111 $ns = $this->mNamespace == NS_MAIN ?
2112 wfMessage( 'nstab-main' )->text() : $this->getNsText();
2113 $errors[] = $this->mNamespace == NS_MEDIAWIKI ?
2114 array( 'protectedinterface', $action ) : array( 'namespaceprotected', $ns, $action );
2115 }
2116
2117 return $errors;
2118 }
2119
2120 /**
2121 * Check CSS/JS sub-page permissions
2122 *
2123 * @param string $action The action to check
2124 * @param User $user User to check
2125 * @param array $errors List of current errors
2126 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2127 * @param bool $short Short circuit on first error
2128 *
2129 * @return array List of errors
2130 */
2131 private function checkCSSandJSPermissions( $action, $user, $errors, $rigor, $short ) {
2132 # Protect css/js subpages of user pages
2133 # XXX: this might be better using restrictions
2134 # XXX: right 'editusercssjs' is deprecated, for backward compatibility only
2135 if ( $action != 'patrol' && !$user->isAllowed( 'editusercssjs' ) ) {
2136 if ( preg_match( '/^' . preg_quote( $user->getName(), '/' ) . '\//', $this->mTextform ) ) {
2137 if ( $this->isCssSubpage() && !$user->isAllowedAny( 'editmyusercss', 'editusercss' ) ) {
2138 $errors[] = array( 'mycustomcssprotected', $action );
2139 } elseif ( $this->isJsSubpage() && !$user->isAllowedAny( 'editmyuserjs', 'edituserjs' ) ) {
2140 $errors[] = array( 'mycustomjsprotected', $action );
2141 }
2142 } else {
2143 if ( $this->isCssSubpage() && !$user->isAllowed( 'editusercss' ) ) {
2144 $errors[] = array( 'customcssprotected', $action );
2145 } elseif ( $this->isJsSubpage() && !$user->isAllowed( 'edituserjs' ) ) {
2146 $errors[] = array( 'customjsprotected', $action );
2147 }
2148 }
2149 }
2150
2151 return $errors;
2152 }
2153
2154 /**
2155 * Check against page_restrictions table requirements on this
2156 * page. The user must possess all required rights for this
2157 * action.
2158 *
2159 * @param string $action The action to check
2160 * @param User $user User to check
2161 * @param array $errors List of current errors
2162 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2163 * @param bool $short Short circuit on first error
2164 *
2165 * @return array List of errors
2166 */
2167 private function checkPageRestrictions( $action, $user, $errors, $rigor, $short ) {
2168 foreach ( $this->getRestrictions( $action ) as $right ) {
2169 // Backwards compatibility, rewrite sysop -> editprotected
2170 if ( $right == 'sysop' ) {
2171 $right = 'editprotected';
2172 }
2173 // Backwards compatibility, rewrite autoconfirmed -> editsemiprotected
2174 if ( $right == 'autoconfirmed' ) {
2175 $right = 'editsemiprotected';
2176 }
2177 if ( $right == '' ) {
2178 continue;
2179 }
2180 if ( !$user->isAllowed( $right ) ) {
2181 $errors[] = array( 'protectedpagetext', $right, $action );
2182 } elseif ( $this->mCascadeRestriction && !$user->isAllowed( 'protect' ) ) {
2183 $errors[] = array( 'protectedpagetext', 'protect', $action );
2184 }
2185 }
2186
2187 return $errors;
2188 }
2189
2190 /**
2191 * Check restrictions on cascading pages.
2192 *
2193 * @param string $action The action to check
2194 * @param User $user User to check
2195 * @param array $errors List of current errors
2196 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2197 * @param bool $short Short circuit on first error
2198 *
2199 * @return array List of errors
2200 */
2201 private function checkCascadingSourcesRestrictions( $action, $user, $errors, $rigor, $short ) {
2202 if ( $rigor !== 'quick' && !$this->isCssJsSubpage() ) {
2203 # We /could/ use the protection level on the source page, but it's
2204 # fairly ugly as we have to establish a precedence hierarchy for pages
2205 # included by multiple cascade-protected pages. So just restrict
2206 # it to people with 'protect' permission, as they could remove the
2207 # protection anyway.
2208 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
2209 # Cascading protection depends on more than this page...
2210 # Several cascading protected pages may include this page...
2211 # Check each cascading level
2212 # This is only for protection restrictions, not for all actions
2213 if ( isset( $restrictions[$action] ) ) {
2214 foreach ( $restrictions[$action] as $right ) {
2215 // Backwards compatibility, rewrite sysop -> editprotected
2216 if ( $right == 'sysop' ) {
2217 $right = 'editprotected';
2218 }
2219 // Backwards compatibility, rewrite autoconfirmed -> editsemiprotected
2220 if ( $right == 'autoconfirmed' ) {
2221 $right = 'editsemiprotected';
2222 }
2223 if ( $right != '' && !$user->isAllowedAll( 'protect', $right ) ) {
2224 $pages = '';
2225 foreach ( $cascadingSources as $page ) {
2226 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
2227 }
2228 $errors[] = array( 'cascadeprotected', count( $cascadingSources ), $pages, $action );
2229 }
2230 }
2231 }
2232 }
2233
2234 return $errors;
2235 }
2236
2237 /**
2238 * Check action permissions not already checked in checkQuickPermissions
2239 *
2240 * @param string $action The action to check
2241 * @param User $user User to check
2242 * @param array $errors List of current errors
2243 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2244 * @param bool $short Short circuit on first error
2245 *
2246 * @return array List of errors
2247 */
2248 private function checkActionPermissions( $action, $user, $errors, $rigor, $short ) {
2249 global $wgDeleteRevisionsLimit, $wgLang;
2250
2251 if ( $action == 'protect' ) {
2252 if ( count( $this->getUserPermissionsErrorsInternal( 'edit', $user, $rigor, true ) ) ) {
2253 // If they can't edit, they shouldn't protect.
2254 $errors[] = array( 'protect-cantedit' );
2255 }
2256 } elseif ( $action == 'create' ) {
2257 $title_protection = $this->getTitleProtection();
2258 if ( $title_protection ) {
2259 if ( $title_protection['permission'] == ''
2260 || !$user->isAllowed( $title_protection['permission'] )
2261 ) {
2262 $errors[] = array(
2263 'titleprotected',
2264 User::whoIs( $title_protection['user'] ),
2265 $title_protection['reason']
2266 );
2267 }
2268 }
2269 } elseif ( $action == 'move' ) {
2270 // Check for immobile pages
2271 if ( !MWNamespace::isMovable( $this->mNamespace ) ) {
2272 // Specific message for this case
2273 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
2274 } elseif ( !$this->isMovable() ) {
2275 // Less specific message for rarer cases
2276 $errors[] = array( 'immobile-source-page' );
2277 }
2278 } elseif ( $action == 'move-target' ) {
2279 if ( !MWNamespace::isMovable( $this->mNamespace ) ) {
2280 $errors[] = array( 'immobile-target-namespace', $this->getNsText() );
2281 } elseif ( !$this->isMovable() ) {
2282 $errors[] = array( 'immobile-target-page' );
2283 }
2284 } elseif ( $action == 'delete' ) {
2285 $tempErrors = $this->checkPageRestrictions( 'edit', $user, array(), $rigor, true );
2286 if ( !$tempErrors ) {
2287 $tempErrors = $this->checkCascadingSourcesRestrictions( 'edit',
2288 $user, $tempErrors, $rigor, true );
2289 }
2290 if ( $tempErrors ) {
2291 // If protection keeps them from editing, they shouldn't be able to delete.
2292 $errors[] = array( 'deleteprotected' );
2293 }
2294 if ( $rigor !== 'quick' && $wgDeleteRevisionsLimit
2295 && !$this->userCan( 'bigdelete', $user ) && $this->isBigDeletion()
2296 ) {
2297 $errors[] = array( 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) );
2298 }
2299 }
2300 return $errors;
2301 }
2302
2303 /**
2304 * Check that the user isn't blocked from editing.
2305 *
2306 * @param string $action The action to check
2307 * @param User $user User to check
2308 * @param array $errors List of current errors
2309 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2310 * @param bool $short Short circuit on first error
2311 *
2312 * @return array List of errors
2313 */
2314 private function checkUserBlock( $action, $user, $errors, $rigor, $short ) {
2315 // Account creation blocks handled at userlogin.
2316 // Unblocking handled in SpecialUnblock
2317 if ( $rigor === 'quick' || in_array( $action, array( 'createaccount', 'unblock' ) ) ) {
2318 return $errors;
2319 }
2320
2321 global $wgEmailConfirmToEdit;
2322
2323 if ( $wgEmailConfirmToEdit && !$user->isEmailConfirmed() ) {
2324 $errors[] = array( 'confirmedittext' );
2325 }
2326
2327 $useSlave = ( $rigor !== 'secure' );
2328 if ( ( $action == 'edit' || $action == 'create' )
2329 && !$user->isBlockedFrom( $this, $useSlave )
2330 ) {
2331 // Don't block the user from editing their own talk page unless they've been
2332 // explicitly blocked from that too.
2333 } elseif ( $user->isBlocked() && $user->getBlock()->prevents( $action ) !== false ) {
2334 // @todo FIXME: Pass the relevant context into this function.
2335 $errors[] = $user->getBlock()->getPermissionsError( RequestContext::getMain() );
2336 }
2337
2338 return $errors;
2339 }
2340
2341 /**
2342 * Check that the user is allowed to read this page.
2343 *
2344 * @param string $action The action to check
2345 * @param User $user User to check
2346 * @param array $errors List of current errors
2347 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2348 * @param bool $short Short circuit on first error
2349 *
2350 * @return array List of errors
2351 */
2352 private function checkReadPermissions( $action, $user, $errors, $rigor, $short ) {
2353 global $wgWhitelistRead, $wgWhitelistReadRegexp;
2354
2355 $whitelisted = false;
2356 if ( User::isEveryoneAllowed( 'read' ) ) {
2357 # Shortcut for public wikis, allows skipping quite a bit of code
2358 $whitelisted = true;
2359 } elseif ( $user->isAllowed( 'read' ) ) {
2360 # If the user is allowed to read pages, he is allowed to read all pages
2361 $whitelisted = true;
2362 } elseif ( $this->isSpecial( 'Userlogin' )
2363 || $this->isSpecial( 'ChangePassword' )
2364 || $this->isSpecial( 'PasswordReset' )
2365 ) {
2366 # Always grant access to the login page.
2367 # Even anons need to be able to log in.
2368 $whitelisted = true;
2369 } elseif ( is_array( $wgWhitelistRead ) && count( $wgWhitelistRead ) ) {
2370 # Time to check the whitelist
2371 # Only do these checks is there's something to check against
2372 $name = $this->getPrefixedText();
2373 $dbName = $this->getPrefixedDBkey();
2374
2375 // Check for explicit whitelisting with and without underscores
2376 if ( in_array( $name, $wgWhitelistRead, true ) || in_array( $dbName, $wgWhitelistRead, true ) ) {
2377 $whitelisted = true;
2378 } elseif ( $this->getNamespace() == NS_MAIN ) {
2379 # Old settings might have the title prefixed with
2380 # a colon for main-namespace pages
2381 if ( in_array( ':' . $name, $wgWhitelistRead ) ) {
2382 $whitelisted = true;
2383 }
2384 } elseif ( $this->isSpecialPage() ) {
2385 # If it's a special page, ditch the subpage bit and check again
2386 $name = $this->getDBkey();
2387 list( $name, /* $subpage */ ) = SpecialPageFactory::resolveAlias( $name );
2388 if ( $name ) {
2389 $pure = SpecialPage::getTitleFor( $name )->getPrefixedText();
2390 if ( in_array( $pure, $wgWhitelistRead, true ) ) {
2391 $whitelisted = true;
2392 }
2393 }
2394 }
2395 }
2396
2397 if ( !$whitelisted && is_array( $wgWhitelistReadRegexp ) && !empty( $wgWhitelistReadRegexp ) ) {
2398 $name = $this->getPrefixedText();
2399 // Check for regex whitelisting
2400 foreach ( $wgWhitelistReadRegexp as $listItem ) {
2401 if ( preg_match( $listItem, $name ) ) {
2402 $whitelisted = true;
2403 break;
2404 }
2405 }
2406 }
2407
2408 if ( !$whitelisted ) {
2409 # If the title is not whitelisted, give extensions a chance to do so...
2410 Hooks::run( 'TitleReadWhitelist', array( $this, $user, &$whitelisted ) );
2411 if ( !$whitelisted ) {
2412 $errors[] = $this->missingPermissionError( $action, $short );
2413 }
2414 }
2415
2416 return $errors;
2417 }
2418
2419 /**
2420 * Get a description array when the user doesn't have the right to perform
2421 * $action (i.e. when User::isAllowed() returns false)
2422 *
2423 * @param string $action The action to check
2424 * @param bool $short Short circuit on first error
2425 * @return array List of errors
2426 */
2427 private function missingPermissionError( $action, $short ) {
2428 // We avoid expensive display logic for quickUserCan's and such
2429 if ( $short ) {
2430 return array( 'badaccess-group0' );
2431 }
2432
2433 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
2434 User::getGroupsWithPermission( $action ) );
2435
2436 if ( count( $groups ) ) {
2437 global $wgLang;
2438 return array(
2439 'badaccess-groups',
2440 $wgLang->commaList( $groups ),
2441 count( $groups )
2442 );
2443 } else {
2444 return array( 'badaccess-group0' );
2445 }
2446 }
2447
2448 /**
2449 * Can $user perform $action on this page? This is an internal function,
2450 * which checks ONLY that previously checked by userCan (i.e. it leaves out
2451 * checks on wfReadOnly() and blocks)
2452 *
2453 * @param string $action Action that permission needs to be checked for
2454 * @param User $user User to check
2455 * @param string $rigor One of (quick,full,secure)
2456 * - quick : does cheap permission checks from slaves (usable for GUI creation)
2457 * - full : does cheap and expensive checks possibly from a slave
2458 * - secure : does cheap and expensive checks, using the master as needed
2459 * @param bool $short Set this to true to stop after the first permission error.
2460 * @return array Array of arrays of the arguments to wfMessage to explain permissions problems.
2461 */
2462 protected function getUserPermissionsErrorsInternal(
2463 $action, $user, $rigor = 'secure', $short = false
2464 ) {
2465 if ( $rigor === true ) {
2466 $rigor = 'secure'; // b/c
2467 } elseif ( $rigor === false ) {
2468 $rigor = 'quick'; // b/c
2469 } elseif ( !in_array( $rigor, array( 'quick', 'full', 'secure' ) ) ) {
2470 throw new Exception( "Invalid rigor parameter '$rigor'." );
2471 }
2472
2473 # Read has special handling
2474 if ( $action == 'read' ) {
2475 $checks = array(
2476 'checkPermissionHooks',
2477 'checkReadPermissions',
2478 );
2479 # Don't call checkSpecialsAndNSPermissions or checkCSSandJSPermissions
2480 # here as it will lead to duplicate error messages. This is okay to do
2481 # since anywhere that checks for create will also check for edit, and
2482 # those checks are called for edit.
2483 } elseif ( $action == 'create' ) {
2484 $checks = array(
2485 'checkQuickPermissions',
2486 'checkPermissionHooks',
2487 'checkPageRestrictions',
2488 'checkCascadingSourcesRestrictions',
2489 'checkActionPermissions',
2490 'checkUserBlock'
2491 );
2492 } else {
2493 $checks = array(
2494 'checkQuickPermissions',
2495 'checkPermissionHooks',
2496 'checkSpecialsAndNSPermissions',
2497 'checkCSSandJSPermissions',
2498 'checkPageRestrictions',
2499 'checkCascadingSourcesRestrictions',
2500 'checkActionPermissions',
2501 'checkUserBlock'
2502 );
2503 }
2504
2505 $errors = array();
2506 while ( count( $checks ) > 0 &&
2507 !( $short && count( $errors ) > 0 ) ) {
2508 $method = array_shift( $checks );
2509 $errors = $this->$method( $action, $user, $errors, $rigor, $short );
2510 }
2511
2512 return $errors;
2513 }
2514
2515 /**
2516 * Get a filtered list of all restriction types supported by this wiki.
2517 * @param bool $exists True to get all restriction types that apply to
2518 * titles that do exist, False for all restriction types that apply to
2519 * titles that do not exist
2520 * @return array
2521 */
2522 public static function getFilteredRestrictionTypes( $exists = true ) {
2523 global $wgRestrictionTypes;
2524 $types = $wgRestrictionTypes;
2525 if ( $exists ) {
2526 # Remove the create restriction for existing titles
2527 $types = array_diff( $types, array( 'create' ) );
2528 } else {
2529 # Only the create and upload restrictions apply to non-existing titles
2530 $types = array_intersect( $types, array( 'create', 'upload' ) );
2531 }
2532 return $types;
2533 }
2534
2535 /**
2536 * Returns restriction types for the current Title
2537 *
2538 * @return array Applicable restriction types
2539 */
2540 public function getRestrictionTypes() {
2541 if ( $this->isSpecialPage() ) {
2542 return array();
2543 }
2544
2545 $types = self::getFilteredRestrictionTypes( $this->exists() );
2546
2547 if ( $this->getNamespace() != NS_FILE ) {
2548 # Remove the upload restriction for non-file titles
2549 $types = array_diff( $types, array( 'upload' ) );
2550 }
2551
2552 Hooks::run( 'TitleGetRestrictionTypes', array( $this, &$types ) );
2553
2554 wfDebug( __METHOD__ . ': applicable restrictions to [[' .
2555 $this->getPrefixedText() . ']] are {' . implode( ',', $types ) . "}\n" );
2556
2557 return $types;
2558 }
2559
2560 /**
2561 * Is this title subject to title protection?
2562 * Title protection is the one applied against creation of such title.
2563 *
2564 * @return array|bool An associative array representing any existent title
2565 * protection, or false if there's none.
2566 */
2567 public function getTitleProtection() {
2568 // Can't protect pages in special namespaces
2569 if ( $this->getNamespace() < 0 ) {
2570 return false;
2571 }
2572
2573 // Can't protect pages that exist.
2574 if ( $this->exists() ) {
2575 return false;
2576 }
2577
2578 if ( $this->mTitleProtection === null ) {
2579 $dbr = wfGetDB( DB_SLAVE );
2580 $res = $dbr->select(
2581 'protected_titles',
2582 array(
2583 'user' => 'pt_user',
2584 'reason' => 'pt_reason',
2585 'expiry' => 'pt_expiry',
2586 'permission' => 'pt_create_perm'
2587 ),
2588 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
2589 __METHOD__
2590 );
2591
2592 // fetchRow returns false if there are no rows.
2593 $row = $dbr->fetchRow( $res );
2594 if ( $row ) {
2595 if ( $row['permission'] == 'sysop' ) {
2596 $row['permission'] = 'editprotected'; // B/C
2597 }
2598 if ( $row['permission'] == 'autoconfirmed' ) {
2599 $row['permission'] = 'editsemiprotected'; // B/C
2600 }
2601 $row['expiry'] = $dbr->decodeExpiry( $row['expiry'] );
2602 }
2603 $this->mTitleProtection = $row;
2604 }
2605 return $this->mTitleProtection;
2606 }
2607
2608 /**
2609 * Remove any title protection due to page existing
2610 */
2611 public function deleteTitleProtection() {
2612 $dbw = wfGetDB( DB_MASTER );
2613
2614 $dbw->delete(
2615 'protected_titles',
2616 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
2617 __METHOD__
2618 );
2619 $this->mTitleProtection = false;
2620 }
2621
2622 /**
2623 * Is this page "semi-protected" - the *only* protection levels are listed
2624 * in $wgSemiprotectedRestrictionLevels?
2625 *
2626 * @param string $action Action to check (default: edit)
2627 * @return bool
2628 */
2629 public function isSemiProtected( $action = 'edit' ) {
2630 global $wgSemiprotectedRestrictionLevels;
2631
2632 $restrictions = $this->getRestrictions( $action );
2633 $semi = $wgSemiprotectedRestrictionLevels;
2634 if ( !$restrictions || !$semi ) {
2635 // Not protected, or all protection is full protection
2636 return false;
2637 }
2638
2639 // Remap autoconfirmed to editsemiprotected for BC
2640 foreach ( array_keys( $semi, 'autoconfirmed' ) as $key ) {
2641 $semi[$key] = 'editsemiprotected';
2642 }
2643 foreach ( array_keys( $restrictions, 'autoconfirmed' ) as $key ) {
2644 $restrictions[$key] = 'editsemiprotected';
2645 }
2646
2647 return !array_diff( $restrictions, $semi );
2648 }
2649
2650 /**
2651 * Does the title correspond to a protected article?
2652 *
2653 * @param string $action The action the page is protected from,
2654 * by default checks all actions.
2655 * @return bool
2656 */
2657 public function isProtected( $action = '' ) {
2658 global $wgRestrictionLevels;
2659
2660 $restrictionTypes = $this->getRestrictionTypes();
2661
2662 # Special pages have inherent protection
2663 if ( $this->isSpecialPage() ) {
2664 return true;
2665 }
2666
2667 # Check regular protection levels
2668 foreach ( $restrictionTypes as $type ) {
2669 if ( $action == $type || $action == '' ) {
2670 $r = $this->getRestrictions( $type );
2671 foreach ( $wgRestrictionLevels as $level ) {
2672 if ( in_array( $level, $r ) && $level != '' ) {
2673 return true;
2674 }
2675 }
2676 }
2677 }
2678
2679 return false;
2680 }
2681
2682 /**
2683 * Determines if $user is unable to edit this page because it has been protected
2684 * by $wgNamespaceProtection.
2685 *
2686 * @param User $user User object to check permissions
2687 * @return bool
2688 */
2689 public function isNamespaceProtected( User $user ) {
2690 global $wgNamespaceProtection;
2691
2692 if ( isset( $wgNamespaceProtection[$this->mNamespace] ) ) {
2693 foreach ( (array)$wgNamespaceProtection[$this->mNamespace] as $right ) {
2694 if ( $right != '' && !$user->isAllowed( $right ) ) {
2695 return true;
2696 }
2697 }
2698 }
2699 return false;
2700 }
2701
2702 /**
2703 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
2704 *
2705 * @return bool If the page is subject to cascading restrictions.
2706 */
2707 public function isCascadeProtected() {
2708 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
2709 return ( $sources > 0 );
2710 }
2711
2712 /**
2713 * Determines whether cascading protection sources have already been loaded from
2714 * the database.
2715 *
2716 * @param bool $getPages True to check if the pages are loaded, or false to check
2717 * if the status is loaded.
2718 * @return bool Whether or not the specified information has been loaded
2719 * @since 1.23
2720 */
2721 public function areCascadeProtectionSourcesLoaded( $getPages = true ) {
2722 return $getPages ? $this->mCascadeSources !== null : $this->mHasCascadingRestrictions !== null;
2723 }
2724
2725 /**
2726 * Cascading protection: Get the source of any cascading restrictions on this page.
2727 *
2728 * @param bool $getPages Whether or not to retrieve the actual pages
2729 * that the restrictions have come from and the actual restrictions
2730 * themselves.
2731 * @return array Two elements: First is an array of Title objects of the
2732 * pages from which cascading restrictions have come, false for
2733 * none, or true if such restrictions exist but $getPages was not
2734 * set. Second is an array like that returned by
2735 * Title::getAllRestrictions(), or an empty array if $getPages is
2736 * false.
2737 */
2738 public function getCascadeProtectionSources( $getPages = true ) {
2739 $pagerestrictions = array();
2740
2741 if ( $this->mCascadeSources !== null && $getPages ) {
2742 return array( $this->mCascadeSources, $this->mCascadingRestrictions );
2743 } elseif ( $this->mHasCascadingRestrictions !== null && !$getPages ) {
2744 return array( $this->mHasCascadingRestrictions, $pagerestrictions );
2745 }
2746
2747 $dbr = wfGetDB( DB_SLAVE );
2748
2749 if ( $this->getNamespace() == NS_FILE ) {
2750 $tables = array( 'imagelinks', 'page_restrictions' );
2751 $where_clauses = array(
2752 'il_to' => $this->getDBkey(),
2753 'il_from=pr_page',
2754 'pr_cascade' => 1
2755 );
2756 } else {
2757 $tables = array( 'templatelinks', 'page_restrictions' );
2758 $where_clauses = array(
2759 'tl_namespace' => $this->getNamespace(),
2760 'tl_title' => $this->getDBkey(),
2761 'tl_from=pr_page',
2762 'pr_cascade' => 1
2763 );
2764 }
2765
2766 if ( $getPages ) {
2767 $cols = array( 'pr_page', 'page_namespace', 'page_title',
2768 'pr_expiry', 'pr_type', 'pr_level' );
2769 $where_clauses[] = 'page_id=pr_page';
2770 $tables[] = 'page';
2771 } else {
2772 $cols = array( 'pr_expiry' );
2773 }
2774
2775 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__ );
2776
2777 $sources = $getPages ? array() : false;
2778 $now = wfTimestampNow();
2779
2780 foreach ( $res as $row ) {
2781 $expiry = $dbr->decodeExpiry( $row->pr_expiry );
2782 if ( $expiry > $now ) {
2783 if ( $getPages ) {
2784 $page_id = $row->pr_page;
2785 $page_ns = $row->page_namespace;
2786 $page_title = $row->page_title;
2787 $sources[$page_id] = Title::makeTitle( $page_ns, $page_title );
2788 # Add groups needed for each restriction type if its not already there
2789 # Make sure this restriction type still exists
2790
2791 if ( !isset( $pagerestrictions[$row->pr_type] ) ) {
2792 $pagerestrictions[$row->pr_type] = array();
2793 }
2794
2795 if (
2796 isset( $pagerestrictions[$row->pr_type] )
2797 && !in_array( $row->pr_level, $pagerestrictions[$row->pr_type] )
2798 ) {
2799 $pagerestrictions[$row->pr_type][] = $row->pr_level;
2800 }
2801 } else {
2802 $sources = true;
2803 }
2804 }
2805 }
2806
2807 if ( $getPages ) {
2808 $this->mCascadeSources = $sources;
2809 $this->mCascadingRestrictions = $pagerestrictions;
2810 } else {
2811 $this->mHasCascadingRestrictions = $sources;
2812 }
2813
2814 return array( $sources, $pagerestrictions );
2815 }
2816
2817 /**
2818 * Accessor for mRestrictionsLoaded
2819 *
2820 * @return bool Whether or not the page's restrictions have already been
2821 * loaded from the database
2822 * @since 1.23
2823 */
2824 public function areRestrictionsLoaded() {
2825 return $this->mRestrictionsLoaded;
2826 }
2827
2828 /**
2829 * Accessor/initialisation for mRestrictions
2830 *
2831 * @param string $action Action that permission needs to be checked for
2832 * @return array Restriction levels needed to take the action. All levels are
2833 * required. Note that restriction levels are normally user rights, but 'sysop'
2834 * and 'autoconfirmed' are also allowed for backwards compatibility. These should
2835 * be mapped to 'editprotected' and 'editsemiprotected' respectively.
2836 */
2837 public function getRestrictions( $action ) {
2838 if ( !$this->mRestrictionsLoaded ) {
2839 $this->loadRestrictions();
2840 }
2841 return isset( $this->mRestrictions[$action] )
2842 ? $this->mRestrictions[$action]
2843 : array();
2844 }
2845
2846 /**
2847 * Accessor/initialisation for mRestrictions
2848 *
2849 * @return array Keys are actions, values are arrays as returned by
2850 * Title::getRestrictions()
2851 * @since 1.23
2852 */
2853 public function getAllRestrictions() {
2854 if ( !$this->mRestrictionsLoaded ) {
2855 $this->loadRestrictions();
2856 }
2857 return $this->mRestrictions;
2858 }
2859
2860 /**
2861 * Get the expiry time for the restriction against a given action
2862 *
2863 * @param string $action
2864 * @return string|bool 14-char timestamp, or 'infinity' if the page is protected forever
2865 * or not protected at all, or false if the action is not recognised.
2866 */
2867 public function getRestrictionExpiry( $action ) {
2868 if ( !$this->mRestrictionsLoaded ) {
2869 $this->loadRestrictions();
2870 }
2871 return isset( $this->mRestrictionsExpiry[$action] ) ? $this->mRestrictionsExpiry[$action] : false;
2872 }
2873
2874 /**
2875 * Returns cascading restrictions for the current article
2876 *
2877 * @return bool
2878 */
2879 function areRestrictionsCascading() {
2880 if ( !$this->mRestrictionsLoaded ) {
2881 $this->loadRestrictions();
2882 }
2883
2884 return $this->mCascadeRestriction;
2885 }
2886
2887 /**
2888 * Loads a string into mRestrictions array
2889 *
2890 * @param ResultWrapper $res Resource restrictions as an SQL result.
2891 * @param string $oldFashionedRestrictions Comma-separated list of page
2892 * restrictions from page table (pre 1.10)
2893 */
2894 private function loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions = null ) {
2895 $rows = array();
2896
2897 foreach ( $res as $row ) {
2898 $rows[] = $row;
2899 }
2900
2901 $this->loadRestrictionsFromRows( $rows, $oldFashionedRestrictions );
2902 }
2903
2904 /**
2905 * Compiles list of active page restrictions from both page table (pre 1.10)
2906 * and page_restrictions table for this existing page.
2907 * Public for usage by LiquidThreads.
2908 *
2909 * @param array $rows Array of db result objects
2910 * @param string $oldFashionedRestrictions Comma-separated list of page
2911 * restrictions from page table (pre 1.10)
2912 */
2913 public function loadRestrictionsFromRows( $rows, $oldFashionedRestrictions = null ) {
2914 $dbr = wfGetDB( DB_SLAVE );
2915
2916 $restrictionTypes = $this->getRestrictionTypes();
2917
2918 foreach ( $restrictionTypes as $type ) {
2919 $this->mRestrictions[$type] = array();
2920 $this->mRestrictionsExpiry[$type] = 'infinity';
2921 }
2922
2923 $this->mCascadeRestriction = false;
2924
2925 # Backwards-compatibility: also load the restrictions from the page record (old format).
2926 if ( $oldFashionedRestrictions !== null ) {
2927 $this->mOldRestrictions = $oldFashionedRestrictions;
2928 }
2929
2930 if ( $this->mOldRestrictions === false ) {
2931 $this->mOldRestrictions = $dbr->selectField( 'page', 'page_restrictions',
2932 array( 'page_id' => $this->getArticleID() ), __METHOD__ );
2933 }
2934
2935 if ( $this->mOldRestrictions != '' ) {
2936 foreach ( explode( ':', trim( $this->mOldRestrictions ) ) as $restrict ) {
2937 $temp = explode( '=', trim( $restrict ) );
2938 if ( count( $temp ) == 1 ) {
2939 // old old format should be treated as edit/move restriction
2940 $this->mRestrictions['edit'] = explode( ',', trim( $temp[0] ) );
2941 $this->mRestrictions['move'] = explode( ',', trim( $temp[0] ) );
2942 } else {
2943 $restriction = trim( $temp[1] );
2944 if ( $restriction != '' ) { // some old entries are empty
2945 $this->mRestrictions[$temp[0]] = explode( ',', $restriction );
2946 }
2947 }
2948 }
2949 }
2950
2951 if ( count( $rows ) ) {
2952 # Current system - load second to make them override.
2953 $now = wfTimestampNow();
2954
2955 # Cycle through all the restrictions.
2956 foreach ( $rows as $row ) {
2957
2958 // Don't take care of restrictions types that aren't allowed
2959 if ( !in_array( $row->pr_type, $restrictionTypes ) ) {
2960 continue;
2961 }
2962
2963 // This code should be refactored, now that it's being used more generally,
2964 // But I don't really see any harm in leaving it in Block for now -werdna
2965 $expiry = $dbr->decodeExpiry( $row->pr_expiry );
2966
2967 // Only apply the restrictions if they haven't expired!
2968 if ( !$expiry || $expiry > $now ) {
2969 $this->mRestrictionsExpiry[$row->pr_type] = $expiry;
2970 $this->mRestrictions[$row->pr_type] = explode( ',', trim( $row->pr_level ) );
2971
2972 $this->mCascadeRestriction |= $row->pr_cascade;
2973 }
2974 }
2975 }
2976
2977 $this->mRestrictionsLoaded = true;
2978 }
2979
2980 /**
2981 * Load restrictions from the page_restrictions table
2982 *
2983 * @param string $oldFashionedRestrictions Comma-separated list of page
2984 * restrictions from page table (pre 1.10)
2985 */
2986 public function loadRestrictions( $oldFashionedRestrictions = null ) {
2987 if ( !$this->mRestrictionsLoaded ) {
2988 $dbr = wfGetDB( DB_SLAVE );
2989 if ( $this->exists() ) {
2990 $res = $dbr->select(
2991 'page_restrictions',
2992 array( 'pr_type', 'pr_expiry', 'pr_level', 'pr_cascade' ),
2993 array( 'pr_page' => $this->getArticleID() ),
2994 __METHOD__
2995 );
2996
2997 $this->loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions );
2998 } else {
2999 $title_protection = $this->getTitleProtection();
3000
3001 if ( $title_protection ) {
3002 $now = wfTimestampNow();
3003 $expiry = $dbr->decodeExpiry( $title_protection['expiry'] );
3004
3005 if ( !$expiry || $expiry > $now ) {
3006 // Apply the restrictions
3007 $this->mRestrictionsExpiry['create'] = $expiry;
3008 $this->mRestrictions['create'] = explode( ',', trim( $title_protection['permission'] ) );
3009 } else { // Get rid of the old restrictions
3010 $this->mTitleProtection = false;
3011 }
3012 } else {
3013 $this->mRestrictionsExpiry['create'] = 'infinity';
3014 }
3015 $this->mRestrictionsLoaded = true;
3016 }
3017 }
3018 }
3019
3020 /**
3021 * Flush the protection cache in this object and force reload from the database.
3022 * This is used when updating protection from WikiPage::doUpdateRestrictions().
3023 */
3024 public function flushRestrictions() {
3025 $this->mRestrictionsLoaded = false;
3026 $this->mTitleProtection = null;
3027 }
3028
3029 /**
3030 * Purge expired restrictions from the page_restrictions table
3031 */
3032 static function purgeExpiredRestrictions() {
3033 if ( wfReadOnly() ) {
3034 return;
3035 }
3036
3037 DeferredUpdates::addUpdate( new AtomicSectionUpdate(
3038 wfGetDB( DB_MASTER ),
3039 __METHOD__,
3040 function ( IDatabase $dbw, $fname ) {
3041 $dbw->delete(
3042 'page_restrictions',
3043 array( 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
3044 $fname
3045 );
3046 $dbw->delete(
3047 'protected_titles',
3048 array( 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
3049 $fname
3050 );
3051 }
3052 ) );
3053 }
3054
3055 /**
3056 * Does this have subpages? (Warning, usually requires an extra DB query.)
3057 *
3058 * @return bool
3059 */
3060 public function hasSubpages() {
3061 if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
3062 # Duh
3063 return false;
3064 }
3065
3066 # We dynamically add a member variable for the purpose of this method
3067 # alone to cache the result. There's no point in having it hanging
3068 # around uninitialized in every Title object; therefore we only add it
3069 # if needed and don't declare it statically.
3070 if ( $this->mHasSubpages === null ) {
3071 $this->mHasSubpages = false;
3072 $subpages = $this->getSubpages( 1 );
3073 if ( $subpages instanceof TitleArray ) {
3074 $this->mHasSubpages = (bool)$subpages->count();
3075 }
3076 }
3077
3078 return $this->mHasSubpages;
3079 }
3080
3081 /**
3082 * Get all subpages of this page.
3083 *
3084 * @param int $limit Maximum number of subpages to fetch; -1 for no limit
3085 * @return TitleArray|array TitleArray, or empty array if this page's namespace
3086 * doesn't allow subpages
3087 */
3088 public function getSubpages( $limit = -1 ) {
3089 if ( !MWNamespace::hasSubpages( $this->getNamespace() ) ) {
3090 return array();
3091 }
3092
3093 $dbr = wfGetDB( DB_SLAVE );
3094 $conds['page_namespace'] = $this->getNamespace();
3095 $conds[] = 'page_title ' . $dbr->buildLike( $this->getDBkey() . '/', $dbr->anyString() );
3096 $options = array();
3097 if ( $limit > -1 ) {
3098 $options['LIMIT'] = $limit;
3099 }
3100 $this->mSubpages = TitleArray::newFromResult(
3101 $dbr->select( 'page',
3102 array( 'page_id', 'page_namespace', 'page_title', 'page_is_redirect' ),
3103 $conds,
3104 __METHOD__,
3105 $options
3106 )
3107 );
3108 return $this->mSubpages;
3109 }
3110
3111 /**
3112 * Is there a version of this page in the deletion archive?
3113 *
3114 * @return int The number of archived revisions
3115 */
3116 public function isDeleted() {
3117 if ( $this->getNamespace() < 0 ) {
3118 $n = 0;
3119 } else {
3120 $dbr = wfGetDB( DB_SLAVE );
3121
3122 $n = $dbr->selectField( 'archive', 'COUNT(*)',
3123 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
3124 __METHOD__
3125 );
3126 if ( $this->getNamespace() == NS_FILE ) {
3127 $n += $dbr->selectField( 'filearchive', 'COUNT(*)',
3128 array( 'fa_name' => $this->getDBkey() ),
3129 __METHOD__
3130 );
3131 }
3132 }
3133 return (int)$n;
3134 }
3135
3136 /**
3137 * Is there a version of this page in the deletion archive?
3138 *
3139 * @return bool
3140 */
3141 public function isDeletedQuick() {
3142 if ( $this->getNamespace() < 0 ) {
3143 return false;
3144 }
3145 $dbr = wfGetDB( DB_SLAVE );
3146 $deleted = (bool)$dbr->selectField( 'archive', '1',
3147 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
3148 __METHOD__
3149 );
3150 if ( !$deleted && $this->getNamespace() == NS_FILE ) {
3151 $deleted = (bool)$dbr->selectField( 'filearchive', '1',
3152 array( 'fa_name' => $this->getDBkey() ),
3153 __METHOD__
3154 );
3155 }
3156 return $deleted;
3157 }
3158
3159 /**
3160 * Get the article ID for this Title from the link cache,
3161 * adding it if necessary
3162 *
3163 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select
3164 * for update
3165 * @return int The ID
3166 */
3167 public function getArticleID( $flags = 0 ) {
3168 if ( $this->getNamespace() < 0 ) {
3169 $this->mArticleID = 0;
3170 return $this->mArticleID;
3171 }
3172 $linkCache = LinkCache::singleton();
3173 if ( $flags & self::GAID_FOR_UPDATE ) {
3174 $oldUpdate = $linkCache->forUpdate( true );
3175 $linkCache->clearLink( $this );
3176 $this->mArticleID = $linkCache->addLinkObj( $this );
3177 $linkCache->forUpdate( $oldUpdate );
3178 } else {
3179 if ( -1 == $this->mArticleID ) {
3180 $this->mArticleID = $linkCache->addLinkObj( $this );
3181 }
3182 }
3183 return $this->mArticleID;
3184 }
3185
3186 /**
3187 * Is this an article that is a redirect page?
3188 * Uses link cache, adding it if necessary
3189 *
3190 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3191 * @return bool
3192 */
3193 public function isRedirect( $flags = 0 ) {
3194 if ( !is_null( $this->mRedirect ) ) {
3195 return $this->mRedirect;
3196 }
3197 if ( !$this->getArticleID( $flags ) ) {
3198 $this->mRedirect = false;
3199 return $this->mRedirect;
3200 }
3201
3202 $linkCache = LinkCache::singleton();
3203 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3204 $cached = $linkCache->getGoodLinkFieldObj( $this, 'redirect' );
3205 if ( $cached === null ) {
3206 # Trust LinkCache's state over our own
3207 # LinkCache is telling us that the page doesn't exist, despite there being cached
3208 # data relating to an existing page in $this->mArticleID. Updaters should clear
3209 # LinkCache as appropriate, or use $flags = Title::GAID_FOR_UPDATE. If that flag is
3210 # set, then LinkCache will definitely be up to date here, since getArticleID() forces
3211 # LinkCache to refresh its data from the master.
3212 $this->mRedirect = false;
3213 return $this->mRedirect;
3214 }
3215
3216 $this->mRedirect = (bool)$cached;
3217
3218 return $this->mRedirect;
3219 }
3220
3221 /**
3222 * What is the length of this page?
3223 * Uses link cache, adding it if necessary
3224 *
3225 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3226 * @return int
3227 */
3228 public function getLength( $flags = 0 ) {
3229 if ( $this->mLength != -1 ) {
3230 return $this->mLength;
3231 }
3232 if ( !$this->getArticleID( $flags ) ) {
3233 $this->mLength = 0;
3234 return $this->mLength;
3235 }
3236 $linkCache = LinkCache::singleton();
3237 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3238 $cached = $linkCache->getGoodLinkFieldObj( $this, 'length' );
3239 if ( $cached === null ) {
3240 # Trust LinkCache's state over our own, as for isRedirect()
3241 $this->mLength = 0;
3242 return $this->mLength;
3243 }
3244
3245 $this->mLength = intval( $cached );
3246
3247 return $this->mLength;
3248 }
3249
3250 /**
3251 * What is the page_latest field for this page?
3252 *
3253 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3254 * @return int Int or 0 if the page doesn't exist
3255 */
3256 public function getLatestRevID( $flags = 0 ) {
3257 if ( !( $flags & Title::GAID_FOR_UPDATE ) && $this->mLatestID !== false ) {
3258 return intval( $this->mLatestID );
3259 }
3260 if ( !$this->getArticleID( $flags ) ) {
3261 $this->mLatestID = 0;
3262 return $this->mLatestID;
3263 }
3264 $linkCache = LinkCache::singleton();
3265 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3266 $cached = $linkCache->getGoodLinkFieldObj( $this, 'revision' );
3267 if ( $cached === null ) {
3268 # Trust LinkCache's state over our own, as for isRedirect()
3269 $this->mLatestID = 0;
3270 return $this->mLatestID;
3271 }
3272
3273 $this->mLatestID = intval( $cached );
3274
3275 return $this->mLatestID;
3276 }
3277
3278 /**
3279 * This clears some fields in this object, and clears any associated
3280 * keys in the "bad links" section of the link cache.
3281 *
3282 * - This is called from WikiPage::doEdit() and WikiPage::insertOn() to allow
3283 * loading of the new page_id. It's also called from
3284 * WikiPage::doDeleteArticleReal()
3285 *
3286 * @param int $newid The new Article ID
3287 */
3288 public function resetArticleID( $newid ) {
3289 $linkCache = LinkCache::singleton();
3290 $linkCache->clearLink( $this );
3291
3292 if ( $newid === false ) {
3293 $this->mArticleID = -1;
3294 } else {
3295 $this->mArticleID = intval( $newid );
3296 }
3297 $this->mRestrictionsLoaded = false;
3298 $this->mRestrictions = array();
3299 $this->mOldRestrictions = false;
3300 $this->mRedirect = null;
3301 $this->mLength = -1;
3302 $this->mLatestID = false;
3303 $this->mContentModel = false;
3304 $this->mEstimateRevisions = null;
3305 $this->mPageLanguage = false;
3306 $this->mDbPageLanguage = null;
3307 $this->mIsBigDeletion = null;
3308 }
3309
3310 public static function clearCaches() {
3311 $linkCache = LinkCache::singleton();
3312 $linkCache->clear();
3313
3314 $titleCache = self::getTitleCache();
3315 $titleCache->clear();
3316 }
3317
3318 /**
3319 * Capitalize a text string for a title if it belongs to a namespace that capitalizes
3320 *
3321 * @param string $text Containing title to capitalize
3322 * @param int $ns Namespace index, defaults to NS_MAIN
3323 * @return string Containing capitalized title
3324 */
3325 public static function capitalize( $text, $ns = NS_MAIN ) {
3326 global $wgContLang;
3327
3328 if ( MWNamespace::isCapitalized( $ns ) ) {
3329 return $wgContLang->ucfirst( $text );
3330 } else {
3331 return $text;
3332 }
3333 }
3334
3335 /**
3336 * Secure and split - main initialisation function for this object
3337 *
3338 * Assumes that mDbkeyform has been set, and is urldecoded
3339 * and uses underscores, but not otherwise munged. This function
3340 * removes illegal characters, splits off the interwiki and
3341 * namespace prefixes, sets the other forms, and canonicalizes
3342 * everything.
3343 *
3344 * @throws MalformedTitleException On invalid titles
3345 * @return bool True on success
3346 */
3347 private function secureAndSplit() {
3348 # Initialisation
3349 $this->mInterwiki = '';
3350 $this->mFragment = '';
3351 $this->mNamespace = $this->mDefaultNamespace; # Usually NS_MAIN
3352
3353 $dbkey = $this->mDbkeyform;
3354
3355 // @note: splitTitleString() is a temporary hack to allow MediaWikiTitleCodec to share
3356 // the parsing code with Title, while avoiding massive refactoring.
3357 // @todo: get rid of secureAndSplit, refactor parsing code.
3358 $titleParser = self::getMediaWikiTitleCodec();
3359 // MalformedTitleException can be thrown here
3360 $parts = $titleParser->splitTitleString( $dbkey, $this->getDefaultNamespace() );
3361
3362 # Fill fields
3363 $this->setFragment( '#' . $parts['fragment'] );
3364 $this->mInterwiki = $parts['interwiki'];
3365 $this->mLocalInterwiki = $parts['local_interwiki'];
3366 $this->mNamespace = $parts['namespace'];
3367 $this->mUserCaseDBKey = $parts['user_case_dbkey'];
3368
3369 $this->mDbkeyform = $parts['dbkey'];
3370 $this->mUrlform = wfUrlencode( $this->mDbkeyform );
3371 $this->mTextform = strtr( $this->mDbkeyform, '_', ' ' );
3372
3373 # We already know that some pages won't be in the database!
3374 if ( $this->isExternal() || $this->mNamespace == NS_SPECIAL ) {
3375 $this->mArticleID = 0;
3376 }
3377
3378 return true;
3379 }
3380
3381 /**
3382 * Get an array of Title objects linking to this Title
3383 * Also stores the IDs in the link cache.
3384 *
3385 * WARNING: do not use this function on arbitrary user-supplied titles!
3386 * On heavily-used templates it will max out the memory.
3387 *
3388 * @param array $options May be FOR UPDATE
3389 * @param string $table Table name
3390 * @param string $prefix Fields prefix
3391 * @return Title[] Array of Title objects linking here
3392 */
3393 public function getLinksTo( $options = array(), $table = 'pagelinks', $prefix = 'pl' ) {
3394 if ( count( $options ) > 0 ) {
3395 $db = wfGetDB( DB_MASTER );
3396 } else {
3397 $db = wfGetDB( DB_SLAVE );
3398 }
3399
3400 $res = $db->select(
3401 array( 'page', $table ),
3402 self::getSelectFields(),
3403 array(
3404 "{$prefix}_from=page_id",
3405 "{$prefix}_namespace" => $this->getNamespace(),
3406 "{$prefix}_title" => $this->getDBkey() ),
3407 __METHOD__,
3408 $options
3409 );
3410
3411 $retVal = array();
3412 if ( $res->numRows() ) {
3413 $linkCache = LinkCache::singleton();
3414 foreach ( $res as $row ) {
3415 $titleObj = Title::makeTitle( $row->page_namespace, $row->page_title );
3416 if ( $titleObj ) {
3417 $linkCache->addGoodLinkObjFromRow( $titleObj, $row );
3418 $retVal[] = $titleObj;
3419 }
3420 }
3421 }
3422 return $retVal;
3423 }
3424
3425 /**
3426 * Get an array of Title objects using this Title as a template
3427 * Also stores the IDs in the link cache.
3428 *
3429 * WARNING: do not use this function on arbitrary user-supplied titles!
3430 * On heavily-used templates it will max out the memory.
3431 *
3432 * @param array $options May be FOR UPDATE
3433 * @return Title[] Array of Title the Title objects linking here
3434 */
3435 public function getTemplateLinksTo( $options = array() ) {
3436 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
3437 }
3438
3439 /**
3440 * Get an array of Title objects linked from this Title
3441 * Also stores the IDs in the link cache.
3442 *
3443 * WARNING: do not use this function on arbitrary user-supplied titles!
3444 * On heavily-used templates it will max out the memory.
3445 *
3446 * @param array $options May be FOR UPDATE
3447 * @param string $table Table name
3448 * @param string $prefix Fields prefix
3449 * @return array Array of Title objects linking here
3450 */
3451 public function getLinksFrom( $options = array(), $table = 'pagelinks', $prefix = 'pl' ) {
3452 $id = $this->getArticleID();
3453
3454 # If the page doesn't exist; there can't be any link from this page
3455 if ( !$id ) {
3456 return array();
3457 }
3458
3459 if ( count( $options ) > 0 ) {
3460 $db = wfGetDB( DB_MASTER );
3461 } else {
3462 $db = wfGetDB( DB_SLAVE );
3463 }
3464
3465 $blNamespace = "{$prefix}_namespace";
3466 $blTitle = "{$prefix}_title";
3467
3468 $res = $db->select(
3469 array( $table, 'page' ),
3470 array_merge(
3471 array( $blNamespace, $blTitle ),
3472 WikiPage::selectFields()
3473 ),
3474 array( "{$prefix}_from" => $id ),
3475 __METHOD__,
3476 $options,
3477 array( 'page' => array(
3478 'LEFT JOIN',
3479 array( "page_namespace=$blNamespace", "page_title=$blTitle" )
3480 ) )
3481 );
3482
3483 $retVal = array();
3484 $linkCache = LinkCache::singleton();
3485 foreach ( $res as $row ) {
3486 if ( $row->page_id ) {
3487 $titleObj = Title::newFromRow( $row );
3488 } else {
3489 $titleObj = Title::makeTitle( $row->$blNamespace, $row->$blTitle );
3490 $linkCache->addBadLinkObj( $titleObj );
3491 }
3492 $retVal[] = $titleObj;
3493 }
3494
3495 return $retVal;
3496 }
3497
3498 /**
3499 * Get an array of Title objects used on this Title as a template
3500 * Also stores the IDs in the link cache.
3501 *
3502 * WARNING: do not use this function on arbitrary user-supplied titles!
3503 * On heavily-used templates it will max out the memory.
3504 *
3505 * @param array $options May be FOR UPDATE
3506 * @return Title[] Array of Title the Title objects used here
3507 */
3508 public function getTemplateLinksFrom( $options = array() ) {
3509 return $this->getLinksFrom( $options, 'templatelinks', 'tl' );
3510 }
3511
3512 /**
3513 * Get an array of Title objects referring to non-existent articles linked
3514 * from this page.
3515 *
3516 * @todo check if needed (used only in SpecialBrokenRedirects.php, and
3517 * should use redirect table in this case).
3518 * @return Title[] Array of Title the Title objects
3519 */
3520 public function getBrokenLinksFrom() {
3521 if ( $this->getArticleID() == 0 ) {
3522 # All links from article ID 0 are false positives
3523 return array();
3524 }
3525
3526 $dbr = wfGetDB( DB_SLAVE );
3527 $res = $dbr->select(
3528 array( 'page', 'pagelinks' ),
3529 array( 'pl_namespace', 'pl_title' ),
3530 array(
3531 'pl_from' => $this->getArticleID(),
3532 'page_namespace IS NULL'
3533 ),
3534 __METHOD__, array(),
3535 array(
3536 'page' => array(
3537 'LEFT JOIN',
3538 array( 'pl_namespace=page_namespace', 'pl_title=page_title' )
3539 )
3540 )
3541 );
3542
3543 $retVal = array();
3544 foreach ( $res as $row ) {
3545 $retVal[] = Title::makeTitle( $row->pl_namespace, $row->pl_title );
3546 }
3547 return $retVal;
3548 }
3549
3550 /**
3551 * Get a list of URLs to purge from the CDN cache when this
3552 * page changes
3553 *
3554 * @return string[] Array of String the URLs
3555 */
3556 public function getCdnUrls() {
3557 $urls = array(
3558 $this->getInternalURL(),
3559 $this->getInternalURL( 'action=history' )
3560 );
3561
3562 $pageLang = $this->getPageLanguage();
3563 if ( $pageLang->hasVariants() ) {
3564 $variants = $pageLang->getVariants();
3565 foreach ( $variants as $vCode ) {
3566 $urls[] = $this->getInternalURL( $vCode );
3567 }
3568 }
3569
3570 // If we are looking at a css/js user subpage, purge the action=raw.
3571 if ( $this->isJsSubpage() ) {
3572 $urls[] = $this->getInternalUrl( 'action=raw&ctype=text/javascript' );
3573 } elseif ( $this->isCssSubpage() ) {
3574 $urls[] = $this->getInternalUrl( 'action=raw&ctype=text/css' );
3575 }
3576
3577 Hooks::run( 'TitleSquidURLs', array( $this, &$urls ) );
3578 return $urls;
3579 }
3580
3581 /**
3582 * @deprecated since 1.27 use getCdnUrls()
3583 */
3584 public function getSquidURLs() {
3585 return $this->getCdnUrls();
3586 }
3587
3588 /**
3589 * Purge all applicable CDN URLs
3590 */
3591 public function purgeSquid() {
3592 DeferredUpdates::addUpdate(
3593 new CdnCacheUpdate( $this->getCdnUrls() ),
3594 DeferredUpdates::PRESEND
3595 );
3596 }
3597
3598 /**
3599 * Move this page without authentication
3600 *
3601 * @deprecated since 1.25 use MovePage class instead
3602 * @param Title $nt The new page Title
3603 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
3604 */
3605 public function moveNoAuth( &$nt ) {
3606 wfDeprecated( __METHOD__, '1.25' );
3607 return $this->moveTo( $nt, false );
3608 }
3609
3610 /**
3611 * Check whether a given move operation would be valid.
3612 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
3613 *
3614 * @deprecated since 1.25, use MovePage's methods instead
3615 * @param Title $nt The new title
3616 * @param bool $auth Whether to check user permissions (uses $wgUser)
3617 * @param string $reason Is the log summary of the move, used for spam checking
3618 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
3619 */
3620 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
3621 global $wgUser;
3622
3623 if ( !( $nt instanceof Title ) ) {
3624 // Normally we'd add this to $errors, but we'll get
3625 // lots of syntax errors if $nt is not an object
3626 return array( array( 'badtitletext' ) );
3627 }
3628
3629 $mp = new MovePage( $this, $nt );
3630 $errors = $mp->isValidMove()->getErrorsArray();
3631 if ( $auth ) {
3632 $errors = wfMergeErrorArrays(
3633 $errors,
3634 $mp->checkPermissions( $wgUser, $reason )->getErrorsArray()
3635 );
3636 }
3637
3638 return $errors ?: true;
3639 }
3640
3641 /**
3642 * Check if the requested move target is a valid file move target
3643 * @todo move this to MovePage
3644 * @param Title $nt Target title
3645 * @return array List of errors
3646 */
3647 protected function validateFileMoveOperation( $nt ) {
3648 global $wgUser;
3649
3650 $errors = array();
3651
3652 $destFile = wfLocalFile( $nt );
3653 $destFile->load( File::READ_LATEST );
3654 if ( !$wgUser->isAllowed( 'reupload-shared' )
3655 && !$destFile->exists() && wfFindFile( $nt )
3656 ) {
3657 $errors[] = array( 'file-exists-sharedrepo' );
3658 }
3659
3660 return $errors;
3661 }
3662
3663 /**
3664 * Move a title to a new location
3665 *
3666 * @deprecated since 1.25, use the MovePage class instead
3667 * @param Title $nt The new title
3668 * @param bool $auth Indicates whether $wgUser's permissions
3669 * should be checked
3670 * @param string $reason The reason for the move
3671 * @param bool $createRedirect Whether to create a redirect from the old title to the new title.
3672 * Ignored if the user doesn't have the suppressredirect right.
3673 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
3674 */
3675 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true ) {
3676 global $wgUser;
3677 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
3678 if ( is_array( $err ) ) {
3679 // Auto-block user's IP if the account was "hard" blocked
3680 $wgUser->spreadAnyEditBlock();
3681 return $err;
3682 }
3683 // Check suppressredirect permission
3684 if ( $auth && !$wgUser->isAllowed( 'suppressredirect' ) ) {
3685 $createRedirect = true;
3686 }
3687
3688 $mp = new MovePage( $this, $nt );
3689 $status = $mp->move( $wgUser, $reason, $createRedirect );
3690 if ( $status->isOK() ) {
3691 return true;
3692 } else {
3693 return $status->getErrorsArray();
3694 }
3695 }
3696
3697 /**
3698 * Move this page's subpages to be subpages of $nt
3699 *
3700 * @param Title $nt Move target
3701 * @param bool $auth Whether $wgUser's permissions should be checked
3702 * @param string $reason The reason for the move
3703 * @param bool $createRedirect Whether to create redirects from the old subpages to
3704 * the new ones Ignored if the user doesn't have the 'suppressredirect' right
3705 * @return array Array with old page titles as keys, and strings (new page titles) or
3706 * arrays (errors) as values, or an error array with numeric indices if no pages
3707 * were moved
3708 */
3709 public function moveSubpages( $nt, $auth = true, $reason = '', $createRedirect = true ) {
3710 global $wgMaximumMovedPages;
3711 // Check permissions
3712 if ( !$this->userCan( 'move-subpages' ) ) {
3713 return array( 'cant-move-subpages' );
3714 }
3715 // Do the source and target namespaces support subpages?
3716 if ( !MWNamespace::hasSubpages( $this->getNamespace() ) ) {
3717 return array( 'namespace-nosubpages',
3718 MWNamespace::getCanonicalName( $this->getNamespace() ) );
3719 }
3720 if ( !MWNamespace::hasSubpages( $nt->getNamespace() ) ) {
3721 return array( 'namespace-nosubpages',
3722 MWNamespace::getCanonicalName( $nt->getNamespace() ) );
3723 }
3724
3725 $subpages = $this->getSubpages( $wgMaximumMovedPages + 1 );
3726 $retval = array();
3727 $count = 0;
3728 foreach ( $subpages as $oldSubpage ) {
3729 $count++;
3730 if ( $count > $wgMaximumMovedPages ) {
3731 $retval[$oldSubpage->getPrefixedText()] =
3732 array( 'movepage-max-pages',
3733 $wgMaximumMovedPages );
3734 break;
3735 }
3736
3737 // We don't know whether this function was called before
3738 // or after moving the root page, so check both
3739 // $this and $nt
3740 if ( $oldSubpage->getArticleID() == $this->getArticleID()
3741 || $oldSubpage->getArticleID() == $nt->getArticleID()
3742 ) {
3743 // When moving a page to a subpage of itself,
3744 // don't move it twice
3745 continue;
3746 }
3747 $newPageName = preg_replace(
3748 '#^' . preg_quote( $this->getDBkey(), '#' ) . '#',
3749 StringUtils::escapeRegexReplacement( $nt->getDBkey() ), # bug 21234
3750 $oldSubpage->getDBkey() );
3751 if ( $oldSubpage->isTalkPage() ) {
3752 $newNs = $nt->getTalkPage()->getNamespace();
3753 } else {
3754 $newNs = $nt->getSubjectPage()->getNamespace();
3755 }
3756 # Bug 14385: we need makeTitleSafe because the new page names may
3757 # be longer than 255 characters.
3758 $newSubpage = Title::makeTitleSafe( $newNs, $newPageName );
3759
3760 $success = $oldSubpage->moveTo( $newSubpage, $auth, $reason, $createRedirect );
3761 if ( $success === true ) {
3762 $retval[$oldSubpage->getPrefixedText()] = $newSubpage->getPrefixedText();
3763 } else {
3764 $retval[$oldSubpage->getPrefixedText()] = $success;
3765 }
3766 }
3767 return $retval;
3768 }
3769
3770 /**
3771 * Checks if this page is just a one-rev redirect.
3772 * Adds lock, so don't use just for light purposes.
3773 *
3774 * @return bool
3775 */
3776 public function isSingleRevRedirect() {
3777 global $wgContentHandlerUseDB;
3778
3779 $dbw = wfGetDB( DB_MASTER );
3780
3781 # Is it a redirect?
3782 $fields = array( 'page_is_redirect', 'page_latest', 'page_id' );
3783 if ( $wgContentHandlerUseDB ) {
3784 $fields[] = 'page_content_model';
3785 }
3786
3787 $row = $dbw->selectRow( 'page',
3788 $fields,
3789 $this->pageCond(),
3790 __METHOD__,
3791 array( 'FOR UPDATE' )
3792 );
3793 # Cache some fields we may want
3794 $this->mArticleID = $row ? intval( $row->page_id ) : 0;
3795 $this->mRedirect = $row ? (bool)$row->page_is_redirect : false;
3796 $this->mLatestID = $row ? intval( $row->page_latest ) : false;
3797 $this->mContentModel = $row && isset( $row->page_content_model )
3798 ? strval( $row->page_content_model )
3799 : false;
3800
3801 if ( !$this->mRedirect ) {
3802 return false;
3803 }
3804 # Does the article have a history?
3805 $row = $dbw->selectField( array( 'page', 'revision' ),
3806 'rev_id',
3807 array( 'page_namespace' => $this->getNamespace(),
3808 'page_title' => $this->getDBkey(),
3809 'page_id=rev_page',
3810 'page_latest != rev_id'
3811 ),
3812 __METHOD__,
3813 array( 'FOR UPDATE' )
3814 );
3815 # Return true if there was no history
3816 return ( $row === false );
3817 }
3818
3819 /**
3820 * Checks if $this can be moved to a given Title
3821 * - Selects for update, so don't call it unless you mean business
3822 *
3823 * @deprecated since 1.25, use MovePage's methods instead
3824 * @param Title $nt The new title to check
3825 * @return bool
3826 */
3827 public function isValidMoveTarget( $nt ) {
3828 # Is it an existing file?
3829 if ( $nt->getNamespace() == NS_FILE ) {
3830 $file = wfLocalFile( $nt );
3831 $file->load( File::READ_LATEST );
3832 if ( $file->exists() ) {
3833 wfDebug( __METHOD__ . ": file exists\n" );
3834 return false;
3835 }
3836 }
3837 # Is it a redirect with no history?
3838 if ( !$nt->isSingleRevRedirect() ) {
3839 wfDebug( __METHOD__ . ": not a one-rev redirect\n" );
3840 return false;
3841 }
3842 # Get the article text
3843 $rev = Revision::newFromTitle( $nt, false, Revision::READ_LATEST );
3844 if ( !is_object( $rev ) ) {
3845 return false;
3846 }
3847 $content = $rev->getContent();
3848 # Does the redirect point to the source?
3849 # Or is it a broken self-redirect, usually caused by namespace collisions?
3850 $redirTitle = $content ? $content->getRedirectTarget() : null;
3851
3852 if ( $redirTitle ) {
3853 if ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
3854 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) {
3855 wfDebug( __METHOD__ . ": redirect points to other page\n" );
3856 return false;
3857 } else {
3858 return true;
3859 }
3860 } else {
3861 # Fail safe (not a redirect after all. strange.)
3862 wfDebug( __METHOD__ . ": failsafe: database sais " . $nt->getPrefixedDBkey() .
3863 " is a redirect, but it doesn't contain a valid redirect.\n" );
3864 return false;
3865 }
3866 }
3867
3868 /**
3869 * Get categories to which this Title belongs and return an array of
3870 * categories' names.
3871 *
3872 * @return array Array of parents in the form:
3873 * $parent => $currentarticle
3874 */
3875 public function getParentCategories() {
3876 global $wgContLang;
3877
3878 $data = array();
3879
3880 $titleKey = $this->getArticleID();
3881
3882 if ( $titleKey === 0 ) {
3883 return $data;
3884 }
3885
3886 $dbr = wfGetDB( DB_SLAVE );
3887
3888 $res = $dbr->select(
3889 'categorylinks',
3890 'cl_to',
3891 array( 'cl_from' => $titleKey ),
3892 __METHOD__
3893 );
3894
3895 if ( $res->numRows() > 0 ) {
3896 foreach ( $res as $row ) {
3897 // $data[] = Title::newFromText($wgContLang->getNsText ( NS_CATEGORY ).':'.$row->cl_to);
3898 $data[$wgContLang->getNsText( NS_CATEGORY ) . ':' . $row->cl_to] = $this->getFullText();
3899 }
3900 }
3901 return $data;
3902 }
3903
3904 /**
3905 * Get a tree of parent categories
3906 *
3907 * @param array $children Array with the children in the keys, to check for circular refs
3908 * @return array Tree of parent categories
3909 */
3910 public function getParentCategoryTree( $children = array() ) {
3911 $stack = array();
3912 $parents = $this->getParentCategories();
3913
3914 if ( $parents ) {
3915 foreach ( $parents as $parent => $current ) {
3916 if ( array_key_exists( $parent, $children ) ) {
3917 # Circular reference
3918 $stack[$parent] = array();
3919 } else {
3920 $nt = Title::newFromText( $parent );
3921 if ( $nt ) {
3922 $stack[$parent] = $nt->getParentCategoryTree( $children + array( $parent => 1 ) );
3923 }
3924 }
3925 }
3926 }
3927
3928 return $stack;
3929 }
3930
3931 /**
3932 * Get an associative array for selecting this title from
3933 * the "page" table
3934 *
3935 * @return array Array suitable for the $where parameter of DB::select()
3936 */
3937 public function pageCond() {
3938 if ( $this->mArticleID > 0 ) {
3939 // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs
3940 return array( 'page_id' => $this->mArticleID );
3941 } else {
3942 return array( 'page_namespace' => $this->mNamespace, 'page_title' => $this->mDbkeyform );
3943 }
3944 }
3945
3946 /**
3947 * Get the revision ID of the previous revision
3948 *
3949 * @param int $revId Revision ID. Get the revision that was before this one.
3950 * @param int $flags Title::GAID_FOR_UPDATE
3951 * @return int|bool Old revision ID, or false if none exists
3952 */
3953 public function getPreviousRevisionID( $revId, $flags = 0 ) {
3954 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
3955 $revId = $db->selectField( 'revision', 'rev_id',
3956 array(
3957 'rev_page' => $this->getArticleID( $flags ),
3958 'rev_id < ' . intval( $revId )
3959 ),
3960 __METHOD__,
3961 array( 'ORDER BY' => 'rev_id DESC' )
3962 );
3963
3964 if ( $revId === false ) {
3965 return false;
3966 } else {
3967 return intval( $revId );
3968 }
3969 }
3970
3971 /**
3972 * Get the revision ID of the next revision
3973 *
3974 * @param int $revId Revision ID. Get the revision that was after this one.
3975 * @param int $flags Title::GAID_FOR_UPDATE
3976 * @return int|bool Next revision ID, or false if none exists
3977 */
3978 public function getNextRevisionID( $revId, $flags = 0 ) {
3979 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
3980 $revId = $db->selectField( 'revision', 'rev_id',
3981 array(
3982 'rev_page' => $this->getArticleID( $flags ),
3983 'rev_id > ' . intval( $revId )
3984 ),
3985 __METHOD__,
3986 array( 'ORDER BY' => 'rev_id' )
3987 );
3988
3989 if ( $revId === false ) {
3990 return false;
3991 } else {
3992 return intval( $revId );
3993 }
3994 }
3995
3996 /**
3997 * Get the first revision of the page
3998 *
3999 * @param int $flags Title::GAID_FOR_UPDATE
4000 * @return Revision|null If page doesn't exist
4001 */
4002 public function getFirstRevision( $flags = 0 ) {
4003 $pageId = $this->getArticleID( $flags );
4004 if ( $pageId ) {
4005 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
4006 $row = $db->selectRow( 'revision', Revision::selectFields(),
4007 array( 'rev_page' => $pageId ),
4008 __METHOD__,
4009 array( 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 1 )
4010 );
4011 if ( $row ) {
4012 return new Revision( $row );
4013 }
4014 }
4015 return null;
4016 }
4017
4018 /**
4019 * Get the oldest revision timestamp of this page
4020 *
4021 * @param int $flags Title::GAID_FOR_UPDATE
4022 * @return string MW timestamp
4023 */
4024 public function getEarliestRevTime( $flags = 0 ) {
4025 $rev = $this->getFirstRevision( $flags );
4026 return $rev ? $rev->getTimestamp() : null;
4027 }
4028
4029 /**
4030 * Check if this is a new page
4031 *
4032 * @return bool
4033 */
4034 public function isNewPage() {
4035 $dbr = wfGetDB( DB_SLAVE );
4036 return (bool)$dbr->selectField( 'page', 'page_is_new', $this->pageCond(), __METHOD__ );
4037 }
4038
4039 /**
4040 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
4041 *
4042 * @return bool
4043 */
4044 public function isBigDeletion() {
4045 global $wgDeleteRevisionsLimit;
4046
4047 if ( !$wgDeleteRevisionsLimit ) {
4048 return false;
4049 }
4050
4051 if ( $this->mIsBigDeletion === null ) {
4052 $dbr = wfGetDB( DB_SLAVE );
4053
4054 $revCount = $dbr->selectRowCount(
4055 'revision',
4056 '1',
4057 array( 'rev_page' => $this->getArticleID() ),
4058 __METHOD__,
4059 array( 'LIMIT' => $wgDeleteRevisionsLimit + 1 )
4060 );
4061
4062 $this->mIsBigDeletion = $revCount > $wgDeleteRevisionsLimit;
4063 }
4064
4065 return $this->mIsBigDeletion;
4066 }
4067
4068 /**
4069 * Get the approximate revision count of this page.
4070 *
4071 * @return int
4072 */
4073 public function estimateRevisionCount() {
4074 if ( !$this->exists() ) {
4075 return 0;
4076 }
4077
4078 if ( $this->mEstimateRevisions === null ) {
4079 $dbr = wfGetDB( DB_SLAVE );
4080 $this->mEstimateRevisions = $dbr->estimateRowCount( 'revision', '*',
4081 array( 'rev_page' => $this->getArticleID() ), __METHOD__ );
4082 }
4083
4084 return $this->mEstimateRevisions;
4085 }
4086
4087 /**
4088 * Get the number of revisions between the given revision.
4089 * Used for diffs and other things that really need it.
4090 *
4091 * @param int|Revision $old Old revision or rev ID (first before range)
4092 * @param int|Revision $new New revision or rev ID (first after range)
4093 * @param int|null $max Limit of Revisions to count, will be incremented to detect truncations
4094 * @return int Number of revisions between these revisions.
4095 */
4096 public function countRevisionsBetween( $old, $new, $max = null ) {
4097 if ( !( $old instanceof Revision ) ) {
4098 $old = Revision::newFromTitle( $this, (int)$old );
4099 }
4100 if ( !( $new instanceof Revision ) ) {
4101 $new = Revision::newFromTitle( $this, (int)$new );
4102 }
4103 if ( !$old || !$new ) {
4104 return 0; // nothing to compare
4105 }
4106 $dbr = wfGetDB( DB_SLAVE );
4107 $conds = array(
4108 'rev_page' => $this->getArticleID(),
4109 'rev_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4110 'rev_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4111 );
4112 if ( $max !== null ) {
4113 return $dbr->selectRowCount( 'revision', '1',
4114 $conds,
4115 __METHOD__,
4116 array( 'LIMIT' => $max + 1 ) // extra to detect truncation
4117 );
4118 } else {
4119 return (int)$dbr->selectField( 'revision', 'count(*)', $conds, __METHOD__ );
4120 }
4121 }
4122
4123 /**
4124 * Get the authors between the given revisions or revision IDs.
4125 * Used for diffs and other things that really need it.
4126 *
4127 * @since 1.23
4128 *
4129 * @param int|Revision $old Old revision or rev ID (first before range by default)
4130 * @param int|Revision $new New revision or rev ID (first after range by default)
4131 * @param int $limit Maximum number of authors
4132 * @param string|array $options (Optional): Single option, or an array of options:
4133 * 'include_old' Include $old in the range; $new is excluded.
4134 * 'include_new' Include $new in the range; $old is excluded.
4135 * 'include_both' Include both $old and $new in the range.
4136 * Unknown option values are ignored.
4137 * @return array|null Names of revision authors in the range; null if not both revisions exist
4138 */
4139 public function getAuthorsBetween( $old, $new, $limit, $options = array() ) {
4140 if ( !( $old instanceof Revision ) ) {
4141 $old = Revision::newFromTitle( $this, (int)$old );
4142 }
4143 if ( !( $new instanceof Revision ) ) {
4144 $new = Revision::newFromTitle( $this, (int)$new );
4145 }
4146 // XXX: what if Revision objects are passed in, but they don't refer to this title?
4147 // Add $old->getPage() != $new->getPage() || $old->getPage() != $this->getArticleID()
4148 // in the sanity check below?
4149 if ( !$old || !$new ) {
4150 return null; // nothing to compare
4151 }
4152 $authors = array();
4153 $old_cmp = '>';
4154 $new_cmp = '<';
4155 $options = (array)$options;
4156 if ( in_array( 'include_old', $options ) ) {
4157 $old_cmp = '>=';
4158 }
4159 if ( in_array( 'include_new', $options ) ) {
4160 $new_cmp = '<=';
4161 }
4162 if ( in_array( 'include_both', $options ) ) {
4163 $old_cmp = '>=';
4164 $new_cmp = '<=';
4165 }
4166 // No DB query needed if $old and $new are the same or successive revisions:
4167 if ( $old->getId() === $new->getId() ) {
4168 return ( $old_cmp === '>' && $new_cmp === '<' ) ?
4169 array() :
4170 array( $old->getUserText( Revision::RAW ) );
4171 } elseif ( $old->getId() === $new->getParentId() ) {
4172 if ( $old_cmp === '>=' && $new_cmp === '<=' ) {
4173 $authors[] = $old->getUserText( Revision::RAW );
4174 if ( $old->getUserText( Revision::RAW ) != $new->getUserText( Revision::RAW ) ) {
4175 $authors[] = $new->getUserText( Revision::RAW );
4176 }
4177 } elseif ( $old_cmp === '>=' ) {
4178 $authors[] = $old->getUserText( Revision::RAW );
4179 } elseif ( $new_cmp === '<=' ) {
4180 $authors[] = $new->getUserText( Revision::RAW );
4181 }
4182 return $authors;
4183 }
4184 $dbr = wfGetDB( DB_SLAVE );
4185 $res = $dbr->select( 'revision', 'DISTINCT rev_user_text',
4186 array(
4187 'rev_page' => $this->getArticleID(),
4188 "rev_timestamp $old_cmp " . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4189 "rev_timestamp $new_cmp " . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4190 ), __METHOD__,
4191 array( 'LIMIT' => $limit + 1 ) // add one so caller knows it was truncated
4192 );
4193 foreach ( $res as $row ) {
4194 $authors[] = $row->rev_user_text;
4195 }
4196 return $authors;
4197 }
4198
4199 /**
4200 * Get the number of authors between the given revisions or revision IDs.
4201 * Used for diffs and other things that really need it.
4202 *
4203 * @param int|Revision $old Old revision or rev ID (first before range by default)
4204 * @param int|Revision $new New revision or rev ID (first after range by default)
4205 * @param int $limit Maximum number of authors
4206 * @param string|array $options (Optional): Single option, or an array of options:
4207 * 'include_old' Include $old in the range; $new is excluded.
4208 * 'include_new' Include $new in the range; $old is excluded.
4209 * 'include_both' Include both $old and $new in the range.
4210 * Unknown option values are ignored.
4211 * @return int Number of revision authors in the range; zero if not both revisions exist
4212 */
4213 public function countAuthorsBetween( $old, $new, $limit, $options = array() ) {
4214 $authors = $this->getAuthorsBetween( $old, $new, $limit, $options );
4215 return $authors ? count( $authors ) : 0;
4216 }
4217
4218 /**
4219 * Compare with another title.
4220 *
4221 * @param Title $title
4222 * @return bool
4223 */
4224 public function equals( Title $title ) {
4225 // Note: === is necessary for proper matching of number-like titles.
4226 return $this->getInterwiki() === $title->getInterwiki()
4227 && $this->getNamespace() == $title->getNamespace()
4228 && $this->getDBkey() === $title->getDBkey();
4229 }
4230
4231 /**
4232 * Check if this title is a subpage of another title
4233 *
4234 * @param Title $title
4235 * @return bool
4236 */
4237 public function isSubpageOf( Title $title ) {
4238 return $this->getInterwiki() === $title->getInterwiki()
4239 && $this->getNamespace() == $title->getNamespace()
4240 && strpos( $this->getDBkey(), $title->getDBkey() . '/' ) === 0;
4241 }
4242
4243 /**
4244 * Check if page exists. For historical reasons, this function simply
4245 * checks for the existence of the title in the page table, and will
4246 * thus return false for interwiki links, special pages and the like.
4247 * If you want to know if a title can be meaningfully viewed, you should
4248 * probably call the isKnown() method instead.
4249 *
4250 * @param int $flags An optional bit field; may be Title::GAID_FOR_UPDATE to check
4251 * from master/for update
4252 * @return bool
4253 */
4254 public function exists( $flags = 0 ) {
4255 $exists = $this->getArticleID( $flags ) != 0;
4256 Hooks::run( 'TitleExists', array( $this, &$exists ) );
4257 return $exists;
4258 }
4259
4260 /**
4261 * Should links to this title be shown as potentially viewable (i.e. as
4262 * "bluelinks"), even if there's no record by this title in the page
4263 * table?
4264 *
4265 * This function is semi-deprecated for public use, as well as somewhat
4266 * misleadingly named. You probably just want to call isKnown(), which
4267 * calls this function internally.
4268 *
4269 * (ISSUE: Most of these checks are cheap, but the file existence check
4270 * can potentially be quite expensive. Including it here fixes a lot of
4271 * existing code, but we might want to add an optional parameter to skip
4272 * it and any other expensive checks.)
4273 *
4274 * @return bool
4275 */
4276 public function isAlwaysKnown() {
4277 $isKnown = null;
4278
4279 /**
4280 * Allows overriding default behavior for determining if a page exists.
4281 * If $isKnown is kept as null, regular checks happen. If it's
4282 * a boolean, this value is returned by the isKnown method.
4283 *
4284 * @since 1.20
4285 *
4286 * @param Title $title
4287 * @param bool|null $isKnown
4288 */
4289 Hooks::run( 'TitleIsAlwaysKnown', array( $this, &$isKnown ) );
4290
4291 if ( !is_null( $isKnown ) ) {
4292 return $isKnown;
4293 }
4294
4295 if ( $this->isExternal() ) {
4296 return true; // any interwiki link might be viewable, for all we know
4297 }
4298
4299 switch ( $this->mNamespace ) {
4300 case NS_MEDIA:
4301 case NS_FILE:
4302 // file exists, possibly in a foreign repo
4303 return (bool)wfFindFile( $this );
4304 case NS_SPECIAL:
4305 // valid special page
4306 return SpecialPageFactory::exists( $this->getDBkey() );
4307 case NS_MAIN:
4308 // selflink, possibly with fragment
4309 return $this->mDbkeyform == '';
4310 case NS_MEDIAWIKI:
4311 // known system message
4312 return $this->hasSourceText() !== false;
4313 default:
4314 return false;
4315 }
4316 }
4317
4318 /**
4319 * Does this title refer to a page that can (or might) be meaningfully
4320 * viewed? In particular, this function may be used to determine if
4321 * links to the title should be rendered as "bluelinks" (as opposed to
4322 * "redlinks" to non-existent pages).
4323 * Adding something else to this function will cause inconsistency
4324 * since LinkHolderArray calls isAlwaysKnown() and does its own
4325 * page existence check.
4326 *
4327 * @return bool
4328 */
4329 public function isKnown() {
4330 return $this->isAlwaysKnown() || $this->exists();
4331 }
4332
4333 /**
4334 * Does this page have source text?
4335 *
4336 * @return bool
4337 */
4338 public function hasSourceText() {
4339 if ( $this->exists() ) {
4340 return true;
4341 }
4342
4343 if ( $this->mNamespace == NS_MEDIAWIKI ) {
4344 // If the page doesn't exist but is a known system message, default
4345 // message content will be displayed, same for language subpages-
4346 // Use always content language to avoid loading hundreds of languages
4347 // to get the link color.
4348 global $wgContLang;
4349 list( $name, ) = MessageCache::singleton()->figureMessage(
4350 $wgContLang->lcfirst( $this->getText() )
4351 );
4352 $message = wfMessage( $name )->inLanguage( $wgContLang )->useDatabase( false );
4353 return $message->exists();
4354 }
4355
4356 return false;
4357 }
4358
4359 /**
4360 * Get the default message text or false if the message doesn't exist
4361 *
4362 * @return string|bool
4363 */
4364 public function getDefaultMessageText() {
4365 global $wgContLang;
4366
4367 if ( $this->getNamespace() != NS_MEDIAWIKI ) { // Just in case
4368 return false;
4369 }
4370
4371 list( $name, $lang ) = MessageCache::singleton()->figureMessage(
4372 $wgContLang->lcfirst( $this->getText() )
4373 );
4374 $message = wfMessage( $name )->inLanguage( $lang )->useDatabase( false );
4375
4376 if ( $message->exists() ) {
4377 return $message->plain();
4378 } else {
4379 return false;
4380 }
4381 }
4382
4383 /**
4384 * Updates page_touched for this page; called from LinksUpdate.php
4385 *
4386 * @param string $purgeTime [optional] TS_MW timestamp
4387 * @return bool True if the update succeeded
4388 */
4389 public function invalidateCache( $purgeTime = null ) {
4390 if ( wfReadOnly() ) {
4391 return false;
4392 }
4393
4394 if ( $this->mArticleID === 0 ) {
4395 return true; // avoid gap locking if we know it's not there
4396 }
4397
4398 $method = __METHOD__;
4399 $dbw = wfGetDB( DB_MASTER );
4400 $conds = $this->pageCond();
4401 $dbw->onTransactionIdle( function () use ( $dbw, $conds, $method, $purgeTime ) {
4402 $dbTimestamp = $dbw->timestamp( $purgeTime ?: time() );
4403
4404 $dbw->update(
4405 'page',
4406 array( 'page_touched' => $dbTimestamp ),
4407 $conds + array( 'page_touched < ' . $dbw->addQuotes( $dbTimestamp ) ),
4408 $method
4409 );
4410 } );
4411
4412 return true;
4413 }
4414
4415 /**
4416 * Update page_touched timestamps and send CDN purge messages for
4417 * pages linking to this title. May be sent to the job queue depending
4418 * on the number of links. Typically called on create and delete.
4419 */
4420 public function touchLinks() {
4421 DeferredUpdates::addUpdate( new HTMLCacheUpdate( $this, 'pagelinks' ) );
4422 if ( $this->getNamespace() == NS_CATEGORY ) {
4423 DeferredUpdates::addUpdate( new HTMLCacheUpdate( $this, 'categorylinks' ) );
4424 }
4425 }
4426
4427 /**
4428 * Get the last touched timestamp
4429 *
4430 * @param IDatabase $db Optional db
4431 * @return string Last-touched timestamp
4432 */
4433 public function getTouched( $db = null ) {
4434 if ( $db === null ) {
4435 $db = wfGetDB( DB_SLAVE );
4436 }
4437 $touched = $db->selectField( 'page', 'page_touched', $this->pageCond(), __METHOD__ );
4438 return $touched;
4439 }
4440
4441 /**
4442 * Get the timestamp when this page was updated since the user last saw it.
4443 *
4444 * @param User $user
4445 * @return string|null
4446 */
4447 public function getNotificationTimestamp( $user = null ) {
4448 global $wgUser;
4449
4450 // Assume current user if none given
4451 if ( !$user ) {
4452 $user = $wgUser;
4453 }
4454 // Check cache first
4455 $uid = $user->getId();
4456 if ( !$uid ) {
4457 return false;
4458 }
4459 // avoid isset here, as it'll return false for null entries
4460 if ( array_key_exists( $uid, $this->mNotificationTimestamp ) ) {
4461 return $this->mNotificationTimestamp[$uid];
4462 }
4463 // Don't cache too much!
4464 if ( count( $this->mNotificationTimestamp ) >= self::CACHE_MAX ) {
4465 $this->mNotificationTimestamp = array();
4466 }
4467
4468 $watchedItem = WatchedItem::fromUserTitle( $user, $this );
4469 $this->mNotificationTimestamp[$uid] = $watchedItem->getNotificationTimestamp();
4470
4471 return $this->mNotificationTimestamp[$uid];
4472 }
4473
4474 /**
4475 * Generate strings used for xml 'id' names in monobook tabs
4476 *
4477 * @param string $prepend Defaults to 'nstab-'
4478 * @return string XML 'id' name
4479 */
4480 public function getNamespaceKey( $prepend = 'nstab-' ) {
4481 global $wgContLang;
4482 // Gets the subject namespace if this title
4483 $namespace = MWNamespace::getSubject( $this->getNamespace() );
4484 // Checks if canonical namespace name exists for namespace
4485 if ( MWNamespace::exists( $this->getNamespace() ) ) {
4486 // Uses canonical namespace name
4487 $namespaceKey = MWNamespace::getCanonicalName( $namespace );
4488 } else {
4489 // Uses text of namespace
4490 $namespaceKey = $this->getSubjectNsText();
4491 }
4492 // Makes namespace key lowercase
4493 $namespaceKey = $wgContLang->lc( $namespaceKey );
4494 // Uses main
4495 if ( $namespaceKey == '' ) {
4496 $namespaceKey = 'main';
4497 }
4498 // Changes file to image for backwards compatibility
4499 if ( $namespaceKey == 'file' ) {
4500 $namespaceKey = 'image';
4501 }
4502 return $prepend . $namespaceKey;
4503 }
4504
4505 /**
4506 * Get all extant redirects to this Title
4507 *
4508 * @param int|null $ns Single namespace to consider; null to consider all namespaces
4509 * @return Title[] Array of Title redirects to this title
4510 */
4511 public function getRedirectsHere( $ns = null ) {
4512 $redirs = array();
4513
4514 $dbr = wfGetDB( DB_SLAVE );
4515 $where = array(
4516 'rd_namespace' => $this->getNamespace(),
4517 'rd_title' => $this->getDBkey(),
4518 'rd_from = page_id'
4519 );
4520 if ( $this->isExternal() ) {
4521 $where['rd_interwiki'] = $this->getInterwiki();
4522 } else {
4523 $where[] = 'rd_interwiki = ' . $dbr->addQuotes( '' ) . ' OR rd_interwiki IS NULL';
4524 }
4525 if ( !is_null( $ns ) ) {
4526 $where['page_namespace'] = $ns;
4527 }
4528
4529 $res = $dbr->select(
4530 array( 'redirect', 'page' ),
4531 array( 'page_namespace', 'page_title' ),
4532 $where,
4533 __METHOD__
4534 );
4535
4536 foreach ( $res as $row ) {
4537 $redirs[] = self::newFromRow( $row );
4538 }
4539 return $redirs;
4540 }
4541
4542 /**
4543 * Check if this Title is a valid redirect target
4544 *
4545 * @return bool
4546 */
4547 public function isValidRedirectTarget() {
4548 global $wgInvalidRedirectTargets;
4549
4550 if ( $this->isSpecialPage() ) {
4551 // invalid redirect targets are stored in a global array, but explicitly disallow Userlogout here
4552 if ( $this->isSpecial( 'Userlogout' ) ) {
4553 return false;
4554 }
4555
4556 foreach ( $wgInvalidRedirectTargets as $target ) {
4557 if ( $this->isSpecial( $target ) ) {
4558 return false;
4559 }
4560 }
4561 }
4562
4563 return true;
4564 }
4565
4566 /**
4567 * Get a backlink cache object
4568 *
4569 * @return BacklinkCache
4570 */
4571 public function getBacklinkCache() {
4572 return BacklinkCache::get( $this );
4573 }
4574
4575 /**
4576 * Whether the magic words __INDEX__ and __NOINDEX__ function for this page.
4577 *
4578 * @return bool
4579 */
4580 public function canUseNoindex() {
4581 global $wgContentNamespaces, $wgExemptFromUserRobotsControl;
4582
4583 $bannedNamespaces = is_null( $wgExemptFromUserRobotsControl )
4584 ? $wgContentNamespaces
4585 : $wgExemptFromUserRobotsControl;
4586
4587 return !in_array( $this->mNamespace, $bannedNamespaces );
4588
4589 }
4590
4591 /**
4592 * Returns the raw sort key to be used for categories, with the specified
4593 * prefix. This will be fed to Collation::getSortKey() to get a
4594 * binary sortkey that can be used for actual sorting.
4595 *
4596 * @param string $prefix The prefix to be used, specified using
4597 * {{defaultsort:}} or like [[Category:Foo|prefix]]. Empty for no
4598 * prefix.
4599 * @return string
4600 */
4601 public function getCategorySortkey( $prefix = '' ) {
4602 $unprefixed = $this->getText();
4603
4604 // Anything that uses this hook should only depend
4605 // on the Title object passed in, and should probably
4606 // tell the users to run updateCollations.php --force
4607 // in order to re-sort existing category relations.
4608 Hooks::run( 'GetDefaultSortkey', array( $this, &$unprefixed ) );
4609 if ( $prefix !== '' ) {
4610 # Separate with a line feed, so the unprefixed part is only used as
4611 # a tiebreaker when two pages have the exact same prefix.
4612 # In UCA, tab is the only character that can sort above LF
4613 # so we strip both of them from the original prefix.
4614 $prefix = strtr( $prefix, "\n\t", ' ' );
4615 return "$prefix\n$unprefixed";
4616 }
4617 return $unprefixed;
4618 }
4619
4620 /**
4621 * Get the language in which the content of this page is written in
4622 * wikitext. Defaults to $wgContLang, but in certain cases it can be
4623 * e.g. $wgLang (such as special pages, which are in the user language).
4624 *
4625 * @since 1.18
4626 * @return Language
4627 */
4628 public function getPageLanguage() {
4629 global $wgLang, $wgLanguageCode;
4630 if ( $this->isSpecialPage() ) {
4631 // special pages are in the user language
4632 return $wgLang;
4633 }
4634
4635 // Checking if DB language is set
4636 if ( $this->mDbPageLanguage ) {
4637 return wfGetLangObj( $this->mDbPageLanguage );
4638 }
4639
4640 if ( !$this->mPageLanguage || $this->mPageLanguage[1] !== $wgLanguageCode ) {
4641 // Note that this may depend on user settings, so the cache should
4642 // be only per-request.
4643 // NOTE: ContentHandler::getPageLanguage() may need to load the
4644 // content to determine the page language!
4645 // Checking $wgLanguageCode hasn't changed for the benefit of unit
4646 // tests.
4647 $contentHandler = ContentHandler::getForTitle( $this );
4648 $langObj = $contentHandler->getPageLanguage( $this );
4649 $this->mPageLanguage = array( $langObj->getCode(), $wgLanguageCode );
4650 } else {
4651 $langObj = wfGetLangObj( $this->mPageLanguage[0] );
4652 }
4653
4654 return $langObj;
4655 }
4656
4657 /**
4658 * Get the language in which the content of this page is written when
4659 * viewed by user. Defaults to $wgContLang, but in certain cases it can be
4660 * e.g. $wgLang (such as special pages, which are in the user language).
4661 *
4662 * @since 1.20
4663 * @return Language
4664 */
4665 public function getPageViewLanguage() {
4666 global $wgLang;
4667
4668 if ( $this->isSpecialPage() ) {
4669 // If the user chooses a variant, the content is actually
4670 // in a language whose code is the variant code.
4671 $variant = $wgLang->getPreferredVariant();
4672 if ( $wgLang->getCode() !== $variant ) {
4673 return Language::factory( $variant );
4674 }
4675
4676 return $wgLang;
4677 }
4678
4679 // @note Can't be cached persistently, depends on user settings.
4680 // @note ContentHandler::getPageViewLanguage() may need to load the
4681 // content to determine the page language!
4682 $contentHandler = ContentHandler::getForTitle( $this );
4683 $pageLang = $contentHandler->getPageViewLanguage( $this );
4684 return $pageLang;
4685 }
4686
4687 /**
4688 * Get a list of rendered edit notices for this page.
4689 *
4690 * Array is keyed by the original message key, and values are rendered using parseAsBlock, so
4691 * they will already be wrapped in paragraphs.
4692 *
4693 * @since 1.21
4694 * @param int $oldid Revision ID that's being edited
4695 * @return array
4696 */
4697 public function getEditNotices( $oldid = 0 ) {
4698 $notices = array();
4699
4700 // Optional notice for the entire namespace
4701 $editnotice_ns = 'editnotice-' . $this->getNamespace();
4702 $msg = wfMessage( $editnotice_ns );
4703 if ( $msg->exists() ) {
4704 $html = $msg->parseAsBlock();
4705 // Edit notices may have complex logic, but output nothing (T91715)
4706 if ( trim( $html ) !== '' ) {
4707 $notices[$editnotice_ns] = Html::rawElement(
4708 'div',
4709 array( 'class' => array(
4710 'mw-editnotice',
4711 'mw-editnotice-namespace',
4712 Sanitizer::escapeClass( "mw-$editnotice_ns" )
4713 ) ),
4714 $html
4715 );
4716 }
4717 }
4718
4719 if ( MWNamespace::hasSubpages( $this->getNamespace() ) ) {
4720 // Optional notice for page itself and any parent page
4721 $parts = explode( '/', $this->getDBkey() );
4722 $editnotice_base = $editnotice_ns;
4723 while ( count( $parts ) > 0 ) {
4724 $editnotice_base .= '-' . array_shift( $parts );
4725 $msg = wfMessage( $editnotice_base );
4726 if ( $msg->exists() ) {
4727 $html = $msg->parseAsBlock();
4728 if ( trim( $html ) !== '' ) {
4729 $notices[$editnotice_base] = Html::rawElement(
4730 'div',
4731 array( 'class' => array(
4732 'mw-editnotice',
4733 'mw-editnotice-base',
4734 Sanitizer::escapeClass( "mw-$editnotice_base" )
4735 ) ),
4736 $html
4737 );
4738 }
4739 }
4740 }
4741 } else {
4742 // Even if there are no subpages in namespace, we still don't want "/" in MediaWiki message keys
4743 $editnoticeText = $editnotice_ns . '-' . strtr( $this->getDBkey(), '/', '-' );
4744 $msg = wfMessage( $editnoticeText );
4745 if ( $msg->exists() ) {
4746 $html = $msg->parseAsBlock();
4747 if ( trim( $html ) !== '' ) {
4748 $notices[$editnoticeText] = Html::rawElement(
4749 'div',
4750 array( 'class' => array(
4751 'mw-editnotice',
4752 'mw-editnotice-page',
4753 Sanitizer::escapeClass( "mw-$editnoticeText" )
4754 ) ),
4755 $html
4756 );
4757 }
4758 }
4759 }
4760
4761 Hooks::run( 'TitleGetEditNotices', array( $this, $oldid, &$notices ) );
4762 return $notices;
4763 }
4764
4765 /**
4766 * @return array
4767 */
4768 public function __sleep() {
4769 return array(
4770 'mNamespace',
4771 'mDbkeyform',
4772 'mFragment',
4773 'mInterwiki',
4774 'mLocalInterwiki',
4775 'mUserCaseDBKey',
4776 'mDefaultNamespace',
4777 );
4778 }
4779
4780 public function __wakeup() {
4781 $this->mArticleID = ( $this->mNamespace >= 0 ) ? -1 : 0;
4782 $this->mUrlform = wfUrlencode( $this->mDbkeyform );
4783 $this->mTextform = strtr( $this->mDbkeyform, '_', ' ' );
4784 }
4785
4786 }