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