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