Merge "Revert "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 && !$user->isAllowed( 'protect' ) ) {
2126 $errors[] = [ 'protectedpagetext', 'protect', $action ];
2127 }
2128 }
2129
2130 return $errors;
2131 }
2132
2133 /**
2134 * Check restrictions on cascading pages.
2135 *
2136 * @param string $action The action to check
2137 * @param User $user User to check
2138 * @param array $errors List of current errors
2139 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2140 * @param bool $short Short circuit on first error
2141 *
2142 * @return array List of errors
2143 */
2144 private function checkCascadingSourcesRestrictions( $action, $user, $errors, $rigor, $short ) {
2145 if ( $rigor !== 'quick' && !$this->isCssJsSubpage() ) {
2146 # We /could/ use the protection level on the source page, but it's
2147 # fairly ugly as we have to establish a precedence hierarchy for pages
2148 # included by multiple cascade-protected pages. So just restrict
2149 # it to people with 'protect' permission, as they could remove the
2150 # protection anyway.
2151 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
2152 # Cascading protection depends on more than this page...
2153 # Several cascading protected pages may include this page...
2154 # Check each cascading level
2155 # This is only for protection restrictions, not for all actions
2156 if ( isset( $restrictions[$action] ) ) {
2157 foreach ( $restrictions[$action] as $right ) {
2158 // Backwards compatibility, rewrite sysop -> editprotected
2159 if ( $right == 'sysop' ) {
2160 $right = 'editprotected';
2161 }
2162 // Backwards compatibility, rewrite autoconfirmed -> editsemiprotected
2163 if ( $right == 'autoconfirmed' ) {
2164 $right = 'editsemiprotected';
2165 }
2166 if ( $right != '' && !$user->isAllowedAll( 'protect', $right ) ) {
2167 $pages = '';
2168 foreach ( $cascadingSources as $page ) {
2169 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
2170 }
2171 $errors[] = [ 'cascadeprotected', count( $cascadingSources ), $pages, $action ];
2172 }
2173 }
2174 }
2175 }
2176
2177 return $errors;
2178 }
2179
2180 /**
2181 * Check action permissions not already checked in checkQuickPermissions
2182 *
2183 * @param string $action The action to check
2184 * @param User $user User to check
2185 * @param array $errors List of current errors
2186 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2187 * @param bool $short Short circuit on first error
2188 *
2189 * @return array List of errors
2190 */
2191 private function checkActionPermissions( $action, $user, $errors, $rigor, $short ) {
2192 global $wgDeleteRevisionsLimit, $wgLang;
2193
2194 if ( $action == 'protect' ) {
2195 if ( count( $this->getUserPermissionsErrorsInternal( 'edit', $user, $rigor, true ) ) ) {
2196 // If they can't edit, they shouldn't protect.
2197 $errors[] = [ 'protect-cantedit' ];
2198 }
2199 } elseif ( $action == 'create' ) {
2200 $title_protection = $this->getTitleProtection();
2201 if ( $title_protection ) {
2202 if ( $title_protection['permission'] == ''
2203 || !$user->isAllowed( $title_protection['permission'] )
2204 ) {
2205 $errors[] = [
2206 'titleprotected',
2207 User::whoIs( $title_protection['user'] ),
2208 $title_protection['reason']
2209 ];
2210 }
2211 }
2212 } elseif ( $action == 'move' ) {
2213 // Check for immobile pages
2214 if ( !MWNamespace::isMovable( $this->mNamespace ) ) {
2215 // Specific message for this case
2216 $errors[] = [ 'immobile-source-namespace', $this->getNsText() ];
2217 } elseif ( !$this->isMovable() ) {
2218 // Less specific message for rarer cases
2219 $errors[] = [ 'immobile-source-page' ];
2220 }
2221 } elseif ( $action == 'move-target' ) {
2222 if ( !MWNamespace::isMovable( $this->mNamespace ) ) {
2223 $errors[] = [ 'immobile-target-namespace', $this->getNsText() ];
2224 } elseif ( !$this->isMovable() ) {
2225 $errors[] = [ 'immobile-target-page' ];
2226 }
2227 } elseif ( $action == 'delete' ) {
2228 $tempErrors = $this->checkPageRestrictions( 'edit', $user, [], $rigor, true );
2229 if ( !$tempErrors ) {
2230 $tempErrors = $this->checkCascadingSourcesRestrictions( 'edit',
2231 $user, $tempErrors, $rigor, true );
2232 }
2233 if ( $tempErrors ) {
2234 // If protection keeps them from editing, they shouldn't be able to delete.
2235 $errors[] = [ 'deleteprotected' ];
2236 }
2237 if ( $rigor !== 'quick' && $wgDeleteRevisionsLimit
2238 && !$this->userCan( 'bigdelete', $user ) && $this->isBigDeletion()
2239 ) {
2240 $errors[] = [ 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ];
2241 }
2242 }
2243 return $errors;
2244 }
2245
2246 /**
2247 * Check that the user isn't blocked from editing.
2248 *
2249 * @param string $action The action to check
2250 * @param User $user User to check
2251 * @param array $errors List of current errors
2252 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2253 * @param bool $short Short circuit on first error
2254 *
2255 * @return array List of errors
2256 */
2257 private function checkUserBlock( $action, $user, $errors, $rigor, $short ) {
2258 // Account creation blocks handled at userlogin.
2259 // Unblocking handled in SpecialUnblock
2260 if ( $rigor === 'quick' || in_array( $action, [ 'createaccount', 'unblock' ] ) ) {
2261 return $errors;
2262 }
2263
2264 global $wgEmailConfirmToEdit;
2265
2266 if ( $wgEmailConfirmToEdit && !$user->isEmailConfirmed() ) {
2267 $errors[] = [ 'confirmedittext' ];
2268 }
2269
2270 $useSlave = ( $rigor !== 'secure' );
2271 if ( ( $action == 'edit' || $action == 'create' )
2272 && !$user->isBlockedFrom( $this, $useSlave )
2273 ) {
2274 // Don't block the user from editing their own talk page unless they've been
2275 // explicitly blocked from that too.
2276 } elseif ( $user->isBlocked() && $user->getBlock()->prevents( $action ) !== false ) {
2277 // @todo FIXME: Pass the relevant context into this function.
2278 $errors[] = $user->getBlock()->getPermissionsError( RequestContext::getMain() );
2279 }
2280
2281 return $errors;
2282 }
2283
2284 /**
2285 * Check that the user is allowed to read this page.
2286 *
2287 * @param string $action The action to check
2288 * @param User $user User to check
2289 * @param array $errors List of current errors
2290 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2291 * @param bool $short Short circuit on first error
2292 *
2293 * @return array List of errors
2294 */
2295 private function checkReadPermissions( $action, $user, $errors, $rigor, $short ) {
2296 global $wgWhitelistRead, $wgWhitelistReadRegexp;
2297
2298 $whitelisted = false;
2299 if ( User::isEveryoneAllowed( 'read' ) ) {
2300 # Shortcut for public wikis, allows skipping quite a bit of code
2301 $whitelisted = true;
2302 } elseif ( $user->isAllowed( 'read' ) ) {
2303 # If the user is allowed to read pages, he is allowed to read all pages
2304 $whitelisted = true;
2305 } elseif ( $this->isSpecial( 'Userlogin' )
2306 || $this->isSpecial( 'ChangePassword' )
2307 || $this->isSpecial( 'PasswordReset' )
2308 ) {
2309 # Always grant access to the login page.
2310 # Even anons need to be able to log in.
2311 $whitelisted = true;
2312 } elseif ( is_array( $wgWhitelistRead ) && count( $wgWhitelistRead ) ) {
2313 # Time to check the whitelist
2314 # Only do these checks is there's something to check against
2315 $name = $this->getPrefixedText();
2316 $dbName = $this->getPrefixedDBkey();
2317
2318 // Check for explicit whitelisting with and without underscores
2319 if ( in_array( $name, $wgWhitelistRead, true ) || in_array( $dbName, $wgWhitelistRead, true ) ) {
2320 $whitelisted = true;
2321 } elseif ( $this->getNamespace() == NS_MAIN ) {
2322 # Old settings might have the title prefixed with
2323 # a colon for main-namespace pages
2324 if ( in_array( ':' . $name, $wgWhitelistRead ) ) {
2325 $whitelisted = true;
2326 }
2327 } elseif ( $this->isSpecialPage() ) {
2328 # If it's a special page, ditch the subpage bit and check again
2329 $name = $this->getDBkey();
2330 list( $name, /* $subpage */ ) = SpecialPageFactory::resolveAlias( $name );
2331 if ( $name ) {
2332 $pure = SpecialPage::getTitleFor( $name )->getPrefixedText();
2333 if ( in_array( $pure, $wgWhitelistRead, true ) ) {
2334 $whitelisted = true;
2335 }
2336 }
2337 }
2338 }
2339
2340 if ( !$whitelisted && is_array( $wgWhitelistReadRegexp ) && !empty( $wgWhitelistReadRegexp ) ) {
2341 $name = $this->getPrefixedText();
2342 // Check for regex whitelisting
2343 foreach ( $wgWhitelistReadRegexp as $listItem ) {
2344 if ( preg_match( $listItem, $name ) ) {
2345 $whitelisted = true;
2346 break;
2347 }
2348 }
2349 }
2350
2351 if ( !$whitelisted ) {
2352 # If the title is not whitelisted, give extensions a chance to do so...
2353 Hooks::run( 'TitleReadWhitelist', [ $this, $user, &$whitelisted ] );
2354 if ( !$whitelisted ) {
2355 $errors[] = $this->missingPermissionError( $action, $short );
2356 }
2357 }
2358
2359 return $errors;
2360 }
2361
2362 /**
2363 * Get a description array when the user doesn't have the right to perform
2364 * $action (i.e. when User::isAllowed() returns false)
2365 *
2366 * @param string $action The action to check
2367 * @param bool $short Short circuit on first error
2368 * @return array List of errors
2369 */
2370 private function missingPermissionError( $action, $short ) {
2371 // We avoid expensive display logic for quickUserCan's and such
2372 if ( $short ) {
2373 return [ 'badaccess-group0' ];
2374 }
2375
2376 $groups = array_map( [ 'User', 'makeGroupLinkWiki' ],
2377 User::getGroupsWithPermission( $action ) );
2378
2379 if ( count( $groups ) ) {
2380 global $wgLang;
2381 return [
2382 'badaccess-groups',
2383 $wgLang->commaList( $groups ),
2384 count( $groups )
2385 ];
2386 } else {
2387 return [ 'badaccess-group0' ];
2388 }
2389 }
2390
2391 /**
2392 * Can $user perform $action on this page? This is an internal function,
2393 * with multiple levels of checks depending on performance needs; see $rigor below.
2394 * It does not check wfReadOnly().
2395 *
2396 * @param string $action Action that permission needs to be checked for
2397 * @param User $user User to check
2398 * @param string $rigor One of (quick,full,secure)
2399 * - quick : does cheap permission checks from slaves (usable for GUI creation)
2400 * - full : does cheap and expensive checks possibly from a slave
2401 * - secure : does cheap and expensive checks, using the master as needed
2402 * @param bool $short Set this to true to stop after the first permission error.
2403 * @return array Array of arrays of the arguments to wfMessage to explain permissions problems.
2404 */
2405 protected function getUserPermissionsErrorsInternal(
2406 $action, $user, $rigor = 'secure', $short = false
2407 ) {
2408 if ( $rigor === true ) {
2409 $rigor = 'secure'; // b/c
2410 } elseif ( $rigor === false ) {
2411 $rigor = 'quick'; // b/c
2412 } elseif ( !in_array( $rigor, [ 'quick', 'full', 'secure' ] ) ) {
2413 throw new Exception( "Invalid rigor parameter '$rigor'." );
2414 }
2415
2416 # Read has special handling
2417 if ( $action == 'read' ) {
2418 $checks = [
2419 'checkPermissionHooks',
2420 'checkReadPermissions',
2421 ];
2422 # Don't call checkSpecialsAndNSPermissions or checkCSSandJSPermissions
2423 # here as it will lead to duplicate error messages. This is okay to do
2424 # since anywhere that checks for create will also check for edit, and
2425 # those checks are called for edit.
2426 } elseif ( $action == 'create' ) {
2427 $checks = [
2428 'checkQuickPermissions',
2429 'checkPermissionHooks',
2430 'checkPageRestrictions',
2431 'checkCascadingSourcesRestrictions',
2432 'checkActionPermissions',
2433 'checkUserBlock'
2434 ];
2435 } else {
2436 $checks = [
2437 'checkQuickPermissions',
2438 'checkPermissionHooks',
2439 'checkSpecialsAndNSPermissions',
2440 'checkCSSandJSPermissions',
2441 'checkPageRestrictions',
2442 'checkCascadingSourcesRestrictions',
2443 'checkActionPermissions',
2444 'checkUserBlock'
2445 ];
2446 }
2447
2448 $errors = [];
2449 while ( count( $checks ) > 0 &&
2450 !( $short && count( $errors ) > 0 ) ) {
2451 $method = array_shift( $checks );
2452 $errors = $this->$method( $action, $user, $errors, $rigor, $short );
2453 }
2454
2455 return $errors;
2456 }
2457
2458 /**
2459 * Get a filtered list of all restriction types supported by this wiki.
2460 * @param bool $exists True to get all restriction types that apply to
2461 * titles that do exist, False for all restriction types that apply to
2462 * titles that do not exist
2463 * @return array
2464 */
2465 public static function getFilteredRestrictionTypes( $exists = true ) {
2466 global $wgRestrictionTypes;
2467 $types = $wgRestrictionTypes;
2468 if ( $exists ) {
2469 # Remove the create restriction for existing titles
2470 $types = array_diff( $types, [ 'create' ] );
2471 } else {
2472 # Only the create and upload restrictions apply to non-existing titles
2473 $types = array_intersect( $types, [ 'create', 'upload' ] );
2474 }
2475 return $types;
2476 }
2477
2478 /**
2479 * Returns restriction types for the current Title
2480 *
2481 * @return array Applicable restriction types
2482 */
2483 public function getRestrictionTypes() {
2484 if ( $this->isSpecialPage() ) {
2485 return [];
2486 }
2487
2488 $types = self::getFilteredRestrictionTypes( $this->exists() );
2489
2490 if ( $this->getNamespace() != NS_FILE ) {
2491 # Remove the upload restriction for non-file titles
2492 $types = array_diff( $types, [ 'upload' ] );
2493 }
2494
2495 Hooks::run( 'TitleGetRestrictionTypes', [ $this, &$types ] );
2496
2497 wfDebug( __METHOD__ . ': applicable restrictions to [[' .
2498 $this->getPrefixedText() . ']] are {' . implode( ',', $types ) . "}\n" );
2499
2500 return $types;
2501 }
2502
2503 /**
2504 * Is this title subject to title protection?
2505 * Title protection is the one applied against creation of such title.
2506 *
2507 * @return array|bool An associative array representing any existent title
2508 * protection, or false if there's none.
2509 */
2510 public function getTitleProtection() {
2511 // Can't protect pages in special namespaces
2512 if ( $this->getNamespace() < 0 ) {
2513 return false;
2514 }
2515
2516 // Can't protect pages that exist.
2517 if ( $this->exists() ) {
2518 return false;
2519 }
2520
2521 if ( $this->mTitleProtection === null ) {
2522 $dbr = wfGetDB( DB_SLAVE );
2523 $res = $dbr->select(
2524 'protected_titles',
2525 [
2526 'user' => 'pt_user',
2527 'reason' => 'pt_reason',
2528 'expiry' => 'pt_expiry',
2529 'permission' => 'pt_create_perm'
2530 ],
2531 [ 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ],
2532 __METHOD__
2533 );
2534
2535 // fetchRow returns false if there are no rows.
2536 $row = $dbr->fetchRow( $res );
2537 if ( $row ) {
2538 if ( $row['permission'] == 'sysop' ) {
2539 $row['permission'] = 'editprotected'; // B/C
2540 }
2541 if ( $row['permission'] == 'autoconfirmed' ) {
2542 $row['permission'] = 'editsemiprotected'; // B/C
2543 }
2544 $row['expiry'] = $dbr->decodeExpiry( $row['expiry'] );
2545 }
2546 $this->mTitleProtection = $row;
2547 }
2548 return $this->mTitleProtection;
2549 }
2550
2551 /**
2552 * Remove any title protection due to page existing
2553 */
2554 public function deleteTitleProtection() {
2555 $dbw = wfGetDB( DB_MASTER );
2556
2557 $dbw->delete(
2558 'protected_titles',
2559 [ 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ],
2560 __METHOD__
2561 );
2562 $this->mTitleProtection = false;
2563 }
2564
2565 /**
2566 * Is this page "semi-protected" - the *only* protection levels are listed
2567 * in $wgSemiprotectedRestrictionLevels?
2568 *
2569 * @param string $action Action to check (default: edit)
2570 * @return bool
2571 */
2572 public function isSemiProtected( $action = 'edit' ) {
2573 global $wgSemiprotectedRestrictionLevels;
2574
2575 $restrictions = $this->getRestrictions( $action );
2576 $semi = $wgSemiprotectedRestrictionLevels;
2577 if ( !$restrictions || !$semi ) {
2578 // Not protected, or all protection is full protection
2579 return false;
2580 }
2581
2582 // Remap autoconfirmed to editsemiprotected for BC
2583 foreach ( array_keys( $semi, 'autoconfirmed' ) as $key ) {
2584 $semi[$key] = 'editsemiprotected';
2585 }
2586 foreach ( array_keys( $restrictions, 'autoconfirmed' ) as $key ) {
2587 $restrictions[$key] = 'editsemiprotected';
2588 }
2589
2590 return !array_diff( $restrictions, $semi );
2591 }
2592
2593 /**
2594 * Does the title correspond to a protected article?
2595 *
2596 * @param string $action The action the page is protected from,
2597 * by default checks all actions.
2598 * @return bool
2599 */
2600 public function isProtected( $action = '' ) {
2601 global $wgRestrictionLevels;
2602
2603 $restrictionTypes = $this->getRestrictionTypes();
2604
2605 # Special pages have inherent protection
2606 if ( $this->isSpecialPage() ) {
2607 return true;
2608 }
2609
2610 # Check regular protection levels
2611 foreach ( $restrictionTypes as $type ) {
2612 if ( $action == $type || $action == '' ) {
2613 $r = $this->getRestrictions( $type );
2614 foreach ( $wgRestrictionLevels as $level ) {
2615 if ( in_array( $level, $r ) && $level != '' ) {
2616 return true;
2617 }
2618 }
2619 }
2620 }
2621
2622 return false;
2623 }
2624
2625 /**
2626 * Determines if $user is unable to edit this page because it has been protected
2627 * by $wgNamespaceProtection.
2628 *
2629 * @param User $user User object to check permissions
2630 * @return bool
2631 */
2632 public function isNamespaceProtected( User $user ) {
2633 global $wgNamespaceProtection;
2634
2635 if ( isset( $wgNamespaceProtection[$this->mNamespace] ) ) {
2636 foreach ( (array)$wgNamespaceProtection[$this->mNamespace] as $right ) {
2637 if ( $right != '' && !$user->isAllowed( $right ) ) {
2638 return true;
2639 }
2640 }
2641 }
2642 return false;
2643 }
2644
2645 /**
2646 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
2647 *
2648 * @return bool If the page is subject to cascading restrictions.
2649 */
2650 public function isCascadeProtected() {
2651 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
2652 return ( $sources > 0 );
2653 }
2654
2655 /**
2656 * Determines whether cascading protection sources have already been loaded from
2657 * the database.
2658 *
2659 * @param bool $getPages True to check if the pages are loaded, or false to check
2660 * if the status is loaded.
2661 * @return bool Whether or not the specified information has been loaded
2662 * @since 1.23
2663 */
2664 public function areCascadeProtectionSourcesLoaded( $getPages = true ) {
2665 return $getPages ? $this->mCascadeSources !== null : $this->mHasCascadingRestrictions !== null;
2666 }
2667
2668 /**
2669 * Cascading protection: Get the source of any cascading restrictions on this page.
2670 *
2671 * @param bool $getPages Whether or not to retrieve the actual pages
2672 * that the restrictions have come from and the actual restrictions
2673 * themselves.
2674 * @return array Two elements: First is an array of Title objects of the
2675 * pages from which cascading restrictions have come, false for
2676 * none, or true if such restrictions exist but $getPages was not
2677 * set. Second is an array like that returned by
2678 * Title::getAllRestrictions(), or an empty array if $getPages is
2679 * false.
2680 */
2681 public function getCascadeProtectionSources( $getPages = true ) {
2682 $pagerestrictions = [];
2683
2684 if ( $this->mCascadeSources !== null && $getPages ) {
2685 return [ $this->mCascadeSources, $this->mCascadingRestrictions ];
2686 } elseif ( $this->mHasCascadingRestrictions !== null && !$getPages ) {
2687 return [ $this->mHasCascadingRestrictions, $pagerestrictions ];
2688 }
2689
2690 $dbr = wfGetDB( DB_SLAVE );
2691
2692 if ( $this->getNamespace() == NS_FILE ) {
2693 $tables = [ 'imagelinks', 'page_restrictions' ];
2694 $where_clauses = [
2695 'il_to' => $this->getDBkey(),
2696 'il_from=pr_page',
2697 'pr_cascade' => 1
2698 ];
2699 } else {
2700 $tables = [ 'templatelinks', 'page_restrictions' ];
2701 $where_clauses = [
2702 'tl_namespace' => $this->getNamespace(),
2703 'tl_title' => $this->getDBkey(),
2704 'tl_from=pr_page',
2705 'pr_cascade' => 1
2706 ];
2707 }
2708
2709 if ( $getPages ) {
2710 $cols = [ 'pr_page', 'page_namespace', 'page_title',
2711 'pr_expiry', 'pr_type', 'pr_level' ];
2712 $where_clauses[] = 'page_id=pr_page';
2713 $tables[] = 'page';
2714 } else {
2715 $cols = [ 'pr_expiry' ];
2716 }
2717
2718 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__ );
2719
2720 $sources = $getPages ? [] : false;
2721 $now = wfTimestampNow();
2722
2723 foreach ( $res as $row ) {
2724 $expiry = $dbr->decodeExpiry( $row->pr_expiry );
2725 if ( $expiry > $now ) {
2726 if ( $getPages ) {
2727 $page_id = $row->pr_page;
2728 $page_ns = $row->page_namespace;
2729 $page_title = $row->page_title;
2730 $sources[$page_id] = Title::makeTitle( $page_ns, $page_title );
2731 # Add groups needed for each restriction type if its not already there
2732 # Make sure this restriction type still exists
2733
2734 if ( !isset( $pagerestrictions[$row->pr_type] ) ) {
2735 $pagerestrictions[$row->pr_type] = [];
2736 }
2737
2738 if (
2739 isset( $pagerestrictions[$row->pr_type] )
2740 && !in_array( $row->pr_level, $pagerestrictions[$row->pr_type] )
2741 ) {
2742 $pagerestrictions[$row->pr_type][] = $row->pr_level;
2743 }
2744 } else {
2745 $sources = true;
2746 }
2747 }
2748 }
2749
2750 if ( $getPages ) {
2751 $this->mCascadeSources = $sources;
2752 $this->mCascadingRestrictions = $pagerestrictions;
2753 } else {
2754 $this->mHasCascadingRestrictions = $sources;
2755 }
2756
2757 return [ $sources, $pagerestrictions ];
2758 }
2759
2760 /**
2761 * Accessor for mRestrictionsLoaded
2762 *
2763 * @return bool Whether or not the page's restrictions have already been
2764 * loaded from the database
2765 * @since 1.23
2766 */
2767 public function areRestrictionsLoaded() {
2768 return $this->mRestrictionsLoaded;
2769 }
2770
2771 /**
2772 * Accessor/initialisation for mRestrictions
2773 *
2774 * @param string $action Action that permission needs to be checked for
2775 * @return array Restriction levels needed to take the action. All levels are
2776 * required. Note that restriction levels are normally user rights, but 'sysop'
2777 * and 'autoconfirmed' are also allowed for backwards compatibility. These should
2778 * be mapped to 'editprotected' and 'editsemiprotected' respectively.
2779 */
2780 public function getRestrictions( $action ) {
2781 if ( !$this->mRestrictionsLoaded ) {
2782 $this->loadRestrictions();
2783 }
2784 return isset( $this->mRestrictions[$action] )
2785 ? $this->mRestrictions[$action]
2786 : [];
2787 }
2788
2789 /**
2790 * Accessor/initialisation for mRestrictions
2791 *
2792 * @return array Keys are actions, values are arrays as returned by
2793 * Title::getRestrictions()
2794 * @since 1.23
2795 */
2796 public function getAllRestrictions() {
2797 if ( !$this->mRestrictionsLoaded ) {
2798 $this->loadRestrictions();
2799 }
2800 return $this->mRestrictions;
2801 }
2802
2803 /**
2804 * Get the expiry time for the restriction against a given action
2805 *
2806 * @param string $action
2807 * @return string|bool 14-char timestamp, or 'infinity' if the page is protected forever
2808 * or not protected at all, or false if the action is not recognised.
2809 */
2810 public function getRestrictionExpiry( $action ) {
2811 if ( !$this->mRestrictionsLoaded ) {
2812 $this->loadRestrictions();
2813 }
2814 return isset( $this->mRestrictionsExpiry[$action] ) ? $this->mRestrictionsExpiry[$action] : false;
2815 }
2816
2817 /**
2818 * Returns cascading restrictions for the current article
2819 *
2820 * @return bool
2821 */
2822 function areRestrictionsCascading() {
2823 if ( !$this->mRestrictionsLoaded ) {
2824 $this->loadRestrictions();
2825 }
2826
2827 return $this->mCascadeRestriction;
2828 }
2829
2830 /**
2831 * Loads a string into mRestrictions array
2832 *
2833 * @param ResultWrapper $res Resource restrictions as an SQL result.
2834 * @param string $oldFashionedRestrictions Comma-separated list of page
2835 * restrictions from page table (pre 1.10)
2836 */
2837 private function loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions = null ) {
2838 $rows = [];
2839
2840 foreach ( $res as $row ) {
2841 $rows[] = $row;
2842 }
2843
2844 $this->loadRestrictionsFromRows( $rows, $oldFashionedRestrictions );
2845 }
2846
2847 /**
2848 * Compiles list of active page restrictions from both page table (pre 1.10)
2849 * and page_restrictions table for this existing page.
2850 * Public for usage by LiquidThreads.
2851 *
2852 * @param array $rows Array of db result objects
2853 * @param string $oldFashionedRestrictions Comma-separated list of page
2854 * restrictions from page table (pre 1.10)
2855 */
2856 public function loadRestrictionsFromRows( $rows, $oldFashionedRestrictions = null ) {
2857 $dbr = wfGetDB( DB_SLAVE );
2858
2859 $restrictionTypes = $this->getRestrictionTypes();
2860
2861 foreach ( $restrictionTypes as $type ) {
2862 $this->mRestrictions[$type] = [];
2863 $this->mRestrictionsExpiry[$type] = 'infinity';
2864 }
2865
2866 $this->mCascadeRestriction = false;
2867
2868 # Backwards-compatibility: also load the restrictions from the page record (old format).
2869 if ( $oldFashionedRestrictions !== null ) {
2870 $this->mOldRestrictions = $oldFashionedRestrictions;
2871 }
2872
2873 if ( $this->mOldRestrictions === false ) {
2874 $this->mOldRestrictions = $dbr->selectField( 'page', 'page_restrictions',
2875 [ 'page_id' => $this->getArticleID() ], __METHOD__ );
2876 }
2877
2878 if ( $this->mOldRestrictions != '' ) {
2879 foreach ( explode( ':', trim( $this->mOldRestrictions ) ) as $restrict ) {
2880 $temp = explode( '=', trim( $restrict ) );
2881 if ( count( $temp ) == 1 ) {
2882 // old old format should be treated as edit/move restriction
2883 $this->mRestrictions['edit'] = explode( ',', trim( $temp[0] ) );
2884 $this->mRestrictions['move'] = explode( ',', trim( $temp[0] ) );
2885 } else {
2886 $restriction = trim( $temp[1] );
2887 if ( $restriction != '' ) { // some old entries are empty
2888 $this->mRestrictions[$temp[0]] = explode( ',', $restriction );
2889 }
2890 }
2891 }
2892 }
2893
2894 if ( count( $rows ) ) {
2895 # Current system - load second to make them override.
2896 $now = wfTimestampNow();
2897
2898 # Cycle through all the restrictions.
2899 foreach ( $rows as $row ) {
2900
2901 // Don't take care of restrictions types that aren't allowed
2902 if ( !in_array( $row->pr_type, $restrictionTypes ) ) {
2903 continue;
2904 }
2905
2906 // This code should be refactored, now that it's being used more generally,
2907 // But I don't really see any harm in leaving it in Block for now -werdna
2908 $expiry = $dbr->decodeExpiry( $row->pr_expiry );
2909
2910 // Only apply the restrictions if they haven't expired!
2911 if ( !$expiry || $expiry > $now ) {
2912 $this->mRestrictionsExpiry[$row->pr_type] = $expiry;
2913 $this->mRestrictions[$row->pr_type] = explode( ',', trim( $row->pr_level ) );
2914
2915 $this->mCascadeRestriction |= $row->pr_cascade;
2916 }
2917 }
2918 }
2919
2920 $this->mRestrictionsLoaded = true;
2921 }
2922
2923 /**
2924 * Load restrictions from the page_restrictions table
2925 *
2926 * @param string $oldFashionedRestrictions Comma-separated list of page
2927 * restrictions from page table (pre 1.10)
2928 */
2929 public function loadRestrictions( $oldFashionedRestrictions = null ) {
2930 if ( !$this->mRestrictionsLoaded ) {
2931 $dbr = wfGetDB( DB_SLAVE );
2932 if ( $this->exists() ) {
2933 $res = $dbr->select(
2934 'page_restrictions',
2935 [ 'pr_type', 'pr_expiry', 'pr_level', 'pr_cascade' ],
2936 [ 'pr_page' => $this->getArticleID() ],
2937 __METHOD__
2938 );
2939
2940 $this->loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions );
2941 } else {
2942 $title_protection = $this->getTitleProtection();
2943
2944 if ( $title_protection ) {
2945 $now = wfTimestampNow();
2946 $expiry = $dbr->decodeExpiry( $title_protection['expiry'] );
2947
2948 if ( !$expiry || $expiry > $now ) {
2949 // Apply the restrictions
2950 $this->mRestrictionsExpiry['create'] = $expiry;
2951 $this->mRestrictions['create'] = explode( ',', trim( $title_protection['permission'] ) );
2952 } else { // Get rid of the old restrictions
2953 $this->mTitleProtection = false;
2954 }
2955 } else {
2956 $this->mRestrictionsExpiry['create'] = 'infinity';
2957 }
2958 $this->mRestrictionsLoaded = true;
2959 }
2960 }
2961 }
2962
2963 /**
2964 * Flush the protection cache in this object and force reload from the database.
2965 * This is used when updating protection from WikiPage::doUpdateRestrictions().
2966 */
2967 public function flushRestrictions() {
2968 $this->mRestrictionsLoaded = false;
2969 $this->mTitleProtection = null;
2970 }
2971
2972 /**
2973 * Purge expired restrictions from the page_restrictions table
2974 */
2975 static function purgeExpiredRestrictions() {
2976 if ( wfReadOnly() ) {
2977 return;
2978 }
2979
2980 DeferredUpdates::addUpdate( new AtomicSectionUpdate(
2981 wfGetDB( DB_MASTER ),
2982 __METHOD__,
2983 function ( IDatabase $dbw, $fname ) {
2984 $dbw->delete(
2985 'page_restrictions',
2986 [ 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
2987 $fname
2988 );
2989 $dbw->delete(
2990 'protected_titles',
2991 [ 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
2992 $fname
2993 );
2994 }
2995 ) );
2996 }
2997
2998 /**
2999 * Does this have subpages? (Warning, usually requires an extra DB query.)
3000 *
3001 * @return bool
3002 */
3003 public function hasSubpages() {
3004 if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
3005 # Duh
3006 return false;
3007 }
3008
3009 # We dynamically add a member variable for the purpose of this method
3010 # alone to cache the result. There's no point in having it hanging
3011 # around uninitialized in every Title object; therefore we only add it
3012 # if needed and don't declare it statically.
3013 if ( $this->mHasSubpages === null ) {
3014 $this->mHasSubpages = false;
3015 $subpages = $this->getSubpages( 1 );
3016 if ( $subpages instanceof TitleArray ) {
3017 $this->mHasSubpages = (bool)$subpages->count();
3018 }
3019 }
3020
3021 return $this->mHasSubpages;
3022 }
3023
3024 /**
3025 * Get all subpages of this page.
3026 *
3027 * @param int $limit Maximum number of subpages to fetch; -1 for no limit
3028 * @return TitleArray|array TitleArray, or empty array if this page's namespace
3029 * doesn't allow subpages
3030 */
3031 public function getSubpages( $limit = -1 ) {
3032 if ( !MWNamespace::hasSubpages( $this->getNamespace() ) ) {
3033 return [];
3034 }
3035
3036 $dbr = wfGetDB( DB_SLAVE );
3037 $conds['page_namespace'] = $this->getNamespace();
3038 $conds[] = 'page_title ' . $dbr->buildLike( $this->getDBkey() . '/', $dbr->anyString() );
3039 $options = [];
3040 if ( $limit > -1 ) {
3041 $options['LIMIT'] = $limit;
3042 }
3043 $this->mSubpages = TitleArray::newFromResult(
3044 $dbr->select( 'page',
3045 [ 'page_id', 'page_namespace', 'page_title', 'page_is_redirect' ],
3046 $conds,
3047 __METHOD__,
3048 $options
3049 )
3050 );
3051 return $this->mSubpages;
3052 }
3053
3054 /**
3055 * Is there a version of this page in the deletion archive?
3056 *
3057 * @return int The number of archived revisions
3058 */
3059 public function isDeleted() {
3060 if ( $this->getNamespace() < 0 ) {
3061 $n = 0;
3062 } else {
3063 $dbr = wfGetDB( DB_SLAVE );
3064
3065 $n = $dbr->selectField( 'archive', 'COUNT(*)',
3066 [ 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ],
3067 __METHOD__
3068 );
3069 if ( $this->getNamespace() == NS_FILE ) {
3070 $n += $dbr->selectField( 'filearchive', 'COUNT(*)',
3071 [ 'fa_name' => $this->getDBkey() ],
3072 __METHOD__
3073 );
3074 }
3075 }
3076 return (int)$n;
3077 }
3078
3079 /**
3080 * Is there a version of this page in the deletion archive?
3081 *
3082 * @return bool
3083 */
3084 public function isDeletedQuick() {
3085 if ( $this->getNamespace() < 0 ) {
3086 return false;
3087 }
3088 $dbr = wfGetDB( DB_SLAVE );
3089 $deleted = (bool)$dbr->selectField( 'archive', '1',
3090 [ 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ],
3091 __METHOD__
3092 );
3093 if ( !$deleted && $this->getNamespace() == NS_FILE ) {
3094 $deleted = (bool)$dbr->selectField( 'filearchive', '1',
3095 [ 'fa_name' => $this->getDBkey() ],
3096 __METHOD__
3097 );
3098 }
3099 return $deleted;
3100 }
3101
3102 /**
3103 * Get the article ID for this Title from the link cache,
3104 * adding it if necessary
3105 *
3106 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select
3107 * for update
3108 * @return int The ID
3109 */
3110 public function getArticleID( $flags = 0 ) {
3111 if ( $this->getNamespace() < 0 ) {
3112 $this->mArticleID = 0;
3113 return $this->mArticleID;
3114 }
3115 $linkCache = LinkCache::singleton();
3116 if ( $flags & self::GAID_FOR_UPDATE ) {
3117 $oldUpdate = $linkCache->forUpdate( true );
3118 $linkCache->clearLink( $this );
3119 $this->mArticleID = $linkCache->addLinkObj( $this );
3120 $linkCache->forUpdate( $oldUpdate );
3121 } else {
3122 if ( -1 == $this->mArticleID ) {
3123 $this->mArticleID = $linkCache->addLinkObj( $this );
3124 }
3125 }
3126 return $this->mArticleID;
3127 }
3128
3129 /**
3130 * Is this an article that is a redirect page?
3131 * Uses link cache, adding it if necessary
3132 *
3133 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3134 * @return bool
3135 */
3136 public function isRedirect( $flags = 0 ) {
3137 if ( !is_null( $this->mRedirect ) ) {
3138 return $this->mRedirect;
3139 }
3140 if ( !$this->getArticleID( $flags ) ) {
3141 $this->mRedirect = false;
3142 return $this->mRedirect;
3143 }
3144
3145 $linkCache = LinkCache::singleton();
3146 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3147 $cached = $linkCache->getGoodLinkFieldObj( $this, 'redirect' );
3148 if ( $cached === null ) {
3149 # Trust LinkCache's state over our own
3150 # LinkCache is telling us that the page doesn't exist, despite there being cached
3151 # data relating to an existing page in $this->mArticleID. Updaters should clear
3152 # LinkCache as appropriate, or use $flags = Title::GAID_FOR_UPDATE. If that flag is
3153 # set, then LinkCache will definitely be up to date here, since getArticleID() forces
3154 # LinkCache to refresh its data from the master.
3155 $this->mRedirect = false;
3156 return $this->mRedirect;
3157 }
3158
3159 $this->mRedirect = (bool)$cached;
3160
3161 return $this->mRedirect;
3162 }
3163
3164 /**
3165 * What is the length of this page?
3166 * Uses link cache, adding it if necessary
3167 *
3168 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3169 * @return int
3170 */
3171 public function getLength( $flags = 0 ) {
3172 if ( $this->mLength != -1 ) {
3173 return $this->mLength;
3174 }
3175 if ( !$this->getArticleID( $flags ) ) {
3176 $this->mLength = 0;
3177 return $this->mLength;
3178 }
3179 $linkCache = LinkCache::singleton();
3180 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3181 $cached = $linkCache->getGoodLinkFieldObj( $this, 'length' );
3182 if ( $cached === null ) {
3183 # Trust LinkCache's state over our own, as for isRedirect()
3184 $this->mLength = 0;
3185 return $this->mLength;
3186 }
3187
3188 $this->mLength = intval( $cached );
3189
3190 return $this->mLength;
3191 }
3192
3193 /**
3194 * What is the page_latest field for this page?
3195 *
3196 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3197 * @return int Int or 0 if the page doesn't exist
3198 */
3199 public function getLatestRevID( $flags = 0 ) {
3200 if ( !( $flags & Title::GAID_FOR_UPDATE ) && $this->mLatestID !== false ) {
3201 return intval( $this->mLatestID );
3202 }
3203 if ( !$this->getArticleID( $flags ) ) {
3204 $this->mLatestID = 0;
3205 return $this->mLatestID;
3206 }
3207 $linkCache = LinkCache::singleton();
3208 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3209 $cached = $linkCache->getGoodLinkFieldObj( $this, 'revision' );
3210 if ( $cached === null ) {
3211 # Trust LinkCache's state over our own, as for isRedirect()
3212 $this->mLatestID = 0;
3213 return $this->mLatestID;
3214 }
3215
3216 $this->mLatestID = intval( $cached );
3217
3218 return $this->mLatestID;
3219 }
3220
3221 /**
3222 * This clears some fields in this object, and clears any associated
3223 * keys in the "bad links" section of the link cache.
3224 *
3225 * - This is called from WikiPage::doEdit() and WikiPage::insertOn() to allow
3226 * loading of the new page_id. It's also called from
3227 * WikiPage::doDeleteArticleReal()
3228 *
3229 * @param int $newid The new Article ID
3230 */
3231 public function resetArticleID( $newid ) {
3232 $linkCache = LinkCache::singleton();
3233 $linkCache->clearLink( $this );
3234
3235 if ( $newid === false ) {
3236 $this->mArticleID = -1;
3237 } else {
3238 $this->mArticleID = intval( $newid );
3239 }
3240 $this->mRestrictionsLoaded = false;
3241 $this->mRestrictions = [];
3242 $this->mOldRestrictions = false;
3243 $this->mRedirect = null;
3244 $this->mLength = -1;
3245 $this->mLatestID = false;
3246 $this->mContentModel = false;
3247 $this->mEstimateRevisions = null;
3248 $this->mPageLanguage = false;
3249 $this->mDbPageLanguage = false;
3250 $this->mIsBigDeletion = null;
3251 }
3252
3253 public static function clearCaches() {
3254 $linkCache = LinkCache::singleton();
3255 $linkCache->clear();
3256
3257 $titleCache = self::getTitleCache();
3258 $titleCache->clear();
3259 }
3260
3261 /**
3262 * Capitalize a text string for a title if it belongs to a namespace that capitalizes
3263 *
3264 * @param string $text Containing title to capitalize
3265 * @param int $ns Namespace index, defaults to NS_MAIN
3266 * @return string Containing capitalized title
3267 */
3268 public static function capitalize( $text, $ns = NS_MAIN ) {
3269 global $wgContLang;
3270
3271 if ( MWNamespace::isCapitalized( $ns ) ) {
3272 return $wgContLang->ucfirst( $text );
3273 } else {
3274 return $text;
3275 }
3276 }
3277
3278 /**
3279 * Secure and split - main initialisation function for this object
3280 *
3281 * Assumes that mDbkeyform has been set, and is urldecoded
3282 * and uses underscores, but not otherwise munged. This function
3283 * removes illegal characters, splits off the interwiki and
3284 * namespace prefixes, sets the other forms, and canonicalizes
3285 * everything.
3286 *
3287 * @throws MalformedTitleException On invalid titles
3288 * @return bool True on success
3289 */
3290 private function secureAndSplit() {
3291 # Initialisation
3292 $this->mInterwiki = '';
3293 $this->mFragment = '';
3294 $this->mNamespace = $this->mDefaultNamespace; # Usually NS_MAIN
3295
3296 $dbkey = $this->mDbkeyform;
3297
3298 // @note: splitTitleString() is a temporary hack to allow MediaWikiTitleCodec to share
3299 // the parsing code with Title, while avoiding massive refactoring.
3300 // @todo: get rid of secureAndSplit, refactor parsing code.
3301 // @note: getTitleParser() returns a TitleParser implementation which does not have a
3302 // splitTitleString method, but the only implementation (MediaWikiTitleCodec) does
3303 $titleCodec = MediaWikiServices::getInstance()->getTitleParser();
3304 // MalformedTitleException can be thrown here
3305 $parts = $titleCodec->splitTitleString( $dbkey, $this->getDefaultNamespace() );
3306
3307 # Fill fields
3308 $this->setFragment( '#' . $parts['fragment'] );
3309 $this->mInterwiki = $parts['interwiki'];
3310 $this->mLocalInterwiki = $parts['local_interwiki'];
3311 $this->mNamespace = $parts['namespace'];
3312 $this->mUserCaseDBKey = $parts['user_case_dbkey'];
3313
3314 $this->mDbkeyform = $parts['dbkey'];
3315 $this->mUrlform = wfUrlencode( $this->mDbkeyform );
3316 $this->mTextform = strtr( $this->mDbkeyform, '_', ' ' );
3317
3318 # We already know that some pages won't be in the database!
3319 if ( $this->isExternal() || $this->mNamespace == NS_SPECIAL ) {
3320 $this->mArticleID = 0;
3321 }
3322
3323 return true;
3324 }
3325
3326 /**
3327 * Get an array of Title objects linking to this Title
3328 * Also stores the IDs in the link cache.
3329 *
3330 * WARNING: do not use this function on arbitrary user-supplied titles!
3331 * On heavily-used templates it will max out the memory.
3332 *
3333 * @param array $options May be FOR UPDATE
3334 * @param string $table Table name
3335 * @param string $prefix Fields prefix
3336 * @return Title[] Array of Title objects linking here
3337 */
3338 public function getLinksTo( $options = [], $table = 'pagelinks', $prefix = 'pl' ) {
3339 if ( count( $options ) > 0 ) {
3340 $db = wfGetDB( DB_MASTER );
3341 } else {
3342 $db = wfGetDB( DB_SLAVE );
3343 }
3344
3345 $res = $db->select(
3346 [ 'page', $table ],
3347 self::getSelectFields(),
3348 [
3349 "{$prefix}_from=page_id",
3350 "{$prefix}_namespace" => $this->getNamespace(),
3351 "{$prefix}_title" => $this->getDBkey() ],
3352 __METHOD__,
3353 $options
3354 );
3355
3356 $retVal = [];
3357 if ( $res->numRows() ) {
3358 $linkCache = LinkCache::singleton();
3359 foreach ( $res as $row ) {
3360 $titleObj = Title::makeTitle( $row->page_namespace, $row->page_title );
3361 if ( $titleObj ) {
3362 $linkCache->addGoodLinkObjFromRow( $titleObj, $row );
3363 $retVal[] = $titleObj;
3364 }
3365 }
3366 }
3367 return $retVal;
3368 }
3369
3370 /**
3371 * Get an array of Title objects using this Title as a template
3372 * Also stores the IDs in the link cache.
3373 *
3374 * WARNING: do not use this function on arbitrary user-supplied titles!
3375 * On heavily-used templates it will max out the memory.
3376 *
3377 * @param array $options Query option to Database::select()
3378 * @return Title[] Array of Title the Title objects linking here
3379 */
3380 public function getTemplateLinksTo( $options = [] ) {
3381 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
3382 }
3383
3384 /**
3385 * Get an array of Title objects linked from this Title
3386 * Also stores the IDs in the link cache.
3387 *
3388 * WARNING: do not use this function on arbitrary user-supplied titles!
3389 * On heavily-used templates it will max out the memory.
3390 *
3391 * @param array $options Query option to Database::select()
3392 * @param string $table Table name
3393 * @param string $prefix Fields prefix
3394 * @return array Array of Title objects linking here
3395 */
3396 public function getLinksFrom( $options = [], $table = 'pagelinks', $prefix = 'pl' ) {
3397 $id = $this->getArticleID();
3398
3399 # If the page doesn't exist; there can't be any link from this page
3400 if ( !$id ) {
3401 return [];
3402 }
3403
3404 $db = wfGetDB( DB_SLAVE );
3405
3406 $blNamespace = "{$prefix}_namespace";
3407 $blTitle = "{$prefix}_title";
3408
3409 $res = $db->select(
3410 [ $table, 'page' ],
3411 array_merge(
3412 [ $blNamespace, $blTitle ],
3413 WikiPage::selectFields()
3414 ),
3415 [ "{$prefix}_from" => $id ],
3416 __METHOD__,
3417 $options,
3418 [ 'page' => [
3419 'LEFT JOIN',
3420 [ "page_namespace=$blNamespace", "page_title=$blTitle" ]
3421 ] ]
3422 );
3423
3424 $retVal = [];
3425 $linkCache = LinkCache::singleton();
3426 foreach ( $res as $row ) {
3427 if ( $row->page_id ) {
3428 $titleObj = Title::newFromRow( $row );
3429 } else {
3430 $titleObj = Title::makeTitle( $row->$blNamespace, $row->$blTitle );
3431 $linkCache->addBadLinkObj( $titleObj );
3432 }
3433 $retVal[] = $titleObj;
3434 }
3435
3436 return $retVal;
3437 }
3438
3439 /**
3440 * Get an array of Title objects used on this Title as a template
3441 * Also stores the IDs in the link cache.
3442 *
3443 * WARNING: do not use this function on arbitrary user-supplied titles!
3444 * On heavily-used templates it will max out the memory.
3445 *
3446 * @param array $options May be FOR UPDATE
3447 * @return Title[] Array of Title the Title objects used here
3448 */
3449 public function getTemplateLinksFrom( $options = [] ) {
3450 return $this->getLinksFrom( $options, 'templatelinks', 'tl' );
3451 }
3452
3453 /**
3454 * Get an array of Title objects referring to non-existent articles linked
3455 * from this page.
3456 *
3457 * @todo check if needed (used only in SpecialBrokenRedirects.php, and
3458 * should use redirect table in this case).
3459 * @return Title[] Array of Title the Title objects
3460 */
3461 public function getBrokenLinksFrom() {
3462 if ( $this->getArticleID() == 0 ) {
3463 # All links from article ID 0 are false positives
3464 return [];
3465 }
3466
3467 $dbr = wfGetDB( DB_SLAVE );
3468 $res = $dbr->select(
3469 [ 'page', 'pagelinks' ],
3470 [ 'pl_namespace', 'pl_title' ],
3471 [
3472 'pl_from' => $this->getArticleID(),
3473 'page_namespace IS NULL'
3474 ],
3475 __METHOD__, [],
3476 [
3477 'page' => [
3478 'LEFT JOIN',
3479 [ 'pl_namespace=page_namespace', 'pl_title=page_title' ]
3480 ]
3481 ]
3482 );
3483
3484 $retVal = [];
3485 foreach ( $res as $row ) {
3486 $retVal[] = Title::makeTitle( $row->pl_namespace, $row->pl_title );
3487 }
3488 return $retVal;
3489 }
3490
3491 /**
3492 * Get a list of URLs to purge from the CDN cache when this
3493 * page changes
3494 *
3495 * @return string[] Array of String the URLs
3496 */
3497 public function getCdnUrls() {
3498 $urls = [
3499 $this->getInternalURL(),
3500 $this->getInternalURL( 'action=history' )
3501 ];
3502
3503 $pageLang = $this->getPageLanguage();
3504 if ( $pageLang->hasVariants() ) {
3505 $variants = $pageLang->getVariants();
3506 foreach ( $variants as $vCode ) {
3507 $urls[] = $this->getInternalURL( $vCode );
3508 }
3509 }
3510
3511 // If we are looking at a css/js user subpage, purge the action=raw.
3512 if ( $this->isJsSubpage() ) {
3513 $urls[] = $this->getInternalURL( 'action=raw&ctype=text/javascript' );
3514 } elseif ( $this->isCssSubpage() ) {
3515 $urls[] = $this->getInternalURL( 'action=raw&ctype=text/css' );
3516 }
3517
3518 Hooks::run( 'TitleSquidURLs', [ $this, &$urls ] );
3519 return $urls;
3520 }
3521
3522 /**
3523 * @deprecated since 1.27 use getCdnUrls()
3524 */
3525 public function getSquidURLs() {
3526 return $this->getCdnUrls();
3527 }
3528
3529 /**
3530 * Purge all applicable CDN URLs
3531 */
3532 public function purgeSquid() {
3533 DeferredUpdates::addUpdate(
3534 new CdnCacheUpdate( $this->getCdnUrls() ),
3535 DeferredUpdates::PRESEND
3536 );
3537 }
3538
3539 /**
3540 * Move this page without authentication
3541 *
3542 * @deprecated since 1.25 use MovePage class instead
3543 * @param Title $nt The new page Title
3544 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
3545 */
3546 public function moveNoAuth( &$nt ) {
3547 wfDeprecated( __METHOD__, '1.25' );
3548 return $this->moveTo( $nt, false );
3549 }
3550
3551 /**
3552 * Check whether a given move operation would be valid.
3553 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
3554 *
3555 * @deprecated since 1.25, use MovePage's methods instead
3556 * @param Title $nt The new title
3557 * @param bool $auth Whether to check user permissions (uses $wgUser)
3558 * @param string $reason Is the log summary of the move, used for spam checking
3559 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
3560 */
3561 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
3562 global $wgUser;
3563
3564 if ( !( $nt instanceof Title ) ) {
3565 // Normally we'd add this to $errors, but we'll get
3566 // lots of syntax errors if $nt is not an object
3567 return [ [ 'badtitletext' ] ];
3568 }
3569
3570 $mp = new MovePage( $this, $nt );
3571 $errors = $mp->isValidMove()->getErrorsArray();
3572 if ( $auth ) {
3573 $errors = wfMergeErrorArrays(
3574 $errors,
3575 $mp->checkPermissions( $wgUser, $reason )->getErrorsArray()
3576 );
3577 }
3578
3579 return $errors ?: true;
3580 }
3581
3582 /**
3583 * Check if the requested move target is a valid file move target
3584 * @todo move this to MovePage
3585 * @param Title $nt Target title
3586 * @return array List of errors
3587 */
3588 protected function validateFileMoveOperation( $nt ) {
3589 global $wgUser;
3590
3591 $errors = [];
3592
3593 $destFile = wfLocalFile( $nt );
3594 $destFile->load( File::READ_LATEST );
3595 if ( !$wgUser->isAllowed( 'reupload-shared' )
3596 && !$destFile->exists() && wfFindFile( $nt )
3597 ) {
3598 $errors[] = [ 'file-exists-sharedrepo' ];
3599 }
3600
3601 return $errors;
3602 }
3603
3604 /**
3605 * Move a title to a new location
3606 *
3607 * @deprecated since 1.25, use the MovePage class instead
3608 * @param Title $nt The new title
3609 * @param bool $auth Indicates whether $wgUser's permissions
3610 * should be checked
3611 * @param string $reason The reason for the move
3612 * @param bool $createRedirect Whether to create a redirect from the old title to the new title.
3613 * Ignored if the user doesn't have the suppressredirect right.
3614 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
3615 */
3616 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true ) {
3617 global $wgUser;
3618 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
3619 if ( is_array( $err ) ) {
3620 // Auto-block user's IP if the account was "hard" blocked
3621 $wgUser->spreadAnyEditBlock();
3622 return $err;
3623 }
3624 // Check suppressredirect permission
3625 if ( $auth && !$wgUser->isAllowed( 'suppressredirect' ) ) {
3626 $createRedirect = true;
3627 }
3628
3629 $mp = new MovePage( $this, $nt );
3630 $status = $mp->move( $wgUser, $reason, $createRedirect );
3631 if ( $status->isOK() ) {
3632 return true;
3633 } else {
3634 return $status->getErrorsArray();
3635 }
3636 }
3637
3638 /**
3639 * Move this page's subpages to be subpages of $nt
3640 *
3641 * @param Title $nt Move target
3642 * @param bool $auth Whether $wgUser's permissions should be checked
3643 * @param string $reason The reason for the move
3644 * @param bool $createRedirect Whether to create redirects from the old subpages to
3645 * the new ones Ignored if the user doesn't have the 'suppressredirect' right
3646 * @return array Array with old page titles as keys, and strings (new page titles) or
3647 * arrays (errors) as values, or an error array with numeric indices if no pages
3648 * were moved
3649 */
3650 public function moveSubpages( $nt, $auth = true, $reason = '', $createRedirect = true ) {
3651 global $wgMaximumMovedPages;
3652 // Check permissions
3653 if ( !$this->userCan( 'move-subpages' ) ) {
3654 return [ 'cant-move-subpages' ];
3655 }
3656 // Do the source and target namespaces support subpages?
3657 if ( !MWNamespace::hasSubpages( $this->getNamespace() ) ) {
3658 return [ 'namespace-nosubpages',
3659 MWNamespace::getCanonicalName( $this->getNamespace() ) ];
3660 }
3661 if ( !MWNamespace::hasSubpages( $nt->getNamespace() ) ) {
3662 return [ 'namespace-nosubpages',
3663 MWNamespace::getCanonicalName( $nt->getNamespace() ) ];
3664 }
3665
3666 $subpages = $this->getSubpages( $wgMaximumMovedPages + 1 );
3667 $retval = [];
3668 $count = 0;
3669 foreach ( $subpages as $oldSubpage ) {
3670 $count++;
3671 if ( $count > $wgMaximumMovedPages ) {
3672 $retval[$oldSubpage->getPrefixedText()] =
3673 [ 'movepage-max-pages',
3674 $wgMaximumMovedPages ];
3675 break;
3676 }
3677
3678 // We don't know whether this function was called before
3679 // or after moving the root page, so check both
3680 // $this and $nt
3681 if ( $oldSubpage->getArticleID() == $this->getArticleID()
3682 || $oldSubpage->getArticleID() == $nt->getArticleID()
3683 ) {
3684 // When moving a page to a subpage of itself,
3685 // don't move it twice
3686 continue;
3687 }
3688 $newPageName = preg_replace(
3689 '#^' . preg_quote( $this->getDBkey(), '#' ) . '#',
3690 StringUtils::escapeRegexReplacement( $nt->getDBkey() ), # bug 21234
3691 $oldSubpage->getDBkey() );
3692 if ( $oldSubpage->isTalkPage() ) {
3693 $newNs = $nt->getTalkPage()->getNamespace();
3694 } else {
3695 $newNs = $nt->getSubjectPage()->getNamespace();
3696 }
3697 # Bug 14385: we need makeTitleSafe because the new page names may
3698 # be longer than 255 characters.
3699 $newSubpage = Title::makeTitleSafe( $newNs, $newPageName );
3700
3701 $success = $oldSubpage->moveTo( $newSubpage, $auth, $reason, $createRedirect );
3702 if ( $success === true ) {
3703 $retval[$oldSubpage->getPrefixedText()] = $newSubpage->getPrefixedText();
3704 } else {
3705 $retval[$oldSubpage->getPrefixedText()] = $success;
3706 }
3707 }
3708 return $retval;
3709 }
3710
3711 /**
3712 * Checks if this page is just a one-rev redirect.
3713 * Adds lock, so don't use just for light purposes.
3714 *
3715 * @return bool
3716 */
3717 public function isSingleRevRedirect() {
3718 global $wgContentHandlerUseDB;
3719
3720 $dbw = wfGetDB( DB_MASTER );
3721
3722 # Is it a redirect?
3723 $fields = [ 'page_is_redirect', 'page_latest', 'page_id' ];
3724 if ( $wgContentHandlerUseDB ) {
3725 $fields[] = 'page_content_model';
3726 }
3727
3728 $row = $dbw->selectRow( 'page',
3729 $fields,
3730 $this->pageCond(),
3731 __METHOD__,
3732 [ 'FOR UPDATE' ]
3733 );
3734 # Cache some fields we may want
3735 $this->mArticleID = $row ? intval( $row->page_id ) : 0;
3736 $this->mRedirect = $row ? (bool)$row->page_is_redirect : false;
3737 $this->mLatestID = $row ? intval( $row->page_latest ) : false;
3738 $this->mContentModel = $row && isset( $row->page_content_model )
3739 ? strval( $row->page_content_model )
3740 : false;
3741
3742 if ( !$this->mRedirect ) {
3743 return false;
3744 }
3745 # Does the article have a history?
3746 $row = $dbw->selectField( [ 'page', 'revision' ],
3747 'rev_id',
3748 [ 'page_namespace' => $this->getNamespace(),
3749 'page_title' => $this->getDBkey(),
3750 'page_id=rev_page',
3751 'page_latest != rev_id'
3752 ],
3753 __METHOD__,
3754 [ 'FOR UPDATE' ]
3755 );
3756 # Return true if there was no history
3757 return ( $row === false );
3758 }
3759
3760 /**
3761 * Checks if $this can be moved to a given Title
3762 * - Selects for update, so don't call it unless you mean business
3763 *
3764 * @deprecated since 1.25, use MovePage's methods instead
3765 * @param Title $nt The new title to check
3766 * @return bool
3767 */
3768 public function isValidMoveTarget( $nt ) {
3769 # Is it an existing file?
3770 if ( $nt->getNamespace() == NS_FILE ) {
3771 $file = wfLocalFile( $nt );
3772 $file->load( File::READ_LATEST );
3773 if ( $file->exists() ) {
3774 wfDebug( __METHOD__ . ": file exists\n" );
3775 return false;
3776 }
3777 }
3778 # Is it a redirect with no history?
3779 if ( !$nt->isSingleRevRedirect() ) {
3780 wfDebug( __METHOD__ . ": not a one-rev redirect\n" );
3781 return false;
3782 }
3783 # Get the article text
3784 $rev = Revision::newFromTitle( $nt, false, Revision::READ_LATEST );
3785 if ( !is_object( $rev ) ) {
3786 return false;
3787 }
3788 $content = $rev->getContent();
3789 # Does the redirect point to the source?
3790 # Or is it a broken self-redirect, usually caused by namespace collisions?
3791 $redirTitle = $content ? $content->getRedirectTarget() : null;
3792
3793 if ( $redirTitle ) {
3794 if ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
3795 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) {
3796 wfDebug( __METHOD__ . ": redirect points to other page\n" );
3797 return false;
3798 } else {
3799 return true;
3800 }
3801 } else {
3802 # Fail safe (not a redirect after all. strange.)
3803 wfDebug( __METHOD__ . ": failsafe: database sais " . $nt->getPrefixedDBkey() .
3804 " is a redirect, but it doesn't contain a valid redirect.\n" );
3805 return false;
3806 }
3807 }
3808
3809 /**
3810 * Get categories to which this Title belongs and return an array of
3811 * categories' names.
3812 *
3813 * @return array Array of parents in the form:
3814 * $parent => $currentarticle
3815 */
3816 public function getParentCategories() {
3817 global $wgContLang;
3818
3819 $data = [];
3820
3821 $titleKey = $this->getArticleID();
3822
3823 if ( $titleKey === 0 ) {
3824 return $data;
3825 }
3826
3827 $dbr = wfGetDB( DB_SLAVE );
3828
3829 $res = $dbr->select(
3830 'categorylinks',
3831 'cl_to',
3832 [ 'cl_from' => $titleKey ],
3833 __METHOD__
3834 );
3835
3836 if ( $res->numRows() > 0 ) {
3837 foreach ( $res as $row ) {
3838 // $data[] = Title::newFromText($wgContLang->getNsText ( NS_CATEGORY ).':'.$row->cl_to);
3839 $data[$wgContLang->getNsText( NS_CATEGORY ) . ':' . $row->cl_to] = $this->getFullText();
3840 }
3841 }
3842 return $data;
3843 }
3844
3845 /**
3846 * Get a tree of parent categories
3847 *
3848 * @param array $children Array with the children in the keys, to check for circular refs
3849 * @return array Tree of parent categories
3850 */
3851 public function getParentCategoryTree( $children = [] ) {
3852 $stack = [];
3853 $parents = $this->getParentCategories();
3854
3855 if ( $parents ) {
3856 foreach ( $parents as $parent => $current ) {
3857 if ( array_key_exists( $parent, $children ) ) {
3858 # Circular reference
3859 $stack[$parent] = [];
3860 } else {
3861 $nt = Title::newFromText( $parent );
3862 if ( $nt ) {
3863 $stack[$parent] = $nt->getParentCategoryTree( $children + [ $parent => 1 ] );
3864 }
3865 }
3866 }
3867 }
3868
3869 return $stack;
3870 }
3871
3872 /**
3873 * Get an associative array for selecting this title from
3874 * the "page" table
3875 *
3876 * @return array Array suitable for the $where parameter of DB::select()
3877 */
3878 public function pageCond() {
3879 if ( $this->mArticleID > 0 ) {
3880 // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs
3881 return [ 'page_id' => $this->mArticleID ];
3882 } else {
3883 return [ 'page_namespace' => $this->mNamespace, 'page_title' => $this->mDbkeyform ];
3884 }
3885 }
3886
3887 /**
3888 * Get the revision ID of the previous revision
3889 *
3890 * @param int $revId Revision ID. Get the revision that was before this one.
3891 * @param int $flags Title::GAID_FOR_UPDATE
3892 * @return int|bool Old revision ID, or false if none exists
3893 */
3894 public function getPreviousRevisionID( $revId, $flags = 0 ) {
3895 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
3896 $revId = $db->selectField( 'revision', 'rev_id',
3897 [
3898 'rev_page' => $this->getArticleID( $flags ),
3899 'rev_id < ' . intval( $revId )
3900 ],
3901 __METHOD__,
3902 [ 'ORDER BY' => 'rev_id DESC' ]
3903 );
3904
3905 if ( $revId === false ) {
3906 return false;
3907 } else {
3908 return intval( $revId );
3909 }
3910 }
3911
3912 /**
3913 * Get the revision ID of the next revision
3914 *
3915 * @param int $revId Revision ID. Get the revision that was after this one.
3916 * @param int $flags Title::GAID_FOR_UPDATE
3917 * @return int|bool Next revision ID, or false if none exists
3918 */
3919 public function getNextRevisionID( $revId, $flags = 0 ) {
3920 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
3921 $revId = $db->selectField( 'revision', 'rev_id',
3922 [
3923 'rev_page' => $this->getArticleID( $flags ),
3924 'rev_id > ' . intval( $revId )
3925 ],
3926 __METHOD__,
3927 [ 'ORDER BY' => 'rev_id' ]
3928 );
3929
3930 if ( $revId === false ) {
3931 return false;
3932 } else {
3933 return intval( $revId );
3934 }
3935 }
3936
3937 /**
3938 * Get the first revision of the page
3939 *
3940 * @param int $flags Title::GAID_FOR_UPDATE
3941 * @return Revision|null If page doesn't exist
3942 */
3943 public function getFirstRevision( $flags = 0 ) {
3944 $pageId = $this->getArticleID( $flags );
3945 if ( $pageId ) {
3946 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
3947 $row = $db->selectRow( 'revision', Revision::selectFields(),
3948 [ 'rev_page' => $pageId ],
3949 __METHOD__,
3950 [ 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 1 ]
3951 );
3952 if ( $row ) {
3953 return new Revision( $row );
3954 }
3955 }
3956 return null;
3957 }
3958
3959 /**
3960 * Get the oldest revision timestamp of this page
3961 *
3962 * @param int $flags Title::GAID_FOR_UPDATE
3963 * @return string MW timestamp
3964 */
3965 public function getEarliestRevTime( $flags = 0 ) {
3966 $rev = $this->getFirstRevision( $flags );
3967 return $rev ? $rev->getTimestamp() : null;
3968 }
3969
3970 /**
3971 * Check if this is a new page
3972 *
3973 * @return bool
3974 */
3975 public function isNewPage() {
3976 $dbr = wfGetDB( DB_SLAVE );
3977 return (bool)$dbr->selectField( 'page', 'page_is_new', $this->pageCond(), __METHOD__ );
3978 }
3979
3980 /**
3981 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
3982 *
3983 * @return bool
3984 */
3985 public function isBigDeletion() {
3986 global $wgDeleteRevisionsLimit;
3987
3988 if ( !$wgDeleteRevisionsLimit ) {
3989 return false;
3990 }
3991
3992 if ( $this->mIsBigDeletion === null ) {
3993 $dbr = wfGetDB( DB_SLAVE );
3994
3995 $revCount = $dbr->selectRowCount(
3996 'revision',
3997 '1',
3998 [ 'rev_page' => $this->getArticleID() ],
3999 __METHOD__,
4000 [ 'LIMIT' => $wgDeleteRevisionsLimit + 1 ]
4001 );
4002
4003 $this->mIsBigDeletion = $revCount > $wgDeleteRevisionsLimit;
4004 }
4005
4006 return $this->mIsBigDeletion;
4007 }
4008
4009 /**
4010 * Get the approximate revision count of this page.
4011 *
4012 * @return int
4013 */
4014 public function estimateRevisionCount() {
4015 if ( !$this->exists() ) {
4016 return 0;
4017 }
4018
4019 if ( $this->mEstimateRevisions === null ) {
4020 $dbr = wfGetDB( DB_SLAVE );
4021 $this->mEstimateRevisions = $dbr->estimateRowCount( 'revision', '*',
4022 [ 'rev_page' => $this->getArticleID() ], __METHOD__ );
4023 }
4024
4025 return $this->mEstimateRevisions;
4026 }
4027
4028 /**
4029 * Get the number of revisions between the given revision.
4030 * Used for diffs and other things that really need it.
4031 *
4032 * @param int|Revision $old Old revision or rev ID (first before range)
4033 * @param int|Revision $new New revision or rev ID (first after range)
4034 * @param int|null $max Limit of Revisions to count, will be incremented to detect truncations
4035 * @return int Number of revisions between these revisions.
4036 */
4037 public function countRevisionsBetween( $old, $new, $max = null ) {
4038 if ( !( $old instanceof Revision ) ) {
4039 $old = Revision::newFromTitle( $this, (int)$old );
4040 }
4041 if ( !( $new instanceof Revision ) ) {
4042 $new = Revision::newFromTitle( $this, (int)$new );
4043 }
4044 if ( !$old || !$new ) {
4045 return 0; // nothing to compare
4046 }
4047 $dbr = wfGetDB( DB_SLAVE );
4048 $conds = [
4049 'rev_page' => $this->getArticleID(),
4050 'rev_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4051 'rev_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4052 ];
4053 if ( $max !== null ) {
4054 return $dbr->selectRowCount( 'revision', '1',
4055 $conds,
4056 __METHOD__,
4057 [ 'LIMIT' => $max + 1 ] // extra to detect truncation
4058 );
4059 } else {
4060 return (int)$dbr->selectField( 'revision', 'count(*)', $conds, __METHOD__ );
4061 }
4062 }
4063
4064 /**
4065 * Get the authors between the given revisions or revision IDs.
4066 * Used for diffs and other things that really need it.
4067 *
4068 * @since 1.23
4069 *
4070 * @param int|Revision $old Old revision or rev ID (first before range by default)
4071 * @param int|Revision $new New revision or rev ID (first after range by default)
4072 * @param int $limit Maximum number of authors
4073 * @param string|array $options (Optional): Single option, or an array of options:
4074 * 'include_old' Include $old in the range; $new is excluded.
4075 * 'include_new' Include $new in the range; $old is excluded.
4076 * 'include_both' Include both $old and $new in the range.
4077 * Unknown option values are ignored.
4078 * @return array|null Names of revision authors in the range; null if not both revisions exist
4079 */
4080 public function getAuthorsBetween( $old, $new, $limit, $options = [] ) {
4081 if ( !( $old instanceof Revision ) ) {
4082 $old = Revision::newFromTitle( $this, (int)$old );
4083 }
4084 if ( !( $new instanceof Revision ) ) {
4085 $new = Revision::newFromTitle( $this, (int)$new );
4086 }
4087 // XXX: what if Revision objects are passed in, but they don't refer to this title?
4088 // Add $old->getPage() != $new->getPage() || $old->getPage() != $this->getArticleID()
4089 // in the sanity check below?
4090 if ( !$old || !$new ) {
4091 return null; // nothing to compare
4092 }
4093 $authors = [];
4094 $old_cmp = '>';
4095 $new_cmp = '<';
4096 $options = (array)$options;
4097 if ( in_array( 'include_old', $options ) ) {
4098 $old_cmp = '>=';
4099 }
4100 if ( in_array( 'include_new', $options ) ) {
4101 $new_cmp = '<=';
4102 }
4103 if ( in_array( 'include_both', $options ) ) {
4104 $old_cmp = '>=';
4105 $new_cmp = '<=';
4106 }
4107 // No DB query needed if $old and $new are the same or successive revisions:
4108 if ( $old->getId() === $new->getId() ) {
4109 return ( $old_cmp === '>' && $new_cmp === '<' ) ?
4110 [] :
4111 [ $old->getUserText( Revision::RAW ) ];
4112 } elseif ( $old->getId() === $new->getParentId() ) {
4113 if ( $old_cmp === '>=' && $new_cmp === '<=' ) {
4114 $authors[] = $old->getUserText( Revision::RAW );
4115 if ( $old->getUserText( Revision::RAW ) != $new->getUserText( Revision::RAW ) ) {
4116 $authors[] = $new->getUserText( Revision::RAW );
4117 }
4118 } elseif ( $old_cmp === '>=' ) {
4119 $authors[] = $old->getUserText( Revision::RAW );
4120 } elseif ( $new_cmp === '<=' ) {
4121 $authors[] = $new->getUserText( Revision::RAW );
4122 }
4123 return $authors;
4124 }
4125 $dbr = wfGetDB( DB_SLAVE );
4126 $res = $dbr->select( 'revision', 'DISTINCT rev_user_text',
4127 [
4128 'rev_page' => $this->getArticleID(),
4129 "rev_timestamp $old_cmp " . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4130 "rev_timestamp $new_cmp " . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4131 ], __METHOD__,
4132 [ 'LIMIT' => $limit + 1 ] // add one so caller knows it was truncated
4133 );
4134 foreach ( $res as $row ) {
4135 $authors[] = $row->rev_user_text;
4136 }
4137 return $authors;
4138 }
4139
4140 /**
4141 * Get the number of authors between the given revisions or revision IDs.
4142 * Used for diffs and other things that really need it.
4143 *
4144 * @param int|Revision $old Old revision or rev ID (first before range by default)
4145 * @param int|Revision $new New revision or rev ID (first after range by default)
4146 * @param int $limit Maximum number of authors
4147 * @param string|array $options (Optional): Single option, or an array of options:
4148 * 'include_old' Include $old in the range; $new is excluded.
4149 * 'include_new' Include $new in the range; $old is excluded.
4150 * 'include_both' Include both $old and $new in the range.
4151 * Unknown option values are ignored.
4152 * @return int Number of revision authors in the range; zero if not both revisions exist
4153 */
4154 public function countAuthorsBetween( $old, $new, $limit, $options = [] ) {
4155 $authors = $this->getAuthorsBetween( $old, $new, $limit, $options );
4156 return $authors ? count( $authors ) : 0;
4157 }
4158
4159 /**
4160 * Compare with another title.
4161 *
4162 * @param Title $title
4163 * @return bool
4164 */
4165 public function equals( Title $title ) {
4166 // Note: === is necessary for proper matching of number-like titles.
4167 return $this->getInterwiki() === $title->getInterwiki()
4168 && $this->getNamespace() == $title->getNamespace()
4169 && $this->getDBkey() === $title->getDBkey();
4170 }
4171
4172 /**
4173 * Check if this title is a subpage of another title
4174 *
4175 * @param Title $title
4176 * @return bool
4177 */
4178 public function isSubpageOf( Title $title ) {
4179 return $this->getInterwiki() === $title->getInterwiki()
4180 && $this->getNamespace() == $title->getNamespace()
4181 && strpos( $this->getDBkey(), $title->getDBkey() . '/' ) === 0;
4182 }
4183
4184 /**
4185 * Check if page exists. For historical reasons, this function simply
4186 * checks for the existence of the title in the page table, and will
4187 * thus return false for interwiki links, special pages and the like.
4188 * If you want to know if a title can be meaningfully viewed, you should
4189 * probably call the isKnown() method instead.
4190 *
4191 * @param int $flags An optional bit field; may be Title::GAID_FOR_UPDATE to check
4192 * from master/for update
4193 * @return bool
4194 */
4195 public function exists( $flags = 0 ) {
4196 $exists = $this->getArticleID( $flags ) != 0;
4197 Hooks::run( 'TitleExists', [ $this, &$exists ] );
4198 return $exists;
4199 }
4200
4201 /**
4202 * Should links to this title be shown as potentially viewable (i.e. as
4203 * "bluelinks"), even if there's no record by this title in the page
4204 * table?
4205 *
4206 * This function is semi-deprecated for public use, as well as somewhat
4207 * misleadingly named. You probably just want to call isKnown(), which
4208 * calls this function internally.
4209 *
4210 * (ISSUE: Most of these checks are cheap, but the file existence check
4211 * can potentially be quite expensive. Including it here fixes a lot of
4212 * existing code, but we might want to add an optional parameter to skip
4213 * it and any other expensive checks.)
4214 *
4215 * @return bool
4216 */
4217 public function isAlwaysKnown() {
4218 $isKnown = null;
4219
4220 /**
4221 * Allows overriding default behavior for determining if a page exists.
4222 * If $isKnown is kept as null, regular checks happen. If it's
4223 * a boolean, this value is returned by the isKnown method.
4224 *
4225 * @since 1.20
4226 *
4227 * @param Title $title
4228 * @param bool|null $isKnown
4229 */
4230 Hooks::run( 'TitleIsAlwaysKnown', [ $this, &$isKnown ] );
4231
4232 if ( !is_null( $isKnown ) ) {
4233 return $isKnown;
4234 }
4235
4236 if ( $this->isExternal() ) {
4237 return true; // any interwiki link might be viewable, for all we know
4238 }
4239
4240 switch ( $this->mNamespace ) {
4241 case NS_MEDIA:
4242 case NS_FILE:
4243 // file exists, possibly in a foreign repo
4244 return (bool)wfFindFile( $this );
4245 case NS_SPECIAL:
4246 // valid special page
4247 return SpecialPageFactory::exists( $this->getDBkey() );
4248 case NS_MAIN:
4249 // selflink, possibly with fragment
4250 return $this->mDbkeyform == '';
4251 case NS_MEDIAWIKI:
4252 // known system message
4253 return $this->hasSourceText() !== false;
4254 default:
4255 return false;
4256 }
4257 }
4258
4259 /**
4260 * Does this title refer to a page that can (or might) be meaningfully
4261 * viewed? In particular, this function may be used to determine if
4262 * links to the title should be rendered as "bluelinks" (as opposed to
4263 * "redlinks" to non-existent pages).
4264 * Adding something else to this function will cause inconsistency
4265 * since LinkHolderArray calls isAlwaysKnown() and does its own
4266 * page existence check.
4267 *
4268 * @return bool
4269 */
4270 public function isKnown() {
4271 return $this->isAlwaysKnown() || $this->exists();
4272 }
4273
4274 /**
4275 * Does this page have source text?
4276 *
4277 * @return bool
4278 */
4279 public function hasSourceText() {
4280 if ( $this->exists() ) {
4281 return true;
4282 }
4283
4284 if ( $this->mNamespace == NS_MEDIAWIKI ) {
4285 // If the page doesn't exist but is a known system message, default
4286 // message content will be displayed, same for language subpages-
4287 // Use always content language to avoid loading hundreds of languages
4288 // to get the link color.
4289 global $wgContLang;
4290 list( $name, ) = MessageCache::singleton()->figureMessage(
4291 $wgContLang->lcfirst( $this->getText() )
4292 );
4293 $message = wfMessage( $name )->inLanguage( $wgContLang )->useDatabase( false );
4294 return $message->exists();
4295 }
4296
4297 return false;
4298 }
4299
4300 /**
4301 * Get the default message text or false if the message doesn't exist
4302 *
4303 * @return string|bool
4304 */
4305 public function getDefaultMessageText() {
4306 global $wgContLang;
4307
4308 if ( $this->getNamespace() != NS_MEDIAWIKI ) { // Just in case
4309 return false;
4310 }
4311
4312 list( $name, $lang ) = MessageCache::singleton()->figureMessage(
4313 $wgContLang->lcfirst( $this->getText() )
4314 );
4315 $message = wfMessage( $name )->inLanguage( $lang )->useDatabase( false );
4316
4317 if ( $message->exists() ) {
4318 return $message->plain();
4319 } else {
4320 return false;
4321 }
4322 }
4323
4324 /**
4325 * Updates page_touched for this page; called from LinksUpdate.php
4326 *
4327 * @param string $purgeTime [optional] TS_MW timestamp
4328 * @return bool True if the update succeeded
4329 */
4330 public function invalidateCache( $purgeTime = null ) {
4331 if ( wfReadOnly() ) {
4332 return false;
4333 }
4334
4335 if ( $this->mArticleID === 0 ) {
4336 return true; // avoid gap locking if we know it's not there
4337 }
4338
4339 $method = __METHOD__;
4340 $dbw = wfGetDB( DB_MASTER );
4341 $conds = $this->pageCond();
4342 $dbw->onTransactionIdle( function () use ( $dbw, $conds, $method, $purgeTime ) {
4343 $dbTimestamp = $dbw->timestamp( $purgeTime ?: time() );
4344
4345 $dbw->update(
4346 'page',
4347 [ 'page_touched' => $dbTimestamp ],
4348 $conds + [ 'page_touched < ' . $dbw->addQuotes( $dbTimestamp ) ],
4349 $method
4350 );
4351 } );
4352
4353 return true;
4354 }
4355
4356 /**
4357 * Update page_touched timestamps and send CDN purge messages for
4358 * pages linking to this title. May be sent to the job queue depending
4359 * on the number of links. Typically called on create and delete.
4360 */
4361 public function touchLinks() {
4362 DeferredUpdates::addUpdate( new HTMLCacheUpdate( $this, 'pagelinks' ) );
4363 if ( $this->getNamespace() == NS_CATEGORY ) {
4364 DeferredUpdates::addUpdate( new HTMLCacheUpdate( $this, 'categorylinks' ) );
4365 }
4366 }
4367
4368 /**
4369 * Get the last touched timestamp
4370 *
4371 * @param IDatabase $db Optional db
4372 * @return string Last-touched timestamp
4373 */
4374 public function getTouched( $db = null ) {
4375 if ( $db === null ) {
4376 $db = wfGetDB( DB_SLAVE );
4377 }
4378 $touched = $db->selectField( 'page', 'page_touched', $this->pageCond(), __METHOD__ );
4379 return $touched;
4380 }
4381
4382 /**
4383 * Get the timestamp when this page was updated since the user last saw it.
4384 *
4385 * @param User $user
4386 * @return string|null
4387 */
4388 public function getNotificationTimestamp( $user = null ) {
4389 global $wgUser;
4390
4391 // Assume current user if none given
4392 if ( !$user ) {
4393 $user = $wgUser;
4394 }
4395 // Check cache first
4396 $uid = $user->getId();
4397 if ( !$uid ) {
4398 return false;
4399 }
4400 // avoid isset here, as it'll return false for null entries
4401 if ( array_key_exists( $uid, $this->mNotificationTimestamp ) ) {
4402 return $this->mNotificationTimestamp[$uid];
4403 }
4404 // Don't cache too much!
4405 if ( count( $this->mNotificationTimestamp ) >= self::CACHE_MAX ) {
4406 $this->mNotificationTimestamp = [];
4407 }
4408
4409 $store = MediaWikiServices::getInstance()->getWatchedItemStore();
4410 $watchedItem = $store->getWatchedItem( $user, $this );
4411 if ( $watchedItem ) {
4412 $this->mNotificationTimestamp[$uid] = $watchedItem->getNotificationTimestamp();
4413 } else {
4414 $this->mNotificationTimestamp[$uid] = false;
4415 }
4416
4417 return $this->mNotificationTimestamp[$uid];
4418 }
4419
4420 /**
4421 * Generate strings used for xml 'id' names in monobook tabs
4422 *
4423 * @param string $prepend Defaults to 'nstab-'
4424 * @return string XML 'id' name
4425 */
4426 public function getNamespaceKey( $prepend = 'nstab-' ) {
4427 global $wgContLang;
4428 // Gets the subject namespace if this title
4429 $namespace = MWNamespace::getSubject( $this->getNamespace() );
4430 // Checks if canonical namespace name exists for namespace
4431 if ( MWNamespace::exists( $this->getNamespace() ) ) {
4432 // Uses canonical namespace name
4433 $namespaceKey = MWNamespace::getCanonicalName( $namespace );
4434 } else {
4435 // Uses text of namespace
4436 $namespaceKey = $this->getSubjectNsText();
4437 }
4438 // Makes namespace key lowercase
4439 $namespaceKey = $wgContLang->lc( $namespaceKey );
4440 // Uses main
4441 if ( $namespaceKey == '' ) {
4442 $namespaceKey = 'main';
4443 }
4444 // Changes file to image for backwards compatibility
4445 if ( $namespaceKey == 'file' ) {
4446 $namespaceKey = 'image';
4447 }
4448 return $prepend . $namespaceKey;
4449 }
4450
4451 /**
4452 * Get all extant redirects to this Title
4453 *
4454 * @param int|null $ns Single namespace to consider; null to consider all namespaces
4455 * @return Title[] Array of Title redirects to this title
4456 */
4457 public function getRedirectsHere( $ns = null ) {
4458 $redirs = [];
4459
4460 $dbr = wfGetDB( DB_SLAVE );
4461 $where = [
4462 'rd_namespace' => $this->getNamespace(),
4463 'rd_title' => $this->getDBkey(),
4464 'rd_from = page_id'
4465 ];
4466 if ( $this->isExternal() ) {
4467 $where['rd_interwiki'] = $this->getInterwiki();
4468 } else {
4469 $where[] = 'rd_interwiki = ' . $dbr->addQuotes( '' ) . ' OR rd_interwiki IS NULL';
4470 }
4471 if ( !is_null( $ns ) ) {
4472 $where['page_namespace'] = $ns;
4473 }
4474
4475 $res = $dbr->select(
4476 [ 'redirect', 'page' ],
4477 [ 'page_namespace', 'page_title' ],
4478 $where,
4479 __METHOD__
4480 );
4481
4482 foreach ( $res as $row ) {
4483 $redirs[] = self::newFromRow( $row );
4484 }
4485 return $redirs;
4486 }
4487
4488 /**
4489 * Check if this Title is a valid redirect target
4490 *
4491 * @return bool
4492 */
4493 public function isValidRedirectTarget() {
4494 global $wgInvalidRedirectTargets;
4495
4496 if ( $this->isSpecialPage() ) {
4497 // invalid redirect targets are stored in a global array, but explicitly disallow Userlogout here
4498 if ( $this->isSpecial( 'Userlogout' ) ) {
4499 return false;
4500 }
4501
4502 foreach ( $wgInvalidRedirectTargets as $target ) {
4503 if ( $this->isSpecial( $target ) ) {
4504 return false;
4505 }
4506 }
4507 }
4508
4509 return true;
4510 }
4511
4512 /**
4513 * Get a backlink cache object
4514 *
4515 * @return BacklinkCache
4516 */
4517 public function getBacklinkCache() {
4518 return BacklinkCache::get( $this );
4519 }
4520
4521 /**
4522 * Whether the magic words __INDEX__ and __NOINDEX__ function for this page.
4523 *
4524 * @return bool
4525 */
4526 public function canUseNoindex() {
4527 global $wgContentNamespaces, $wgExemptFromUserRobotsControl;
4528
4529 $bannedNamespaces = is_null( $wgExemptFromUserRobotsControl )
4530 ? $wgContentNamespaces
4531 : $wgExemptFromUserRobotsControl;
4532
4533 return !in_array( $this->mNamespace, $bannedNamespaces );
4534
4535 }
4536
4537 /**
4538 * Returns the raw sort key to be used for categories, with the specified
4539 * prefix. This will be fed to Collation::getSortKey() to get a
4540 * binary sortkey that can be used for actual sorting.
4541 *
4542 * @param string $prefix The prefix to be used, specified using
4543 * {{defaultsort:}} or like [[Category:Foo|prefix]]. Empty for no
4544 * prefix.
4545 * @return string
4546 */
4547 public function getCategorySortkey( $prefix = '' ) {
4548 $unprefixed = $this->getText();
4549
4550 // Anything that uses this hook should only depend
4551 // on the Title object passed in, and should probably
4552 // tell the users to run updateCollations.php --force
4553 // in order to re-sort existing category relations.
4554 Hooks::run( 'GetDefaultSortkey', [ $this, &$unprefixed ] );
4555 if ( $prefix !== '' ) {
4556 # Separate with a line feed, so the unprefixed part is only used as
4557 # a tiebreaker when two pages have the exact same prefix.
4558 # In UCA, tab is the only character that can sort above LF
4559 # so we strip both of them from the original prefix.
4560 $prefix = strtr( $prefix, "\n\t", ' ' );
4561 return "$prefix\n$unprefixed";
4562 }
4563 return $unprefixed;
4564 }
4565
4566 /**
4567 * Returns the page language code saved in the database, if $wgPageLanguageUseDB is set
4568 * to true in LocalSettings.php, otherwise returns false. If there is no language saved in
4569 * the db, it will return NULL.
4570 *
4571 * @return string|null|bool
4572 */
4573 private function getDbPageLanguageCode() {
4574 global $wgPageLanguageUseDB;
4575
4576 // check, if the page language could be saved in the database, and if so and
4577 // the value is not requested already, lookup the page language using LinkCache
4578 if ( $wgPageLanguageUseDB && $this->mDbPageLanguage === false ) {
4579 $linkCache = LinkCache::singleton();
4580 $linkCache->addLinkObj( $this );
4581 $this->mDbPageLanguage = $linkCache->getGoodLinkFieldObj( $this, 'lang' );
4582 }
4583
4584 return $this->mDbPageLanguage;
4585 }
4586
4587 /**
4588 * Get the language in which the content of this page is written in
4589 * wikitext. Defaults to $wgContLang, but in certain cases it can be
4590 * e.g. $wgLang (such as special pages, which are in the user language).
4591 *
4592 * @since 1.18
4593 * @return Language
4594 */
4595 public function getPageLanguage() {
4596 global $wgLang, $wgLanguageCode;
4597 if ( $this->isSpecialPage() ) {
4598 // special pages are in the user language
4599 return $wgLang;
4600 }
4601
4602 // Checking if DB language is set
4603 $dbPageLanguage = $this->getDbPageLanguageCode();
4604 if ( $dbPageLanguage ) {
4605 return wfGetLangObj( $dbPageLanguage );
4606 }
4607
4608 if ( !$this->mPageLanguage || $this->mPageLanguage[1] !== $wgLanguageCode ) {
4609 // Note that this may depend on user settings, so the cache should
4610 // be only per-request.
4611 // NOTE: ContentHandler::getPageLanguage() may need to load the
4612 // content to determine the page language!
4613 // Checking $wgLanguageCode hasn't changed for the benefit of unit
4614 // tests.
4615 $contentHandler = ContentHandler::getForTitle( $this );
4616 $langObj = $contentHandler->getPageLanguage( $this );
4617 $this->mPageLanguage = [ $langObj->getCode(), $wgLanguageCode ];
4618 } else {
4619 $langObj = wfGetLangObj( $this->mPageLanguage[0] );
4620 }
4621
4622 return $langObj;
4623 }
4624
4625 /**
4626 * Get the language in which the content of this page is written when
4627 * viewed by user. Defaults to $wgContLang, but in certain cases it can be
4628 * e.g. $wgLang (such as special pages, which are in the user language).
4629 *
4630 * @since 1.20
4631 * @return Language
4632 */
4633 public function getPageViewLanguage() {
4634 global $wgLang;
4635
4636 if ( $this->isSpecialPage() ) {
4637 // If the user chooses a variant, the content is actually
4638 // in a language whose code is the variant code.
4639 $variant = $wgLang->getPreferredVariant();
4640 if ( $wgLang->getCode() !== $variant ) {
4641 return Language::factory( $variant );
4642 }
4643
4644 return $wgLang;
4645 }
4646
4647 // Checking if DB language is set
4648 $dbPageLanguage = $this->getDbPageLanguageCode();
4649 if ( $dbPageLanguage ) {
4650 $pageLang = wfGetLangObj( $dbPageLanguage );
4651 $variant = $pageLang->getPreferredVariant();
4652 if ( $pageLang->getCode() !== $variant ) {
4653 $pageLang = Language::factory( $variant );
4654 }
4655
4656 return $pageLang;
4657 }
4658
4659 // @note Can't be cached persistently, depends on user settings.
4660 // @note ContentHandler::getPageViewLanguage() may need to load the
4661 // content to determine the page language!
4662 $contentHandler = ContentHandler::getForTitle( $this );
4663 $pageLang = $contentHandler->getPageViewLanguage( $this );
4664 return $pageLang;
4665 }
4666
4667 /**
4668 * Get a list of rendered edit notices for this page.
4669 *
4670 * Array is keyed by the original message key, and values are rendered using parseAsBlock, so
4671 * they will already be wrapped in paragraphs.
4672 *
4673 * @since 1.21
4674 * @param int $oldid Revision ID that's being edited
4675 * @return array
4676 */
4677 public function getEditNotices( $oldid = 0 ) {
4678 $notices = [];
4679
4680 // Optional notice for the entire namespace
4681 $editnotice_ns = 'editnotice-' . $this->getNamespace();
4682 $msg = wfMessage( $editnotice_ns );
4683 if ( $msg->exists() ) {
4684 $html = $msg->parseAsBlock();
4685 // Edit notices may have complex logic, but output nothing (T91715)
4686 if ( trim( $html ) !== '' ) {
4687 $notices[$editnotice_ns] = Html::rawElement(
4688 'div',
4689 [ 'class' => [
4690 'mw-editnotice',
4691 'mw-editnotice-namespace',
4692 Sanitizer::escapeClass( "mw-$editnotice_ns" )
4693 ] ],
4694 $html
4695 );
4696 }
4697 }
4698
4699 if ( MWNamespace::hasSubpages( $this->getNamespace() ) ) {
4700 // Optional notice for page itself and any parent page
4701 $parts = explode( '/', $this->getDBkey() );
4702 $editnotice_base = $editnotice_ns;
4703 while ( count( $parts ) > 0 ) {
4704 $editnotice_base .= '-' . array_shift( $parts );
4705 $msg = wfMessage( $editnotice_base );
4706 if ( $msg->exists() ) {
4707 $html = $msg->parseAsBlock();
4708 if ( trim( $html ) !== '' ) {
4709 $notices[$editnotice_base] = Html::rawElement(
4710 'div',
4711 [ 'class' => [
4712 'mw-editnotice',
4713 'mw-editnotice-base',
4714 Sanitizer::escapeClass( "mw-$editnotice_base" )
4715 ] ],
4716 $html
4717 );
4718 }
4719 }
4720 }
4721 } else {
4722 // Even if there are no subpages in namespace, we still don't want "/" in MediaWiki message keys
4723 $editnoticeText = $editnotice_ns . '-' . strtr( $this->getDBkey(), '/', '-' );
4724 $msg = wfMessage( $editnoticeText );
4725 if ( $msg->exists() ) {
4726 $html = $msg->parseAsBlock();
4727 if ( trim( $html ) !== '' ) {
4728 $notices[$editnoticeText] = Html::rawElement(
4729 'div',
4730 [ 'class' => [
4731 'mw-editnotice',
4732 'mw-editnotice-page',
4733 Sanitizer::escapeClass( "mw-$editnoticeText" )
4734 ] ],
4735 $html
4736 );
4737 }
4738 }
4739 }
4740
4741 Hooks::run( 'TitleGetEditNotices', [ $this, $oldid, &$notices ] );
4742 return $notices;
4743 }
4744
4745 /**
4746 * @return array
4747 */
4748 public function __sleep() {
4749 return [
4750 'mNamespace',
4751 'mDbkeyform',
4752 'mFragment',
4753 'mInterwiki',
4754 'mLocalInterwiki',
4755 'mUserCaseDBKey',
4756 'mDefaultNamespace',
4757 ];
4758 }
4759
4760 public function __wakeup() {
4761 $this->mArticleID = ( $this->mNamespace >= 0 ) ? -1 : 0;
4762 $this->mUrlform = wfUrlencode( $this->mDbkeyform );
4763 $this->mTextform = strtr( $this->mDbkeyform, '_', ' ' );
4764 }
4765
4766 }