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