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