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