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