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