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