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