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