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