Removed deprecated Title::moveNoAuth function
[lhc/web/wiklou.git] / includes / Title.php
1 <?php
2 /**
3 * Representation of a title within %MediaWiki.
4 *
5 * See title.txt
6 *
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License along
18 * with this program; if not, write to the Free Software Foundation, Inc.,
19 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 * http://www.gnu.org/copyleft/gpl.html
21 *
22 * @file
23 */
24 use MediaWiki\Linker\LinkTarget;
25 use MediaWiki\Interwiki\InterwikiLookup;
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 private $mContentModel = false;
95
96 /**
97 * @var bool If a content model was forced via setContentModel()
98 * this will be true to avoid having other code paths reset it
99 */
100 private $mForcedContentModel = false;
101
102 /** @var int Estimated number of revisions; null of not loaded */
103 private $mEstimateRevisions;
104
105 /** @var array Array of groups allowed to edit this article */
106 public $mRestrictions = [];
107
108 /** @var string|bool */
109 protected $mOldRestrictions = false;
110
111 /** @var bool Cascade restrictions on this page to included templates and images? */
112 public $mCascadeRestriction;
113
114 /** Caching the results of getCascadeProtectionSources */
115 public $mCascadingRestrictions;
116
117 /** @var array When do the restrictions on this page expire? */
118 protected $mRestrictionsExpiry = [];
119
120 /** @var bool Are cascading restrictions in effect on this page? */
121 protected $mHasCascadingRestrictions;
122
123 /** @var array Where are the cascading restrictions coming from on this page? */
124 public $mCascadeSources;
125
126 /** @var bool Boolean for initialisation on demand */
127 public $mRestrictionsLoaded = false;
128
129 /** @var string Text form including namespace/interwiki, initialised on demand */
130 protected $mPrefixedText = null;
131
132 /** @var mixed Cached value for getTitleProtection (create protection) */
133 public $mTitleProtection;
134
135 /**
136 * @var int Namespace index when there is no namespace. Don't change the
137 * following default, NS_MAIN is hardcoded in several places. See bug 696.
138 * Zero except in {{transclusion}} tags.
139 */
140 public $mDefaultNamespace = NS_MAIN;
141
142 /** @var int The page length, 0 for special pages */
143 protected $mLength = -1;
144
145 /** @var null Is the article at this title a redirect? */
146 public $mRedirect = null;
147
148 /** @var array Associative array of user ID -> timestamp/false */
149 private $mNotificationTimestamp = [];
150
151 /** @var bool Whether a page has any subpages */
152 private $mHasSubpages;
153
154 /** @var bool The (string) language code of the page's language and content code. */
155 private $mPageLanguage = false;
156
157 /** @var string|bool|null The page language code from the database, null if not saved in
158 * the database or false if not loaded, yet. */
159 private $mDbPageLanguage = false;
160
161 /** @var TitleValue A corresponding TitleValue object */
162 private $mTitleValue = null;
163
164 /** @var bool Would deleting this page be a big deletion? */
165 private $mIsBigDeletion = null;
166 // @}
167
168 /**
169 * B/C kludge: provide a TitleParser for use by Title.
170 * Ideally, Title would have no methods that need this.
171 * Avoid usage of this singleton by using TitleValue
172 * and the associated services when possible.
173 *
174 * @return TitleFormatter
175 */
176 private static function getTitleFormatter() {
177 return MediaWikiServices::getInstance()->getTitleFormatter();
178 }
179
180 /**
181 * B/C kludge: provide an InterwikiLookup for use by Title.
182 * Ideally, Title would have no methods that need this.
183 * Avoid usage of this singleton by using TitleValue
184 * and the associated services when possible.
185 *
186 * @return InterwikiLookup
187 */
188 private static function getInterwikiLookup() {
189 return MediaWikiServices::getInstance()->getInterwikiLookup();
190 }
191
192 /**
193 * @access protected
194 */
195 function __construct() {
196 }
197
198 /**
199 * Create a new Title from a prefixed DB key
200 *
201 * @param string $key The database key, which has underscores
202 * instead of spaces, possibly including namespace and
203 * interwiki prefixes
204 * @return Title|null Title, or null on an error
205 */
206 public static function newFromDBkey( $key ) {
207 $t = new Title();
208 $t->mDbkeyform = $key;
209
210 try {
211 $t->secureAndSplit();
212 return $t;
213 } catch ( MalformedTitleException $ex ) {
214 return null;
215 }
216 }
217
218 /**
219 * Create a new Title from a TitleValue
220 *
221 * @param TitleValue $titleValue Assumed to be safe.
222 *
223 * @return Title
224 */
225 public static function newFromTitleValue( TitleValue $titleValue ) {
226 return self::newFromLinkTarget( $titleValue );
227 }
228
229 /**
230 * Create a new Title from a LinkTarget
231 *
232 * @param LinkTarget $linkTarget Assumed to be safe.
233 *
234 * @return Title
235 */
236 public static function newFromLinkTarget( LinkTarget $linkTarget ) {
237 if ( $linkTarget instanceof Title ) {
238 // Special case if it's already a Title object
239 return $linkTarget;
240 }
241 return self::makeTitle(
242 $linkTarget->getNamespace(),
243 $linkTarget->getText(),
244 $linkTarget->getFragment(),
245 $linkTarget->getInterwiki()
246 );
247 }
248
249 /**
250 * Create a new Title from text, such as what one would find in a link. De-
251 * codes any HTML entities in the text.
252 *
253 * @param string|int|null $text The link text; spaces, prefixes, and an
254 * initial ':' indicating the main namespace are accepted.
255 * @param int $defaultNamespace The namespace to use if none is specified
256 * by a prefix. If you want to force a specific namespace even if
257 * $text might begin with a namespace prefix, use makeTitle() or
258 * makeTitleSafe().
259 * @throws InvalidArgumentException
260 * @return Title|null Title or null on an error.
261 */
262 public static function newFromText( $text, $defaultNamespace = NS_MAIN ) {
263 // DWIM: Integers can be passed in here when page titles are used as array keys.
264 if ( $text !== null && !is_string( $text ) && !is_int( $text ) ) {
265 throw new InvalidArgumentException( '$text must be a string.' );
266 }
267 if ( $text === null ) {
268 return null;
269 }
270
271 try {
272 return Title::newFromTextThrow( strval( $text ), $defaultNamespace );
273 } catch ( MalformedTitleException $ex ) {
274 return null;
275 }
276 }
277
278 /**
279 * Like Title::newFromText(), but throws MalformedTitleException when the title is invalid,
280 * rather than returning null.
281 *
282 * The exception subclasses encode detailed information about why the title is invalid.
283 *
284 * @see Title::newFromText
285 *
286 * @since 1.25
287 * @param string $text Title text to check
288 * @param int $defaultNamespace
289 * @throws MalformedTitleException If the title is invalid
290 * @return Title
291 */
292 public static function newFromTextThrow( $text, $defaultNamespace = NS_MAIN ) {
293 if ( is_object( $text ) ) {
294 throw new MWException( '$text must be a string, given an object' );
295 }
296
297 $titleCache = self::getTitleCache();
298
299 // Wiki pages often contain multiple links to the same page.
300 // Title normalization and parsing can become expensive on pages with many
301 // links, so we can save a little time by caching them.
302 // In theory these are value objects and won't get changed...
303 if ( $defaultNamespace == NS_MAIN ) {
304 $t = $titleCache->get( $text );
305 if ( $t ) {
306 return $t;
307 }
308 }
309
310 // Convert things like &eacute; &#257; or &#x3017; into normalized (bug 14952) text
311 $filteredText = Sanitizer::decodeCharReferencesAndNormalize( $text );
312
313 $t = new Title();
314 $t->mDbkeyform = strtr( $filteredText, ' ', '_' );
315 $t->mDefaultNamespace = intval( $defaultNamespace );
316
317 $t->secureAndSplit();
318 if ( $defaultNamespace == NS_MAIN ) {
319 $titleCache->set( $text, $t );
320 }
321 return $t;
322 }
323
324 /**
325 * THIS IS NOT THE FUNCTION YOU WANT. Use Title::newFromText().
326 *
327 * Example of wrong and broken code:
328 * $title = Title::newFromURL( $wgRequest->getVal( 'title' ) );
329 *
330 * Example of right code:
331 * $title = Title::newFromText( $wgRequest->getVal( 'title' ) );
332 *
333 * Create a new Title from URL-encoded text. Ensures that
334 * the given title's length does not exceed the maximum.
335 *
336 * @param string $url The title, as might be taken from a URL
337 * @return Title|null The new object, or null on an error
338 */
339 public static function newFromURL( $url ) {
340 $t = new Title();
341
342 # For compatibility with old buggy URLs. "+" is usually not valid in titles,
343 # but some URLs used it as a space replacement and they still come
344 # from some external search tools.
345 if ( strpos( self::legalChars(), '+' ) === false ) {
346 $url = strtr( $url, '+', ' ' );
347 }
348
349 $t->mDbkeyform = strtr( $url, ' ', '_' );
350
351 try {
352 $t->secureAndSplit();
353 return $t;
354 } catch ( MalformedTitleException $ex ) {
355 return null;
356 }
357 }
358
359 /**
360 * @return HashBagOStuff
361 */
362 private static function getTitleCache() {
363 if ( self::$titleCache == null ) {
364 self::$titleCache = new HashBagOStuff( [ 'maxKeys' => self::CACHE_MAX ] );
365 }
366 return self::$titleCache;
367 }
368
369 /**
370 * Returns a list of fields that are to be selected for initializing Title
371 * objects or LinkCache entries. Uses $wgContentHandlerUseDB to determine
372 * whether to include page_content_model.
373 *
374 * @return array
375 */
376 protected static function getSelectFields() {
377 global $wgContentHandlerUseDB, $wgPageLanguageUseDB;
378
379 $fields = [
380 'page_namespace', 'page_title', 'page_id',
381 'page_len', 'page_is_redirect', 'page_latest',
382 ];
383
384 if ( $wgContentHandlerUseDB ) {
385 $fields[] = 'page_content_model';
386 }
387
388 if ( $wgPageLanguageUseDB ) {
389 $fields[] = 'page_lang';
390 }
391
392 return $fields;
393 }
394
395 /**
396 * Create a new Title from an article ID
397 *
398 * @param int $id The page_id corresponding to the Title to create
399 * @param int $flags Use Title::GAID_FOR_UPDATE to use master
400 * @return Title|null The new object, or null on an error
401 */
402 public static function newFromID( $id, $flags = 0 ) {
403 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_REPLICA );
404 $row = $db->selectRow(
405 'page',
406 self::getSelectFields(),
407 [ 'page_id' => $id ],
408 __METHOD__
409 );
410 if ( $row !== false ) {
411 $title = Title::newFromRow( $row );
412 } else {
413 $title = null;
414 }
415 return $title;
416 }
417
418 /**
419 * Make an array of titles from an array of IDs
420 *
421 * @param int[] $ids Array of IDs
422 * @return Title[] Array of Titles
423 */
424 public static function newFromIDs( $ids ) {
425 if ( !count( $ids ) ) {
426 return [];
427 }
428 $dbr = wfGetDB( DB_REPLICA );
429
430 $res = $dbr->select(
431 'page',
432 self::getSelectFields(),
433 [ 'page_id' => $ids ],
434 __METHOD__
435 );
436
437 $titles = [];
438 foreach ( $res as $row ) {
439 $titles[] = Title::newFromRow( $row );
440 }
441 return $titles;
442 }
443
444 /**
445 * Make a Title object from a DB row
446 *
447 * @param stdClass $row Object database row (needs at least page_title,page_namespace)
448 * @return Title Corresponding Title
449 */
450 public static function newFromRow( $row ) {
451 $t = self::makeTitle( $row->page_namespace, $row->page_title );
452 $t->loadFromRow( $row );
453 return $t;
454 }
455
456 /**
457 * Load Title object fields from a DB row.
458 * If false is given, the title will be treated as non-existing.
459 *
460 * @param stdClass|bool $row Database row
461 */
462 public function loadFromRow( $row ) {
463 if ( $row ) { // page found
464 if ( isset( $row->page_id ) ) {
465 $this->mArticleID = (int)$row->page_id;
466 }
467 if ( isset( $row->page_len ) ) {
468 $this->mLength = (int)$row->page_len;
469 }
470 if ( isset( $row->page_is_redirect ) ) {
471 $this->mRedirect = (bool)$row->page_is_redirect;
472 }
473 if ( isset( $row->page_latest ) ) {
474 $this->mLatestID = (int)$row->page_latest;
475 }
476 if ( !$this->mForcedContentModel && isset( $row->page_content_model ) ) {
477 $this->mContentModel = strval( $row->page_content_model );
478 } elseif ( !$this->mForcedContentModel ) {
479 $this->mContentModel = false; # initialized lazily in getContentModel()
480 }
481 if ( isset( $row->page_lang ) ) {
482 $this->mDbPageLanguage = (string)$row->page_lang;
483 }
484 if ( isset( $row->page_restrictions ) ) {
485 $this->mOldRestrictions = $row->page_restrictions;
486 }
487 } else { // page not found
488 $this->mArticleID = 0;
489 $this->mLength = 0;
490 $this->mRedirect = false;
491 $this->mLatestID = 0;
492 if ( !$this->mForcedContentModel ) {
493 $this->mContentModel = false; # initialized lazily in getContentModel()
494 }
495 }
496 }
497
498 /**
499 * Create a new Title from a namespace index and a DB key.
500 * It's assumed that $ns and $title are *valid*, for instance when
501 * they came directly from the database or a special page name.
502 * For convenience, spaces are converted to underscores so that
503 * eg user_text fields can be used directly.
504 *
505 * @param int $ns The namespace of the article
506 * @param string $title The unprefixed database key form
507 * @param string $fragment The link fragment (after the "#")
508 * @param string $interwiki The interwiki prefix
509 * @return Title The new object
510 */
511 public static function makeTitle( $ns, $title, $fragment = '', $interwiki = '' ) {
512 $t = new Title();
513 $t->mInterwiki = $interwiki;
514 $t->mFragment = $fragment;
515 $t->mNamespace = $ns = intval( $ns );
516 $t->mDbkeyform = strtr( $title, ' ', '_' );
517 $t->mArticleID = ( $ns >= 0 ) ? -1 : 0;
518 $t->mUrlform = wfUrlencode( $t->mDbkeyform );
519 $t->mTextform = strtr( $title, '_', ' ' );
520 $t->mContentModel = false; # initialized lazily in getContentModel()
521 return $t;
522 }
523
524 /**
525 * Create a new Title from a namespace index and a DB key.
526 * The parameters will be checked for validity, which is a bit slower
527 * than makeTitle() but safer for user-provided data.
528 *
529 * @param int $ns The namespace of the article
530 * @param string $title Database key form
531 * @param string $fragment The link fragment (after the "#")
532 * @param string $interwiki Interwiki prefix
533 * @return Title|null The new object, or null on an error
534 */
535 public static function makeTitleSafe( $ns, $title, $fragment = '', $interwiki = '' ) {
536 if ( !MWNamespace::exists( $ns ) ) {
537 return null;
538 }
539
540 $t = new Title();
541 $t->mDbkeyform = Title::makeName( $ns, $title, $fragment, $interwiki, true );
542
543 try {
544 $t->secureAndSplit();
545 return $t;
546 } catch ( MalformedTitleException $ex ) {
547 return null;
548 }
549 }
550
551 /**
552 * Create a new Title for the Main Page
553 *
554 * @return Title The new object
555 */
556 public static function newMainPage() {
557 $title = Title::newFromText( wfMessage( 'mainpage' )->inContentLanguage()->text() );
558 // Don't give fatal errors if the message is broken
559 if ( !$title ) {
560 $title = Title::newFromText( 'Main Page' );
561 }
562 return $title;
563 }
564
565 /**
566 * Get the prefixed DB key associated with an ID
567 *
568 * @param int $id The page_id of the article
569 * @return Title|null An object representing the article, or null if no such article was found
570 */
571 public static function nameOf( $id ) {
572 $dbr = wfGetDB( DB_REPLICA );
573
574 $s = $dbr->selectRow(
575 'page',
576 [ 'page_namespace', 'page_title' ],
577 [ 'page_id' => $id ],
578 __METHOD__
579 );
580 if ( $s === false ) {
581 return null;
582 }
583
584 $n = self::makeName( $s->page_namespace, $s->page_title );
585 return $n;
586 }
587
588 /**
589 * Get a regex character class describing the legal characters in a link
590 *
591 * @return string The list of characters, not delimited
592 */
593 public static function legalChars() {
594 global $wgLegalTitleChars;
595 return $wgLegalTitleChars;
596 }
597
598 /**
599 * Returns a simple regex that will match on characters and sequences invalid in titles.
600 * Note that this doesn't pick up many things that could be wrong with titles, but that
601 * replacing this regex with something valid will make many titles valid.
602 *
603 * @deprecated since 1.25, use MediaWikiTitleCodec::getTitleInvalidRegex() instead
604 *
605 * @return string Regex string
606 */
607 static function getTitleInvalidRegex() {
608 wfDeprecated( __METHOD__, '1.25' );
609 return MediaWikiTitleCodec::getTitleInvalidRegex();
610 }
611
612 /**
613 * Utility method for converting a character sequence from bytes to Unicode.
614 *
615 * Primary usecase being converting $wgLegalTitleChars to a sequence usable in
616 * javascript, as PHP uses UTF-8 bytes where javascript uses Unicode code units.
617 *
618 * @param string $byteClass
619 * @return string
620 */
621 public static function convertByteClassToUnicodeClass( $byteClass ) {
622 $length = strlen( $byteClass );
623 // Input token queue
624 $x0 = $x1 = $x2 = '';
625 // Decoded queue
626 $d0 = $d1 = $d2 = '';
627 // Decoded integer codepoints
628 $ord0 = $ord1 = $ord2 = 0;
629 // Re-encoded queue
630 $r0 = $r1 = $r2 = '';
631 // Output
632 $out = '';
633 // Flags
634 $allowUnicode = false;
635 for ( $pos = 0; $pos < $length; $pos++ ) {
636 // Shift the queues down
637 $x2 = $x1;
638 $x1 = $x0;
639 $d2 = $d1;
640 $d1 = $d0;
641 $ord2 = $ord1;
642 $ord1 = $ord0;
643 $r2 = $r1;
644 $r1 = $r0;
645 // Load the current input token and decoded values
646 $inChar = $byteClass[$pos];
647 if ( $inChar == '\\' ) {
648 if ( preg_match( '/x([0-9a-fA-F]{2})/A', $byteClass, $m, 0, $pos + 1 ) ) {
649 $x0 = $inChar . $m[0];
650 $d0 = chr( hexdec( $m[1] ) );
651 $pos += strlen( $m[0] );
652 } elseif ( preg_match( '/[0-7]{3}/A', $byteClass, $m, 0, $pos + 1 ) ) {
653 $x0 = $inChar . $m[0];
654 $d0 = chr( octdec( $m[0] ) );
655 $pos += strlen( $m[0] );
656 } elseif ( $pos + 1 >= $length ) {
657 $x0 = $d0 = '\\';
658 } else {
659 $d0 = $byteClass[$pos + 1];
660 $x0 = $inChar . $d0;
661 $pos += 1;
662 }
663 } else {
664 $x0 = $d0 = $inChar;
665 }
666 $ord0 = ord( $d0 );
667 // Load the current re-encoded value
668 if ( $ord0 < 32 || $ord0 == 0x7f ) {
669 $r0 = sprintf( '\x%02x', $ord0 );
670 } elseif ( $ord0 >= 0x80 ) {
671 // Allow unicode if a single high-bit character appears
672 $r0 = sprintf( '\x%02x', $ord0 );
673 $allowUnicode = true;
674 } elseif ( strpos( '-\\[]^', $d0 ) !== false ) {
675 $r0 = '\\' . $d0;
676 } else {
677 $r0 = $d0;
678 }
679 // Do the output
680 if ( $x0 !== '' && $x1 === '-' && $x2 !== '' ) {
681 // Range
682 if ( $ord2 > $ord0 ) {
683 // Empty range
684 } elseif ( $ord0 >= 0x80 ) {
685 // Unicode range
686 $allowUnicode = true;
687 if ( $ord2 < 0x80 ) {
688 // Keep the non-unicode section of the range
689 $out .= "$r2-\\x7F";
690 }
691 } else {
692 // Normal range
693 $out .= "$r2-$r0";
694 }
695 // Reset state to the initial value
696 $x0 = $x1 = $d0 = $d1 = $r0 = $r1 = '';
697 } elseif ( $ord2 < 0x80 ) {
698 // ASCII character
699 $out .= $r2;
700 }
701 }
702 if ( $ord1 < 0x80 ) {
703 $out .= $r1;
704 }
705 if ( $ord0 < 0x80 ) {
706 $out .= $r0;
707 }
708 if ( $allowUnicode ) {
709 $out .= '\u0080-\uFFFF';
710 }
711 return $out;
712 }
713
714 /**
715 * Make a prefixed DB key from a DB key and a namespace index
716 *
717 * @param int $ns Numerical representation of the namespace
718 * @param string $title The DB key form the title
719 * @param string $fragment The link fragment (after the "#")
720 * @param string $interwiki The interwiki prefix
721 * @param bool $canonicalNamespace If true, use the canonical name for
722 * $ns instead of the localized version.
723 * @return string The prefixed form of the title
724 */
725 public static function makeName( $ns, $title, $fragment = '', $interwiki = '',
726 $canonicalNamespace = false
727 ) {
728 global $wgContLang;
729
730 if ( $canonicalNamespace ) {
731 $namespace = MWNamespace::getCanonicalName( $ns );
732 } else {
733 $namespace = $wgContLang->getNsText( $ns );
734 }
735 $name = $namespace == '' ? $title : "$namespace:$title";
736 if ( strval( $interwiki ) != '' ) {
737 $name = "$interwiki:$name";
738 }
739 if ( strval( $fragment ) != '' ) {
740 $name .= '#' . $fragment;
741 }
742 return $name;
743 }
744
745 /**
746 * Escape a text fragment, say from a link, for a URL
747 *
748 * @param string $fragment Containing a URL or link fragment (after the "#")
749 * @return string Escaped string
750 */
751 static function escapeFragmentForURL( $fragment ) {
752 # Note that we don't urlencode the fragment. urlencoded Unicode
753 # fragments appear not to work in IE (at least up to 7) or in at least
754 # one version of Opera 9.x. The W3C validator, for one, doesn't seem
755 # to care if they aren't encoded.
756 return Sanitizer::escapeId( $fragment, 'noninitial' );
757 }
758
759 /**
760 * Callback for usort() to do title sorts by (namespace, title)
761 *
762 * @param LinkTarget $a
763 * @param LinkTarget $b
764 *
765 * @return int Result of string comparison, or namespace comparison
766 */
767 public static function compare( LinkTarget $a, LinkTarget $b ) {
768 if ( $a->getNamespace() == $b->getNamespace() ) {
769 return strcmp( $a->getText(), $b->getText() );
770 } else {
771 return $a->getNamespace() - $b->getNamespace();
772 }
773 }
774
775 /**
776 * Determine whether the object refers to a page within
777 * this project (either this wiki or a wiki with a local
778 * interwiki, see https://www.mediawiki.org/wiki/Manual:Interwiki_table#iw_local )
779 *
780 * @return bool True if this is an in-project interwiki link or a wikilink, false otherwise
781 */
782 public function isLocal() {
783 if ( $this->isExternal() ) {
784 $iw = self::getInterwikiLookup()->fetch( $this->mInterwiki );
785 if ( $iw ) {
786 return $iw->isLocal();
787 }
788 }
789 return true;
790 }
791
792 /**
793 * Is this Title interwiki?
794 *
795 * @return bool
796 */
797 public function isExternal() {
798 return $this->mInterwiki !== '';
799 }
800
801 /**
802 * Get the interwiki prefix
803 *
804 * Use Title::isExternal to check if a interwiki is set
805 *
806 * @return string Interwiki prefix
807 */
808 public function getInterwiki() {
809 return $this->mInterwiki;
810 }
811
812 /**
813 * Was this a local interwiki link?
814 *
815 * @return bool
816 */
817 public function wasLocalInterwiki() {
818 return $this->mLocalInterwiki;
819 }
820
821 /**
822 * Determine whether the object refers to a page within
823 * this project and is transcludable.
824 *
825 * @return bool True if this is transcludable
826 */
827 public function isTrans() {
828 if ( !$this->isExternal() ) {
829 return false;
830 }
831
832 return self::getInterwikiLookup()->fetch( $this->mInterwiki )->isTranscludable();
833 }
834
835 /**
836 * Returns the DB name of the distant wiki which owns the object.
837 *
838 * @return string|false The DB name
839 */
840 public function getTransWikiID() {
841 if ( !$this->isExternal() ) {
842 return false;
843 }
844
845 return self::getInterwikiLookup()->fetch( $this->mInterwiki )->getWikiID();
846 }
847
848 /**
849 * Get a TitleValue object representing this Title.
850 *
851 * @note Not all valid Titles have a corresponding valid TitleValue
852 * (e.g. TitleValues cannot represent page-local links that have a
853 * fragment but no title text).
854 *
855 * @return TitleValue|null
856 */
857 public function getTitleValue() {
858 if ( $this->mTitleValue === null ) {
859 try {
860 $this->mTitleValue = new TitleValue(
861 $this->getNamespace(),
862 $this->getDBkey(),
863 $this->getFragment(),
864 $this->getInterwiki()
865 );
866 } catch ( InvalidArgumentException $ex ) {
867 wfDebug( __METHOD__ . ': Can\'t create a TitleValue for [[' .
868 $this->getPrefixedText() . ']]: ' . $ex->getMessage() . "\n" );
869 }
870 }
871
872 return $this->mTitleValue;
873 }
874
875 /**
876 * Get the text form (spaces not underscores) of the main part
877 *
878 * @return string Main part of the title
879 */
880 public function getText() {
881 return $this->mTextform;
882 }
883
884 /**
885 * Get the URL-encoded form of the main part
886 *
887 * @return string Main part of the title, URL-encoded
888 */
889 public function getPartialURL() {
890 return $this->mUrlform;
891 }
892
893 /**
894 * Get the main part with underscores
895 *
896 * @return string Main part of the title, with underscores
897 */
898 public function getDBkey() {
899 return $this->mDbkeyform;
900 }
901
902 /**
903 * Get the DB key with the initial letter case as specified by the user
904 *
905 * @return string DB key
906 */
907 function getUserCaseDBKey() {
908 if ( !is_null( $this->mUserCaseDBKey ) ) {
909 return $this->mUserCaseDBKey;
910 } else {
911 // If created via makeTitle(), $this->mUserCaseDBKey is not set.
912 return $this->mDbkeyform;
913 }
914 }
915
916 /**
917 * Get the namespace index, i.e. one of the NS_xxxx constants.
918 *
919 * @return int Namespace index
920 */
921 public function getNamespace() {
922 return $this->mNamespace;
923 }
924
925 /**
926 * Get the page's content model id, see the CONTENT_MODEL_XXX constants.
927 *
928 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
929 * @return string Content model id
930 */
931 public function getContentModel( $flags = 0 ) {
932 if ( !$this->mForcedContentModel
933 && ( !$this->mContentModel || $flags === Title::GAID_FOR_UPDATE )
934 && $this->getArticleID( $flags )
935 ) {
936 $linkCache = LinkCache::singleton();
937 $linkCache->addLinkObj( $this ); # in case we already had an article ID
938 $this->mContentModel = $linkCache->getGoodLinkFieldObj( $this, 'model' );
939 }
940
941 if ( !$this->mContentModel ) {
942 $this->mContentModel = ContentHandler::getDefaultModelFor( $this );
943 }
944
945 return $this->mContentModel;
946 }
947
948 /**
949 * Convenience method for checking a title's content model name
950 *
951 * @param string $id The content model ID (use the CONTENT_MODEL_XXX constants).
952 * @return bool True if $this->getContentModel() == $id
953 */
954 public function hasContentModel( $id ) {
955 return $this->getContentModel() == $id;
956 }
957
958 /**
959 * Set a proposed content model for the page for permissions
960 * checking. This does not actually change the content model
961 * of a title!
962 *
963 * Additionally, you should make sure you've checked
964 * ContentHandler::canBeUsedOn() first.
965 *
966 * @since 1.28
967 * @param string $model CONTENT_MODEL_XXX constant
968 */
969 public function setContentModel( $model ) {
970 $this->mContentModel = $model;
971 $this->mForcedContentModel = true;
972 }
973
974 /**
975 * Get the namespace text
976 *
977 * @return string|false Namespace text
978 */
979 public function getNsText() {
980 if ( $this->isExternal() ) {
981 // This probably shouldn't even happen,
982 // but for interwiki transclusion it sometimes does.
983 // Use the canonical namespaces if possible to try to
984 // resolve a foreign namespace.
985 if ( MWNamespace::exists( $this->mNamespace ) ) {
986 return MWNamespace::getCanonicalName( $this->mNamespace );
987 }
988 }
989
990 try {
991 $formatter = self::getTitleFormatter();
992 return $formatter->getNamespaceName( $this->mNamespace, $this->mDbkeyform );
993 } catch ( InvalidArgumentException $ex ) {
994 wfDebug( __METHOD__ . ': ' . $ex->getMessage() . "\n" );
995 return false;
996 }
997 }
998
999 /**
1000 * Get the namespace text of the subject (rather than talk) page
1001 *
1002 * @return string Namespace text
1003 */
1004 public function getSubjectNsText() {
1005 global $wgContLang;
1006 return $wgContLang->getNsText( MWNamespace::getSubject( $this->mNamespace ) );
1007 }
1008
1009 /**
1010 * Get the namespace text of the talk page
1011 *
1012 * @return string Namespace text
1013 */
1014 public function getTalkNsText() {
1015 global $wgContLang;
1016 return $wgContLang->getNsText( MWNamespace::getTalk( $this->mNamespace ) );
1017 }
1018
1019 /**
1020 * Could this title have a corresponding talk page?
1021 *
1022 * @return bool
1023 */
1024 public function canTalk() {
1025 return MWNamespace::canTalk( $this->mNamespace );
1026 }
1027
1028 /**
1029 * Is this in a namespace that allows actual pages?
1030 *
1031 * @return bool
1032 */
1033 public function canExist() {
1034 return $this->mNamespace >= NS_MAIN;
1035 }
1036
1037 /**
1038 * Can this title be added to a user's watchlist?
1039 *
1040 * @return bool
1041 */
1042 public function isWatchable() {
1043 return !$this->isExternal() && MWNamespace::isWatchable( $this->getNamespace() );
1044 }
1045
1046 /**
1047 * Returns true if this is a special page.
1048 *
1049 * @return bool
1050 */
1051 public function isSpecialPage() {
1052 return $this->getNamespace() == NS_SPECIAL;
1053 }
1054
1055 /**
1056 * Returns true if this title resolves to the named special page
1057 *
1058 * @param string $name The special page name
1059 * @return bool
1060 */
1061 public function isSpecial( $name ) {
1062 if ( $this->isSpecialPage() ) {
1063 list( $thisName, /* $subpage */ ) = SpecialPageFactory::resolveAlias( $this->getDBkey() );
1064 if ( $name == $thisName ) {
1065 return true;
1066 }
1067 }
1068 return false;
1069 }
1070
1071 /**
1072 * If the Title refers to a special page alias which is not the local default, resolve
1073 * the alias, and localise the name as necessary. Otherwise, return $this
1074 *
1075 * @return Title
1076 */
1077 public function fixSpecialName() {
1078 if ( $this->isSpecialPage() ) {
1079 list( $canonicalName, $par ) = SpecialPageFactory::resolveAlias( $this->mDbkeyform );
1080 if ( $canonicalName ) {
1081 $localName = SpecialPageFactory::getLocalNameFor( $canonicalName, $par );
1082 if ( $localName != $this->mDbkeyform ) {
1083 return Title::makeTitle( NS_SPECIAL, $localName );
1084 }
1085 }
1086 }
1087 return $this;
1088 }
1089
1090 /**
1091 * Returns true if the title is inside the specified namespace.
1092 *
1093 * Please make use of this instead of comparing to getNamespace()
1094 * This function is much more resistant to changes we may make
1095 * to namespaces than code that makes direct comparisons.
1096 * @param int $ns The namespace
1097 * @return bool
1098 * @since 1.19
1099 */
1100 public function inNamespace( $ns ) {
1101 return MWNamespace::equals( $this->getNamespace(), $ns );
1102 }
1103
1104 /**
1105 * Returns true if the title is inside one of the specified namespaces.
1106 *
1107 * @param int|int[] $namespaces,... The namespaces to check for
1108 * @return bool
1109 * @since 1.19
1110 */
1111 public function inNamespaces( /* ... */ ) {
1112 $namespaces = func_get_args();
1113 if ( count( $namespaces ) > 0 && is_array( $namespaces[0] ) ) {
1114 $namespaces = $namespaces[0];
1115 }
1116
1117 foreach ( $namespaces as $ns ) {
1118 if ( $this->inNamespace( $ns ) ) {
1119 return true;
1120 }
1121 }
1122
1123 return false;
1124 }
1125
1126 /**
1127 * Returns true if the title has the same subject namespace as the
1128 * namespace specified.
1129 * For example this method will take NS_USER and return true if namespace
1130 * is either NS_USER or NS_USER_TALK since both of them have NS_USER
1131 * as their subject namespace.
1132 *
1133 * This is MUCH simpler than individually testing for equivalence
1134 * against both NS_USER and NS_USER_TALK, and is also forward compatible.
1135 * @since 1.19
1136 * @param int $ns
1137 * @return bool
1138 */
1139 public function hasSubjectNamespace( $ns ) {
1140 return MWNamespace::subjectEquals( $this->getNamespace(), $ns );
1141 }
1142
1143 /**
1144 * Is this Title in a namespace which contains content?
1145 * In other words, is this a content page, for the purposes of calculating
1146 * statistics, etc?
1147 *
1148 * @return bool
1149 */
1150 public function isContentPage() {
1151 return MWNamespace::isContent( $this->getNamespace() );
1152 }
1153
1154 /**
1155 * Would anybody with sufficient privileges be able to move this page?
1156 * Some pages just aren't movable.
1157 *
1158 * @return bool
1159 */
1160 public function isMovable() {
1161 if ( !MWNamespace::isMovable( $this->getNamespace() ) || $this->isExternal() ) {
1162 // Interwiki title or immovable namespace. Hooks don't get to override here
1163 return false;
1164 }
1165
1166 $result = true;
1167 Hooks::run( 'TitleIsMovable', [ $this, &$result ] );
1168 return $result;
1169 }
1170
1171 /**
1172 * Is this the mainpage?
1173 * @note Title::newFromText seems to be sufficiently optimized by the title
1174 * cache that we don't need to over-optimize by doing direct comparisons and
1175 * accidentally creating new bugs where $title->equals( Title::newFromText() )
1176 * ends up reporting something differently than $title->isMainPage();
1177 *
1178 * @since 1.18
1179 * @return bool
1180 */
1181 public function isMainPage() {
1182 return $this->equals( Title::newMainPage() );
1183 }
1184
1185 /**
1186 * Is this a subpage?
1187 *
1188 * @return bool
1189 */
1190 public function isSubpage() {
1191 return MWNamespace::hasSubpages( $this->mNamespace )
1192 ? strpos( $this->getText(), '/' ) !== false
1193 : false;
1194 }
1195
1196 /**
1197 * Is this a conversion table for the LanguageConverter?
1198 *
1199 * @return bool
1200 */
1201 public function isConversionTable() {
1202 // @todo ConversionTable should become a separate content model.
1203
1204 return $this->getNamespace() == NS_MEDIAWIKI &&
1205 strpos( $this->getText(), 'Conversiontable/' ) === 0;
1206 }
1207
1208 /**
1209 * Does that page contain wikitext, or it is JS, CSS or whatever?
1210 *
1211 * @return bool
1212 */
1213 public function isWikitextPage() {
1214 return $this->hasContentModel( CONTENT_MODEL_WIKITEXT );
1215 }
1216
1217 /**
1218 * Could this page contain custom CSS or JavaScript for the global UI.
1219 * This is generally true for pages in the MediaWiki namespace having CONTENT_MODEL_CSS
1220 * or CONTENT_MODEL_JAVASCRIPT.
1221 *
1222 * This method does *not* return true for per-user JS/CSS. Use isCssJsSubpage()
1223 * for that!
1224 *
1225 * Note that this method should not return true for pages that contain and
1226 * show "inactive" CSS or JS.
1227 *
1228 * @return bool
1229 * @todo FIXME: Rename to isSiteConfigPage() and remove deprecated hook
1230 */
1231 public function isCssOrJsPage() {
1232 $isCssOrJsPage = NS_MEDIAWIKI == $this->mNamespace
1233 && ( $this->hasContentModel( CONTENT_MODEL_CSS )
1234 || $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT ) );
1235
1236 # @note This hook is also called in ContentHandler::getDefaultModel.
1237 # It's called here again to make sure hook functions can force this
1238 # method to return true even outside the MediaWiki namespace.
1239
1240 Hooks::run( 'TitleIsCssOrJsPage', [ $this, &$isCssOrJsPage ], '1.25' );
1241
1242 return $isCssOrJsPage;
1243 }
1244
1245 /**
1246 * Is this a .css or .js subpage of a user page?
1247 * @return bool
1248 * @todo FIXME: Rename to isUserConfigPage()
1249 */
1250 public function isCssJsSubpage() {
1251 return ( NS_USER == $this->mNamespace && $this->isSubpage()
1252 && ( $this->hasContentModel( CONTENT_MODEL_CSS )
1253 || $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT ) ) );
1254 }
1255
1256 /**
1257 * Trim down a .css or .js subpage title to get the corresponding skin name
1258 *
1259 * @return string Containing skin name from .css or .js subpage title
1260 */
1261 public function getSkinFromCssJsSubpage() {
1262 $subpage = explode( '/', $this->mTextform );
1263 $subpage = $subpage[count( $subpage ) - 1];
1264 $lastdot = strrpos( $subpage, '.' );
1265 if ( $lastdot === false ) {
1266 return $subpage; # Never happens: only called for names ending in '.css' or '.js'
1267 }
1268 return substr( $subpage, 0, $lastdot );
1269 }
1270
1271 /**
1272 * Is this a .css subpage of a user page?
1273 *
1274 * @return bool
1275 */
1276 public function isCssSubpage() {
1277 return ( NS_USER == $this->mNamespace && $this->isSubpage()
1278 && $this->hasContentModel( CONTENT_MODEL_CSS ) );
1279 }
1280
1281 /**
1282 * Is this a .js subpage of a user page?
1283 *
1284 * @return bool
1285 */
1286 public function isJsSubpage() {
1287 return ( NS_USER == $this->mNamespace && $this->isSubpage()
1288 && $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT ) );
1289 }
1290
1291 /**
1292 * Is this a talk page of some sort?
1293 *
1294 * @return bool
1295 */
1296 public function isTalkPage() {
1297 return MWNamespace::isTalk( $this->getNamespace() );
1298 }
1299
1300 /**
1301 * Get a Title object associated with the talk page of this article
1302 *
1303 * @return Title The object for the talk page
1304 */
1305 public function getTalkPage() {
1306 return Title::makeTitle( MWNamespace::getTalk( $this->getNamespace() ), $this->getDBkey() );
1307 }
1308
1309 /**
1310 * Get a title object associated with the subject page of this
1311 * talk page
1312 *
1313 * @return Title The object for the subject page
1314 */
1315 public function getSubjectPage() {
1316 // Is this the same title?
1317 $subjectNS = MWNamespace::getSubject( $this->getNamespace() );
1318 if ( $this->getNamespace() == $subjectNS ) {
1319 return $this;
1320 }
1321 return Title::makeTitle( $subjectNS, $this->getDBkey() );
1322 }
1323
1324 /**
1325 * Get the other title for this page, if this is a subject page
1326 * get the talk page, if it is a subject page get the talk page
1327 *
1328 * @since 1.25
1329 * @throws MWException
1330 * @return Title
1331 */
1332 public function getOtherPage() {
1333 if ( $this->isSpecialPage() ) {
1334 throw new MWException( 'Special pages cannot have other pages' );
1335 }
1336 if ( $this->isTalkPage() ) {
1337 return $this->getSubjectPage();
1338 } else {
1339 return $this->getTalkPage();
1340 }
1341 }
1342
1343 /**
1344 * Get the default namespace index, for when there is no namespace
1345 *
1346 * @return int Default namespace index
1347 */
1348 public function getDefaultNamespace() {
1349 return $this->mDefaultNamespace;
1350 }
1351
1352 /**
1353 * Get the Title fragment (i.e.\ the bit after the #) in text form
1354 *
1355 * Use Title::hasFragment to check for a fragment
1356 *
1357 * @return string Title fragment
1358 */
1359 public function getFragment() {
1360 return $this->mFragment;
1361 }
1362
1363 /**
1364 * Check if a Title fragment is set
1365 *
1366 * @return bool
1367 * @since 1.23
1368 */
1369 public function hasFragment() {
1370 return $this->mFragment !== '';
1371 }
1372
1373 /**
1374 * Get the fragment in URL form, including the "#" character if there is one
1375 * @return string Fragment in URL form
1376 */
1377 public function getFragmentForURL() {
1378 if ( !$this->hasFragment() ) {
1379 return '';
1380 } else {
1381 return '#' . Title::escapeFragmentForURL( $this->getFragment() );
1382 }
1383 }
1384
1385 /**
1386 * Set the fragment for this title. Removes the first character from the
1387 * specified fragment before setting, so it assumes you're passing it with
1388 * an initial "#".
1389 *
1390 * Deprecated for public use, use Title::makeTitle() with fragment parameter,
1391 * or Title::createFragmentTarget().
1392 * Still in active use privately.
1393 *
1394 * @private
1395 * @param string $fragment Text
1396 */
1397 public function setFragment( $fragment ) {
1398 $this->mFragment = strtr( substr( $fragment, 1 ), '_', ' ' );
1399 }
1400
1401 /**
1402 * Creates a new Title for a different fragment of the same page.
1403 *
1404 * @since 1.27
1405 * @param string $fragment
1406 * @return Title
1407 */
1408 public function createFragmentTarget( $fragment ) {
1409 return self::makeTitle(
1410 $this->getNamespace(),
1411 $this->getText(),
1412 $fragment,
1413 $this->getInterwiki()
1414 );
1415 }
1416
1417 /**
1418 * Prefix some arbitrary text with the namespace or interwiki prefix
1419 * of this object
1420 *
1421 * @param string $name The text
1422 * @return string The prefixed text
1423 */
1424 private function prefix( $name ) {
1425 $p = '';
1426 if ( $this->isExternal() ) {
1427 $p = $this->mInterwiki . ':';
1428 }
1429
1430 if ( 0 != $this->mNamespace ) {
1431 $p .= $this->getNsText() . ':';
1432 }
1433 return $p . $name;
1434 }
1435
1436 /**
1437 * Get the prefixed database key form
1438 *
1439 * @return string The prefixed title, with underscores and
1440 * any interwiki and namespace prefixes
1441 */
1442 public function getPrefixedDBkey() {
1443 $s = $this->prefix( $this->mDbkeyform );
1444 $s = strtr( $s, ' ', '_' );
1445 return $s;
1446 }
1447
1448 /**
1449 * Get the prefixed title with spaces.
1450 * This is the form usually used for display
1451 *
1452 * @return string The prefixed title, with spaces
1453 */
1454 public function getPrefixedText() {
1455 if ( $this->mPrefixedText === null ) {
1456 $s = $this->prefix( $this->mTextform );
1457 $s = strtr( $s, '_', ' ' );
1458 $this->mPrefixedText = $s;
1459 }
1460 return $this->mPrefixedText;
1461 }
1462
1463 /**
1464 * Return a string representation of this title
1465 *
1466 * @return string Representation of this title
1467 */
1468 public function __toString() {
1469 return $this->getPrefixedText();
1470 }
1471
1472 /**
1473 * Get the prefixed title with spaces, plus any fragment
1474 * (part beginning with '#')
1475 *
1476 * @return string The prefixed title, with spaces and the fragment, including '#'
1477 */
1478 public function getFullText() {
1479 $text = $this->getPrefixedText();
1480 if ( $this->hasFragment() ) {
1481 $text .= '#' . $this->getFragment();
1482 }
1483 return $text;
1484 }
1485
1486 /**
1487 * Get the root page name text without a namespace, i.e. the leftmost part before any slashes
1488 *
1489 * @par Example:
1490 * @code
1491 * Title::newFromText('User:Foo/Bar/Baz')->getRootText();
1492 * # returns: 'Foo'
1493 * @endcode
1494 *
1495 * @return string Root name
1496 * @since 1.20
1497 */
1498 public function getRootText() {
1499 if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
1500 return $this->getText();
1501 }
1502
1503 return strtok( $this->getText(), '/' );
1504 }
1505
1506 /**
1507 * Get the root page name title, i.e. the leftmost part before any slashes
1508 *
1509 * @par Example:
1510 * @code
1511 * Title::newFromText('User:Foo/Bar/Baz')->getRootTitle();
1512 * # returns: Title{User:Foo}
1513 * @endcode
1514 *
1515 * @return Title Root title
1516 * @since 1.20
1517 */
1518 public function getRootTitle() {
1519 return Title::makeTitle( $this->getNamespace(), $this->getRootText() );
1520 }
1521
1522 /**
1523 * Get the base page name without a namespace, i.e. the part before the subpage name
1524 *
1525 * @par Example:
1526 * @code
1527 * Title::newFromText('User:Foo/Bar/Baz')->getBaseText();
1528 * # returns: 'Foo/Bar'
1529 * @endcode
1530 *
1531 * @return string Base name
1532 */
1533 public function getBaseText() {
1534 if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
1535 return $this->getText();
1536 }
1537
1538 $parts = explode( '/', $this->getText() );
1539 # Don't discard the real title if there's no subpage involved
1540 if ( count( $parts ) > 1 ) {
1541 unset( $parts[count( $parts ) - 1] );
1542 }
1543 return implode( '/', $parts );
1544 }
1545
1546 /**
1547 * Get the base page name title, i.e. the part before the subpage name
1548 *
1549 * @par Example:
1550 * @code
1551 * Title::newFromText('User:Foo/Bar/Baz')->getBaseTitle();
1552 * # returns: Title{User:Foo/Bar}
1553 * @endcode
1554 *
1555 * @return Title Base title
1556 * @since 1.20
1557 */
1558 public function getBaseTitle() {
1559 return Title::makeTitle( $this->getNamespace(), $this->getBaseText() );
1560 }
1561
1562 /**
1563 * Get the lowest-level subpage name, i.e. the rightmost part after any slashes
1564 *
1565 * @par Example:
1566 * @code
1567 * Title::newFromText('User:Foo/Bar/Baz')->getSubpageText();
1568 * # returns: "Baz"
1569 * @endcode
1570 *
1571 * @return string Subpage name
1572 */
1573 public function getSubpageText() {
1574 if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
1575 return $this->mTextform;
1576 }
1577 $parts = explode( '/', $this->mTextform );
1578 return $parts[count( $parts ) - 1];
1579 }
1580
1581 /**
1582 * Get the title for a subpage of the current page
1583 *
1584 * @par Example:
1585 * @code
1586 * Title::newFromText('User:Foo/Bar/Baz')->getSubpage("Asdf");
1587 * # returns: Title{User:Foo/Bar/Baz/Asdf}
1588 * @endcode
1589 *
1590 * @param string $text The subpage name to add to the title
1591 * @return Title Subpage title
1592 * @since 1.20
1593 */
1594 public function getSubpage( $text ) {
1595 return Title::makeTitleSafe( $this->getNamespace(), $this->getText() . '/' . $text );
1596 }
1597
1598 /**
1599 * Get a URL-encoded form of the subpage text
1600 *
1601 * @return string URL-encoded subpage name
1602 */
1603 public function getSubpageUrlForm() {
1604 $text = $this->getSubpageText();
1605 $text = wfUrlencode( strtr( $text, ' ', '_' ) );
1606 return $text;
1607 }
1608
1609 /**
1610 * Get a URL-encoded title (not an actual URL) including interwiki
1611 *
1612 * @return string The URL-encoded form
1613 */
1614 public function getPrefixedURL() {
1615 $s = $this->prefix( $this->mDbkeyform );
1616 $s = wfUrlencode( strtr( $s, ' ', '_' ) );
1617 return $s;
1618 }
1619
1620 /**
1621 * Helper to fix up the get{Canonical,Full,Link,Local,Internal}URL args
1622 * get{Canonical,Full,Link,Local,Internal}URL methods accepted an optional
1623 * second argument named variant. This was deprecated in favor
1624 * of passing an array of option with a "variant" key
1625 * Once $query2 is removed for good, this helper can be dropped
1626 * and the wfArrayToCgi moved to getLocalURL();
1627 *
1628 * @since 1.19 (r105919)
1629 * @param array|string $query
1630 * @param string|string[]|bool $query2
1631 * @return string
1632 */
1633 private static function fixUrlQueryArgs( $query, $query2 = false ) {
1634 if ( $query2 !== false ) {
1635 wfDeprecated( "Title::get{Canonical,Full,Link,Local,Internal}URL " .
1636 "method called with a second parameter is deprecated. Add your " .
1637 "parameter to an array passed as the first parameter.", "1.19" );
1638 }
1639 if ( is_array( $query ) ) {
1640 $query = wfArrayToCgi( $query );
1641 }
1642 if ( $query2 ) {
1643 if ( is_string( $query2 ) ) {
1644 // $query2 is a string, we will consider this to be
1645 // a deprecated $variant argument and add it to the query
1646 $query2 = wfArrayToCgi( [ 'variant' => $query2 ] );
1647 } else {
1648 $query2 = wfArrayToCgi( $query2 );
1649 }
1650 // If we have $query content add a & to it first
1651 if ( $query ) {
1652 $query .= '&';
1653 }
1654 // Now append the queries together
1655 $query .= $query2;
1656 }
1657 return $query;
1658 }
1659
1660 /**
1661 * Get a real URL referring to this title, with interwiki link and
1662 * fragment
1663 *
1664 * @see self::getLocalURL for the arguments.
1665 * @see wfExpandUrl
1666 * @param string|string[] $query
1667 * @param string|string[]|bool $query2
1668 * @param string $proto Protocol type to use in URL
1669 * @return string The URL
1670 */
1671 public function getFullURL( $query = '', $query2 = false, $proto = PROTO_RELATIVE ) {
1672 $query = self::fixUrlQueryArgs( $query, $query2 );
1673
1674 # Hand off all the decisions on urls to getLocalURL
1675 $url = $this->getLocalURL( $query );
1676
1677 # Expand the url to make it a full url. Note that getLocalURL has the
1678 # potential to output full urls for a variety of reasons, so we use
1679 # wfExpandUrl instead of simply prepending $wgServer
1680 $url = wfExpandUrl( $url, $proto );
1681
1682 # Finally, add the fragment.
1683 $url .= $this->getFragmentForURL();
1684 // Avoid PHP 7.1 warning from passing $this by reference
1685 $titleRef = $this;
1686 Hooks::run( 'GetFullURL', [ &$titleRef, &$url, $query ] );
1687 return $url;
1688 }
1689
1690 /**
1691 * Get a URL with no fragment or server name (relative URL) from a Title object.
1692 * If this page is generated with action=render, however,
1693 * $wgServer is prepended to make an absolute URL.
1694 *
1695 * @see self::getFullURL to always get an absolute URL.
1696 * @see self::getLinkURL to always get a URL that's the simplest URL that will be
1697 * valid to link, locally, to the current Title.
1698 * @see self::newFromText to produce a Title object.
1699 *
1700 * @param string|string[] $query An optional query string,
1701 * not used for interwiki links. Can be specified as an associative array as well,
1702 * e.g., array( 'action' => 'edit' ) (keys and values will be URL-escaped).
1703 * Some query patterns will trigger various shorturl path replacements.
1704 * @param string|string[]|bool $query2 An optional secondary query array. This one MUST
1705 * be an array. If a string is passed it will be interpreted as a deprecated
1706 * variant argument and urlencoded into a variant= argument.
1707 * This second query argument will be added to the $query
1708 * The second parameter is deprecated since 1.19. Pass it as a key,value
1709 * pair in the first parameter array instead.
1710 *
1711 * @return string String of the URL.
1712 */
1713 public function getLocalURL( $query = '', $query2 = false ) {
1714 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
1715
1716 $query = self::fixUrlQueryArgs( $query, $query2 );
1717
1718 $interwiki = self::getInterwikiLookup()->fetch( $this->mInterwiki );
1719 if ( $interwiki ) {
1720 $namespace = $this->getNsText();
1721 if ( $namespace != '' ) {
1722 # Can this actually happen? Interwikis shouldn't be parsed.
1723 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
1724 $namespace .= ':';
1725 }
1726 $url = $interwiki->getURL( $namespace . $this->getDBkey() );
1727 $url = wfAppendQuery( $url, $query );
1728 } else {
1729 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
1730 if ( $query == '' ) {
1731 $url = str_replace( '$1', $dbkey, $wgArticlePath );
1732 // Avoid PHP 7.1 warning from passing $this by reference
1733 $titleRef = $this;
1734 Hooks::run( 'GetLocalURL::Article', [ &$titleRef, &$url ] );
1735 } else {
1736 global $wgVariantArticlePath, $wgActionPaths, $wgContLang;
1737 $url = false;
1738 $matches = [];
1739
1740 if ( !empty( $wgActionPaths )
1741 && preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches )
1742 ) {
1743 $action = urldecode( $matches[2] );
1744 if ( isset( $wgActionPaths[$action] ) ) {
1745 $query = $matches[1];
1746 if ( isset( $matches[4] ) ) {
1747 $query .= $matches[4];
1748 }
1749 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
1750 if ( $query != '' ) {
1751 $url = wfAppendQuery( $url, $query );
1752 }
1753 }
1754 }
1755
1756 if ( $url === false
1757 && $wgVariantArticlePath
1758 && preg_match( '/^variant=([^&]*)$/', $query, $matches )
1759 && $this->getPageLanguage()->equals( $wgContLang )
1760 && $this->getPageLanguage()->hasVariants()
1761 ) {
1762 $variant = urldecode( $matches[1] );
1763 if ( $this->getPageLanguage()->hasVariant( $variant ) ) {
1764 // Only do the variant replacement if the given variant is a valid
1765 // variant for the page's language.
1766 $url = str_replace( '$2', urlencode( $variant ), $wgVariantArticlePath );
1767 $url = str_replace( '$1', $dbkey, $url );
1768 }
1769 }
1770
1771 if ( $url === false ) {
1772 if ( $query == '-' ) {
1773 $query = '';
1774 }
1775 $url = "{$wgScript}?title={$dbkey}&{$query}";
1776 }
1777 }
1778 // Avoid PHP 7.1 warning from passing $this by reference
1779 $titleRef = $this;
1780 Hooks::run( 'GetLocalURL::Internal', [ &$titleRef, &$url, $query ] );
1781
1782 // @todo FIXME: This causes breakage in various places when we
1783 // actually expected a local URL and end up with dupe prefixes.
1784 if ( $wgRequest->getVal( 'action' ) == 'render' ) {
1785 $url = $wgServer . $url;
1786 }
1787 }
1788 // Avoid PHP 7.1 warning from passing $this by reference
1789 $titleRef = $this;
1790 Hooks::run( 'GetLocalURL', [ &$titleRef, &$url, $query ] );
1791 return $url;
1792 }
1793
1794 /**
1795 * Get a URL that's the simplest URL that will be valid to link, locally,
1796 * to the current Title. It includes the fragment, but does not include
1797 * the server unless action=render is used (or the link is external). If
1798 * there's a fragment but the prefixed text is empty, we just return a link
1799 * to the fragment.
1800 *
1801 * The result obviously should not be URL-escaped, but does need to be
1802 * HTML-escaped if it's being output in HTML.
1803 *
1804 * @param string|string[] $query
1805 * @param bool $query2
1806 * @param string|int|bool $proto A PROTO_* constant on how the URL should be expanded,
1807 * or false (default) for no expansion
1808 * @see self::getLocalURL for the arguments.
1809 * @return string The URL
1810 */
1811 public function getLinkURL( $query = '', $query2 = false, $proto = false ) {
1812 if ( $this->isExternal() || $proto !== false ) {
1813 $ret = $this->getFullURL( $query, $query2, $proto );
1814 } elseif ( $this->getPrefixedText() === '' && $this->hasFragment() ) {
1815 $ret = $this->getFragmentForURL();
1816 } else {
1817 $ret = $this->getLocalURL( $query, $query2 ) . $this->getFragmentForURL();
1818 }
1819 return $ret;
1820 }
1821
1822 /**
1823 * Get the URL form for an internal link.
1824 * - Used in various CDN-related code, in case we have a different
1825 * internal hostname for the server from the exposed one.
1826 *
1827 * This uses $wgInternalServer to qualify the path, or $wgServer
1828 * if $wgInternalServer is not set. If the server variable used is
1829 * protocol-relative, the URL will be expanded to http://
1830 *
1831 * @see self::getLocalURL for the arguments.
1832 * @return string The URL
1833 */
1834 public function getInternalURL( $query = '', $query2 = false ) {
1835 global $wgInternalServer, $wgServer;
1836 $query = self::fixUrlQueryArgs( $query, $query2 );
1837 $server = $wgInternalServer !== false ? $wgInternalServer : $wgServer;
1838 $url = wfExpandUrl( $server . $this->getLocalURL( $query ), PROTO_HTTP );
1839 // Avoid PHP 7.1 warning from passing $this by reference
1840 $titleRef = $this;
1841 Hooks::run( 'GetInternalURL', [ &$titleRef, &$url, $query ] );
1842 return $url;
1843 }
1844
1845 /**
1846 * Get the URL for a canonical link, for use in things like IRC and
1847 * e-mail notifications. Uses $wgCanonicalServer and the
1848 * GetCanonicalURL hook.
1849 *
1850 * NOTE: Unlike getInternalURL(), the canonical URL includes the fragment
1851 *
1852 * @see self::getLocalURL for the arguments.
1853 * @return string The URL
1854 * @since 1.18
1855 */
1856 public function getCanonicalURL( $query = '', $query2 = false ) {
1857 $query = self::fixUrlQueryArgs( $query, $query2 );
1858 $url = wfExpandUrl( $this->getLocalURL( $query ) . $this->getFragmentForURL(), PROTO_CANONICAL );
1859 // Avoid PHP 7.1 warning from passing $this by reference
1860 $titleRef = $this;
1861 Hooks::run( 'GetCanonicalURL', [ &$titleRef, &$url, $query ] );
1862 return $url;
1863 }
1864
1865 /**
1866 * Get the edit URL for this Title
1867 *
1868 * @return string The URL, or a null string if this is an interwiki link
1869 */
1870 public function getEditURL() {
1871 if ( $this->isExternal() ) {
1872 return '';
1873 }
1874 $s = $this->getLocalURL( 'action=edit' );
1875
1876 return $s;
1877 }
1878
1879 /**
1880 * Can $user perform $action on this page?
1881 * This skips potentially expensive cascading permission checks
1882 * as well as avoids expensive error formatting
1883 *
1884 * Suitable for use for nonessential UI controls in common cases, but
1885 * _not_ for functional access control.
1886 *
1887 * May provide false positives, but should never provide a false negative.
1888 *
1889 * @param string $action Action that permission needs to be checked for
1890 * @param User $user User to check (since 1.19); $wgUser will be used if not provided.
1891 * @return bool
1892 */
1893 public function quickUserCan( $action, $user = null ) {
1894 return $this->userCan( $action, $user, false );
1895 }
1896
1897 /**
1898 * Can $user perform $action on this page?
1899 *
1900 * @param string $action Action that permission needs to be checked for
1901 * @param User $user User to check (since 1.19); $wgUser will be used if not
1902 * provided.
1903 * @param string $rigor Same format as Title::getUserPermissionsErrors()
1904 * @return bool
1905 */
1906 public function userCan( $action, $user = null, $rigor = 'secure' ) {
1907 if ( !$user instanceof User ) {
1908 global $wgUser;
1909 $user = $wgUser;
1910 }
1911
1912 return !count( $this->getUserPermissionsErrorsInternal( $action, $user, $rigor, true ) );
1913 }
1914
1915 /**
1916 * Can $user perform $action on this page?
1917 *
1918 * @todo FIXME: This *does not* check throttles (User::pingLimiter()).
1919 *
1920 * @param string $action Action that permission needs to be checked for
1921 * @param User $user User to check
1922 * @param string $rigor One of (quick,full,secure)
1923 * - quick : does cheap permission checks from replica DBs (usable for GUI creation)
1924 * - full : does cheap and expensive checks possibly from a replica DB
1925 * - secure : does cheap and expensive checks, using the master as needed
1926 * @param array $ignoreErrors Array of Strings Set this to a list of message keys
1927 * whose corresponding errors may be ignored.
1928 * @return array Array of arrays of the arguments to wfMessage to explain permissions problems.
1929 */
1930 public function getUserPermissionsErrors(
1931 $action, $user, $rigor = 'secure', $ignoreErrors = []
1932 ) {
1933 $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $rigor );
1934
1935 // Remove the errors being ignored.
1936 foreach ( $errors as $index => $error ) {
1937 $errKey = is_array( $error ) ? $error[0] : $error;
1938
1939 if ( in_array( $errKey, $ignoreErrors ) ) {
1940 unset( $errors[$index] );
1941 }
1942 if ( $errKey instanceof MessageSpecifier && in_array( $errKey->getKey(), $ignoreErrors ) ) {
1943 unset( $errors[$index] );
1944 }
1945 }
1946
1947 return $errors;
1948 }
1949
1950 /**
1951 * Permissions checks that fail most often, and which are easiest to test.
1952 *
1953 * @param string $action The action to check
1954 * @param User $user User to check
1955 * @param array $errors List of current errors
1956 * @param string $rigor Same format as Title::getUserPermissionsErrors()
1957 * @param bool $short Short circuit on first error
1958 *
1959 * @return array List of errors
1960 */
1961 private function checkQuickPermissions( $action, $user, $errors, $rigor, $short ) {
1962 if ( !Hooks::run( 'TitleQuickPermissions',
1963 [ $this, $user, $action, &$errors, ( $rigor !== 'quick' ), $short ] )
1964 ) {
1965 return $errors;
1966 }
1967
1968 if ( $action == 'create' ) {
1969 if (
1970 ( $this->isTalkPage() && !$user->isAllowed( 'createtalk' ) ) ||
1971 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage' ) )
1972 ) {
1973 $errors[] = $user->isAnon() ? [ 'nocreatetext' ] : [ 'nocreate-loggedin' ];
1974 }
1975 } elseif ( $action == 'move' ) {
1976 if ( !$user->isAllowed( 'move-rootuserpages' )
1977 && $this->mNamespace == NS_USER && !$this->isSubpage() ) {
1978 // Show user page-specific message only if the user can move other pages
1979 $errors[] = [ 'cant-move-user-page' ];
1980 }
1981
1982 // Check if user is allowed to move files if it's a file
1983 if ( $this->mNamespace == NS_FILE && !$user->isAllowed( 'movefile' ) ) {
1984 $errors[] = [ 'movenotallowedfile' ];
1985 }
1986
1987 // Check if user is allowed to move category pages if it's a category page
1988 if ( $this->mNamespace == NS_CATEGORY && !$user->isAllowed( 'move-categorypages' ) ) {
1989 $errors[] = [ 'cant-move-category-page' ];
1990 }
1991
1992 if ( !$user->isAllowed( 'move' ) ) {
1993 // User can't move anything
1994 $userCanMove = User::groupHasPermission( 'user', 'move' );
1995 $autoconfirmedCanMove = User::groupHasPermission( 'autoconfirmed', 'move' );
1996 if ( $user->isAnon() && ( $userCanMove || $autoconfirmedCanMove ) ) {
1997 // custom message if logged-in users without any special rights can move
1998 $errors[] = [ 'movenologintext' ];
1999 } else {
2000 $errors[] = [ 'movenotallowed' ];
2001 }
2002 }
2003 } elseif ( $action == 'move-target' ) {
2004 if ( !$user->isAllowed( 'move' ) ) {
2005 // User can't move anything
2006 $errors[] = [ 'movenotallowed' ];
2007 } elseif ( !$user->isAllowed( 'move-rootuserpages' )
2008 && $this->mNamespace == NS_USER && !$this->isSubpage() ) {
2009 // Show user page-specific message only if the user can move other pages
2010 $errors[] = [ 'cant-move-to-user-page' ];
2011 } elseif ( !$user->isAllowed( 'move-categorypages' )
2012 && $this->mNamespace == NS_CATEGORY ) {
2013 // Show category page-specific message only if the user can move other pages
2014 $errors[] = [ 'cant-move-to-category-page' ];
2015 }
2016 } elseif ( !$user->isAllowed( $action ) ) {
2017 $errors[] = $this->missingPermissionError( $action, $short );
2018 }
2019
2020 return $errors;
2021 }
2022
2023 /**
2024 * Add the resulting error code to the errors array
2025 *
2026 * @param array $errors List of current errors
2027 * @param array $result Result of errors
2028 *
2029 * @return array List of errors
2030 */
2031 private function resultToError( $errors, $result ) {
2032 if ( is_array( $result ) && count( $result ) && !is_array( $result[0] ) ) {
2033 // A single array representing an error
2034 $errors[] = $result;
2035 } elseif ( is_array( $result ) && is_array( $result[0] ) ) {
2036 // A nested array representing multiple errors
2037 $errors = array_merge( $errors, $result );
2038 } elseif ( $result !== '' && is_string( $result ) ) {
2039 // A string representing a message-id
2040 $errors[] = [ $result ];
2041 } elseif ( $result instanceof MessageSpecifier ) {
2042 // A message specifier representing an error
2043 $errors[] = [ $result ];
2044 } elseif ( $result === false ) {
2045 // a generic "We don't want them to do that"
2046 $errors[] = [ 'badaccess-group0' ];
2047 }
2048 return $errors;
2049 }
2050
2051 /**
2052 * Check various permission hooks
2053 *
2054 * @param string $action The action to check
2055 * @param User $user User to check
2056 * @param array $errors List of current errors
2057 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2058 * @param bool $short Short circuit on first error
2059 *
2060 * @return array List of errors
2061 */
2062 private function checkPermissionHooks( $action, $user, $errors, $rigor, $short ) {
2063 // Use getUserPermissionsErrors instead
2064 $result = '';
2065 // Avoid PHP 7.1 warning from passing $this by reference
2066 $titleRef = $this;
2067 if ( !Hooks::run( 'userCan', [ &$titleRef, &$user, $action, &$result ] ) ) {
2068 return $result ? [] : [ [ 'badaccess-group0' ] ];
2069 }
2070 // Check getUserPermissionsErrors hook
2071 // Avoid PHP 7.1 warning from passing $this by reference
2072 $titleRef = $this;
2073 if ( !Hooks::run( 'getUserPermissionsErrors', [ &$titleRef, &$user, $action, &$result ] ) ) {
2074 $errors = $this->resultToError( $errors, $result );
2075 }
2076 // Check getUserPermissionsErrorsExpensive hook
2077 if (
2078 $rigor !== 'quick'
2079 && !( $short && count( $errors ) > 0 )
2080 && !Hooks::run( 'getUserPermissionsErrorsExpensive', [ &$titleRef, &$user, $action, &$result ] )
2081 ) {
2082 $errors = $this->resultToError( $errors, $result );
2083 }
2084
2085 return $errors;
2086 }
2087
2088 /**
2089 * Check permissions on special pages & namespaces
2090 *
2091 * @param string $action The action to check
2092 * @param User $user User to check
2093 * @param array $errors List of current errors
2094 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2095 * @param bool $short Short circuit on first error
2096 *
2097 * @return array List of errors
2098 */
2099 private function checkSpecialsAndNSPermissions( $action, $user, $errors, $rigor, $short ) {
2100 # Only 'createaccount' can be performed on special pages,
2101 # which don't actually exist in the DB.
2102 if ( NS_SPECIAL == $this->mNamespace && $action !== 'createaccount' ) {
2103 $errors[] = [ 'ns-specialprotected' ];
2104 }
2105
2106 # Check $wgNamespaceProtection for restricted namespaces
2107 if ( $this->isNamespaceProtected( $user ) ) {
2108 $ns = $this->mNamespace == NS_MAIN ?
2109 wfMessage( 'nstab-main' )->text() : $this->getNsText();
2110 $errors[] = $this->mNamespace == NS_MEDIAWIKI ?
2111 [ 'protectedinterface', $action ] : [ 'namespaceprotected', $ns, $action ];
2112 }
2113
2114 return $errors;
2115 }
2116
2117 /**
2118 * Check CSS/JS sub-page permissions
2119 *
2120 * @param string $action The action to check
2121 * @param User $user User to check
2122 * @param array $errors List of current errors
2123 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2124 * @param bool $short Short circuit on first error
2125 *
2126 * @return array List of errors
2127 */
2128 private function checkCSSandJSPermissions( $action, $user, $errors, $rigor, $short ) {
2129 # Protect css/js subpages of user pages
2130 # XXX: this might be better using restrictions
2131 # XXX: right 'editusercssjs' is deprecated, for backward compatibility only
2132 if ( $action != 'patrol' && !$user->isAllowed( 'editusercssjs' ) ) {
2133 if ( preg_match( '/^' . preg_quote( $user->getName(), '/' ) . '\//', $this->mTextform ) ) {
2134 if ( $this->isCssSubpage() && !$user->isAllowedAny( 'editmyusercss', 'editusercss' ) ) {
2135 $errors[] = [ 'mycustomcssprotected', $action ];
2136 } elseif ( $this->isJsSubpage() && !$user->isAllowedAny( 'editmyuserjs', 'edituserjs' ) ) {
2137 $errors[] = [ 'mycustomjsprotected', $action ];
2138 }
2139 } else {
2140 if ( $this->isCssSubpage() && !$user->isAllowed( 'editusercss' ) ) {
2141 $errors[] = [ 'customcssprotected', $action ];
2142 } elseif ( $this->isJsSubpage() && !$user->isAllowed( 'edituserjs' ) ) {
2143 $errors[] = [ 'customjsprotected', $action ];
2144 }
2145 }
2146 }
2147
2148 return $errors;
2149 }
2150
2151 /**
2152 * Check against page_restrictions table requirements on this
2153 * page. The user must possess all required rights for this
2154 * action.
2155 *
2156 * @param string $action The action to check
2157 * @param User $user User to check
2158 * @param array $errors List of current errors
2159 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2160 * @param bool $short Short circuit on first error
2161 *
2162 * @return array List of errors
2163 */
2164 private function checkPageRestrictions( $action, $user, $errors, $rigor, $short ) {
2165 foreach ( $this->getRestrictions( $action ) as $right ) {
2166 // Backwards compatibility, rewrite sysop -> editprotected
2167 if ( $right == 'sysop' ) {
2168 $right = 'editprotected';
2169 }
2170 // Backwards compatibility, rewrite autoconfirmed -> editsemiprotected
2171 if ( $right == 'autoconfirmed' ) {
2172 $right = 'editsemiprotected';
2173 }
2174 if ( $right == '' ) {
2175 continue;
2176 }
2177 if ( !$user->isAllowed( $right ) ) {
2178 $errors[] = [ 'protectedpagetext', $right, $action ];
2179 } elseif ( $this->mCascadeRestriction && !$user->isAllowed( 'protect' ) ) {
2180 $errors[] = [ 'protectedpagetext', 'protect', $action ];
2181 }
2182 }
2183
2184 return $errors;
2185 }
2186
2187 /**
2188 * Check restrictions on cascading pages.
2189 *
2190 * @param string $action The action to check
2191 * @param User $user User to check
2192 * @param array $errors List of current errors
2193 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2194 * @param bool $short Short circuit on first error
2195 *
2196 * @return array List of errors
2197 */
2198 private function checkCascadingSourcesRestrictions( $action, $user, $errors, $rigor, $short ) {
2199 if ( $rigor !== 'quick' && !$this->isCssJsSubpage() ) {
2200 # We /could/ use the protection level on the source page, but it's
2201 # fairly ugly as we have to establish a precedence hierarchy for pages
2202 # included by multiple cascade-protected pages. So just restrict
2203 # it to people with 'protect' permission, as they could remove the
2204 # protection anyway.
2205 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
2206 # Cascading protection depends on more than this page...
2207 # Several cascading protected pages may include this page...
2208 # Check each cascading level
2209 # This is only for protection restrictions, not for all actions
2210 if ( isset( $restrictions[$action] ) ) {
2211 foreach ( $restrictions[$action] as $right ) {
2212 // Backwards compatibility, rewrite sysop -> editprotected
2213 if ( $right == 'sysop' ) {
2214 $right = 'editprotected';
2215 }
2216 // Backwards compatibility, rewrite autoconfirmed -> editsemiprotected
2217 if ( $right == 'autoconfirmed' ) {
2218 $right = 'editsemiprotected';
2219 }
2220 if ( $right != '' && !$user->isAllowedAll( 'protect', $right ) ) {
2221 $pages = '';
2222 foreach ( $cascadingSources as $page ) {
2223 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
2224 }
2225 $errors[] = [ 'cascadeprotected', count( $cascadingSources ), $pages, $action ];
2226 }
2227 }
2228 }
2229 }
2230
2231 return $errors;
2232 }
2233
2234 /**
2235 * Check action permissions not already checked in checkQuickPermissions
2236 *
2237 * @param string $action The action to check
2238 * @param User $user User to check
2239 * @param array $errors List of current errors
2240 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2241 * @param bool $short Short circuit on first error
2242 *
2243 * @return array List of errors
2244 */
2245 private function checkActionPermissions( $action, $user, $errors, $rigor, $short ) {
2246 global $wgDeleteRevisionsLimit, $wgLang;
2247
2248 if ( $action == 'protect' ) {
2249 if ( count( $this->getUserPermissionsErrorsInternal( 'edit', $user, $rigor, true ) ) ) {
2250 // If they can't edit, they shouldn't protect.
2251 $errors[] = [ 'protect-cantedit' ];
2252 }
2253 } elseif ( $action == 'create' ) {
2254 $title_protection = $this->getTitleProtection();
2255 if ( $title_protection ) {
2256 if ( $title_protection['permission'] == ''
2257 || !$user->isAllowed( $title_protection['permission'] )
2258 ) {
2259 $errors[] = [
2260 'titleprotected',
2261 User::whoIs( $title_protection['user'] ),
2262 $title_protection['reason']
2263 ];
2264 }
2265 }
2266 } elseif ( $action == 'move' ) {
2267 // Check for immobile pages
2268 if ( !MWNamespace::isMovable( $this->mNamespace ) ) {
2269 // Specific message for this case
2270 $errors[] = [ 'immobile-source-namespace', $this->getNsText() ];
2271 } elseif ( !$this->isMovable() ) {
2272 // Less specific message for rarer cases
2273 $errors[] = [ 'immobile-source-page' ];
2274 }
2275 } elseif ( $action == 'move-target' ) {
2276 if ( !MWNamespace::isMovable( $this->mNamespace ) ) {
2277 $errors[] = [ 'immobile-target-namespace', $this->getNsText() ];
2278 } elseif ( !$this->isMovable() ) {
2279 $errors[] = [ 'immobile-target-page' ];
2280 }
2281 } elseif ( $action == 'delete' ) {
2282 $tempErrors = $this->checkPageRestrictions( 'edit', $user, [], $rigor, true );
2283 if ( !$tempErrors ) {
2284 $tempErrors = $this->checkCascadingSourcesRestrictions( 'edit',
2285 $user, $tempErrors, $rigor, true );
2286 }
2287 if ( $tempErrors ) {
2288 // If protection keeps them from editing, they shouldn't be able to delete.
2289 $errors[] = [ 'deleteprotected' ];
2290 }
2291 if ( $rigor !== 'quick' && $wgDeleteRevisionsLimit
2292 && !$this->userCan( 'bigdelete', $user ) && $this->isBigDeletion()
2293 ) {
2294 $errors[] = [ 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ];
2295 }
2296 }
2297 return $errors;
2298 }
2299
2300 /**
2301 * Check that the user isn't blocked from editing.
2302 *
2303 * @param string $action The action to check
2304 * @param User $user User to check
2305 * @param array $errors List of current errors
2306 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2307 * @param bool $short Short circuit on first error
2308 *
2309 * @return array List of errors
2310 */
2311 private function checkUserBlock( $action, $user, $errors, $rigor, $short ) {
2312 global $wgEmailConfirmToEdit, $wgBlockDisablesLogin;
2313 // Account creation blocks handled at userlogin.
2314 // Unblocking handled in SpecialUnblock
2315 if ( $rigor === 'quick' || in_array( $action, [ 'createaccount', 'unblock' ] ) ) {
2316 return $errors;
2317 }
2318
2319 // Optimize for a very common case
2320 if ( $action === 'read' && !$wgBlockDisablesLogin ) {
2321 return $errors;
2322 }
2323
2324 if ( $wgEmailConfirmToEdit && !$user->isEmailConfirmed() ) {
2325 $errors[] = [ 'confirmedittext' ];
2326 }
2327
2328 $useSlave = ( $rigor !== 'secure' );
2329 if ( ( $action == 'edit' || $action == 'create' )
2330 && !$user->isBlockedFrom( $this, $useSlave )
2331 ) {
2332 // Don't block the user from editing their own talk page unless they've been
2333 // explicitly blocked from that too.
2334 } elseif ( $user->isBlocked() && $user->getBlock()->prevents( $action ) !== false ) {
2335 // @todo FIXME: Pass the relevant context into this function.
2336 $errors[] = $user->getBlock()->getPermissionsError( RequestContext::getMain() );
2337 }
2338
2339 return $errors;
2340 }
2341
2342 /**
2343 * Check that the user is allowed to read this page.
2344 *
2345 * @param string $action The action to check
2346 * @param User $user User to check
2347 * @param array $errors List of current errors
2348 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2349 * @param bool $short Short circuit on first error
2350 *
2351 * @return array List of errors
2352 */
2353 private function checkReadPermissions( $action, $user, $errors, $rigor, $short ) {
2354 global $wgWhitelistRead, $wgWhitelistReadRegexp;
2355
2356 $whitelisted = false;
2357 if ( User::isEveryoneAllowed( 'read' ) ) {
2358 # Shortcut for public wikis, allows skipping quite a bit of code
2359 $whitelisted = true;
2360 } elseif ( $user->isAllowed( 'read' ) ) {
2361 # If the user is allowed to read pages, he is allowed to read all pages
2362 $whitelisted = true;
2363 } elseif ( $this->isSpecial( 'Userlogin' )
2364 || $this->isSpecial( 'PasswordReset' )
2365 || $this->isSpecial( 'Userlogout' )
2366 ) {
2367 # Always grant access to the login page.
2368 # Even anons need to be able to log in.
2369 $whitelisted = true;
2370 } elseif ( is_array( $wgWhitelistRead ) && count( $wgWhitelistRead ) ) {
2371 # Time to check the whitelist
2372 # Only do these checks is there's something to check against
2373 $name = $this->getPrefixedText();
2374 $dbName = $this->getPrefixedDBkey();
2375
2376 // Check for explicit whitelisting with and without underscores
2377 if ( in_array( $name, $wgWhitelistRead, true ) || in_array( $dbName, $wgWhitelistRead, true ) ) {
2378 $whitelisted = true;
2379 } elseif ( $this->getNamespace() == NS_MAIN ) {
2380 # Old settings might have the title prefixed with
2381 # a colon for main-namespace pages
2382 if ( in_array( ':' . $name, $wgWhitelistRead ) ) {
2383 $whitelisted = true;
2384 }
2385 } elseif ( $this->isSpecialPage() ) {
2386 # If it's a special page, ditch the subpage bit and check again
2387 $name = $this->getDBkey();
2388 list( $name, /* $subpage */ ) = SpecialPageFactory::resolveAlias( $name );
2389 if ( $name ) {
2390 $pure = SpecialPage::getTitleFor( $name )->getPrefixedText();
2391 if ( in_array( $pure, $wgWhitelistRead, true ) ) {
2392 $whitelisted = true;
2393 }
2394 }
2395 }
2396 }
2397
2398 if ( !$whitelisted && is_array( $wgWhitelistReadRegexp ) && !empty( $wgWhitelistReadRegexp ) ) {
2399 $name = $this->getPrefixedText();
2400 // Check for regex whitelisting
2401 foreach ( $wgWhitelistReadRegexp as $listItem ) {
2402 if ( preg_match( $listItem, $name ) ) {
2403 $whitelisted = true;
2404 break;
2405 }
2406 }
2407 }
2408
2409 if ( !$whitelisted ) {
2410 # If the title is not whitelisted, give extensions a chance to do so...
2411 Hooks::run( 'TitleReadWhitelist', [ $this, $user, &$whitelisted ] );
2412 if ( !$whitelisted ) {
2413 $errors[] = $this->missingPermissionError( $action, $short );
2414 }
2415 }
2416
2417 return $errors;
2418 }
2419
2420 /**
2421 * Get a description array when the user doesn't have the right to perform
2422 * $action (i.e. when User::isAllowed() returns false)
2423 *
2424 * @param string $action The action to check
2425 * @param bool $short Short circuit on first error
2426 * @return array List of errors
2427 */
2428 private function missingPermissionError( $action, $short ) {
2429 // We avoid expensive display logic for quickUserCan's and such
2430 if ( $short ) {
2431 return [ 'badaccess-group0' ];
2432 }
2433
2434 $groups = array_map( [ 'User', 'makeGroupLinkWiki' ],
2435 User::getGroupsWithPermission( $action ) );
2436
2437 if ( count( $groups ) ) {
2438 global $wgLang;
2439 return [
2440 'badaccess-groups',
2441 $wgLang->commaList( $groups ),
2442 count( $groups )
2443 ];
2444 } else {
2445 return [ 'badaccess-group0' ];
2446 }
2447 }
2448
2449 /**
2450 * Can $user perform $action on this page? This is an internal function,
2451 * with multiple levels of checks depending on performance needs; see $rigor below.
2452 * It does not check wfReadOnly().
2453 *
2454 * @param string $action Action that permission needs to be checked for
2455 * @param User $user User to check
2456 * @param string $rigor One of (quick,full,secure)
2457 * - quick : does cheap permission checks from replica DBs (usable for GUI creation)
2458 * - full : does cheap and expensive checks possibly from a replica DB
2459 * - secure : does cheap and expensive checks, using the master as needed
2460 * @param bool $short Set this to true to stop after the first permission error.
2461 * @return array Array of arrays of the arguments to wfMessage to explain permissions problems.
2462 */
2463 protected function getUserPermissionsErrorsInternal(
2464 $action, $user, $rigor = 'secure', $short = false
2465 ) {
2466 if ( $rigor === true ) {
2467 $rigor = 'secure'; // b/c
2468 } elseif ( $rigor === false ) {
2469 $rigor = 'quick'; // b/c
2470 } elseif ( !in_array( $rigor, [ 'quick', 'full', 'secure' ] ) ) {
2471 throw new Exception( "Invalid rigor parameter '$rigor'." );
2472 }
2473
2474 # Read has special handling
2475 if ( $action == 'read' ) {
2476 $checks = [
2477 'checkPermissionHooks',
2478 'checkReadPermissions',
2479 'checkUserBlock', // for wgBlockDisablesLogin
2480 ];
2481 # Don't call checkSpecialsAndNSPermissions or checkCSSandJSPermissions
2482 # here as it will lead to duplicate error messages. This is okay to do
2483 # since anywhere that checks for create will also check for edit, and
2484 # those checks are called for edit.
2485 } elseif ( $action == 'create' ) {
2486 $checks = [
2487 'checkQuickPermissions',
2488 'checkPermissionHooks',
2489 'checkPageRestrictions',
2490 'checkCascadingSourcesRestrictions',
2491 'checkActionPermissions',
2492 'checkUserBlock'
2493 ];
2494 } else {
2495 $checks = [
2496 'checkQuickPermissions',
2497 'checkPermissionHooks',
2498 'checkSpecialsAndNSPermissions',
2499 'checkCSSandJSPermissions',
2500 'checkPageRestrictions',
2501 'checkCascadingSourcesRestrictions',
2502 'checkActionPermissions',
2503 'checkUserBlock'
2504 ];
2505 }
2506
2507 $errors = [];
2508 while ( count( $checks ) > 0 &&
2509 !( $short && count( $errors ) > 0 ) ) {
2510 $method = array_shift( $checks );
2511 $errors = $this->$method( $action, $user, $errors, $rigor, $short );
2512 }
2513
2514 return $errors;
2515 }
2516
2517 /**
2518 * Get a filtered list of all restriction types supported by this wiki.
2519 * @param bool $exists True to get all restriction types that apply to
2520 * titles that do exist, False for all restriction types that apply to
2521 * titles that do not exist
2522 * @return array
2523 */
2524 public static function getFilteredRestrictionTypes( $exists = true ) {
2525 global $wgRestrictionTypes;
2526 $types = $wgRestrictionTypes;
2527 if ( $exists ) {
2528 # Remove the create restriction for existing titles
2529 $types = array_diff( $types, [ 'create' ] );
2530 } else {
2531 # Only the create and upload restrictions apply to non-existing titles
2532 $types = array_intersect( $types, [ 'create', 'upload' ] );
2533 }
2534 return $types;
2535 }
2536
2537 /**
2538 * Returns restriction types for the current Title
2539 *
2540 * @return array Applicable restriction types
2541 */
2542 public function getRestrictionTypes() {
2543 if ( $this->isSpecialPage() ) {
2544 return [];
2545 }
2546
2547 $types = self::getFilteredRestrictionTypes( $this->exists() );
2548
2549 if ( $this->getNamespace() != NS_FILE ) {
2550 # Remove the upload restriction for non-file titles
2551 $types = array_diff( $types, [ 'upload' ] );
2552 }
2553
2554 Hooks::run( 'TitleGetRestrictionTypes', [ $this, &$types ] );
2555
2556 wfDebug( __METHOD__ . ': applicable restrictions to [[' .
2557 $this->getPrefixedText() . ']] are {' . implode( ',', $types ) . "}\n" );
2558
2559 return $types;
2560 }
2561
2562 /**
2563 * Is this title subject to title protection?
2564 * Title protection is the one applied against creation of such title.
2565 *
2566 * @return array|bool An associative array representing any existent title
2567 * protection, or false if there's none.
2568 */
2569 public function getTitleProtection() {
2570 // Can't protect pages in special namespaces
2571 if ( $this->getNamespace() < 0 ) {
2572 return false;
2573 }
2574
2575 // Can't protect pages that exist.
2576 if ( $this->exists() ) {
2577 return false;
2578 }
2579
2580 if ( $this->mTitleProtection === null ) {
2581 $dbr = wfGetDB( DB_REPLICA );
2582 $res = $dbr->select(
2583 'protected_titles',
2584 [
2585 'user' => 'pt_user',
2586 'reason' => 'pt_reason',
2587 'expiry' => 'pt_expiry',
2588 'permission' => 'pt_create_perm'
2589 ],
2590 [ 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ],
2591 __METHOD__
2592 );
2593
2594 // fetchRow returns false if there are no rows.
2595 $row = $dbr->fetchRow( $res );
2596 if ( $row ) {
2597 if ( $row['permission'] == 'sysop' ) {
2598 $row['permission'] = 'editprotected'; // B/C
2599 }
2600 if ( $row['permission'] == 'autoconfirmed' ) {
2601 $row['permission'] = 'editsemiprotected'; // B/C
2602 }
2603 $row['expiry'] = $dbr->decodeExpiry( $row['expiry'] );
2604 }
2605 $this->mTitleProtection = $row;
2606 }
2607 return $this->mTitleProtection;
2608 }
2609
2610 /**
2611 * Remove any title protection due to page existing
2612 */
2613 public function deleteTitleProtection() {
2614 $dbw = wfGetDB( DB_MASTER );
2615
2616 $dbw->delete(
2617 'protected_titles',
2618 [ 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ],
2619 __METHOD__
2620 );
2621 $this->mTitleProtection = false;
2622 }
2623
2624 /**
2625 * Is this page "semi-protected" - the *only* protection levels are listed
2626 * in $wgSemiprotectedRestrictionLevels?
2627 *
2628 * @param string $action Action to check (default: edit)
2629 * @return bool
2630 */
2631 public function isSemiProtected( $action = 'edit' ) {
2632 global $wgSemiprotectedRestrictionLevels;
2633
2634 $restrictions = $this->getRestrictions( $action );
2635 $semi = $wgSemiprotectedRestrictionLevels;
2636 if ( !$restrictions || !$semi ) {
2637 // Not protected, or all protection is full protection
2638 return false;
2639 }
2640
2641 // Remap autoconfirmed to editsemiprotected for BC
2642 foreach ( array_keys( $semi, 'autoconfirmed' ) as $key ) {
2643 $semi[$key] = 'editsemiprotected';
2644 }
2645 foreach ( array_keys( $restrictions, 'autoconfirmed' ) as $key ) {
2646 $restrictions[$key] = 'editsemiprotected';
2647 }
2648
2649 return !array_diff( $restrictions, $semi );
2650 }
2651
2652 /**
2653 * Does the title correspond to a protected article?
2654 *
2655 * @param string $action The action the page is protected from,
2656 * by default checks all actions.
2657 * @return bool
2658 */
2659 public function isProtected( $action = '' ) {
2660 global $wgRestrictionLevels;
2661
2662 $restrictionTypes = $this->getRestrictionTypes();
2663
2664 # Special pages have inherent protection
2665 if ( $this->isSpecialPage() ) {
2666 return true;
2667 }
2668
2669 # Check regular protection levels
2670 foreach ( $restrictionTypes as $type ) {
2671 if ( $action == $type || $action == '' ) {
2672 $r = $this->getRestrictions( $type );
2673 foreach ( $wgRestrictionLevels as $level ) {
2674 if ( in_array( $level, $r ) && $level != '' ) {
2675 return true;
2676 }
2677 }
2678 }
2679 }
2680
2681 return false;
2682 }
2683
2684 /**
2685 * Determines if $user is unable to edit this page because it has been protected
2686 * by $wgNamespaceProtection.
2687 *
2688 * @param User $user User object to check permissions
2689 * @return bool
2690 */
2691 public function isNamespaceProtected( User $user ) {
2692 global $wgNamespaceProtection;
2693
2694 if ( isset( $wgNamespaceProtection[$this->mNamespace] ) ) {
2695 foreach ( (array)$wgNamespaceProtection[$this->mNamespace] as $right ) {
2696 if ( $right != '' && !$user->isAllowed( $right ) ) {
2697 return true;
2698 }
2699 }
2700 }
2701 return false;
2702 }
2703
2704 /**
2705 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
2706 *
2707 * @return bool If the page is subject to cascading restrictions.
2708 */
2709 public function isCascadeProtected() {
2710 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
2711 return ( $sources > 0 );
2712 }
2713
2714 /**
2715 * Determines whether cascading protection sources have already been loaded from
2716 * the database.
2717 *
2718 * @param bool $getPages True to check if the pages are loaded, or false to check
2719 * if the status is loaded.
2720 * @return bool Whether or not the specified information has been loaded
2721 * @since 1.23
2722 */
2723 public function areCascadeProtectionSourcesLoaded( $getPages = true ) {
2724 return $getPages ? $this->mCascadeSources !== null : $this->mHasCascadingRestrictions !== null;
2725 }
2726
2727 /**
2728 * Cascading protection: Get the source of any cascading restrictions on this page.
2729 *
2730 * @param bool $getPages Whether or not to retrieve the actual pages
2731 * that the restrictions have come from and the actual restrictions
2732 * themselves.
2733 * @return array Two elements: First is an array of Title objects of the
2734 * pages from which cascading restrictions have come, false for
2735 * none, or true if such restrictions exist but $getPages was not
2736 * set. Second is an array like that returned by
2737 * Title::getAllRestrictions(), or an empty array if $getPages is
2738 * false.
2739 */
2740 public function getCascadeProtectionSources( $getPages = true ) {
2741 $pagerestrictions = [];
2742
2743 if ( $this->mCascadeSources !== null && $getPages ) {
2744 return [ $this->mCascadeSources, $this->mCascadingRestrictions ];
2745 } elseif ( $this->mHasCascadingRestrictions !== null && !$getPages ) {
2746 return [ $this->mHasCascadingRestrictions, $pagerestrictions ];
2747 }
2748
2749 $dbr = wfGetDB( DB_REPLICA );
2750
2751 if ( $this->getNamespace() == NS_FILE ) {
2752 $tables = [ 'imagelinks', 'page_restrictions' ];
2753 $where_clauses = [
2754 'il_to' => $this->getDBkey(),
2755 'il_from=pr_page',
2756 'pr_cascade' => 1
2757 ];
2758 } else {
2759 $tables = [ 'templatelinks', 'page_restrictions' ];
2760 $where_clauses = [
2761 'tl_namespace' => $this->getNamespace(),
2762 'tl_title' => $this->getDBkey(),
2763 'tl_from=pr_page',
2764 'pr_cascade' => 1
2765 ];
2766 }
2767
2768 if ( $getPages ) {
2769 $cols = [ 'pr_page', 'page_namespace', 'page_title',
2770 'pr_expiry', 'pr_type', 'pr_level' ];
2771 $where_clauses[] = 'page_id=pr_page';
2772 $tables[] = 'page';
2773 } else {
2774 $cols = [ 'pr_expiry' ];
2775 }
2776
2777 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__ );
2778
2779 $sources = $getPages ? [] : false;
2780 $now = wfTimestampNow();
2781
2782 foreach ( $res as $row ) {
2783 $expiry = $dbr->decodeExpiry( $row->pr_expiry );
2784 if ( $expiry > $now ) {
2785 if ( $getPages ) {
2786 $page_id = $row->pr_page;
2787 $page_ns = $row->page_namespace;
2788 $page_title = $row->page_title;
2789 $sources[$page_id] = Title::makeTitle( $page_ns, $page_title );
2790 # Add groups needed for each restriction type if its not already there
2791 # Make sure this restriction type still exists
2792
2793 if ( !isset( $pagerestrictions[$row->pr_type] ) ) {
2794 $pagerestrictions[$row->pr_type] = [];
2795 }
2796
2797 if (
2798 isset( $pagerestrictions[$row->pr_type] )
2799 && !in_array( $row->pr_level, $pagerestrictions[$row->pr_type] )
2800 ) {
2801 $pagerestrictions[$row->pr_type][] = $row->pr_level;
2802 }
2803 } else {
2804 $sources = true;
2805 }
2806 }
2807 }
2808
2809 if ( $getPages ) {
2810 $this->mCascadeSources = $sources;
2811 $this->mCascadingRestrictions = $pagerestrictions;
2812 } else {
2813 $this->mHasCascadingRestrictions = $sources;
2814 }
2815
2816 return [ $sources, $pagerestrictions ];
2817 }
2818
2819 /**
2820 * Accessor for mRestrictionsLoaded
2821 *
2822 * @return bool Whether or not the page's restrictions have already been
2823 * loaded from the database
2824 * @since 1.23
2825 */
2826 public function areRestrictionsLoaded() {
2827 return $this->mRestrictionsLoaded;
2828 }
2829
2830 /**
2831 * Accessor/initialisation for mRestrictions
2832 *
2833 * @param string $action Action that permission needs to be checked for
2834 * @return array Restriction levels needed to take the action. All levels are
2835 * required. Note that restriction levels are normally user rights, but 'sysop'
2836 * and 'autoconfirmed' are also allowed for backwards compatibility. These should
2837 * be mapped to 'editprotected' and 'editsemiprotected' respectively.
2838 */
2839 public function getRestrictions( $action ) {
2840 if ( !$this->mRestrictionsLoaded ) {
2841 $this->loadRestrictions();
2842 }
2843 return isset( $this->mRestrictions[$action] )
2844 ? $this->mRestrictions[$action]
2845 : [];
2846 }
2847
2848 /**
2849 * Accessor/initialisation for mRestrictions
2850 *
2851 * @return array Keys are actions, values are arrays as returned by
2852 * Title::getRestrictions()
2853 * @since 1.23
2854 */
2855 public function getAllRestrictions() {
2856 if ( !$this->mRestrictionsLoaded ) {
2857 $this->loadRestrictions();
2858 }
2859 return $this->mRestrictions;
2860 }
2861
2862 /**
2863 * Get the expiry time for the restriction against a given action
2864 *
2865 * @param string $action
2866 * @return string|bool 14-char timestamp, or 'infinity' if the page is protected forever
2867 * or not protected at all, or false if the action is not recognised.
2868 */
2869 public function getRestrictionExpiry( $action ) {
2870 if ( !$this->mRestrictionsLoaded ) {
2871 $this->loadRestrictions();
2872 }
2873 return isset( $this->mRestrictionsExpiry[$action] ) ? $this->mRestrictionsExpiry[$action] : false;
2874 }
2875
2876 /**
2877 * Returns cascading restrictions for the current article
2878 *
2879 * @return bool
2880 */
2881 function areRestrictionsCascading() {
2882 if ( !$this->mRestrictionsLoaded ) {
2883 $this->loadRestrictions();
2884 }
2885
2886 return $this->mCascadeRestriction;
2887 }
2888
2889 /**
2890 * Compiles list of active page restrictions from both page table (pre 1.10)
2891 * and page_restrictions table for this existing page.
2892 * Public for usage by LiquidThreads.
2893 *
2894 * @param array $rows Array of db result objects
2895 * @param string $oldFashionedRestrictions Comma-separated list of page
2896 * restrictions from page table (pre 1.10)
2897 */
2898 public function loadRestrictionsFromRows( $rows, $oldFashionedRestrictions = null ) {
2899 $dbr = wfGetDB( DB_REPLICA );
2900
2901 $restrictionTypes = $this->getRestrictionTypes();
2902
2903 foreach ( $restrictionTypes as $type ) {
2904 $this->mRestrictions[$type] = [];
2905 $this->mRestrictionsExpiry[$type] = 'infinity';
2906 }
2907
2908 $this->mCascadeRestriction = false;
2909
2910 # Backwards-compatibility: also load the restrictions from the page record (old format).
2911 if ( $oldFashionedRestrictions !== null ) {
2912 $this->mOldRestrictions = $oldFashionedRestrictions;
2913 }
2914
2915 if ( $this->mOldRestrictions === false ) {
2916 $this->mOldRestrictions = $dbr->selectField( 'page', 'page_restrictions',
2917 [ 'page_id' => $this->getArticleID() ], __METHOD__ );
2918 }
2919
2920 if ( $this->mOldRestrictions != '' ) {
2921 foreach ( explode( ':', trim( $this->mOldRestrictions ) ) as $restrict ) {
2922 $temp = explode( '=', trim( $restrict ) );
2923 if ( count( $temp ) == 1 ) {
2924 // old old format should be treated as edit/move restriction
2925 $this->mRestrictions['edit'] = explode( ',', trim( $temp[0] ) );
2926 $this->mRestrictions['move'] = explode( ',', trim( $temp[0] ) );
2927 } else {
2928 $restriction = trim( $temp[1] );
2929 if ( $restriction != '' ) { // some old entries are empty
2930 $this->mRestrictions[$temp[0]] = explode( ',', $restriction );
2931 }
2932 }
2933 }
2934 }
2935
2936 if ( count( $rows ) ) {
2937 # Current system - load second to make them override.
2938 $now = wfTimestampNow();
2939
2940 # Cycle through all the restrictions.
2941 foreach ( $rows as $row ) {
2942 // Don't take care of restrictions types that aren't allowed
2943 if ( !in_array( $row->pr_type, $restrictionTypes ) ) {
2944 continue;
2945 }
2946
2947 // This code should be refactored, now that it's being used more generally,
2948 // But I don't really see any harm in leaving it in Block for now -werdna
2949 $expiry = $dbr->decodeExpiry( $row->pr_expiry );
2950
2951 // Only apply the restrictions if they haven't expired!
2952 if ( !$expiry || $expiry > $now ) {
2953 $this->mRestrictionsExpiry[$row->pr_type] = $expiry;
2954 $this->mRestrictions[$row->pr_type] = explode( ',', trim( $row->pr_level ) );
2955
2956 $this->mCascadeRestriction |= $row->pr_cascade;
2957 }
2958 }
2959 }
2960
2961 $this->mRestrictionsLoaded = true;
2962 }
2963
2964 /**
2965 * Load restrictions from the page_restrictions table
2966 *
2967 * @param string $oldFashionedRestrictions Comma-separated list of page
2968 * restrictions from page table (pre 1.10)
2969 */
2970 public function loadRestrictions( $oldFashionedRestrictions = null ) {
2971 if ( $this->mRestrictionsLoaded ) {
2972 return;
2973 }
2974
2975 $id = $this->getArticleID();
2976 if ( $id ) {
2977 $cache = ObjectCache::getMainWANInstance();
2978 $rows = $cache->getWithSetCallback(
2979 // Page protections always leave a new null revision
2980 $cache->makeKey( 'page-restrictions', $id, $this->getLatestRevID() ),
2981 $cache::TTL_DAY,
2982 function ( $curValue, &$ttl, array &$setOpts ) {
2983 $dbr = wfGetDB( DB_REPLICA );
2984
2985 $setOpts += Database::getCacheSetOptions( $dbr );
2986
2987 return iterator_to_array(
2988 $dbr->select(
2989 'page_restrictions',
2990 [ 'pr_type', 'pr_expiry', 'pr_level', 'pr_cascade' ],
2991 [ 'pr_page' => $this->getArticleID() ],
2992 __METHOD__
2993 )
2994 );
2995 }
2996 );
2997
2998 $this->loadRestrictionsFromRows( $rows, $oldFashionedRestrictions );
2999 } else {
3000 $title_protection = $this->getTitleProtection();
3001
3002 if ( $title_protection ) {
3003 $now = wfTimestampNow();
3004 $expiry = wfGetDB( DB_REPLICA )->decodeExpiry( $title_protection['expiry'] );
3005
3006 if ( !$expiry || $expiry > $now ) {
3007 // Apply the restrictions
3008 $this->mRestrictionsExpiry['create'] = $expiry;
3009 $this->mRestrictions['create'] =
3010 explode( ',', trim( $title_protection['permission'] ) );
3011 } else { // Get rid of the old restrictions
3012 $this->mTitleProtection = false;
3013 }
3014 } else {
3015 $this->mRestrictionsExpiry['create'] = 'infinity';
3016 }
3017 $this->mRestrictionsLoaded = true;
3018 }
3019 }
3020
3021 /**
3022 * Flush the protection cache in this object and force reload from the database.
3023 * This is used when updating protection from WikiPage::doUpdateRestrictions().
3024 */
3025 public function flushRestrictions() {
3026 $this->mRestrictionsLoaded = false;
3027 $this->mTitleProtection = null;
3028 }
3029
3030 /**
3031 * Purge expired restrictions from the page_restrictions table
3032 *
3033 * This will purge no more than $wgUpdateRowsPerQuery page_restrictions rows
3034 */
3035 static function purgeExpiredRestrictions() {
3036 if ( wfReadOnly() ) {
3037 return;
3038 }
3039
3040 DeferredUpdates::addUpdate( new AtomicSectionUpdate(
3041 wfGetDB( DB_MASTER ),
3042 __METHOD__,
3043 function ( IDatabase $dbw, $fname ) {
3044 $config = MediaWikiServices::getInstance()->getMainConfig();
3045 $ids = $dbw->selectFieldValues(
3046 'page_restrictions',
3047 'pr_id',
3048 [ 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
3049 $fname,
3050 [ 'LIMIT' => $config->get( 'UpdateRowsPerQuery' ) ] // T135470
3051 );
3052 if ( $ids ) {
3053 $dbw->delete( 'page_restrictions', [ 'pr_id' => $ids ], $fname );
3054 }
3055 }
3056 ) );
3057
3058 DeferredUpdates::addUpdate( new AtomicSectionUpdate(
3059 wfGetDB( DB_MASTER ),
3060 __METHOD__,
3061 function ( IDatabase $dbw, $fname ) {
3062 $dbw->delete(
3063 'protected_titles',
3064 [ 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
3065 $fname
3066 );
3067 }
3068 ) );
3069 }
3070
3071 /**
3072 * Does this have subpages? (Warning, usually requires an extra DB query.)
3073 *
3074 * @return bool
3075 */
3076 public function hasSubpages() {
3077 if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
3078 # Duh
3079 return false;
3080 }
3081
3082 # We dynamically add a member variable for the purpose of this method
3083 # alone to cache the result. There's no point in having it hanging
3084 # around uninitialized in every Title object; therefore we only add it
3085 # if needed and don't declare it statically.
3086 if ( $this->mHasSubpages === null ) {
3087 $this->mHasSubpages = false;
3088 $subpages = $this->getSubpages( 1 );
3089 if ( $subpages instanceof TitleArray ) {
3090 $this->mHasSubpages = (bool)$subpages->count();
3091 }
3092 }
3093
3094 return $this->mHasSubpages;
3095 }
3096
3097 /**
3098 * Get all subpages of this page.
3099 *
3100 * @param int $limit Maximum number of subpages to fetch; -1 for no limit
3101 * @return TitleArray|array TitleArray, or empty array if this page's namespace
3102 * doesn't allow subpages
3103 */
3104 public function getSubpages( $limit = -1 ) {
3105 if ( !MWNamespace::hasSubpages( $this->getNamespace() ) ) {
3106 return [];
3107 }
3108
3109 $dbr = wfGetDB( DB_REPLICA );
3110 $conds['page_namespace'] = $this->getNamespace();
3111 $conds[] = 'page_title ' . $dbr->buildLike( $this->getDBkey() . '/', $dbr->anyString() );
3112 $options = [];
3113 if ( $limit > -1 ) {
3114 $options['LIMIT'] = $limit;
3115 }
3116 $this->mSubpages = TitleArray::newFromResult(
3117 $dbr->select( 'page',