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