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