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