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