ff85197b92d7a3868236a25a785e282fa04ab8a3
[lhc/web/wiklou.git] / includes / Title.php
1 <?php
2 /**
3 * Representation of a title within %MediaWiki.
4 *
5 * See title.txt
6 *
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License along
18 * with this program; if not, write to the Free Software Foundation, Inc.,
19 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 * http://www.gnu.org/copyleft/gpl.html
21 *
22 * @file
23 */
24
25 /**
26 * Represents a title within MediaWiki.
27 * Optionally may contain an interwiki designation or namespace.
28 * @note This class can fetch various kinds of data from the database;
29 * however, it does so inefficiently.
30 * @note Consider using a TitleValue object instead. TitleValue is more lightweight
31 * and does not rely on global state or the database.
32 */
33 class Title {
34 /** @var MapCacheLRU */
35 static private $titleCache = null;
36
37 /**
38 * Title::newFromText maintains a cache to avoid expensive re-normalization of
39 * commonly used titles. On a batch operation this can become a memory leak
40 * if not bounded. After hitting this many titles reset the cache.
41 */
42 const CACHE_MAX = 1000;
43
44 /**
45 * Used to be GAID_FOR_UPDATE define. Used with getArticleID() and friends
46 * to use the master DB
47 */
48 const GAID_FOR_UPDATE = 1;
49
50 /**
51 * @name Private member variables
52 * Please use the accessor functions instead.
53 * @private
54 */
55 // @{
56
57 /** @var string Text form (spaces not underscores) of the main part */
58 public $mTextform = '';
59
60 /** @var string URL-encoded form of the main part */
61 public $mUrlform = '';
62
63 /** @var string Main part with underscores */
64 public $mDbkeyform = '';
65
66 /** @var string Database key with the initial letter in the case specified by the user */
67 protected $mUserCaseDBKey;
68
69 /** @var int Namespace index, i.e. one of the NS_xxxx constants */
70 public $mNamespace = NS_MAIN;
71
72 /** @var string Interwiki prefix */
73 public $mInterwiki = '';
74
75 /** @var bool Was this Title created from a string with a local interwiki prefix? */
76 private $mLocalInterwiki = false;
77
78 /** @var string Title fragment (i.e. the bit after the #) */
79 public $mFragment = '';
80
81 /** @var int Article ID, fetched from the link cache on demand */
82 public $mArticleID = -1;
83
84 /** @var bool|int ID of most recent revision */
85 protected $mLatestID = false;
86
87 /**
88 * @var bool|string ID of the page's content model, i.e. one of the
89 * CONTENT_MODEL_XXX constants
90 */
91 public $mContentModel = false;
92
93 /** @var int Estimated number of revisions; null of not loaded */
94 private $mEstimateRevisions;
95
96 /** @var array Array of groups allowed to edit this article */
97 public $mRestrictions = array();
98
99 /** @var bool */
100 protected $mOldRestrictions = false;
101
102 /** @var bool Cascade restrictions on this page to included templates and images? */
103 public $mCascadeRestriction;
104
105 /** Caching the results of getCascadeProtectionSources */
106 public $mCascadingRestrictions;
107
108 /** @var array When do the restrictions on this page expire? */
109 protected $mRestrictionsExpiry = array();
110
111 /** @var bool Are cascading restrictions in effect on this page? */
112 protected $mHasCascadingRestrictions;
113
114 /** @var array Where are the cascading restrictions coming from on this page? */
115 public $mCascadeSources;
116
117 /** @var bool Boolean for initialisation on demand */
118 public $mRestrictionsLoaded = false;
119
120 /** @var string Text form including namespace/interwiki, initialised on demand */
121 protected $mPrefixedText = null;
122
123 /** @var mixed Cached value for getTitleProtection (create protection) */
124 public $mTitleProtection;
125
126 /**
127 * @var int Namespace index when there is no namespace. Don't change the
128 * following default, NS_MAIN is hardcoded in several places. See bug 696.
129 * Zero except in {{transclusion}} tags.
130 */
131 public $mDefaultNamespace = NS_MAIN;
132
133 /**
134 * @var bool Is $wgUser watching this page? null if unfilled, accessed
135 * through userIsWatching()
136 */
137 protected $mWatched = null;
138
139 /** @var int The page length, 0 for special pages */
140 protected $mLength = -1;
141
142 /** @var null Is the article at this title a redirect? */
143 public $mRedirect = null;
144
145 /** @var array Associative array of user ID -> timestamp/false */
146 private $mNotificationTimestamp = array();
147
148 /** @var bool Whether a page has any subpages */
149 private $mHasSubpages;
150
151 /** @var bool The (string) language code of the page's language and content code. */
152 private $mPageLanguage = false;
153
154 /** @var string The page language code from the database */
155 private $mDbPageLanguage = null;
156
157 /** @var TitleValue A corresponding TitleValue object */
158 private $mTitleValue = null;
159
160 /** @var bool Would deleting this page be a big deletion? */
161 private $mIsBigDeletion = null;
162 // @}
163
164 /**
165 * B/C kludge: provide a TitleParser for use by Title.
166 * Ideally, Title would have no methods that need this.
167 * Avoid usage of this singleton by using TitleValue
168 * and the associated services when possible.
169 *
170 * @return TitleParser
171 */
172 private static function getTitleParser() {
173 global $wgContLang, $wgLocalInterwikis;
174
175 static $titleCodec = null;
176 static $titleCodecFingerprint = null;
177
178 // $wgContLang and $wgLocalInterwikis may change (especially while testing),
179 // make sure we are using the right one. To detect changes over the course
180 // of a request, we remember a fingerprint of the config used to create the
181 // codec singleton, and re-create it if the fingerprint doesn't match.
182 $fingerprint = spl_object_hash( $wgContLang ) . '|' . join( '+', $wgLocalInterwikis );
183
184 if ( $fingerprint !== $titleCodecFingerprint ) {
185 $titleCodec = null;
186 }
187
188 if ( !$titleCodec ) {
189 $titleCodec = new MediaWikiTitleCodec(
190 $wgContLang,
191 GenderCache::singleton(),
192 $wgLocalInterwikis
193 );
194 $titleCodecFingerprint = $fingerprint;
195 }
196
197 return $titleCodec;
198 }
199
200 /**
201 * B/C kludge: provide a TitleParser for use by Title.
202 * Ideally, Title would have no methods that need this.
203 * Avoid usage of this singleton by using TitleValue
204 * and the associated services when possible.
205 *
206 * @return TitleFormatter
207 */
208 private static function getTitleFormatter() {
209 //NOTE: we know that getTitleParser() returns a MediaWikiTitleCodec,
210 // which implements TitleFormatter.
211 return self::getTitleParser();
212 }
213
214 function __construct() {
215 }
216
217 /**
218 * Create a new Title from a prefixed DB key
219 *
220 * @param string $key The database key, which has underscores
221 * instead of spaces, possibly including namespace and
222 * interwiki prefixes
223 * @return Title|null Title, or null on an error
224 */
225 public static function newFromDBkey( $key ) {
226 $t = new Title();
227 $t->mDbkeyform = $key;
228 if ( $t->secureAndSplit() ) {
229 return $t;
230 } else {
231 return null;
232 }
233 }
234
235 /**
236 * Create a new Title from a TitleValue
237 *
238 * @param TitleValue $titleValue Assumed to be safe.
239 *
240 * @return Title
241 */
242 public static function newFromTitleValue( TitleValue $titleValue ) {
243 return self::makeTitle(
244 $titleValue->getNamespace(),
245 $titleValue->getText(),
246 $titleValue->getFragment() );
247 }
248
249 /**
250 * Create a new Title from text, such as what one would find in a link. De-
251 * codes any HTML entities in the text.
252 *
253 * @param string $text The link text; spaces, prefixes, and an
254 * initial ':' indicating the main namespace are accepted.
255 * @param int $defaultNamespace The namespace to use if none is specified
256 * by a prefix. If you want to force a specific namespace even if
257 * $text might begin with a namespace prefix, use makeTitle() or
258 * makeTitleSafe().
259 * @throws MWException
260 * @return Title|null Title or null on an error.
261 */
262 public static function newFromText( $text, $defaultNamespace = NS_MAIN ) {
263 if ( is_object( $text ) ) {
264 throw new MWException( 'Title::newFromText given an object' );
265 }
266
267 $cache = self::getTitleCache();
268
269 /**
270 * Wiki pages often contain multiple links to the same page.
271 * Title normalization and parsing can become expensive on
272 * pages with many links, so we can save a little time by
273 * caching them.
274 *
275 * In theory these are value objects and won't get changed...
276 */
277 if ( $defaultNamespace == NS_MAIN && $cache->has( $text ) ) {
278 return $cache->get( $text );
279 }
280
281 # Convert things like &eacute; &#257; or &#x3017; into normalized (bug 14952) text
282 $filteredText = Sanitizer::decodeCharReferencesAndNormalize( $text );
283
284 $t = new Title();
285 $t->mDbkeyform = str_replace( ' ', '_', $filteredText );
286 $t->mDefaultNamespace = intval( $defaultNamespace );
287
288 if ( $t->secureAndSplit() ) {
289 if ( $defaultNamespace == NS_MAIN ) {
290 $cache->set( $text, $t );
291 }
292 return $t;
293 } else {
294 return null;
295 }
296 }
297
298 /**
299 * THIS IS NOT THE FUNCTION YOU WANT. Use Title::newFromText().
300 *
301 * Example of wrong and broken code:
302 * $title = Title::newFromURL( $wgRequest->getVal( 'title' ) );
303 *
304 * Example of right code:
305 * $title = Title::newFromText( $wgRequest->getVal( 'title' ) );
306 *
307 * Create a new Title from URL-encoded text. Ensures that
308 * the given title's length does not exceed the maximum.
309 *
310 * @param string $url The title, as might be taken from a URL
311 * @return Title|null The new object, or null on an error
312 */
313 public static function newFromURL( $url ) {
314 $t = new Title();
315
316 # For compatibility with old buggy URLs. "+" is usually not valid in titles,
317 # but some URLs used it as a space replacement and they still come
318 # from some external search tools.
319 if ( strpos( self::legalChars(), '+' ) === false ) {
320 $url = str_replace( '+', ' ', $url );
321 }
322
323 $t->mDbkeyform = str_replace( ' ', '_', $url );
324 if ( $t->secureAndSplit() ) {
325 return $t;
326 } else {
327 return null;
328 }
329 }
330
331 /**
332 * @return MapCacheLRU
333 */
334 private static function getTitleCache() {
335 if ( self::$titleCache == null ) {
336 self::$titleCache = new MapCacheLRU( self::CACHE_MAX );
337 }
338 return self::$titleCache;
339 }
340
341 /**
342 * Returns a list of fields that are to be selected for initializing Title
343 * objects or LinkCache entries. Uses $wgContentHandlerUseDB to determine
344 * whether to include page_content_model.
345 *
346 * @return array
347 */
348 protected static function getSelectFields() {
349 global $wgContentHandlerUseDB;
350
351 $fields = array(
352 'page_namespace', 'page_title', 'page_id',
353 'page_len', 'page_is_redirect', 'page_latest',
354 );
355
356 if ( $wgContentHandlerUseDB ) {
357 $fields[] = 'page_content_model';
358 }
359
360 return $fields;
361 }
362
363 /**
364 * Create a new Title from an article ID
365 *
366 * @param int $id The page_id corresponding to the Title to create
367 * @param int $flags Use Title::GAID_FOR_UPDATE to use master
368 * @return Title|null The new object, or null on an error
369 */
370 public static function newFromID( $id, $flags = 0 ) {
371 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
372 $row = $db->selectRow(
373 'page',
374 self::getSelectFields(),
375 array( 'page_id' => $id ),
376 __METHOD__
377 );
378 if ( $row !== false ) {
379 $title = Title::newFromRow( $row );
380 } else {
381 $title = null;
382 }
383 return $title;
384 }
385
386 /**
387 * Make an array of titles from an array of IDs
388 *
389 * @param int[] $ids Array of IDs
390 * @return Title[] Array of Titles
391 */
392 public static function newFromIDs( $ids ) {
393 if ( !count( $ids ) ) {
394 return array();
395 }
396 $dbr = wfGetDB( DB_SLAVE );
397
398 $res = $dbr->select(
399 'page',
400 self::getSelectFields(),
401 array( 'page_id' => $ids ),
402 __METHOD__
403 );
404
405 $titles = array();
406 foreach ( $res as $row ) {
407 $titles[] = Title::newFromRow( $row );
408 }
409 return $titles;
410 }
411
412 /**
413 * Make a Title object from a DB row
414 *
415 * @param stdClass $row Object database row (needs at least page_title,page_namespace)
416 * @return Title Corresponding Title
417 */
418 public static function newFromRow( $row ) {
419 $t = self::makeTitle( $row->page_namespace, $row->page_title );
420 $t->loadFromRow( $row );
421 return $t;
422 }
423
424 /**
425 * Load Title object fields from a DB row.
426 * If false is given, the title will be treated as non-existing.
427 *
428 * @param stdClass|bool $row Database row
429 */
430 public function loadFromRow( $row ) {
431 if ( $row ) { // page found
432 if ( isset( $row->page_id ) ) {
433 $this->mArticleID = (int)$row->page_id;
434 }
435 if ( isset( $row->page_len ) ) {
436 $this->mLength = (int)$row->page_len;
437 }
438 if ( isset( $row->page_is_redirect ) ) {
439 $this->mRedirect = (bool)$row->page_is_redirect;
440 }
441 if ( isset( $row->page_latest ) ) {
442 $this->mLatestID = (int)$row->page_latest;
443 }
444 if ( isset( $row->page_content_model ) ) {
445 $this->mContentModel = strval( $row->page_content_model );
446 } else {
447 $this->mContentModel = false; # initialized lazily in getContentModel()
448 }
449 if ( isset( $row->page_lang ) ) {
450 $this->mDbPageLanguage = (string)$row->page_lang;
451 }
452 } else { // page not found
453 $this->mArticleID = 0;
454 $this->mLength = 0;
455 $this->mRedirect = false;
456 $this->mLatestID = 0;
457 $this->mContentModel = false; # initialized lazily in getContentModel()
458 }
459 }
460
461 /**
462 * Create a new Title from a namespace index and a DB key.
463 * It's assumed that $ns and $title are *valid*, for instance when
464 * they came directly from the database or a special page name.
465 * For convenience, spaces are converted to underscores so that
466 * eg user_text fields can be used directly.
467 *
468 * @param int $ns The namespace of the article
469 * @param string $title The unprefixed database key form
470 * @param string $fragment The link fragment (after the "#")
471 * @param string $interwiki The interwiki prefix
472 * @return Title The new object
473 */
474 public static function &makeTitle( $ns, $title, $fragment = '', $interwiki = '' ) {
475 $t = new Title();
476 $t->mInterwiki = $interwiki;
477 $t->mFragment = $fragment;
478 $t->mNamespace = $ns = intval( $ns );
479 $t->mDbkeyform = str_replace( ' ', '_', $title );
480 $t->mArticleID = ( $ns >= 0 ) ? -1 : 0;
481 $t->mUrlform = wfUrlencode( $t->mDbkeyform );
482 $t->mTextform = str_replace( '_', ' ', $title );
483 $t->mContentModel = false; # initialized lazily in getContentModel()
484 return $t;
485 }
486
487 /**
488 * Create a new Title from a namespace index and a DB key.
489 * The parameters will be checked for validity, which is a bit slower
490 * than makeTitle() but safer for user-provided data.
491 *
492 * @param int $ns The namespace of the article
493 * @param string $title Database key form
494 * @param string $fragment The link fragment (after the "#")
495 * @param string $interwiki Interwiki prefix
496 * @return Title The new object, or null on an error
497 */
498 public static function makeTitleSafe( $ns, $title, $fragment = '', $interwiki = '' ) {
499 if ( !MWNamespace::exists( $ns ) ) {
500 return null;
501 }
502
503 $t = new Title();
504 $t->mDbkeyform = Title::makeName( $ns, $title, $fragment, $interwiki, true );
505 if ( $t->secureAndSplit() ) {
506 return $t;
507 } else {
508 return null;
509 }
510 }
511
512 /**
513 * Create a new Title for the Main Page
514 *
515 * @return Title The new object
516 */
517 public static function newMainPage() {
518 $title = Title::newFromText( wfMessage( 'mainpage' )->inContentLanguage()->text() );
519 // Don't give fatal errors if the message is broken
520 if ( !$title ) {
521 $title = Title::newFromText( 'Main Page' );
522 }
523 return $title;
524 }
525
526 /**
527 * Extract a redirect destination from a string and return the
528 * Title, or null if the text doesn't contain a valid redirect
529 * This will only return the very next target, useful for
530 * the redirect table and other checks that don't need full recursion
531 *
532 * @param string $text Text with possible redirect
533 * @return Title The corresponding Title
534 * @deprecated since 1.21, use Content::getRedirectTarget instead.
535 */
536 public static function newFromRedirect( $text ) {
537 ContentHandler::deprecated( __METHOD__, '1.21' );
538
539 $content = ContentHandler::makeContent( $text, null, CONTENT_MODEL_WIKITEXT );
540 return $content->getRedirectTarget();
541 }
542
543 /**
544 * Extract a redirect destination from a string and return the
545 * Title, or null if the text doesn't contain a valid redirect
546 * This will recurse down $wgMaxRedirects times or until a non-redirect target is hit
547 * in order to provide (hopefully) the Title of the final destination instead of another redirect
548 *
549 * @param string $text Text with possible redirect
550 * @return Title
551 * @deprecated since 1.21, use Content::getUltimateRedirectTarget instead.
552 */
553 public static function newFromRedirectRecurse( $text ) {
554 ContentHandler::deprecated( __METHOD__, '1.21' );
555
556 $content = ContentHandler::makeContent( $text, null, CONTENT_MODEL_WIKITEXT );
557 return $content->getUltimateRedirectTarget();
558 }
559
560 /**
561 * Extract a redirect destination from a string and return an
562 * array of Titles, or null if the text doesn't contain a valid redirect
563 * The last element in the array is the final destination after all redirects
564 * have been resolved (up to $wgMaxRedirects times)
565 *
566 * @param string $text Text with possible redirect
567 * @return Title[] Array of Titles, with the destination last
568 * @deprecated since 1.21, use Content::getRedirectChain instead.
569 */
570 public static function newFromRedirectArray( $text ) {
571 ContentHandler::deprecated( __METHOD__, '1.21' );
572
573 $content = ContentHandler::makeContent( $text, null, CONTENT_MODEL_WIKITEXT );
574 return $content->getRedirectChain();
575 }
576
577 /**
578 * Get the prefixed DB key associated with an ID
579 *
580 * @param int $id The page_id of the article
581 * @return Title|null An object representing the article, or null if no such article was found
582 */
583 public static function nameOf( $id ) {
584 $dbr = wfGetDB( DB_SLAVE );
585
586 $s = $dbr->selectRow(
587 'page',
588 array( 'page_namespace', 'page_title' ),
589 array( 'page_id' => $id ),
590 __METHOD__
591 );
592 if ( $s === false ) {
593 return null;
594 }
595
596 $n = self::makeName( $s->page_namespace, $s->page_title );
597 return $n;
598 }
599
600 /**
601 * Get a regex character class describing the legal characters in a link
602 *
603 * @return string The list of characters, not delimited
604 */
605 public static function legalChars() {
606 global $wgLegalTitleChars;
607 return $wgLegalTitleChars;
608 }
609
610 /**
611 * Returns a simple regex that will match on characters and sequences invalid in titles.
612 * Note that this doesn't pick up many things that could be wrong with titles, but that
613 * replacing this regex with something valid will make many titles valid.
614 *
615 * @todo move this into MediaWikiTitleCodec
616 *
617 * @return string Regex string
618 */
619 static function getTitleInvalidRegex() {
620 static $rxTc = false;
621 if ( !$rxTc ) {
622 # Matching titles will be held as illegal.
623 $rxTc = '/' .
624 # Any character not allowed is forbidden...
625 '[^' . self::legalChars() . ']' .
626 # URL percent encoding sequences interfere with the ability
627 # to round-trip titles -- you can't link to them consistently.
628 '|%[0-9A-Fa-f]{2}' .
629 # XML/HTML character references produce similar issues.
630 '|&[A-Za-z0-9\x80-\xff]+;' .
631 '|&#[0-9]+;' .
632 '|&#x[0-9A-Fa-f]+;' .
633 '/S';
634 }
635
636 return $rxTc;
637 }
638
639 /**
640 * Utility method for converting a character sequence from bytes to Unicode.
641 *
642 * Primary usecase being converting $wgLegalTitleChars to a sequence usable in
643 * javascript, as PHP uses UTF-8 bytes where javascript uses Unicode code units.
644 *
645 * @param string $byteClass
646 * @return string
647 */
648 public static function convertByteClassToUnicodeClass( $byteClass ) {
649 $length = strlen( $byteClass );
650 // Input token queue
651 $x0 = $x1 = $x2 = '';
652 // Decoded queue
653 $d0 = $d1 = $d2 = '';
654 // Decoded integer codepoints
655 $ord0 = $ord1 = $ord2 = 0;
656 // Re-encoded queue
657 $r0 = $r1 = $r2 = '';
658 // Output
659 $out = '';
660 // Flags
661 $allowUnicode = false;
662 for ( $pos = 0; $pos < $length; $pos++ ) {
663 // Shift the queues down
664 $x2 = $x1;
665 $x1 = $x0;
666 $d2 = $d1;
667 $d1 = $d0;
668 $ord2 = $ord1;
669 $ord1 = $ord0;
670 $r2 = $r1;
671 $r1 = $r0;
672 // Load the current input token and decoded values
673 $inChar = $byteClass[$pos];
674 if ( $inChar == '\\' ) {
675 if ( preg_match( '/x([0-9a-fA-F]{2})/A', $byteClass, $m, 0, $pos + 1 ) ) {
676 $x0 = $inChar . $m[0];
677 $d0 = chr( hexdec( $m[1] ) );
678 $pos += strlen( $m[0] );
679 } elseif ( preg_match( '/[0-7]{3}/A', $byteClass, $m, 0, $pos + 1 ) ) {
680 $x0 = $inChar . $m[0];
681 $d0 = chr( octdec( $m[0] ) );
682 $pos += strlen( $m[0] );
683 } elseif ( $pos + 1 >= $length ) {
684 $x0 = $d0 = '\\';
685 } else {
686 $d0 = $byteClass[$pos + 1];
687 $x0 = $inChar . $d0;
688 $pos += 1;
689 }
690 } else {
691 $x0 = $d0 = $inChar;
692 }
693 $ord0 = ord( $d0 );
694 // Load the current re-encoded value
695 if ( $ord0 < 32 || $ord0 == 0x7f ) {
696 $r0 = sprintf( '\x%02x', $ord0 );
697 } elseif ( $ord0 >= 0x80 ) {
698 // Allow unicode if a single high-bit character appears
699 $r0 = sprintf( '\x%02x', $ord0 );
700 $allowUnicode = true;
701 } elseif ( strpos( '-\\[]^', $d0 ) !== false ) {
702 $r0 = '\\' . $d0;
703 } else {
704 $r0 = $d0;
705 }
706 // Do the output
707 if ( $x0 !== '' && $x1 === '-' && $x2 !== '' ) {
708 // Range
709 if ( $ord2 > $ord0 ) {
710 // Empty range
711 } elseif ( $ord0 >= 0x80 ) {
712 // Unicode range
713 $allowUnicode = true;
714 if ( $ord2 < 0x80 ) {
715 // Keep the non-unicode section of the range
716 $out .= "$r2-\\x7F";
717 }
718 } else {
719 // Normal range
720 $out .= "$r2-$r0";
721 }
722 // Reset state to the initial value
723 $x0 = $x1 = $d0 = $d1 = $r0 = $r1 = '';
724 } elseif ( $ord2 < 0x80 ) {
725 // ASCII character
726 $out .= $r2;
727 }
728 }
729 if ( $ord1 < 0x80 ) {
730 $out .= $r1;
731 }
732 if ( $ord0 < 0x80 ) {
733 $out .= $r0;
734 }
735 if ( $allowUnicode ) {
736 $out .= '\u0080-\uFFFF';
737 }
738 return $out;
739 }
740
741 /**
742 * Make a prefixed DB key from a DB key and a namespace index
743 *
744 * @param int $ns Numerical representation of the namespace
745 * @param string $title The DB key form the title
746 * @param string $fragment The link fragment (after the "#")
747 * @param string $interwiki The interwiki prefix
748 * @param bool $canoncialNamespace If true, use the canonical name for
749 * $ns instead of the localized version.
750 * @return string The prefixed form of the title
751 */
752 public static function makeName( $ns, $title, $fragment = '', $interwiki = '',
753 $canoncialNamespace = false
754 ) {
755 global $wgContLang;
756
757 if ( $canoncialNamespace ) {
758 $namespace = MWNamespace::getCanonicalName( $ns );
759 } else {
760 $namespace = $wgContLang->getNsText( $ns );
761 }
762 $name = $namespace == '' ? $title : "$namespace:$title";
763 if ( strval( $interwiki ) != '' ) {
764 $name = "$interwiki:$name";
765 }
766 if ( strval( $fragment ) != '' ) {
767 $name .= '#' . $fragment;
768 }
769 return $name;
770 }
771
772 /**
773 * Escape a text fragment, say from a link, for a URL
774 *
775 * @param string $fragment Containing a URL or link fragment (after the "#")
776 * @return string Escaped string
777 */
778 static function escapeFragmentForURL( $fragment ) {
779 # Note that we don't urlencode the fragment. urlencoded Unicode
780 # fragments appear not to work in IE (at least up to 7) or in at least
781 # one version of Opera 9.x. The W3C validator, for one, doesn't seem
782 # to care if they aren't encoded.
783 return Sanitizer::escapeId( $fragment, 'noninitial' );
784 }
785
786 /**
787 * Callback for usort() to do title sorts by (namespace, title)
788 *
789 * @param Title $a
790 * @param Title $b
791 *
792 * @return int Result of string comparison, or namespace comparison
793 */
794 public static function compare( $a, $b ) {
795 if ( $a->getNamespace() == $b->getNamespace() ) {
796 return strcmp( $a->getText(), $b->getText() );
797 } else {
798 return $a->getNamespace() - $b->getNamespace();
799 }
800 }
801
802 /**
803 * Determine whether the object refers to a page within
804 * this project (either this wiki or a wiki with a local
805 * interwiki, see https://www.mediawiki.org/wiki/Manual:Interwiki_table#iw_local )
806 *
807 * @return bool True if this is an in-project interwiki link or a wikilink, false otherwise
808 */
809 public function isLocal() {
810 if ( $this->isExternal() ) {
811 $iw = Interwiki::fetch( $this->mInterwiki );
812 if ( $iw ) {
813 return $iw->isLocal();
814 }
815 }
816 return true;
817 }
818
819 /**
820 * Is this Title interwiki?
821 *
822 * @return bool
823 */
824 public function isExternal() {
825 return $this->mInterwiki !== '';
826 }
827
828 /**
829 * Get the interwiki prefix
830 *
831 * Use Title::isExternal to check if a interwiki is set
832 *
833 * @return string Interwiki prefix
834 */
835 public function getInterwiki() {
836 return $this->mInterwiki;
837 }
838
839 /**
840 * Was this a local interwiki link?
841 *
842 * @return bool
843 */
844 public function wasLocalInterwiki() {
845 return $this->mLocalInterwiki;
846 }
847
848 /**
849 * Determine whether the object refers to a page within
850 * this project and is transcludable.
851 *
852 * @return bool True if this is transcludable
853 */
854 public function isTrans() {
855 if ( !$this->isExternal() ) {
856 return false;
857 }
858
859 return Interwiki::fetch( $this->mInterwiki )->isTranscludable();
860 }
861
862 /**
863 * Returns the DB name of the distant wiki which owns the object.
864 *
865 * @return string The DB name
866 */
867 public function getTransWikiID() {
868 if ( !$this->isExternal() ) {
869 return false;
870 }
871
872 return Interwiki::fetch( $this->mInterwiki )->getWikiID();
873 }
874
875 /**
876 * Get a TitleValue object representing this Title.
877 *
878 * @note Not all valid Titles have a corresponding valid TitleValue
879 * (e.g. TitleValues cannot represent page-local links that have a
880 * fragment but no title text).
881 *
882 * @return TitleValue|null
883 */
884 public function getTitleValue() {
885 if ( $this->mTitleValue === null ) {
886 try {
887 $this->mTitleValue = new TitleValue(
888 $this->getNamespace(),
889 $this->getDBkey(),
890 $this->getFragment() );
891 } catch ( InvalidArgumentException $ex ) {
892 wfDebug( __METHOD__ . ': Can\'t create a TitleValue for [[' .
893 $this->getPrefixedText() . ']]: ' . $ex->getMessage() . "\n" );
894 }
895 }
896
897 return $this->mTitleValue;
898 }
899
900 /**
901 * Get the text form (spaces not underscores) of the main part
902 *
903 * @return string Main part of the title
904 */
905 public function getText() {
906 return $this->mTextform;
907 }
908
909 /**
910 * Get the URL-encoded form of the main part
911 *
912 * @return string Main part of the title, URL-encoded
913 */
914 public function getPartialURL() {
915 return $this->mUrlform;
916 }
917
918 /**
919 * Get the main part with underscores
920 *
921 * @return string Main part of the title, with underscores
922 */
923 public function getDBkey() {
924 return $this->mDbkeyform;
925 }
926
927 /**
928 * Get the DB key with the initial letter case as specified by the user
929 *
930 * @return string DB key
931 */
932 function getUserCaseDBKey() {
933 if ( !is_null( $this->mUserCaseDBKey ) ) {
934 return $this->mUserCaseDBKey;
935 } else {
936 // If created via makeTitle(), $this->mUserCaseDBKey is not set.
937 return $this->mDbkeyform;
938 }
939 }
940
941 /**
942 * Get the namespace index, i.e. one of the NS_xxxx constants.
943 *
944 * @return int Namespace index
945 */
946 public function getNamespace() {
947 return $this->mNamespace;
948 }
949
950 /**
951 * Get the page's content model id, see the CONTENT_MODEL_XXX constants.
952 *
953 * @throws MWException
954 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
955 * @return string Content model id
956 */
957 public function getContentModel( $flags = 0 ) {
958 # Calling getArticleID() loads the field from cache as needed
959 if ( !$this->mContentModel && $this->getArticleID( $flags ) ) {
960 $linkCache = LinkCache::singleton();
961 $this->mContentModel = $linkCache->getGoodLinkFieldObj( $this, 'model' );
962 }
963
964 if ( !$this->mContentModel ) {
965 $this->mContentModel = ContentHandler::getDefaultModelFor( $this );
966 }
967
968 if ( !$this->mContentModel ) {
969 throw new MWException( 'Failed to determine content model!' );
970 }
971
972 return $this->mContentModel;
973 }
974
975 /**
976 * Convenience method for checking a title's content model name
977 *
978 * @param string $id The content model ID (use the CONTENT_MODEL_XXX constants).
979 * @return bool True if $this->getContentModel() == $id
980 */
981 public function hasContentModel( $id ) {
982 return $this->getContentModel() == $id;
983 }
984
985 /**
986 * Get the namespace text
987 *
988 * @return string Namespace text
989 */
990 public function getNsText() {
991 if ( $this->isExternal() ) {
992 // This probably shouldn't even happen. ohh man, oh yuck.
993 // But for interwiki transclusion it sometimes does.
994 // Shit. Shit shit shit.
995 //
996 // Use the canonical namespaces if possible to try to
997 // resolve a foreign namespace.
998 if ( MWNamespace::exists( $this->mNamespace ) ) {
999 return MWNamespace::getCanonicalName( $this->mNamespace );
1000 }
1001 }
1002
1003 try {
1004 $formatter = self::getTitleFormatter();
1005 return $formatter->getNamespaceName( $this->mNamespace, $this->mDbkeyform );
1006 } catch ( InvalidArgumentException $ex ) {
1007 wfDebug( __METHOD__ . ': ' . $ex->getMessage() . "\n" );
1008 return false;
1009 }
1010 }
1011
1012 /**
1013 * Get the namespace text of the subject (rather than talk) page
1014 *
1015 * @return string Namespace text
1016 */
1017 public function getSubjectNsText() {
1018 global $wgContLang;
1019 return $wgContLang->getNsText( MWNamespace::getSubject( $this->mNamespace ) );
1020 }
1021
1022 /**
1023 * Get the namespace text of the talk page
1024 *
1025 * @return string Namespace text
1026 */
1027 public function getTalkNsText() {
1028 global $wgContLang;
1029 return $wgContLang->getNsText( MWNamespace::getTalk( $this->mNamespace ) );
1030 }
1031
1032 /**
1033 * Could this title have a corresponding talk page?
1034 *
1035 * @return bool
1036 */
1037 public function canTalk() {
1038 return MWNamespace::canTalk( $this->mNamespace );
1039 }
1040
1041 /**
1042 * Is this in a namespace that allows actual pages?
1043 *
1044 * @return bool
1045 */
1046 public function canExist() {
1047 return $this->mNamespace >= NS_MAIN;
1048 }
1049
1050 /**
1051 * Can this title be added to a user's watchlist?
1052 *
1053 * @return bool
1054 */
1055 public function isWatchable() {
1056 return !$this->isExternal() && MWNamespace::isWatchable( $this->getNamespace() );
1057 }
1058
1059 /**
1060 * Returns true if this is a special page.
1061 *
1062 * @return bool
1063 */
1064 public function isSpecialPage() {
1065 return $this->getNamespace() == NS_SPECIAL;
1066 }
1067
1068 /**
1069 * Returns true if this title resolves to the named special page
1070 *
1071 * @param string $name The special page name
1072 * @return bool
1073 */
1074 public function isSpecial( $name ) {
1075 if ( $this->isSpecialPage() ) {
1076 list( $thisName, /* $subpage */ ) = SpecialPageFactory::resolveAlias( $this->getDBkey() );
1077 if ( $name == $thisName ) {
1078 return true;
1079 }
1080 }
1081 return false;
1082 }
1083
1084 /**
1085 * If the Title refers to a special page alias which is not the local default, resolve
1086 * the alias, and localise the name as necessary. Otherwise, return $this
1087 *
1088 * @return Title
1089 */
1090 public function fixSpecialName() {
1091 if ( $this->isSpecialPage() ) {
1092 list( $canonicalName, $par ) = SpecialPageFactory::resolveAlias( $this->mDbkeyform );
1093 if ( $canonicalName ) {
1094 $localName = SpecialPageFactory::getLocalNameFor( $canonicalName, $par );
1095 if ( $localName != $this->mDbkeyform ) {
1096 return Title::makeTitle( NS_SPECIAL, $localName );
1097 }
1098 }
1099 }
1100 return $this;
1101 }
1102
1103 /**
1104 * Returns true if the title is inside the specified namespace.
1105 *
1106 * Please make use of this instead of comparing to getNamespace()
1107 * This function is much more resistant to changes we may make
1108 * to namespaces than code that makes direct comparisons.
1109 * @param int $ns The namespace
1110 * @return bool
1111 * @since 1.19
1112 */
1113 public function inNamespace( $ns ) {
1114 return MWNamespace::equals( $this->getNamespace(), $ns );
1115 }
1116
1117 /**
1118 * Returns true if the title is inside one of the specified namespaces.
1119 *
1120 * @param int $namespaces,... The namespaces to check for
1121 * @return bool
1122 * @since 1.19
1123 */
1124 public function inNamespaces( /* ... */ ) {
1125 $namespaces = func_get_args();
1126 if ( count( $namespaces ) > 0 && is_array( $namespaces[0] ) ) {
1127 $namespaces = $namespaces[0];
1128 }
1129
1130 foreach ( $namespaces as $ns ) {
1131 if ( $this->inNamespace( $ns ) ) {
1132 return true;
1133 }
1134 }
1135
1136 return false;
1137 }
1138
1139 /**
1140 * Returns true if the title has the same subject namespace as the
1141 * namespace specified.
1142 * For example this method will take NS_USER and return true if namespace
1143 * is either NS_USER or NS_USER_TALK since both of them have NS_USER
1144 * as their subject namespace.
1145 *
1146 * This is MUCH simpler than individually testing for equivalence
1147 * against both NS_USER and NS_USER_TALK, and is also forward compatible.
1148 * @since 1.19
1149 * @param int $ns
1150 * @return bool
1151 */
1152 public function hasSubjectNamespace( $ns ) {
1153 return MWNamespace::subjectEquals( $this->getNamespace(), $ns );
1154 }
1155
1156 /**
1157 * Is this Title in a namespace which contains content?
1158 * In other words, is this a content page, for the purposes of calculating
1159 * statistics, etc?
1160 *
1161 * @return bool
1162 */
1163 public function isContentPage() {
1164 return MWNamespace::isContent( $this->getNamespace() );
1165 }
1166
1167 /**
1168 * Would anybody with sufficient privileges be able to move this page?
1169 * Some pages just aren't movable.
1170 *
1171 * @return bool
1172 */
1173 public function isMovable() {
1174 if ( !MWNamespace::isMovable( $this->getNamespace() ) || $this->isExternal() ) {
1175 // Interwiki title or immovable namespace. Hooks don't get to override here
1176 return false;
1177 }
1178
1179 $result = true;
1180 Hooks::run( 'TitleIsMovable', array( $this, &$result ) );
1181 return $result;
1182 }
1183
1184 /**
1185 * Is this the mainpage?
1186 * @note Title::newFromText seems to be sufficiently optimized by the title
1187 * cache that we don't need to over-optimize by doing direct comparisons and
1188 * accidentally creating new bugs where $title->equals( Title::newFromText() )
1189 * ends up reporting something differently than $title->isMainPage();
1190 *
1191 * @since 1.18
1192 * @return bool
1193 */
1194 public function isMainPage() {
1195 return $this->equals( Title::newMainPage() );
1196 }
1197
1198 /**
1199 * Is this a subpage?
1200 *
1201 * @return bool
1202 */
1203 public function isSubpage() {
1204 return MWNamespace::hasSubpages( $this->mNamespace )
1205 ? strpos( $this->getText(), '/' ) !== false
1206 : false;
1207 }
1208
1209 /**
1210 * Is this a conversion table for the LanguageConverter?
1211 *
1212 * @return bool
1213 */
1214 public function isConversionTable() {
1215 // @todo ConversionTable should become a separate content model.
1216
1217 return $this->getNamespace() == NS_MEDIAWIKI &&
1218 strpos( $this->getText(), 'Conversiontable/' ) === 0;
1219 }
1220
1221 /**
1222 * Does that page contain wikitext, or it is JS, CSS or whatever?
1223 *
1224 * @return bool
1225 */
1226 public function isWikitextPage() {
1227 return $this->hasContentModel( CONTENT_MODEL_WIKITEXT );
1228 }
1229
1230 /**
1231 * Could this page contain custom CSS or JavaScript for the global UI.
1232 * This is generally true for pages in the MediaWiki namespace having CONTENT_MODEL_CSS
1233 * or CONTENT_MODEL_JAVASCRIPT.
1234 *
1235 * This method does *not* return true for per-user JS/CSS. Use isCssJsSubpage()
1236 * for that!
1237 *
1238 * Note that this method should not return true for pages that contain and
1239 * show "inactive" CSS or JS.
1240 *
1241 * @return bool
1242 */
1243 public function isCssOrJsPage() {
1244 $isCssOrJsPage = NS_MEDIAWIKI == $this->mNamespace
1245 && ( $this->hasContentModel( CONTENT_MODEL_CSS )
1246 || $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT ) );
1247
1248 # @note This hook is also called in ContentHandler::getDefaultModel.
1249 # It's called here again to make sure hook functions can force this
1250 # method to return true even outside the MediaWiki namespace.
1251
1252 Hooks::run( 'TitleIsCssOrJsPage', array( $this, &$isCssOrJsPage ), '1.25' );
1253
1254 return $isCssOrJsPage;
1255 }
1256
1257 /**
1258 * Is this a .css or .js subpage of a user page?
1259 * @return bool
1260 */
1261 public function isCssJsSubpage() {
1262 return ( NS_USER == $this->mNamespace && $this->isSubpage()
1263 && ( $this->hasContentModel( CONTENT_MODEL_CSS )
1264 || $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT ) ) );
1265 }
1266
1267 /**
1268 * Trim down a .css or .js subpage title to get the corresponding skin name
1269 *
1270 * @return string Containing skin name from .css or .js subpage title
1271 */
1272 public function getSkinFromCssJsSubpage() {
1273 $subpage = explode( '/', $this->mTextform );
1274 $subpage = $subpage[count( $subpage ) - 1];
1275 $lastdot = strrpos( $subpage, '.' );
1276 if ( $lastdot === false ) {
1277 return $subpage; # Never happens: only called for names ending in '.css' or '.js'
1278 }
1279 return substr( $subpage, 0, $lastdot );
1280 }
1281
1282 /**
1283 * Is this a .css subpage of a user page?
1284 *
1285 * @return bool
1286 */
1287 public function isCssSubpage() {
1288 return ( NS_USER == $this->mNamespace && $this->isSubpage()
1289 && $this->hasContentModel( CONTENT_MODEL_CSS ) );
1290 }
1291
1292 /**
1293 * Is this a .js subpage of a user page?
1294 *
1295 * @return bool
1296 */
1297 public function isJsSubpage() {
1298 return ( NS_USER == $this->mNamespace && $this->isSubpage()
1299 && $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT ) );
1300 }
1301
1302 /**
1303 * Is this a talk page of some sort?
1304 *
1305 * @return bool
1306 */
1307 public function isTalkPage() {
1308 return MWNamespace::isTalk( $this->getNamespace() );
1309 }
1310
1311 /**
1312 * Get a Title object associated with the talk page of this article
1313 *
1314 * @return Title The object for the talk page
1315 */
1316 public function getTalkPage() {
1317 return Title::makeTitle( MWNamespace::getTalk( $this->getNamespace() ), $this->getDBkey() );
1318 }
1319
1320 /**
1321 * Get a title object associated with the subject page of this
1322 * talk page
1323 *
1324 * @return Title The object for the subject page
1325 */
1326 public function getSubjectPage() {
1327 // Is this the same title?
1328 $subjectNS = MWNamespace::getSubject( $this->getNamespace() );
1329 if ( $this->getNamespace() == $subjectNS ) {
1330 return $this;
1331 }
1332 return Title::makeTitle( $subjectNS, $this->getDBkey() );
1333 }
1334
1335 /**
1336 * Get the default namespace index, for when there is no namespace
1337 *
1338 * @return int Default namespace index
1339 */
1340 public function getDefaultNamespace() {
1341 return $this->mDefaultNamespace;
1342 }
1343
1344 /**
1345 * Get the Title fragment (i.e.\ the bit after the #) in text form
1346 *
1347 * Use Title::hasFragment to check for a fragment
1348 *
1349 * @return string Title fragment
1350 */
1351 public function getFragment() {
1352 return $this->mFragment;
1353 }
1354
1355 /**
1356 * Check if a Title fragment is set
1357 *
1358 * @return bool
1359 * @since 1.23
1360 */
1361 public function hasFragment() {
1362 return $this->mFragment !== '';
1363 }
1364
1365 /**
1366 * Get the fragment in URL form, including the "#" character if there is one
1367 * @return string Fragment in URL form
1368 */
1369 public function getFragmentForURL() {
1370 if ( !$this->hasFragment() ) {
1371 return '';
1372 } else {
1373 return '#' . Title::escapeFragmentForURL( $this->getFragment() );
1374 }
1375 }
1376
1377 /**
1378 * Set the fragment for this title. Removes the first character from the
1379 * specified fragment before setting, so it assumes you're passing it with
1380 * an initial "#".
1381 *
1382 * Deprecated for public use, use Title::makeTitle() with fragment parameter.
1383 * Still in active use privately.
1384 *
1385 * @param string $fragment Text
1386 */
1387 public function setFragment( $fragment ) {
1388 $this->mFragment = str_replace( '_', ' ', substr( $fragment, 1 ) );
1389 }
1390
1391 /**
1392 * Prefix some arbitrary text with the namespace or interwiki prefix
1393 * of this object
1394 *
1395 * @param string $name The text
1396 * @return string The prefixed text
1397 */
1398 private function prefix( $name ) {
1399 $p = '';
1400 if ( $this->isExternal() ) {
1401 $p = $this->mInterwiki . ':';
1402 }
1403
1404 if ( 0 != $this->mNamespace ) {
1405 $p .= $this->getNsText() . ':';
1406 }
1407 return $p . $name;
1408 }
1409
1410 /**
1411 * Get the prefixed database key form
1412 *
1413 * @return string The prefixed title, with underscores and
1414 * any interwiki and namespace prefixes
1415 */
1416 public function getPrefixedDBkey() {
1417 $s = $this->prefix( $this->mDbkeyform );
1418 $s = str_replace( ' ', '_', $s );
1419 return $s;
1420 }
1421
1422 /**
1423 * Get the prefixed title with spaces.
1424 * This is the form usually used for display
1425 *
1426 * @return string The prefixed title, with spaces
1427 */
1428 public function getPrefixedText() {
1429 if ( $this->mPrefixedText === null ) {
1430 $s = $this->prefix( $this->mTextform );
1431 $s = str_replace( '_', ' ', $s );
1432 $this->mPrefixedText = $s;
1433 }
1434 return $this->mPrefixedText;
1435 }
1436
1437 /**
1438 * Return a string representation of this title
1439 *
1440 * @return string Representation of this title
1441 */
1442 public function __toString() {
1443 return $this->getPrefixedText();
1444 }
1445
1446 /**
1447 * Get the prefixed title with spaces, plus any fragment
1448 * (part beginning with '#')
1449 *
1450 * @return string The prefixed title, with spaces and the fragment, including '#'
1451 */
1452 public function getFullText() {
1453 $text = $this->getPrefixedText();
1454 if ( $this->hasFragment() ) {
1455 $text .= '#' . $this->getFragment();
1456 }
1457 return $text;
1458 }
1459
1460 /**
1461 * Get the root page name text without a namespace, i.e. the leftmost part before any slashes
1462 *
1463 * @par Example:
1464 * @code
1465 * Title::newFromText('User:Foo/Bar/Baz')->getRootText();
1466 * # returns: 'Foo'
1467 * @endcode
1468 *
1469 * @return string Root name
1470 * @since 1.20
1471 */
1472 public function getRootText() {
1473 if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
1474 return $this->getText();
1475 }
1476
1477 return strtok( $this->getText(), '/' );
1478 }
1479
1480 /**
1481 * Get the root page name title, i.e. the leftmost part before any slashes
1482 *
1483 * @par Example:
1484 * @code
1485 * Title::newFromText('User:Foo/Bar/Baz')->getRootTitle();
1486 * # returns: Title{User:Foo}
1487 * @endcode
1488 *
1489 * @return Title Root title
1490 * @since 1.20
1491 */
1492 public function getRootTitle() {
1493 return Title::makeTitle( $this->getNamespace(), $this->getRootText() );
1494 }
1495
1496 /**
1497 * Get the base page name without a namespace, i.e. the part before the subpage name
1498 *
1499 * @par Example:
1500 * @code
1501 * Title::newFromText('User:Foo/Bar/Baz')->getBaseText();
1502 * # returns: 'Foo/Bar'
1503 * @endcode
1504 *
1505 * @return string Base name
1506 */
1507 public function getBaseText() {
1508 if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
1509 return $this->getText();
1510 }
1511
1512 $parts = explode( '/', $this->getText() );
1513 # Don't discard the real title if there's no subpage involved
1514 if ( count( $parts ) > 1 ) {
1515 unset( $parts[count( $parts ) - 1] );
1516 }
1517 return implode( '/', $parts );
1518 }
1519
1520 /**
1521 * Get the base page name title, i.e. the part before the subpage name
1522 *
1523 * @par Example:
1524 * @code
1525 * Title::newFromText('User:Foo/Bar/Baz')->getBaseTitle();
1526 * # returns: Title{User:Foo/Bar}
1527 * @endcode
1528 *
1529 * @return Title Base title
1530 * @since 1.20
1531 */
1532 public function getBaseTitle() {
1533 return Title::makeTitle( $this->getNamespace(), $this->getBaseText() );
1534 }
1535
1536 /**
1537 * Get the lowest-level subpage name, i.e. the rightmost part after any slashes
1538 *
1539 * @par Example:
1540 * @code
1541 * Title::newFromText('User:Foo/Bar/Baz')->getSubpageText();
1542 * # returns: "Baz"
1543 * @endcode
1544 *
1545 * @return string Subpage name
1546 */
1547 public function getSubpageText() {
1548 if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
1549 return $this->mTextform;
1550 }
1551 $parts = explode( '/', $this->mTextform );
1552 return $parts[count( $parts ) - 1];
1553 }
1554
1555 /**
1556 * Get the title for a subpage of the current page
1557 *
1558 * @par Example:
1559 * @code
1560 * Title::newFromText('User:Foo/Bar/Baz')->getSubpage("Asdf");
1561 * # returns: Title{User:Foo/Bar/Baz/Asdf}
1562 * @endcode
1563 *
1564 * @param string $text The subpage name to add to the title
1565 * @return Title Subpage title
1566 * @since 1.20
1567 */
1568 public function getSubpage( $text ) {
1569 return Title::makeTitleSafe( $this->getNamespace(), $this->getText() . '/' . $text );
1570 }
1571
1572 /**
1573 * Get a URL-encoded form of the subpage text
1574 *
1575 * @return string URL-encoded subpage name
1576 */
1577 public function getSubpageUrlForm() {
1578 $text = $this->getSubpageText();
1579 $text = wfUrlencode( str_replace( ' ', '_', $text ) );
1580 return $text;
1581 }
1582
1583 /**
1584 * Get a URL-encoded title (not an actual URL) including interwiki
1585 *
1586 * @return string The URL-encoded form
1587 */
1588 public function getPrefixedURL() {
1589 $s = $this->prefix( $this->mDbkeyform );
1590 $s = wfUrlencode( str_replace( ' ', '_', $s ) );
1591 return $s;
1592 }
1593
1594 /**
1595 * Helper to fix up the get{Canonical,Full,Link,Local,Internal}URL args
1596 * get{Canonical,Full,Link,Local,Internal}URL methods accepted an optional
1597 * second argument named variant. This was deprecated in favor
1598 * of passing an array of option with a "variant" key
1599 * Once $query2 is removed for good, this helper can be dropped
1600 * and the wfArrayToCgi moved to getLocalURL();
1601 *
1602 * @since 1.19 (r105919)
1603 * @param array|string $query
1604 * @param bool $query2
1605 * @return string
1606 */
1607 private static function fixUrlQueryArgs( $query, $query2 = false ) {
1608 if ( $query2 !== false ) {
1609 wfDeprecated( "Title::get{Canonical,Full,Link,Local,Internal}URL " .
1610 "method called with a second parameter is deprecated. Add your " .
1611 "parameter to an array passed as the first parameter.", "1.19" );
1612 }
1613 if ( is_array( $query ) ) {
1614 $query = wfArrayToCgi( $query );
1615 }
1616 if ( $query2 ) {
1617 if ( is_string( $query2 ) ) {
1618 // $query2 is a string, we will consider this to be
1619 // a deprecated $variant argument and add it to the query
1620 $query2 = wfArrayToCgi( array( 'variant' => $query2 ) );
1621 } else {
1622 $query2 = wfArrayToCgi( $query2 );
1623 }
1624 // If we have $query content add a & to it first
1625 if ( $query ) {
1626 $query .= '&';
1627 }
1628 // Now append the queries together
1629 $query .= $query2;
1630 }
1631 return $query;
1632 }
1633
1634 /**
1635 * Get a real URL referring to this title, with interwiki link and
1636 * fragment
1637 *
1638 * @see self::getLocalURL for the arguments.
1639 * @see wfExpandUrl
1640 * @param array|string $query
1641 * @param bool $query2
1642 * @param string $proto Protocol type to use in URL
1643 * @return string The URL
1644 */
1645 public function getFullURL( $query = '', $query2 = false, $proto = PROTO_RELATIVE ) {
1646 $query = self::fixUrlQueryArgs( $query, $query2 );
1647
1648 # Hand off all the decisions on urls to getLocalURL
1649 $url = $this->getLocalURL( $query );
1650
1651 # Expand the url to make it a full url. Note that getLocalURL has the
1652 # potential to output full urls for a variety of reasons, so we use
1653 # wfExpandUrl instead of simply prepending $wgServer
1654 $url = wfExpandUrl( $url, $proto );
1655
1656 # Finally, add the fragment.
1657 $url .= $this->getFragmentForURL();
1658
1659 Hooks::run( 'GetFullURL', array( &$this, &$url, $query ) );
1660 return $url;
1661 }
1662
1663 /**
1664 * Get a URL with no fragment or server name (relative URL) from a Title object.
1665 * If this page is generated with action=render, however,
1666 * $wgServer is prepended to make an absolute URL.
1667 *
1668 * @see self::getFullURL to always get an absolute URL.
1669 * @see self::getLinkURL to always get a URL that's the simplest URL that will be
1670 * valid to link, locally, to the current Title.
1671 * @see self::newFromText to produce a Title object.
1672 *
1673 * @param string|array $query An optional query string,
1674 * not used for interwiki links. Can be specified as an associative array as well,
1675 * e.g., array( 'action' => 'edit' ) (keys and values will be URL-escaped).
1676 * Some query patterns will trigger various shorturl path replacements.
1677 * @param array $query2 An optional secondary query array. This one MUST
1678 * be an array. If a string is passed it will be interpreted as a deprecated
1679 * variant argument and urlencoded into a variant= argument.
1680 * This second query argument will be added to the $query
1681 * The second parameter is deprecated since 1.19. Pass it as a key,value
1682 * pair in the first parameter array instead.
1683 *
1684 * @return string String of the URL.
1685 */
1686 public function getLocalURL( $query = '', $query2 = false ) {
1687 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
1688
1689 $query = self::fixUrlQueryArgs( $query, $query2 );
1690
1691 $interwiki = Interwiki::fetch( $this->mInterwiki );
1692 if ( $interwiki ) {
1693 $namespace = $this->getNsText();
1694 if ( $namespace != '' ) {
1695 # Can this actually happen? Interwikis shouldn't be parsed.
1696 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
1697 $namespace .= ':';
1698 }
1699 $url = $interwiki->getURL( $namespace . $this->getDBkey() );
1700 $url = wfAppendQuery( $url, $query );
1701 } else {
1702 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
1703 if ( $query == '' ) {
1704 $url = str_replace( '$1', $dbkey, $wgArticlePath );
1705 Hooks::run( 'GetLocalURL::Article', array( &$this, &$url ) );
1706 } else {
1707 global $wgVariantArticlePath, $wgActionPaths, $wgContLang;
1708 $url = false;
1709 $matches = array();
1710
1711 if ( !empty( $wgActionPaths )
1712 && preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches )
1713 ) {
1714 $action = urldecode( $matches[2] );
1715 if ( isset( $wgActionPaths[$action] ) ) {
1716 $query = $matches[1];
1717 if ( isset( $matches[4] ) ) {
1718 $query .= $matches[4];
1719 }
1720 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
1721 if ( $query != '' ) {
1722 $url = wfAppendQuery( $url, $query );
1723 }
1724 }
1725 }
1726
1727 if ( $url === false
1728 && $wgVariantArticlePath
1729 && $wgContLang->getCode() === $this->getPageLanguage()->getCode()
1730 && $this->getPageLanguage()->hasVariants()
1731 && preg_match( '/^variant=([^&]*)$/', $query, $matches )
1732 ) {
1733 $variant = urldecode( $matches[1] );
1734 if ( $this->getPageLanguage()->hasVariant( $variant ) ) {
1735 // Only do the variant replacement if the given variant is a valid
1736 // variant for the page's language.
1737 $url = str_replace( '$2', urlencode( $variant ), $wgVariantArticlePath );
1738 $url = str_replace( '$1', $dbkey, $url );
1739 }
1740 }
1741
1742 if ( $url === false ) {
1743 if ( $query == '-' ) {
1744 $query = '';
1745 }
1746 $url = "{$wgScript}?title={$dbkey}&{$query}";
1747 }
1748 }
1749
1750 Hooks::run( 'GetLocalURL::Internal', array( &$this, &$url, $query ) );
1751
1752 // @todo FIXME: This causes breakage in various places when we
1753 // actually expected a local URL and end up with dupe prefixes.
1754 if ( $wgRequest->getVal( 'action' ) == 'render' ) {
1755 $url = $wgServer . $url;
1756 }
1757 }
1758 Hooks::run( 'GetLocalURL', array( &$this, &$url, $query ) );
1759 return $url;
1760 }
1761
1762 /**
1763 * Get a URL that's the simplest URL that will be valid to link, locally,
1764 * to the current Title. It includes the fragment, but does not include
1765 * the server unless action=render is used (or the link is external). If
1766 * there's a fragment but the prefixed text is empty, we just return a link
1767 * to the fragment.
1768 *
1769 * The result obviously should not be URL-escaped, but does need to be
1770 * HTML-escaped if it's being output in HTML.
1771 *
1772 * @param array $query
1773 * @param bool $query2
1774 * @param string $proto Protocol to use; setting this will cause a full URL to be used
1775 * @see self::getLocalURL for the arguments.
1776 * @return string The URL
1777 */
1778 public function getLinkURL( $query = '', $query2 = false, $proto = PROTO_RELATIVE ) {
1779 wfProfileIn( __METHOD__ );
1780 if ( $this->isExternal() || $proto !== PROTO_RELATIVE ) {
1781 $ret = $this->getFullURL( $query, $query2, $proto );
1782 } elseif ( $this->getPrefixedText() === '' && $this->hasFragment() ) {
1783 $ret = $this->getFragmentForURL();
1784 } else {
1785 $ret = $this->getLocalURL( $query, $query2 ) . $this->getFragmentForURL();
1786 }
1787 wfProfileOut( __METHOD__ );
1788 return $ret;
1789 }
1790
1791 /**
1792 * Get the URL form for an internal link.
1793 * - Used in various Squid-related code, in case we have a different
1794 * internal hostname for the server from the exposed one.
1795 *
1796 * This uses $wgInternalServer to qualify the path, or $wgServer
1797 * if $wgInternalServer is not set. If the server variable used is
1798 * protocol-relative, the URL will be expanded to http://
1799 *
1800 * @see self::getLocalURL for the arguments.
1801 * @return string The URL
1802 */
1803 public function getInternalURL( $query = '', $query2 = false ) {
1804 global $wgInternalServer, $wgServer;
1805 $query = self::fixUrlQueryArgs( $query, $query2 );
1806 $server = $wgInternalServer !== false ? $wgInternalServer : $wgServer;
1807 $url = wfExpandUrl( $server . $this->getLocalURL( $query ), PROTO_HTTP );
1808 Hooks::run( 'GetInternalURL', array( &$this, &$url, $query ) );
1809 return $url;
1810 }
1811
1812 /**
1813 * Get the URL for a canonical link, for use in things like IRC and
1814 * e-mail notifications. Uses $wgCanonicalServer and the
1815 * GetCanonicalURL hook.
1816 *
1817 * NOTE: Unlike getInternalURL(), the canonical URL includes the fragment
1818 *
1819 * @see self::getLocalURL for the arguments.
1820 * @return string The URL
1821 * @since 1.18
1822 */
1823 public function getCanonicalURL( $query = '', $query2 = false ) {
1824 $query = self::fixUrlQueryArgs( $query, $query2 );
1825 $url = wfExpandUrl( $this->getLocalURL( $query ) . $this->getFragmentForURL(), PROTO_CANONICAL );
1826 Hooks::run( 'GetCanonicalURL', array( &$this, &$url, $query ) );
1827 return $url;
1828 }
1829
1830 /**
1831 * Get the edit URL for this Title
1832 *
1833 * @return string The URL, or a null string if this is an interwiki link
1834 */
1835 public function getEditURL() {
1836 if ( $this->isExternal() ) {
1837 return '';
1838 }
1839 $s = $this->getLocalURL( 'action=edit' );
1840
1841 return $s;
1842 }
1843
1844 /**
1845 * Is $wgUser watching this page?
1846 *
1847 * @deprecated since 1.20; use User::isWatched() instead.
1848 * @return bool
1849 */
1850 public function userIsWatching() {
1851 global $wgUser;
1852
1853 if ( is_null( $this->mWatched ) ) {
1854 if ( NS_SPECIAL == $this->mNamespace || !$wgUser->isLoggedIn() ) {
1855 $this->mWatched = false;
1856 } else {
1857 $this->mWatched = $wgUser->isWatched( $this );
1858 }
1859 }
1860 return $this->mWatched;
1861 }
1862
1863 /**
1864 * Can $user perform $action on this page?
1865 * This skips potentially expensive cascading permission checks
1866 * as well as avoids expensive error formatting
1867 *
1868 * Suitable for use for nonessential UI controls in common cases, but
1869 * _not_ for functional access control.
1870 *
1871 * May provide false positives, but should never provide a false negative.
1872 *
1873 * @param string $action Action that permission needs to be checked for
1874 * @param User $user User to check (since 1.19); $wgUser will be used if not provided.
1875 * @return bool
1876 */
1877 public function quickUserCan( $action, $user = null ) {
1878 return $this->userCan( $action, $user, false );
1879 }
1880
1881 /**
1882 * Can $user perform $action on this page?
1883 *
1884 * @param string $action Action that permission needs to be checked for
1885 * @param User $user User to check (since 1.19); $wgUser will be used if not
1886 * provided.
1887 * @param bool $doExpensiveQueries Set this to false to avoid doing
1888 * unnecessary queries.
1889 * @return bool
1890 */
1891 public function userCan( $action, $user = null, $doExpensiveQueries = true ) {
1892 if ( !$user instanceof User ) {
1893 global $wgUser;
1894 $user = $wgUser;
1895 }
1896
1897 return !count( $this->getUserPermissionsErrorsInternal(
1898 $action, $user, $doExpensiveQueries, true ) );
1899 }
1900
1901 /**
1902 * Can $user perform $action on this page?
1903 *
1904 * @todo FIXME: This *does not* check throttles (User::pingLimiter()).
1905 *
1906 * @param string $action Action that permission needs to be checked for
1907 * @param User $user User to check
1908 * @param bool $doExpensiveQueries Set this to false to avoid doing unnecessary
1909 * queries by skipping checks for cascading protections and user blocks.
1910 * @param array $ignoreErrors Array of Strings Set this to a list of message keys
1911 * whose corresponding errors may be ignored.
1912 * @return array Array of arguments to wfMessage to explain permissions problems.
1913 */
1914 public function getUserPermissionsErrors( $action, $user, $doExpensiveQueries = true,
1915 $ignoreErrors = array()
1916 ) {
1917 $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries );
1918
1919 // Remove the errors being ignored.
1920 foreach ( $errors as $index => $error ) {
1921 $error_key = is_array( $error ) ? $error[0] : $error;
1922
1923 if ( in_array( $error_key, $ignoreErrors ) ) {
1924 unset( $errors[$index] );
1925 }
1926 }
1927
1928 return $errors;
1929 }
1930
1931 /**
1932 * Permissions checks that fail most often, and which are easiest to test.
1933 *
1934 * @param string $action The action to check
1935 * @param User $user User to check
1936 * @param array $errors List of current errors
1937 * @param bool $doExpensiveQueries Whether or not to perform expensive queries
1938 * @param bool $short Short circuit on first error
1939 *
1940 * @return array List of errors
1941 */
1942 private function checkQuickPermissions( $action, $user, $errors,
1943 $doExpensiveQueries, $short
1944 ) {
1945 if ( !Hooks::run( 'TitleQuickPermissions',
1946 array( $this, $user, $action, &$errors, $doExpensiveQueries, $short ) )
1947 ) {
1948 return $errors;
1949 }
1950
1951 if ( $action == 'create' ) {
1952 if (
1953 ( $this->isTalkPage() && !$user->isAllowed( 'createtalk' ) ) ||
1954 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage' ) )
1955 ) {
1956 $errors[] = $user->isAnon() ? array( 'nocreatetext' ) : array( 'nocreate-loggedin' );
1957 }
1958 } elseif ( $action == 'move' ) {
1959 if ( !$user->isAllowed( 'move-rootuserpages' )
1960 && $this->mNamespace == NS_USER && !$this->isSubpage() ) {
1961 // Show user page-specific message only if the user can move other pages
1962 $errors[] = array( 'cant-move-user-page' );
1963 }
1964
1965 // Check if user is allowed to move files if it's a file
1966 if ( $this->mNamespace == NS_FILE && !$user->isAllowed( 'movefile' ) ) {
1967 $errors[] = array( 'movenotallowedfile' );
1968 }
1969
1970 // Check if user is allowed to move category pages if it's a category page
1971 if ( $this->mNamespace == NS_CATEGORY && !$user->isAllowed( 'move-categorypages' ) ) {
1972 $errors[] = array( 'cant-move-category-page' );
1973 }
1974
1975 if ( !$user->isAllowed( 'move' ) ) {
1976 // User can't move anything
1977 $userCanMove = User::groupHasPermission( 'user', 'move' );
1978 $autoconfirmedCanMove = User::groupHasPermission( 'autoconfirmed', 'move' );
1979 if ( $user->isAnon() && ( $userCanMove || $autoconfirmedCanMove ) ) {
1980 // custom message if logged-in users without any special rights can move
1981 $errors[] = array( 'movenologintext' );
1982 } else {
1983 $errors[] = array( 'movenotallowed' );
1984 }
1985 }
1986 } elseif ( $action == 'move-target' ) {
1987 if ( !$user->isAllowed( 'move' ) ) {
1988 // User can't move anything
1989 $errors[] = array( 'movenotallowed' );
1990 } elseif ( !$user->isAllowed( 'move-rootuserpages' )
1991 && $this->mNamespace == NS_USER && !$this->isSubpage() ) {
1992 // Show user page-specific message only if the user can move other pages
1993 $errors[] = array( 'cant-move-to-user-page' );
1994 } elseif ( !$user->isAllowed( 'move-categorypages' )
1995 && $this->mNamespace == NS_CATEGORY ) {
1996 // Show category page-specific message only if the user can move other pages
1997 $errors[] = array( 'cant-move-to-category-page' );
1998 }
1999 } elseif ( !$user->isAllowed( $action ) ) {
2000 $errors[] = $this->missingPermissionError( $action, $short );
2001 }
2002
2003 return $errors;
2004 }
2005
2006 /**
2007 * Add the resulting error code to the errors array
2008 *
2009 * @param array $errors List of current errors
2010 * @param array $result Result of errors
2011 *
2012 * @return array List of errors
2013 */
2014 private function resultToError( $errors, $result ) {
2015 if ( is_array( $result ) && count( $result ) && !is_array( $result[0] ) ) {
2016 // A single array representing an error
2017 $errors[] = $result;
2018 } elseif ( is_array( $result ) && is_array( $result[0] ) ) {
2019 // A nested array representing multiple errors
2020 $errors = array_merge( $errors, $result );
2021 } elseif ( $result !== '' && is_string( $result ) ) {
2022 // A string representing a message-id
2023 $errors[] = array( $result );
2024 } elseif ( $result === false ) {
2025 // a generic "We don't want them to do that"
2026 $errors[] = array( 'badaccess-group0' );
2027 }
2028 return $errors;
2029 }
2030
2031 /**
2032 * Check various permission hooks
2033 *
2034 * @param string $action The action to check
2035 * @param User $user User to check
2036 * @param array $errors List of current errors
2037 * @param bool $doExpensiveQueries Whether or not to perform expensive queries
2038 * @param bool $short Short circuit on first error
2039 *
2040 * @return array List of errors
2041 */
2042 private function checkPermissionHooks( $action, $user, $errors, $doExpensiveQueries, $short ) {
2043 // Use getUserPermissionsErrors instead
2044 $result = '';
2045 if ( !Hooks::run( 'userCan', array( &$this, &$user, $action, &$result ) ) ) {
2046 return $result ? array() : array( array( 'badaccess-group0' ) );
2047 }
2048 // Check getUserPermissionsErrors hook
2049 if ( !Hooks::run( 'getUserPermissionsErrors', array( &$this, &$user, $action, &$result ) ) ) {
2050 $errors = $this->resultToError( $errors, $result );
2051 }
2052 // Check getUserPermissionsErrorsExpensive hook
2053 if (
2054 $doExpensiveQueries
2055 && !( $short && count( $errors ) > 0 )
2056 && !Hooks::run( 'getUserPermissionsErrorsExpensive', array( &$this, &$user, $action, &$result ) )
2057 ) {
2058 $errors = $this->resultToError( $errors, $result );
2059 }
2060
2061 return $errors;
2062 }
2063
2064 /**
2065 * Check permissions on special pages & namespaces
2066 *
2067 * @param string $action The action to check
2068 * @param User $user User to check
2069 * @param array $errors List of current errors
2070 * @param bool $doExpensiveQueries Whether or not to perform expensive queries
2071 * @param bool $short Short circuit on first error
2072 *
2073 * @return array List of errors
2074 */
2075 private function checkSpecialsAndNSPermissions( $action, $user, $errors,
2076 $doExpensiveQueries, $short
2077 ) {
2078 # Only 'createaccount' can be performed on special pages,
2079 # which don't actually exist in the DB.
2080 if ( NS_SPECIAL == $this->mNamespace && $action !== 'createaccount' ) {
2081 $errors[] = array( 'ns-specialprotected' );
2082 }
2083
2084 # Check $wgNamespaceProtection for restricted namespaces
2085 if ( $this->isNamespaceProtected( $user ) ) {
2086 $ns = $this->mNamespace == NS_MAIN ?
2087 wfMessage( 'nstab-main' )->text() : $this->getNsText();
2088 $errors[] = $this->mNamespace == NS_MEDIAWIKI ?
2089 array( 'protectedinterface', $action ) : array( 'namespaceprotected', $ns, $action );
2090 }
2091
2092 return $errors;
2093 }
2094
2095 /**
2096 * Check CSS/JS sub-page permissions
2097 *
2098 * @param string $action The action to check
2099 * @param User $user User to check
2100 * @param array $errors List of current errors
2101 * @param bool $doExpensiveQueries Whether or not to perform expensive queries
2102 * @param bool $short Short circuit on first error
2103 *
2104 * @return array List of errors
2105 */
2106 private function checkCSSandJSPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
2107 # Protect css/js subpages of user pages
2108 # XXX: this might be better using restrictions
2109 # XXX: right 'editusercssjs' is deprecated, for backward compatibility only
2110 if ( $action != 'patrol' && !$user->isAllowed( 'editusercssjs' ) ) {
2111 if ( preg_match( '/^' . preg_quote( $user->getName(), '/' ) . '\//', $this->mTextform ) ) {
2112 if ( $this->isCssSubpage() && !$user->isAllowedAny( 'editmyusercss', 'editusercss' ) ) {
2113 $errors[] = array( 'mycustomcssprotected', $action );
2114 } elseif ( $this->isJsSubpage() && !$user->isAllowedAny( 'editmyuserjs', 'edituserjs' ) ) {
2115 $errors[] = array( 'mycustomjsprotected', $action );
2116 }
2117 } else {
2118 if ( $this->isCssSubpage() && !$user->isAllowed( 'editusercss' ) ) {
2119 $errors[] = array( 'customcssprotected', $action );
2120 } elseif ( $this->isJsSubpage() && !$user->isAllowed( 'edituserjs' ) ) {
2121 $errors[] = array( 'customjsprotected', $action );
2122 }
2123 }
2124 }
2125
2126 return $errors;
2127 }
2128
2129 /**
2130 * Check against page_restrictions table requirements on this
2131 * page. The user must possess all required rights for this
2132 * action.
2133 *
2134 * @param string $action The action to check
2135 * @param User $user User to check
2136 * @param array $errors List of current errors
2137 * @param bool $doExpensiveQueries Whether or not to perform expensive queries
2138 * @param bool $short Short circuit on first error
2139 *
2140 * @return array List of errors
2141 */
2142 private function checkPageRestrictions( $action, $user, $errors, $doExpensiveQueries, $short ) {
2143 foreach ( $this->getRestrictions( $action ) as $right ) {
2144 // Backwards compatibility, rewrite sysop -> editprotected
2145 if ( $right == 'sysop' ) {
2146 $right = 'editprotected';
2147 }
2148 // Backwards compatibility, rewrite autoconfirmed -> editsemiprotected
2149 if ( $right == 'autoconfirmed' ) {
2150 $right = 'editsemiprotected';
2151 }
2152 if ( $right == '' ) {
2153 continue;
2154 }
2155 if ( !$user->isAllowed( $right ) ) {
2156 $errors[] = array( 'protectedpagetext', $right, $action );
2157 } elseif ( $this->mCascadeRestriction && !$user->isAllowed( 'protect' ) ) {
2158 $errors[] = array( 'protectedpagetext', 'protect', $action );
2159 }
2160 }
2161
2162 return $errors;
2163 }
2164
2165 /**
2166 * Check restrictions on cascading pages.
2167 *
2168 * @param string $action The action to check
2169 * @param User $user User to check
2170 * @param array $errors List of current errors
2171 * @param bool $doExpensiveQueries Whether or not to perform expensive queries
2172 * @param bool $short Short circuit on first error
2173 *
2174 * @return array List of errors
2175 */
2176 private function checkCascadingSourcesRestrictions( $action, $user, $errors,
2177 $doExpensiveQueries, $short
2178 ) {
2179 if ( $doExpensiveQueries && !$this->isCssJsSubpage() ) {
2180 # We /could/ use the protection level on the source page, but it's
2181 # fairly ugly as we have to establish a precedence hierarchy for pages
2182 # included by multiple cascade-protected pages. So just restrict
2183 # it to people with 'protect' permission, as they could remove the
2184 # protection anyway.
2185 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
2186 # Cascading protection depends on more than this page...
2187 # Several cascading protected pages may include this page...
2188 # Check each cascading level
2189 # This is only for protection restrictions, not for all actions
2190 if ( isset( $restrictions[$action] ) ) {
2191 foreach ( $restrictions[$action] as $right ) {
2192 // Backwards compatibility, rewrite sysop -> editprotected
2193 if ( $right == 'sysop' ) {
2194 $right = 'editprotected';
2195 }
2196 // Backwards compatibility, rewrite autoconfirmed -> editsemiprotected
2197 if ( $right == 'autoconfirmed' ) {
2198 $right = 'editsemiprotected';
2199 }
2200 if ( $right != '' && !$user->isAllowedAll( 'protect', $right ) ) {
2201 $pages = '';
2202 foreach ( $cascadingSources as $page ) {
2203 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
2204 }
2205 $errors[] = array( 'cascadeprotected', count( $cascadingSources ), $pages, $action );
2206 }
2207 }
2208 }
2209 }
2210
2211 return $errors;
2212 }
2213
2214 /**
2215 * Check action permissions not already checked in checkQuickPermissions
2216 *
2217 * @param string $action The action to check
2218 * @param User $user User to check
2219 * @param array $errors List of current errors
2220 * @param bool $doExpensiveQueries Whether or not to perform expensive queries
2221 * @param bool $short Short circuit on first error
2222 *
2223 * @return array List of errors
2224 */
2225 private function checkActionPermissions( $action, $user, $errors,
2226 $doExpensiveQueries, $short
2227 ) {
2228 global $wgDeleteRevisionsLimit, $wgLang;
2229
2230 if ( $action == 'protect' ) {
2231 if ( count( $this->getUserPermissionsErrorsInternal( 'edit',
2232 $user, $doExpensiveQueries, true ) )
2233 ) {
2234 // If they can't edit, they shouldn't protect.
2235 $errors[] = array( 'protect-cantedit' );
2236 }
2237 } elseif ( $action == 'create' ) {
2238 $title_protection = $this->getTitleProtection();
2239 if ( $title_protection ) {
2240 if ( $title_protection['permission'] == ''
2241 || !$user->isAllowed( $title_protection['permission'] )
2242 ) {
2243 $errors[] = array(
2244 'titleprotected',
2245 User::whoIs( $title_protection['user'] ),
2246 $title_protection['reason']
2247 );
2248 }
2249 }
2250 } elseif ( $action == 'move' ) {
2251 // Check for immobile pages
2252 if ( !MWNamespace::isMovable( $this->mNamespace ) ) {
2253 // Specific message for this case
2254 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
2255 } elseif ( !$this->isMovable() ) {
2256 // Less specific message for rarer cases
2257 $errors[] = array( 'immobile-source-page' );
2258 }
2259 } elseif ( $action == 'move-target' ) {
2260 if ( !MWNamespace::isMovable( $this->mNamespace ) ) {
2261 $errors[] = array( 'immobile-target-namespace', $this->getNsText() );
2262 } elseif ( !$this->isMovable() ) {
2263 $errors[] = array( 'immobile-target-page' );
2264 }
2265 } elseif ( $action == 'delete' ) {
2266 $tempErrors = $this->checkPageRestrictions( 'edit',
2267 $user, array(), $doExpensiveQueries, true );
2268 if ( !$tempErrors ) {
2269 $tempErrors = $this->checkCascadingSourcesRestrictions( 'edit',
2270 $user, $tempErrors, $doExpensiveQueries, true );
2271 }
2272 if ( $tempErrors ) {
2273 // If protection keeps them from editing, they shouldn't be able to delete.
2274 $errors[] = array( 'deleteprotected' );
2275 }
2276 if ( $doExpensiveQueries && $wgDeleteRevisionsLimit
2277 && !$this->userCan( 'bigdelete', $user ) && $this->isBigDeletion()
2278 ) {
2279 $errors[] = array( 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) );
2280 }
2281 }
2282 return $errors;
2283 }
2284
2285 /**
2286 * Check that the user isn't blocked from editing.
2287 *
2288 * @param string $action The action to check
2289 * @param User $user User to check
2290 * @param array $errors List of current errors
2291 * @param bool $doExpensiveQueries Whether or not to perform expensive queries
2292 * @param bool $short Short circuit on first error
2293 *
2294 * @return array List of errors
2295 */
2296 private function checkUserBlock( $action, $user, $errors, $doExpensiveQueries, $short ) {
2297 // Account creation blocks handled at userlogin.
2298 // Unblocking handled in SpecialUnblock
2299 if ( !$doExpensiveQueries || in_array( $action, array( 'createaccount', 'unblock' ) ) ) {
2300 return $errors;
2301 }
2302
2303 global $wgEmailConfirmToEdit;
2304
2305 if ( $wgEmailConfirmToEdit && !$user->isEmailConfirmed() ) {
2306 $errors[] = array( 'confirmedittext' );
2307 }
2308
2309 if ( ( $action == 'edit' || $action == 'create' ) && !$user->isBlockedFrom( $this ) ) {
2310 // Don't block the user from editing their own talk page unless they've been
2311 // explicitly blocked from that too.
2312 } elseif ( $user->isBlocked() && $user->mBlock->prevents( $action ) !== false ) {
2313 // @todo FIXME: Pass the relevant context into this function.
2314 $errors[] = $user->getBlock()->getPermissionsError( RequestContext::getMain() );
2315 }
2316
2317 return $errors;
2318 }
2319
2320 /**
2321 * Check that the user is allowed to read this page.
2322 *
2323 * @param string $action The action to check
2324 * @param User $user User to check
2325 * @param array $errors List of current errors
2326 * @param bool $doExpensiveQueries Whether or not to perform expensive queries
2327 * @param bool $short Short circuit on first error
2328 *
2329 * @return array List of errors
2330 */
2331 private function checkReadPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
2332 global $wgWhitelistRead, $wgWhitelistReadRegexp;
2333
2334 $whitelisted = false;
2335 if ( User::isEveryoneAllowed( 'read' ) ) {
2336 # Shortcut for public wikis, allows skipping quite a bit of code
2337 $whitelisted = true;
2338 } elseif ( $user->isAllowed( 'read' ) ) {
2339 # If the user is allowed to read pages, he is allowed to read all pages
2340 $whitelisted = true;
2341 } elseif ( $this->isSpecial( 'Userlogin' )
2342 || $this->isSpecial( 'ChangePassword' )
2343 || $this->isSpecial( 'PasswordReset' )
2344 ) {
2345 # Always grant access to the login page.
2346 # Even anons need to be able to log in.
2347 $whitelisted = true;
2348 } elseif ( is_array( $wgWhitelistRead ) && count( $wgWhitelistRead ) ) {
2349 # Time to check the whitelist
2350 # Only do these checks is there's something to check against
2351 $name = $this->getPrefixedText();
2352 $dbName = $this->getPrefixedDBkey();
2353
2354 // Check for explicit whitelisting with and without underscores
2355 if ( in_array( $name, $wgWhitelistRead, true ) || in_array( $dbName, $wgWhitelistRead, true ) ) {
2356 $whitelisted = true;
2357 } elseif ( $this->getNamespace() == NS_MAIN ) {
2358 # Old settings might have the title prefixed with
2359 # a colon for main-namespace pages
2360 if ( in_array( ':' . $name, $wgWhitelistRead ) ) {
2361 $whitelisted = true;
2362 }
2363 } elseif ( $this->isSpecialPage() ) {
2364 # If it's a special page, ditch the subpage bit and check again
2365 $name = $this->getDBkey();
2366 list( $name, /* $subpage */ ) = SpecialPageFactory::resolveAlias( $name );
2367 if ( $name ) {
2368 $pure = SpecialPage::getTitleFor( $name )->getPrefixedText();
2369 if ( in_array( $pure, $wgWhitelistRead, true ) ) {
2370 $whitelisted = true;
2371 }
2372 }
2373 }
2374 }
2375
2376 if ( !$whitelisted && is_array( $wgWhitelistReadRegexp ) && !empty( $wgWhitelistReadRegexp ) ) {
2377 $name = $this->getPrefixedText();
2378 // Check for regex whitelisting
2379 foreach ( $wgWhitelistReadRegexp as $listItem ) {
2380 if ( preg_match( $listItem, $name ) ) {
2381 $whitelisted = true;
2382 break;
2383 }
2384 }
2385 }
2386
2387 if ( !$whitelisted ) {
2388 # If the title is not whitelisted, give extensions a chance to do so...
2389 Hooks::run( 'TitleReadWhitelist', array( $this, $user, &$whitelisted ) );
2390 if ( !$whitelisted ) {
2391 $errors[] = $this->missingPermissionError( $action, $short );
2392 }
2393 }
2394
2395 return $errors;
2396 }
2397
2398 /**
2399 * Get a description array when the user doesn't have the right to perform
2400 * $action (i.e. when User::isAllowed() returns false)
2401 *
2402 * @param string $action The action to check
2403 * @param bool $short Short circuit on first error
2404 * @return array List of errors
2405 */
2406 private function missingPermissionError( $action, $short ) {
2407 // We avoid expensive display logic for quickUserCan's and such
2408 if ( $short ) {
2409 return array( 'badaccess-group0' );
2410 }
2411
2412 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
2413 User::getGroupsWithPermission( $action ) );
2414
2415 if ( count( $groups ) ) {
2416 global $wgLang;
2417 return array(
2418 'badaccess-groups',
2419 $wgLang->commaList( $groups ),
2420 count( $groups )
2421 );
2422 } else {
2423 return array( 'badaccess-group0' );
2424 }
2425 }
2426
2427 /**
2428 * Can $user perform $action on this page? This is an internal function,
2429 * which checks ONLY that previously checked by userCan (i.e. it leaves out
2430 * checks on wfReadOnly() and blocks)
2431 *
2432 * @param string $action Action that permission needs to be checked for
2433 * @param User $user User to check
2434 * @param bool $doExpensiveQueries Set this to false to avoid doing unnecessary queries.
2435 * @param bool $short Set this to true to stop after the first permission error.
2436 * @return array Array of arrays of the arguments to wfMessage to explain permissions problems.
2437 */
2438 protected function getUserPermissionsErrorsInternal( $action, $user,
2439 $doExpensiveQueries = true, $short = false
2440 ) {
2441 wfProfileIn( __METHOD__ );
2442
2443 # Read has special handling
2444 if ( $action == 'read' ) {
2445 $checks = array(
2446 'checkPermissionHooks',
2447 'checkReadPermissions',
2448 );
2449 # Don't call checkSpecialsAndNSPermissions or checkCSSandJSPermissions
2450 # here as it will lead to duplicate error messages. This is okay to do
2451 # since anywhere that checks for create will also check for edit, and
2452 # those checks are called for edit.
2453 } elseif ( $action == 'create' ) {
2454 $checks = array(
2455 'checkQuickPermissions',
2456 'checkPermissionHooks',
2457 'checkPageRestrictions',
2458 'checkCascadingSourcesRestrictions',
2459 'checkActionPermissions',
2460 'checkUserBlock'
2461 );
2462 } else {
2463 $checks = array(
2464 'checkQuickPermissions',
2465 'checkPermissionHooks',
2466 'checkSpecialsAndNSPermissions',
2467 'checkCSSandJSPermissions',
2468 'checkPageRestrictions',
2469 'checkCascadingSourcesRestrictions',
2470 'checkActionPermissions',
2471 'checkUserBlock'
2472 );
2473 }
2474
2475 $errors = array();
2476 while ( count( $checks ) > 0 &&
2477 !( $short && count( $errors ) > 0 ) ) {
2478 $method = array_shift( $checks );
2479 $errors = $this->$method( $action, $user, $errors, $doExpensiveQueries, $short );
2480 }
2481
2482 wfProfileOut( __METHOD__ );
2483 return $errors;
2484 }
2485
2486 /**
2487 * Get a filtered list of all restriction types supported by this wiki.
2488 * @param bool $exists True to get all restriction types that apply to
2489 * titles that do exist, False for all restriction types that apply to
2490 * titles that do not exist
2491 * @return array
2492 */
2493 public static function getFilteredRestrictionTypes( $exists = true ) {
2494 global $wgRestrictionTypes;
2495 $types = $wgRestrictionTypes;
2496 if ( $exists ) {
2497 # Remove the create restriction for existing titles
2498 $types = array_diff( $types, array( 'create' ) );
2499 } else {
2500 # Only the create and upload restrictions apply to non-existing titles
2501 $types = array_intersect( $types, array( 'create', 'upload' ) );
2502 }
2503 return $types;
2504 }
2505
2506 /**
2507 * Returns restriction types for the current Title
2508 *
2509 * @return array Applicable restriction types
2510 */
2511 public function getRestrictionTypes() {
2512 if ( $this->isSpecialPage() ) {
2513 return array();
2514 }
2515
2516 $types = self::getFilteredRestrictionTypes( $this->exists() );
2517
2518 if ( $this->getNamespace() != NS_FILE ) {
2519 # Remove the upload restriction for non-file titles
2520 $types = array_diff( $types, array( 'upload' ) );
2521 }
2522
2523 Hooks::run( 'TitleGetRestrictionTypes', array( $this, &$types ) );
2524
2525 wfDebug( __METHOD__ . ': applicable restrictions to [[' .
2526 $this->getPrefixedText() . ']] are {' . implode( ',', $types ) . "}\n" );
2527
2528 return $types;
2529 }
2530
2531 /**
2532 * Is this title subject to title protection?
2533 * Title protection is the one applied against creation of such title.
2534 *
2535 * @return array|bool An associative array representing any existent title
2536 * protection, or false if there's none.
2537 */
2538 public function getTitleProtection() {
2539 // Can't protect pages in special namespaces
2540 if ( $this->getNamespace() < 0 ) {
2541 return false;
2542 }
2543
2544 // Can't protect pages that exist.
2545 if ( $this->exists() ) {
2546 return false;
2547 }
2548
2549 if ( $this->mTitleProtection === null ) {
2550 $dbr = wfGetDB( DB_SLAVE );
2551 $res = $dbr->select(
2552 'protected_titles',
2553 array(
2554 'user' => 'pt_user',
2555 'reason' => 'pt_reason',
2556 'expiry' => 'pt_expiry',
2557 'permission' => 'pt_create_perm'
2558 ),
2559 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
2560 __METHOD__
2561 );
2562
2563 // fetchRow returns false if there are no rows.
2564 $row = $dbr->fetchRow( $res );
2565 if ( $row ) {
2566 if ( $row['permission'] == 'sysop' ) {
2567 $row['permission'] = 'editprotected'; // B/C
2568 }
2569 if ( $row['permission'] == 'autoconfirmed' ) {
2570 $row['permission'] = 'editsemiprotected'; // B/C
2571 }
2572 }
2573 $this->mTitleProtection = $row;
2574 }
2575 return $this->mTitleProtection;
2576 }
2577
2578 /**
2579 * Remove any title protection due to page existing
2580 */
2581 public function deleteTitleProtection() {
2582 $dbw = wfGetDB( DB_MASTER );
2583
2584 $dbw->delete(
2585 'protected_titles',
2586 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
2587 __METHOD__
2588 );
2589 $this->mTitleProtection = false;
2590 }
2591
2592 /**
2593 * Is this page "semi-protected" - the *only* protection levels are listed
2594 * in $wgSemiprotectedRestrictionLevels?
2595 *
2596 * @param string $action Action to check (default: edit)
2597 * @return bool
2598 */
2599 public function isSemiProtected( $action = 'edit' ) {
2600 global $wgSemiprotectedRestrictionLevels;
2601
2602 $restrictions = $this->getRestrictions( $action );
2603 $semi = $wgSemiprotectedRestrictionLevels;
2604 if ( !$restrictions || !$semi ) {
2605 // Not protected, or all protection is full protection
2606 return false;
2607 }
2608
2609 // Remap autoconfirmed to editsemiprotected for BC
2610 foreach ( array_keys( $semi, 'autoconfirmed' ) as $key ) {
2611 $semi[$key] = 'editsemiprotected';
2612 }
2613 foreach ( array_keys( $restrictions, 'autoconfirmed' ) as $key ) {
2614 $restrictions[$key] = 'editsemiprotected';
2615 }
2616
2617 return !array_diff( $restrictions, $semi );
2618 }
2619
2620 /**
2621 * Does the title correspond to a protected article?
2622 *
2623 * @param string $action The action the page is protected from,
2624 * by default checks all actions.
2625 * @return bool
2626 */
2627 public function isProtected( $action = '' ) {
2628 global $wgRestrictionLevels;
2629
2630 $restrictionTypes = $this->getRestrictionTypes();
2631
2632 # Special pages have inherent protection
2633 if ( $this->isSpecialPage() ) {
2634 return true;
2635 }
2636
2637 # Check regular protection levels
2638 foreach ( $restrictionTypes as $type ) {
2639 if ( $action == $type || $action == '' ) {
2640 $r = $this->getRestrictions( $type );
2641 foreach ( $wgRestrictionLevels as $level ) {
2642 if ( in_array( $level, $r ) && $level != '' ) {
2643 return true;
2644 }
2645 }
2646 }
2647 }
2648
2649 return false;
2650 }
2651
2652 /**
2653 * Determines if $user is unable to edit this page because it has been protected
2654 * by $wgNamespaceProtection.
2655 *
2656 * @param User $user User object to check permissions
2657 * @return bool
2658 */
2659 public function isNamespaceProtected( User $user ) {
2660 global $wgNamespaceProtection;
2661
2662 if ( isset( $wgNamespaceProtection[$this->mNamespace] ) ) {
2663 foreach ( (array)$wgNamespaceProtection[$this->mNamespace] as $right ) {
2664 if ( $right != '' && !$user->isAllowed( $right ) ) {
2665 return true;
2666 }
2667 }
2668 }
2669 return false;
2670 }
2671
2672 /**
2673 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
2674 *
2675 * @return bool If the page is subject to cascading restrictions.
2676 */
2677 public function isCascadeProtected() {
2678 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
2679 return ( $sources > 0 );
2680 }
2681
2682 /**
2683 * Determines whether cascading protection sources have already been loaded from
2684 * the database.
2685 *
2686 * @param bool $getPages True to check if the pages are loaded, or false to check
2687 * if the status is loaded.
2688 * @return bool Whether or not the specified information has been loaded
2689 * @since 1.23
2690 */
2691 public function areCascadeProtectionSourcesLoaded( $getPages = true ) {
2692 return $getPages ? $this->mCascadeSources !== null : $this->mHasCascadingRestrictions !== null;
2693 }
2694
2695 /**
2696 * Cascading protection: Get the source of any cascading restrictions on this page.
2697 *
2698 * @param bool $getPages Whether or not to retrieve the actual pages
2699 * that the restrictions have come from and the actual restrictions
2700 * themselves.
2701 * @return array Two elements: First is an array of Title objects of the
2702 * pages from which cascading restrictions have come, false for
2703 * none, or true if such restrictions exist but $getPages was not
2704 * set. Second is an array like that returned by
2705 * Title::getAllRestrictions(), or an empty array if $getPages is
2706 * false.
2707 */
2708 public function getCascadeProtectionSources( $getPages = true ) {
2709 global $wgContLang;
2710 $pagerestrictions = array();
2711
2712 if ( $this->mCascadeSources !== null && $getPages ) {
2713 return array( $this->mCascadeSources, $this->mCascadingRestrictions );
2714 } elseif ( $this->mHasCascadingRestrictions !== null && !$getPages ) {
2715 return array( $this->mHasCascadingRestrictions, $pagerestrictions );
2716 }
2717
2718 wfProfileIn( __METHOD__ );
2719
2720 $dbr = wfGetDB( DB_SLAVE );
2721
2722 if ( $this->getNamespace() == NS_FILE ) {
2723 $tables = array( 'imagelinks', 'page_restrictions' );
2724 $where_clauses = array(
2725 'il_to' => $this->getDBkey(),
2726 'il_from=pr_page',
2727 'pr_cascade' => 1
2728 );
2729 } else {
2730 $tables = array( 'templatelinks', 'page_restrictions' );
2731 $where_clauses = array(
2732 'tl_namespace' => $this->getNamespace(),
2733 'tl_title' => $this->getDBkey(),
2734 'tl_from=pr_page',
2735 'pr_cascade' => 1
2736 );
2737 }
2738
2739 if ( $getPages ) {
2740 $cols = array( 'pr_page', 'page_namespace', 'page_title',
2741 'pr_expiry', 'pr_type', 'pr_level' );
2742 $where_clauses[] = 'page_id=pr_page';
2743 $tables[] = 'page';
2744 } else {
2745 $cols = array( 'pr_expiry' );
2746 }
2747
2748 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__ );
2749
2750 $sources = $getPages ? array() : false;
2751 $now = wfTimestampNow();
2752 $purgeExpired = false;
2753
2754 foreach ( $res as $row ) {
2755 $expiry = $wgContLang->formatExpiry( $row->pr_expiry, TS_MW );
2756 if ( $expiry > $now ) {
2757 if ( $getPages ) {
2758 $page_id = $row->pr_page;
2759 $page_ns = $row->page_namespace;
2760 $page_title = $row->page_title;
2761 $sources[$page_id] = Title::makeTitle( $page_ns, $page_title );
2762 # Add groups needed for each restriction type if its not already there
2763 # Make sure this restriction type still exists
2764
2765 if ( !isset( $pagerestrictions[$row->pr_type] ) ) {
2766 $pagerestrictions[$row->pr_type] = array();
2767 }
2768
2769 if (
2770 isset( $pagerestrictions[$row->pr_type] )
2771 && !in_array( $row->pr_level, $pagerestrictions[$row->pr_type] )
2772 ) {
2773 $pagerestrictions[$row->pr_type][] = $row->pr_level;
2774 }
2775 } else {
2776 $sources = true;
2777 }
2778 } else {
2779 // Trigger lazy purge of expired restrictions from the db
2780 $purgeExpired = true;
2781 }
2782 }
2783 if ( $purgeExpired ) {
2784 Title::purgeExpiredRestrictions();
2785 }
2786
2787 if ( $getPages ) {
2788 $this->mCascadeSources = $sources;
2789 $this->mCascadingRestrictions = $pagerestrictions;
2790 } else {
2791 $this->mHasCascadingRestrictions = $sources;
2792 }
2793
2794 wfProfileOut( __METHOD__ );
2795 return array( $sources, $pagerestrictions );
2796 }
2797
2798 /**
2799 * Accessor for mRestrictionsLoaded
2800 *
2801 * @return bool Whether or not the page's restrictions have already been
2802 * loaded from the database
2803 * @since 1.23
2804 */
2805 public function areRestrictionsLoaded() {
2806 return $this->mRestrictionsLoaded;
2807 }
2808
2809 /**
2810 * Accessor/initialisation for mRestrictions
2811 *
2812 * @param string $action Action that permission needs to be checked for
2813 * @return array Restriction levels needed to take the action. All levels are
2814 * required. Note that restriction levels are normally user rights, but 'sysop'
2815 * and 'autoconfirmed' are also allowed for backwards compatibility. These should
2816 * be mapped to 'editprotected' and 'editsemiprotected' respectively.
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 }