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