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