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