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