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