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