Merge "Add and use Title::getOtherPage()"
[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 other title for this page, if this is a subject page
1339 * get the talk page, if it is a subject page get the talk page
1340 *
1341 * @since 1.25
1342 * @throws MWException
1343 * @return Title
1344 */
1345 public function getOtherPage() {
1346 if ( $this->isSpecialPage() ) {
1347 throw new MWException( 'Special pages cannot have other pages' );
1348 }
1349 if ( $this->isTalkPage() ) {
1350 return $this->getSubjectPage();
1351 } else {
1352 return $this->getTalkPage();
1353 }
1354 }
1355
1356 /**
1357 * Get the default namespace index, for when there is no namespace
1358 *
1359 * @return int Default namespace index
1360 */
1361 public function getDefaultNamespace() {
1362 return $this->mDefaultNamespace;
1363 }
1364
1365 /**
1366 * Get the Title fragment (i.e.\ the bit after the #) in text form
1367 *
1368 * Use Title::hasFragment to check for a fragment
1369 *
1370 * @return string Title fragment
1371 */
1372 public function getFragment() {
1373 return $this->mFragment;
1374 }
1375
1376 /**
1377 * Check if a Title fragment is set
1378 *
1379 * @return bool
1380 * @since 1.23
1381 */
1382 public function hasFragment() {
1383 return $this->mFragment !== '';
1384 }
1385
1386 /**
1387 * Get the fragment in URL form, including the "#" character if there is one
1388 * @return string Fragment in URL form
1389 */
1390 public function getFragmentForURL() {
1391 if ( !$this->hasFragment() ) {
1392 return '';
1393 } else {
1394 return '#' . Title::escapeFragmentForURL( $this->getFragment() );
1395 }
1396 }
1397
1398 /**
1399 * Set the fragment for this title. Removes the first character from the
1400 * specified fragment before setting, so it assumes you're passing it with
1401 * an initial "#".
1402 *
1403 * Deprecated for public use, use Title::makeTitle() with fragment parameter.
1404 * Still in active use privately.
1405 *
1406 * @param string $fragment Text
1407 */
1408 public function setFragment( $fragment ) {
1409 $this->mFragment = str_replace( '_', ' ', substr( $fragment, 1 ) );
1410 }
1411
1412 /**
1413 * Prefix some arbitrary text with the namespace or interwiki prefix
1414 * of this object
1415 *
1416 * @param string $name The text
1417 * @return string The prefixed text
1418 */
1419 private function prefix( $name ) {
1420 $p = '';
1421 if ( $this->isExternal() ) {
1422 $p = $this->mInterwiki . ':';
1423 }
1424
1425 if ( 0 != $this->mNamespace ) {
1426 $p .= $this->getNsText() . ':';
1427 }
1428 return $p . $name;
1429 }
1430
1431 /**
1432 * Get the prefixed database key form
1433 *
1434 * @return string The prefixed title, with underscores and
1435 * any interwiki and namespace prefixes
1436 */
1437 public function getPrefixedDBkey() {
1438 $s = $this->prefix( $this->mDbkeyform );
1439 $s = str_replace( ' ', '_', $s );
1440 return $s;
1441 }
1442
1443 /**
1444 * Get the prefixed title with spaces.
1445 * This is the form usually used for display
1446 *
1447 * @return string The prefixed title, with spaces
1448 */
1449 public function getPrefixedText() {
1450 if ( $this->mPrefixedText === null ) {
1451 $s = $this->prefix( $this->mTextform );
1452 $s = str_replace( '_', ' ', $s );
1453 $this->mPrefixedText = $s;
1454 }
1455 return $this->mPrefixedText;
1456 }
1457
1458 /**
1459 * Return a string representation of this title
1460 *
1461 * @return string Representation of this title
1462 */
1463 public function __toString() {
1464 return $this->getPrefixedText();
1465 }
1466
1467 /**
1468 * Get the prefixed title with spaces, plus any fragment
1469 * (part beginning with '#')
1470 *
1471 * @return string The prefixed title, with spaces and the fragment, including '#'
1472 */
1473 public function getFullText() {
1474 $text = $this->getPrefixedText();
1475 if ( $this->hasFragment() ) {
1476 $text .= '#' . $this->getFragment();
1477 }
1478 return $text;
1479 }
1480
1481 /**
1482 * Get the root page name text without a namespace, i.e. the leftmost part before any slashes
1483 *
1484 * @par Example:
1485 * @code
1486 * Title::newFromText('User:Foo/Bar/Baz')->getRootText();
1487 * # returns: 'Foo'
1488 * @endcode
1489 *
1490 * @return string Root name
1491 * @since 1.20
1492 */
1493 public function getRootText() {
1494 if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
1495 return $this->getText();
1496 }
1497
1498 return strtok( $this->getText(), '/' );
1499 }
1500
1501 /**
1502 * Get the root page name title, i.e. the leftmost part before any slashes
1503 *
1504 * @par Example:
1505 * @code
1506 * Title::newFromText('User:Foo/Bar/Baz')->getRootTitle();
1507 * # returns: Title{User:Foo}
1508 * @endcode
1509 *
1510 * @return Title Root title
1511 * @since 1.20
1512 */
1513 public function getRootTitle() {
1514 return Title::makeTitle( $this->getNamespace(), $this->getRootText() );
1515 }
1516
1517 /**
1518 * Get the base page name without a namespace, i.e. the part before the subpage name
1519 *
1520 * @par Example:
1521 * @code
1522 * Title::newFromText('User:Foo/Bar/Baz')->getBaseText();
1523 * # returns: 'Foo/Bar'
1524 * @endcode
1525 *
1526 * @return string Base name
1527 */
1528 public function getBaseText() {
1529 if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
1530 return $this->getText();
1531 }
1532
1533 $parts = explode( '/', $this->getText() );
1534 # Don't discard the real title if there's no subpage involved
1535 if ( count( $parts ) > 1 ) {
1536 unset( $parts[count( $parts ) - 1] );
1537 }
1538 return implode( '/', $parts );
1539 }
1540
1541 /**
1542 * Get the base page name title, i.e. the part before the subpage name
1543 *
1544 * @par Example:
1545 * @code
1546 * Title::newFromText('User:Foo/Bar/Baz')->getBaseTitle();
1547 * # returns: Title{User:Foo/Bar}
1548 * @endcode
1549 *
1550 * @return Title Base title
1551 * @since 1.20
1552 */
1553 public function getBaseTitle() {
1554 return Title::makeTitle( $this->getNamespace(), $this->getBaseText() );
1555 }
1556
1557 /**
1558 * Get the lowest-level subpage name, i.e. the rightmost part after any slashes
1559 *
1560 * @par Example:
1561 * @code
1562 * Title::newFromText('User:Foo/Bar/Baz')->getSubpageText();
1563 * # returns: "Baz"
1564 * @endcode
1565 *
1566 * @return string Subpage name
1567 */
1568 public function getSubpageText() {
1569 if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
1570 return $this->mTextform;
1571 }
1572 $parts = explode( '/', $this->mTextform );
1573 return $parts[count( $parts ) - 1];
1574 }
1575
1576 /**
1577 * Get the title for a subpage of the current page
1578 *
1579 * @par Example:
1580 * @code
1581 * Title::newFromText('User:Foo/Bar/Baz')->getSubpage("Asdf");
1582 * # returns: Title{User:Foo/Bar/Baz/Asdf}
1583 * @endcode
1584 *
1585 * @param string $text The subpage name to add to the title
1586 * @return Title Subpage title
1587 * @since 1.20
1588 */
1589 public function getSubpage( $text ) {
1590 return Title::makeTitleSafe( $this->getNamespace(), $this->getText() . '/' . $text );
1591 }
1592
1593 /**
1594 * Get a URL-encoded form of the subpage text
1595 *
1596 * @return string URL-encoded subpage name
1597 */
1598 public function getSubpageUrlForm() {
1599 $text = $this->getSubpageText();
1600 $text = wfUrlencode( str_replace( ' ', '_', $text ) );
1601 return $text;
1602 }
1603
1604 /**
1605 * Get a URL-encoded title (not an actual URL) including interwiki
1606 *
1607 * @return string The URL-encoded form
1608 */
1609 public function getPrefixedURL() {
1610 $s = $this->prefix( $this->mDbkeyform );
1611 $s = wfUrlencode( str_replace( ' ', '_', $s ) );
1612 return $s;
1613 }
1614
1615 /**
1616 * Helper to fix up the get{Canonical,Full,Link,Local,Internal}URL args
1617 * get{Canonical,Full,Link,Local,Internal}URL methods accepted an optional
1618 * second argument named variant. This was deprecated in favor
1619 * of passing an array of option with a "variant" key
1620 * Once $query2 is removed for good, this helper can be dropped
1621 * and the wfArrayToCgi moved to getLocalURL();
1622 *
1623 * @since 1.19 (r105919)
1624 * @param array|string $query
1625 * @param bool $query2
1626 * @return string
1627 */
1628 private static function fixUrlQueryArgs( $query, $query2 = false ) {
1629 if ( $query2 !== false ) {
1630 wfDeprecated( "Title::get{Canonical,Full,Link,Local,Internal}URL " .
1631 "method called with a second parameter is deprecated. Add your " .
1632 "parameter to an array passed as the first parameter.", "1.19" );
1633 }
1634 if ( is_array( $query ) ) {
1635 $query = wfArrayToCgi( $query );
1636 }
1637 if ( $query2 ) {
1638 if ( is_string( $query2 ) ) {
1639 // $query2 is a string, we will consider this to be
1640 // a deprecated $variant argument and add it to the query
1641 $query2 = wfArrayToCgi( array( 'variant' => $query2 ) );
1642 } else {
1643 $query2 = wfArrayToCgi( $query2 );
1644 }
1645 // If we have $query content add a & to it first
1646 if ( $query ) {
1647 $query .= '&';
1648 }
1649 // Now append the queries together
1650 $query .= $query2;
1651 }
1652 return $query;
1653 }
1654
1655 /**
1656 * Get a real URL referring to this title, with interwiki link and
1657 * fragment
1658 *
1659 * @see self::getLocalURL for the arguments.
1660 * @see wfExpandUrl
1661 * @param array|string $query
1662 * @param bool $query2
1663 * @param string $proto Protocol type to use in URL
1664 * @return string The URL
1665 */
1666 public function getFullURL( $query = '', $query2 = false, $proto = PROTO_RELATIVE ) {
1667 $query = self::fixUrlQueryArgs( $query, $query2 );
1668
1669 # Hand off all the decisions on urls to getLocalURL
1670 $url = $this->getLocalURL( $query );
1671
1672 # Expand the url to make it a full url. Note that getLocalURL has the
1673 # potential to output full urls for a variety of reasons, so we use
1674 # wfExpandUrl instead of simply prepending $wgServer
1675 $url = wfExpandUrl( $url, $proto );
1676
1677 # Finally, add the fragment.
1678 $url .= $this->getFragmentForURL();
1679
1680 Hooks::run( 'GetFullURL', array( &$this, &$url, $query ) );
1681 return $url;
1682 }
1683
1684 /**
1685 * Get a URL with no fragment or server name (relative URL) from a Title object.
1686 * If this page is generated with action=render, however,
1687 * $wgServer is prepended to make an absolute URL.
1688 *
1689 * @see self::getFullURL to always get an absolute URL.
1690 * @see self::getLinkURL to always get a URL that's the simplest URL that will be
1691 * valid to link, locally, to the current Title.
1692 * @see self::newFromText to produce a Title object.
1693 *
1694 * @param string|array $query An optional query string,
1695 * not used for interwiki links. Can be specified as an associative array as well,
1696 * e.g., array( 'action' => 'edit' ) (keys and values will be URL-escaped).
1697 * Some query patterns will trigger various shorturl path replacements.
1698 * @param array $query2 An optional secondary query array. This one MUST
1699 * be an array. If a string is passed it will be interpreted as a deprecated
1700 * variant argument and urlencoded into a variant= argument.
1701 * This second query argument will be added to the $query
1702 * The second parameter is deprecated since 1.19. Pass it as a key,value
1703 * pair in the first parameter array instead.
1704 *
1705 * @return string String of the URL.
1706 */
1707 public function getLocalURL( $query = '', $query2 = false ) {
1708 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
1709
1710 $query = self::fixUrlQueryArgs( $query, $query2 );
1711
1712 $interwiki = Interwiki::fetch( $this->mInterwiki );
1713 if ( $interwiki ) {
1714 $namespace = $this->getNsText();
1715 if ( $namespace != '' ) {
1716 # Can this actually happen? Interwikis shouldn't be parsed.
1717 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
1718 $namespace .= ':';
1719 }
1720 $url = $interwiki->getURL( $namespace . $this->getDBkey() );
1721 $url = wfAppendQuery( $url, $query );
1722 } else {
1723 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
1724 if ( $query == '' ) {
1725 $url = str_replace( '$1', $dbkey, $wgArticlePath );
1726 Hooks::run( 'GetLocalURL::Article', array( &$this, &$url ) );
1727 } else {
1728 global $wgVariantArticlePath, $wgActionPaths, $wgContLang;
1729 $url = false;
1730 $matches = array();
1731
1732 if ( !empty( $wgActionPaths )
1733 && preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches )
1734 ) {
1735 $action = urldecode( $matches[2] );
1736 if ( isset( $wgActionPaths[$action] ) ) {
1737 $query = $matches[1];
1738 if ( isset( $matches[4] ) ) {
1739 $query .= $matches[4];
1740 }
1741 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
1742 if ( $query != '' ) {
1743 $url = wfAppendQuery( $url, $query );
1744 }
1745 }
1746 }
1747
1748 if ( $url === false
1749 && $wgVariantArticlePath
1750 && $wgContLang->getCode() === $this->getPageLanguage()->getCode()
1751 && $this->getPageLanguage()->hasVariants()
1752 && preg_match( '/^variant=([^&]*)$/', $query, $matches )
1753 ) {
1754 $variant = urldecode( $matches[1] );
1755 if ( $this->getPageLanguage()->hasVariant( $variant ) ) {
1756 // Only do the variant replacement if the given variant is a valid
1757 // variant for the page's language.
1758 $url = str_replace( '$2', urlencode( $variant ), $wgVariantArticlePath );
1759 $url = str_replace( '$1', $dbkey, $url );
1760 }
1761 }
1762
1763 if ( $url === false ) {
1764 if ( $query == '-' ) {
1765 $query = '';
1766 }
1767 $url = "{$wgScript}?title={$dbkey}&{$query}";
1768 }
1769 }
1770
1771 Hooks::run( 'GetLocalURL::Internal', array( &$this, &$url, $query ) );
1772
1773 // @todo FIXME: This causes breakage in various places when we
1774 // actually expected a local URL and end up with dupe prefixes.
1775 if ( $wgRequest->getVal( 'action' ) == 'render' ) {
1776 $url = $wgServer . $url;
1777 }
1778 }
1779 Hooks::run( 'GetLocalURL', array( &$this, &$url, $query ) );
1780 return $url;
1781 }
1782
1783 /**
1784 * Get a URL that's the simplest URL that will be valid to link, locally,
1785 * to the current Title. It includes the fragment, but does not include
1786 * the server unless action=render is used (or the link is external). If
1787 * there's a fragment but the prefixed text is empty, we just return a link
1788 * to the fragment.
1789 *
1790 * The result obviously should not be URL-escaped, but does need to be
1791 * HTML-escaped if it's being output in HTML.
1792 *
1793 * @param array $query
1794 * @param bool $query2
1795 * @param string $proto Protocol to use; setting this will cause a full URL to be used
1796 * @see self::getLocalURL for the arguments.
1797 * @return string The URL
1798 */
1799 public function getLinkURL( $query = '', $query2 = false, $proto = PROTO_RELATIVE ) {
1800 wfProfileIn( __METHOD__ );
1801 if ( $this->isExternal() || $proto !== PROTO_RELATIVE ) {
1802 $ret = $this->getFullURL( $query, $query2, $proto );
1803 } elseif ( $this->getPrefixedText() === '' && $this->hasFragment() ) {
1804 $ret = $this->getFragmentForURL();
1805 } else {
1806 $ret = $this->getLocalURL( $query, $query2 ) . $this->getFragmentForURL();
1807 }
1808 wfProfileOut( __METHOD__ );
1809 return $ret;
1810 }
1811
1812 /**
1813 * Get the URL form for an internal link.
1814 * - Used in various Squid-related code, in case we have a different
1815 * internal hostname for the server from the exposed one.
1816 *
1817 * This uses $wgInternalServer to qualify the path, or $wgServer
1818 * if $wgInternalServer is not set. If the server variable used is
1819 * protocol-relative, the URL will be expanded to http://
1820 *
1821 * @see self::getLocalURL for the arguments.
1822 * @return string The URL
1823 */
1824 public function getInternalURL( $query = '', $query2 = false ) {
1825 global $wgInternalServer, $wgServer;
1826 $query = self::fixUrlQueryArgs( $query, $query2 );
1827 $server = $wgInternalServer !== false ? $wgInternalServer : $wgServer;
1828 $url = wfExpandUrl( $server . $this->getLocalURL( $query ), PROTO_HTTP );
1829 Hooks::run( 'GetInternalURL', array( &$this, &$url, $query ) );
1830 return $url;
1831 }
1832
1833 /**
1834 * Get the URL for a canonical link, for use in things like IRC and
1835 * e-mail notifications. Uses $wgCanonicalServer and the
1836 * GetCanonicalURL hook.
1837 *
1838 * NOTE: Unlike getInternalURL(), the canonical URL includes the fragment
1839 *
1840 * @see self::getLocalURL for the arguments.
1841 * @return string The URL
1842 * @since 1.18
1843 */
1844 public function getCanonicalURL( $query = '', $query2 = false ) {
1845 $query = self::fixUrlQueryArgs( $query, $query2 );
1846 $url = wfExpandUrl( $this->getLocalURL( $query ) . $this->getFragmentForURL(), PROTO_CANONICAL );
1847 Hooks::run( 'GetCanonicalURL', array( &$this, &$url, $query ) );
1848 return $url;
1849 }
1850
1851 /**
1852 * Get the edit URL for this Title
1853 *
1854 * @return string The URL, or a null string if this is an interwiki link
1855 */
1856 public function getEditURL() {
1857 if ( $this->isExternal() ) {
1858 return '';
1859 }
1860 $s = $this->getLocalURL( 'action=edit' );
1861
1862 return $s;
1863 }
1864
1865 /**
1866 * Is $wgUser watching this page?
1867 *
1868 * @deprecated since 1.20; use User::isWatched() instead.
1869 * @return bool
1870 */
1871 public function userIsWatching() {
1872 global $wgUser;
1873
1874 if ( is_null( $this->mWatched ) ) {
1875 if ( NS_SPECIAL == $this->mNamespace || !$wgUser->isLoggedIn() ) {
1876 $this->mWatched = false;
1877 } else {
1878 $this->mWatched = $wgUser->isWatched( $this );
1879 }
1880 }
1881 return $this->mWatched;
1882 }
1883
1884 /**
1885 * Can $user perform $action on this page?
1886 * This skips potentially expensive cascading permission checks
1887 * as well as avoids expensive error formatting
1888 *
1889 * Suitable for use for nonessential UI controls in common cases, but
1890 * _not_ for functional access control.
1891 *
1892 * May provide false positives, but should never provide a false negative.
1893 *
1894 * @param string $action Action that permission needs to be checked for
1895 * @param User $user User to check (since 1.19); $wgUser will be used if not provided.
1896 * @return bool
1897 */
1898 public function quickUserCan( $action, $user = null ) {
1899 return $this->userCan( $action, $user, false );
1900 }
1901
1902 /**
1903 * Can $user perform $action on this page?
1904 *
1905 * @param string $action Action that permission needs to be checked for
1906 * @param User $user User to check (since 1.19); $wgUser will be used if not
1907 * provided.
1908 * @param bool $doExpensiveQueries Set this to false to avoid doing
1909 * unnecessary queries.
1910 * @return bool
1911 */
1912 public function userCan( $action, $user = null, $doExpensiveQueries = true ) {
1913 if ( !$user instanceof User ) {
1914 global $wgUser;
1915 $user = $wgUser;
1916 }
1917
1918 return !count( $this->getUserPermissionsErrorsInternal(
1919 $action, $user, $doExpensiveQueries, true ) );
1920 }
1921
1922 /**
1923 * Can $user perform $action on this page?
1924 *
1925 * @todo FIXME: This *does not* check throttles (User::pingLimiter()).
1926 *
1927 * @param string $action Action that permission needs to be checked for
1928 * @param User $user User to check
1929 * @param bool $doExpensiveQueries Set this to false to avoid doing unnecessary
1930 * queries by skipping checks for cascading protections and user blocks.
1931 * @param array $ignoreErrors Array of Strings Set this to a list of message keys
1932 * whose corresponding errors may be ignored.
1933 * @return array Array of arguments to wfMessage to explain permissions problems.
1934 */
1935 public function getUserPermissionsErrors( $action, $user, $doExpensiveQueries = true,
1936 $ignoreErrors = array()
1937 ) {
1938 $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries );
1939
1940 // Remove the errors being ignored.
1941 foreach ( $errors as $index => $error ) {
1942 $error_key = is_array( $error ) ? $error[0] : $error;
1943
1944 if ( in_array( $error_key, $ignoreErrors ) ) {
1945 unset( $errors[$index] );
1946 }
1947 }
1948
1949 return $errors;
1950 }
1951
1952 /**
1953 * Permissions checks that fail most often, and which are easiest to test.
1954 *
1955 * @param string $action The action to check
1956 * @param User $user User to check
1957 * @param array $errors List of current errors
1958 * @param bool $doExpensiveQueries Whether or not to perform expensive queries
1959 * @param bool $short Short circuit on first error
1960 *
1961 * @return array List of errors
1962 */
1963 private function checkQuickPermissions( $action, $user, $errors,
1964 $doExpensiveQueries, $short
1965 ) {
1966 if ( !Hooks::run( 'TitleQuickPermissions',
1967 array( $this, $user, $action, &$errors, $doExpensiveQueries, $short ) )
1968 ) {
1969 return $errors;
1970 }
1971
1972 if ( $action == 'create' ) {
1973 if (
1974 ( $this->isTalkPage() && !$user->isAllowed( 'createtalk' ) ) ||
1975 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage' ) )
1976 ) {
1977 $errors[] = $user->isAnon() ? array( 'nocreatetext' ) : array( 'nocreate-loggedin' );
1978 }
1979 } elseif ( $action == 'move' ) {
1980 if ( !$user->isAllowed( 'move-rootuserpages' )
1981 && $this->mNamespace == NS_USER && !$this->isSubpage() ) {
1982 // Show user page-specific message only if the user can move other pages
1983 $errors[] = array( 'cant-move-user-page' );
1984 }
1985
1986 // Check if user is allowed to move files if it's a file
1987 if ( $this->mNamespace == NS_FILE && !$user->isAllowed( 'movefile' ) ) {
1988 $errors[] = array( 'movenotallowedfile' );
1989 }
1990
1991 // Check if user is allowed to move category pages if it's a category page
1992 if ( $this->mNamespace == NS_CATEGORY && !$user->isAllowed( 'move-categorypages' ) ) {
1993 $errors[] = array( 'cant-move-category-page' );
1994 }
1995
1996 if ( !$user->isAllowed( 'move' ) ) {
1997 // User can't move anything
1998 $userCanMove = User::groupHasPermission( 'user', 'move' );
1999 $autoconfirmedCanMove = User::groupHasPermission( 'autoconfirmed', 'move' );
2000 if ( $user->isAnon() && ( $userCanMove || $autoconfirmedCanMove ) ) {
2001 // custom message if logged-in users without any special rights can move
2002 $errors[] = array( 'movenologintext' );
2003 } else {
2004 $errors[] = array( 'movenotallowed' );
2005 }
2006 }
2007 } elseif ( $action == 'move-target' ) {
2008 if ( !$user->isAllowed( 'move' ) ) {
2009 // User can't move anything
2010 $errors[] = array( 'movenotallowed' );
2011 } elseif ( !$user->isAllowed( 'move-rootuserpages' )
2012 && $this->mNamespace == NS_USER && !$this->isSubpage() ) {
2013 // Show user page-specific message only if the user can move other pages
2014 $errors[] = array( 'cant-move-to-user-page' );
2015 } elseif ( !$user->isAllowed( 'move-categorypages' )
2016 && $this->mNamespace == NS_CATEGORY ) {
2017 // Show category page-specific message only if the user can move other pages
2018 $errors[] = array( 'cant-move-to-category-page' );
2019 }
2020 } elseif ( !$user->isAllowed( $action ) ) {
2021 $errors[] = $this->missingPermissionError( $action, $short );
2022 }
2023
2024 return $errors;
2025 }
2026
2027 /**
2028 * Add the resulting error code to the errors array
2029 *
2030 * @param array $errors List of current errors
2031 * @param array $result Result of errors
2032 *
2033 * @return array List of errors
2034 */
2035 private function resultToError( $errors, $result ) {
2036 if ( is_array( $result ) && count( $result ) && !is_array( $result[0] ) ) {
2037 // A single array representing an error
2038 $errors[] = $result;
2039 } elseif ( is_array( $result ) && is_array( $result[0] ) ) {
2040 // A nested array representing multiple errors
2041 $errors = array_merge( $errors, $result );
2042 } elseif ( $result !== '' && is_string( $result ) ) {
2043 // A string representing a message-id
2044 $errors[] = array( $result );
2045 } elseif ( $result === false ) {
2046 // a generic "We don't want them to do that"
2047 $errors[] = array( 'badaccess-group0' );
2048 }
2049 return $errors;
2050 }
2051
2052 /**
2053 * Check various permission hooks
2054 *
2055 * @param string $action The action to check
2056 * @param User $user User to check
2057 * @param array $errors List of current errors
2058 * @param bool $doExpensiveQueries Whether or not to perform expensive queries
2059 * @param bool $short Short circuit on first error
2060 *
2061 * @return array List of errors
2062 */
2063 private function checkPermissionHooks( $action, $user, $errors, $doExpensiveQueries, $short ) {
2064 // Use getUserPermissionsErrors instead
2065 $result = '';
2066 if ( !Hooks::run( 'userCan', array( &$this, &$user, $action, &$result ) ) ) {
2067 return $result ? array() : array( array( 'badaccess-group0' ) );
2068 }
2069 // Check getUserPermissionsErrors hook
2070 if ( !Hooks::run( 'getUserPermissionsErrors', array( &$this, &$user, $action, &$result ) ) ) {
2071 $errors = $this->resultToError( $errors, $result );
2072 }
2073 // Check getUserPermissionsErrorsExpensive hook
2074 if (
2075 $doExpensiveQueries
2076 && !( $short && count( $errors ) > 0 )
2077 && !Hooks::run( 'getUserPermissionsErrorsExpensive', array( &$this, &$user, $action, &$result ) )
2078 ) {
2079 $errors = $this->resultToError( $errors, $result );
2080 }
2081
2082 return $errors;
2083 }
2084
2085 /**
2086 * Check permissions on special pages & namespaces
2087 *
2088 * @param string $action The action to check
2089 * @param User $user User to check
2090 * @param array $errors List of current errors
2091 * @param bool $doExpensiveQueries Whether or not to perform expensive queries
2092 * @param bool $short Short circuit on first error
2093 *
2094 * @return array List of errors
2095 */
2096 private function checkSpecialsAndNSPermissions( $action, $user, $errors,
2097 $doExpensiveQueries, $short
2098 ) {
2099 # Only 'createaccount' can be performed on special pages,
2100 # which don't actually exist in the DB.
2101 if ( NS_SPECIAL == $this->mNamespace && $action !== 'createaccount' ) {
2102 $errors[] = array( 'ns-specialprotected' );
2103 }
2104
2105 # Check $wgNamespaceProtection for restricted namespaces
2106 if ( $this->isNamespaceProtected( $user ) ) {
2107 $ns = $this->mNamespace == NS_MAIN ?
2108 wfMessage( 'nstab-main' )->text() : $this->getNsText();
2109 $errors[] = $this->mNamespace == NS_MEDIAWIKI ?
2110 array( 'protectedinterface', $action ) : array( 'namespaceprotected', $ns, $action );
2111 }
2112
2113 return $errors;
2114 }
2115
2116 /**
2117 * Check CSS/JS sub-page permissions
2118 *
2119 * @param string $action The action to check
2120 * @param User $user User to check
2121 * @param array $errors List of current errors
2122 * @param bool $doExpensiveQueries Whether or not to perform expensive queries
2123 * @param bool $short Short circuit on first error
2124 *
2125 * @return array List of errors
2126 */
2127 private function checkCSSandJSPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
2128 # Protect css/js subpages of user pages
2129 # XXX: this might be better using restrictions
2130 # XXX: right 'editusercssjs' is deprecated, for backward compatibility only
2131 if ( $action != 'patrol' && !$user->isAllowed( 'editusercssjs' ) ) {
2132 if ( preg_match( '/^' . preg_quote( $user->getName(), '/' ) . '\//', $this->mTextform ) ) {
2133 if ( $this->isCssSubpage() && !$user->isAllowedAny( 'editmyusercss', 'editusercss' ) ) {
2134 $errors[] = array( 'mycustomcssprotected', $action );
2135 } elseif ( $this->isJsSubpage() && !$user->isAllowedAny( 'editmyuserjs', 'edituserjs' ) ) {
2136 $errors[] = array( 'mycustomjsprotected', $action );
2137 }
2138 } else {
2139 if ( $this->isCssSubpage() && !$user->isAllowed( 'editusercss' ) ) {
2140 $errors[] = array( 'customcssprotected', $action );
2141 } elseif ( $this->isJsSubpage() && !$user->isAllowed( 'edituserjs' ) ) {
2142 $errors[] = array( 'customjsprotected', $action );
2143 }
2144 }
2145 }
2146
2147 return $errors;
2148 }
2149
2150 /**
2151 * Check against page_restrictions table requirements on this
2152 * page. The user must possess all required rights for this
2153 * action.
2154 *
2155 * @param string $action The action to check
2156 * @param User $user User to check
2157 * @param array $errors List of current errors
2158 * @param bool $doExpensiveQueries Whether or not to perform expensive queries
2159 * @param bool $short Short circuit on first error
2160 *
2161 * @return array List of errors
2162 */
2163 private function checkPageRestrictions( $action, $user, $errors, $doExpensiveQueries, $short ) {
2164 foreach ( $this->getRestrictions( $action ) as $right ) {
2165 // Backwards compatibility, rewrite sysop -> editprotected
2166 if ( $right == 'sysop' ) {
2167 $right = 'editprotected';
2168 }
2169 // Backwards compatibility, rewrite autoconfirmed -> editsemiprotected
2170 if ( $right == 'autoconfirmed' ) {
2171 $right = 'editsemiprotected';
2172 }
2173 if ( $right == '' ) {
2174 continue;
2175 }
2176 if ( !$user->isAllowed( $right ) ) {
2177 $errors[] = array( 'protectedpagetext', $right, $action );
2178 } elseif ( $this->mCascadeRestriction && !$user->isAllowed( 'protect' ) ) {
2179 $errors[] = array( 'protectedpagetext', 'protect', $action );
2180 }
2181 }
2182
2183 return $errors;
2184 }
2185
2186 /**
2187 * Check restrictions on cascading pages.
2188 *
2189 * @param string $action The action to check
2190 * @param User $user User to check
2191 * @param array $errors List of current errors
2192 * @param bool $doExpensiveQueries Whether or not to perform expensive queries
2193 * @param bool $short Short circuit on first error
2194 *
2195 * @return array List of errors
2196 */
2197 private function checkCascadingSourcesRestrictions( $action, $user, $errors,
2198 $doExpensiveQueries, $short
2199 ) {
2200 if ( $doExpensiveQueries && !$this->isCssJsSubpage() ) {
2201 # We /could/ use the protection level on the source page, but it's
2202 # fairly ugly as we have to establish a precedence hierarchy for pages
2203 # included by multiple cascade-protected pages. So just restrict
2204 # it to people with 'protect' permission, as they could remove the
2205 # protection anyway.
2206 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
2207 # Cascading protection depends on more than this page...
2208 # Several cascading protected pages may include this page...
2209 # Check each cascading level
2210 # This is only for protection restrictions, not for all actions
2211 if ( isset( $restrictions[$action] ) ) {
2212 foreach ( $restrictions[$action] as $right ) {
2213 // Backwards compatibility, rewrite sysop -> editprotected
2214 if ( $right == 'sysop' ) {
2215 $right = 'editprotected';
2216 }
2217 // Backwards compatibility, rewrite autoconfirmed -> editsemiprotected
2218 if ( $right == 'autoconfirmed' ) {
2219 $right = 'editsemiprotected';
2220 }
2221 if ( $right != '' && !$user->isAllowedAll( 'protect', $right ) ) {
2222 $pages = '';
2223 foreach ( $cascadingSources as $page ) {
2224 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
2225 }
2226 $errors[] = array( 'cascadeprotected', count( $cascadingSources ), $pages, $action );
2227 }
2228 }
2229 }
2230 }
2231
2232 return $errors;
2233 }
2234
2235 /**
2236 * Check action permissions not already checked in checkQuickPermissions
2237 *
2238 * @param string $action The action to check
2239 * @param User $user User to check
2240 * @param array $errors List of current errors
2241 * @param bool $doExpensiveQueries Whether or not to perform expensive queries
2242 * @param bool $short Short circuit on first error
2243 *
2244 * @return array List of errors
2245 */
2246 private function checkActionPermissions( $action, $user, $errors,
2247 $doExpensiveQueries, $short
2248 ) {
2249 global $wgDeleteRevisionsLimit, $wgLang;
2250
2251 if ( $action == 'protect' ) {
2252 if ( count( $this->getUserPermissionsErrorsInternal( 'edit',
2253 $user, $doExpensiveQueries, true ) )
2254 ) {
2255 // If they can't edit, they shouldn't protect.
2256 $errors[] = array( 'protect-cantedit' );
2257 }
2258 } elseif ( $action == 'create' ) {
2259 $title_protection = $this->getTitleProtection();
2260 if ( $title_protection ) {
2261 if ( $title_protection['permission'] == ''
2262 || !$user->isAllowed( $title_protection['permission'] )
2263 ) {
2264 $errors[] = array(
2265 'titleprotected',
2266 User::whoIs( $title_protection['user'] ),
2267 $title_protection['reason']
2268 );
2269 }
2270 }
2271 } elseif ( $action == 'move' ) {
2272 // Check for immobile pages
2273 if ( !MWNamespace::isMovable( $this->mNamespace ) ) {
2274 // Specific message for this case
2275 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
2276 } elseif ( !$this->isMovable() ) {
2277 // Less specific message for rarer cases
2278 $errors[] = array( 'immobile-source-page' );
2279 }
2280 } elseif ( $action == 'move-target' ) {
2281 if ( !MWNamespace::isMovable( $this->mNamespace ) ) {
2282 $errors[] = array( 'immobile-target-namespace', $this->getNsText() );
2283 } elseif ( !$this->isMovable() ) {
2284 $errors[] = array( 'immobile-target-page' );
2285 }
2286 } elseif ( $action == 'delete' ) {
2287 $tempErrors = $this->checkPageRestrictions( 'edit',
2288 $user, array(), $doExpensiveQueries, true );
2289 if ( !$tempErrors ) {
2290 $tempErrors = $this->checkCascadingSourcesRestrictions( 'edit',
2291 $user, $tempErrors, $doExpensiveQueries, true );
2292 }
2293 if ( $tempErrors ) {
2294 // If protection keeps them from editing, they shouldn't be able to delete.
2295 $errors[] = array( 'deleteprotected' );
2296 }
2297 if ( $doExpensiveQueries && $wgDeleteRevisionsLimit
2298 && !$this->userCan( 'bigdelete', $user ) && $this->isBigDeletion()
2299 ) {
2300 $errors[] = array( 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) );
2301 }
2302 }
2303 return $errors;
2304 }
2305
2306 /**
2307 * Check that the user isn't blocked from editing.
2308 *
2309 * @param string $action The action to check
2310 * @param User $user User to check
2311 * @param array $errors List of current errors
2312 * @param bool $doExpensiveQueries Whether or not to perform expensive queries
2313 * @param bool $short Short circuit on first error
2314 *
2315 * @return array List of errors
2316 */
2317 private function checkUserBlock( $action, $user, $errors, $doExpensiveQueries, $short ) {
2318 // Account creation blocks handled at userlogin.
2319 // Unblocking handled in SpecialUnblock
2320 if ( !$doExpensiveQueries || in_array( $action, array( 'createaccount', 'unblock' ) ) ) {
2321 return $errors;
2322 }
2323
2324 global $wgEmailConfirmToEdit;
2325
2326 if ( $wgEmailConfirmToEdit && !$user->isEmailConfirmed() ) {
2327 $errors[] = array( 'confirmedittext' );
2328 }
2329
2330 if ( ( $action == 'edit' || $action == 'create' ) && !$user->isBlockedFrom( $this ) ) {
2331 // Don't block the user from editing their own talk page unless they've been
2332 // explicitly blocked from that too.
2333 } elseif ( $user->isBlocked() && $user->mBlock->prevents( $action ) !== false ) {
2334 // @todo FIXME: Pass the relevant context into this function.
2335 $errors[] = $user->getBlock()->getPermissionsError( RequestContext::getMain() );
2336 }
2337
2338 return $errors;
2339 }
2340
2341 /**
2342 * Check that the user is allowed to read this page.
2343 *
2344 * @param string $action The action to check
2345 * @param User $user User to check
2346 * @param array $errors List of current errors
2347 * @param bool $doExpensiveQueries Whether or not to perform expensive queries
2348 * @param bool $short Short circuit on first error
2349 *
2350 * @return array List of errors
2351 */
2352 private function checkReadPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
2353 global $wgWhitelistRead, $wgWhitelistReadRegexp;
2354
2355 $whitelisted = false;
2356 if ( User::isEveryoneAllowed( 'read' ) ) {
2357 # Shortcut for public wikis, allows skipping quite a bit of code
2358 $whitelisted = true;
2359 } elseif ( $user->isAllowed( 'read' ) ) {
2360 # If the user is allowed to read pages, he is allowed to read all pages
2361 $whitelisted = true;
2362 } elseif ( $this->isSpecial( 'Userlogin' )
2363 || $this->isSpecial( 'ChangePassword' )
2364 || $this->isSpecial( 'PasswordReset' )
2365 ) {
2366 # Always grant access to the login page.
2367 # Even anons need to be able to log in.
2368 $whitelisted = true;
2369 } elseif ( is_array( $wgWhitelistRead ) && count( $wgWhitelistRead ) ) {
2370 # Time to check the whitelist
2371 # Only do these checks is there's something to check against
2372 $name = $this->getPrefixedText();
2373 $dbName = $this->getPrefixedDBkey();
2374
2375 // Check for explicit whitelisting with and without underscores
2376 if ( in_array( $name, $wgWhitelistRead, true ) || in_array( $dbName, $wgWhitelistRead, true ) ) {
2377 $whitelisted = true;
2378 } elseif ( $this->getNamespace() == NS_MAIN ) {
2379 # Old settings might have the title prefixed with
2380 # a colon for main-namespace pages
2381 if ( in_array( ':' . $name, $wgWhitelistRead ) ) {
2382 $whitelisted = true;
2383 }
2384 } elseif ( $this->isSpecialPage() ) {
2385 # If it's a special page, ditch the subpage bit and check again
2386 $name = $this->getDBkey();
2387 list( $name, /* $subpage */ ) = SpecialPageFactory::resolveAlias( $name );
2388 if ( $name ) {
2389 $pure = SpecialPage::getTitleFor( $name )->getPrefixedText();
2390 if ( in_array( $pure, $wgWhitelistRead, true ) ) {
2391 $whitelisted = true;
2392 }
2393 }
2394 }
2395 }
2396
2397 if ( !$whitelisted && is_array( $wgWhitelistReadRegexp ) && !empty( $wgWhitelistReadRegexp ) ) {
2398 $name = $this->getPrefixedText();
2399 // Check for regex whitelisting
2400 foreach ( $wgWhitelistReadRegexp as $listItem ) {
2401 if ( preg_match( $listItem, $name ) ) {
2402 $whitelisted = true;
2403 break;
2404 }
2405 }
2406 }
2407
2408 if ( !$whitelisted ) {
2409 # If the title is not whitelisted, give extensions a chance to do so...
2410 Hooks::run( 'TitleReadWhitelist', array( $this, $user, &$whitelisted ) );
2411 if ( !$whitelisted ) {
2412 $errors[] = $this->missingPermissionError( $action, $short );
2413 }
2414 }
2415
2416 return $errors;
2417 }
2418
2419 /**
2420 * Get a description array when the user doesn't have the right to perform
2421 * $action (i.e. when User::isAllowed() returns false)
2422 *
2423 * @param string $action The action to check
2424 * @param bool $short Short circuit on first error
2425 * @return array List of errors
2426 */
2427 private function missingPermissionError( $action, $short ) {
2428 // We avoid expensive display logic for quickUserCan's and such
2429 if ( $short ) {
2430 return array( 'badaccess-group0' );
2431 }
2432
2433 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
2434 User::getGroupsWithPermission( $action ) );
2435
2436 if ( count( $groups ) ) {
2437 global $wgLang;
2438 return array(
2439 'badaccess-groups',
2440 $wgLang->commaList( $groups ),
2441 count( $groups )
2442 );
2443 } else {
2444 return array( 'badaccess-group0' );
2445 }
2446 }
2447
2448 /**
2449 * Can $user perform $action on this page? This is an internal function,
2450 * which checks ONLY that previously checked by userCan (i.e. it leaves out
2451 * checks on wfReadOnly() and blocks)
2452 *
2453 * @param string $action Action that permission needs to be checked for
2454 * @param User $user User to check
2455 * @param bool $doExpensiveQueries Set this to false to avoid doing unnecessary queries.
2456 * @param bool $short Set this to true to stop after the first permission error.
2457 * @return array Array of arrays of the arguments to wfMessage to explain permissions problems.
2458 */
2459 protected function getUserPermissionsErrorsInternal( $action, $user,
2460 $doExpensiveQueries = true, $short = false
2461 ) {
2462 wfProfileIn( __METHOD__ );
2463
2464 # Read has special handling
2465 if ( $action == 'read' ) {
2466 $checks = array(
2467 'checkPermissionHooks',
2468 'checkReadPermissions',
2469 );
2470 # Don't call checkSpecialsAndNSPermissions or checkCSSandJSPermissions
2471 # here as it will lead to duplicate error messages. This is okay to do
2472 # since anywhere that checks for create will also check for edit, and
2473 # those checks are called for edit.
2474 } elseif ( $action == 'create' ) {
2475 $checks = array(
2476 'checkQuickPermissions',
2477 'checkPermissionHooks',
2478 'checkPageRestrictions',
2479 'checkCascadingSourcesRestrictions',
2480 'checkActionPermissions',
2481 'checkUserBlock'
2482 );
2483 } else {
2484 $checks = array(
2485 'checkQuickPermissions',
2486 'checkPermissionHooks',
2487 'checkSpecialsAndNSPermissions',
2488 'checkCSSandJSPermissions',
2489 'checkPageRestrictions',
2490 'checkCascadingSourcesRestrictions',
2491 'checkActionPermissions',
2492 'checkUserBlock'
2493 );
2494 }
2495
2496 $errors = array();
2497 while ( count( $checks ) > 0 &&
2498 !( $short && count( $errors ) > 0 ) ) {
2499 $method = array_shift( $checks );
2500 $errors = $this->$method( $action, $user, $errors, $doExpensiveQueries, $short );
2501 }
2502
2503 wfProfileOut( __METHOD__ );
2504 return $errors;
2505 }
2506
2507 /**
2508 * Get a filtered list of all restriction types supported by this wiki.
2509 * @param bool $exists True to get all restriction types that apply to
2510 * titles that do exist, False for all restriction types that apply to
2511 * titles that do not exist
2512 * @return array
2513 */
2514 public static function getFilteredRestrictionTypes( $exists = true ) {
2515 global $wgRestrictionTypes;
2516 $types = $wgRestrictionTypes;
2517 if ( $exists ) {
2518 # Remove the create restriction for existing titles
2519 $types = array_diff( $types, array( 'create' ) );
2520 } else {
2521 # Only the create and upload restrictions apply to non-existing titles
2522 $types = array_intersect( $types, array( 'create', 'upload' ) );
2523 }
2524 return $types;
2525 }
2526
2527 /**
2528 * Returns restriction types for the current Title
2529 *
2530 * @return array Applicable restriction types
2531 */
2532 public function getRestrictionTypes() {
2533 if ( $this->isSpecialPage() ) {
2534 return array();
2535 }
2536
2537 $types = self::getFilteredRestrictionTypes( $this->exists() );
2538
2539 if ( $this->getNamespace() != NS_FILE ) {
2540 # Remove the upload restriction for non-file titles
2541 $types = array_diff( $types, array( 'upload' ) );
2542 }
2543
2544 Hooks::run( 'TitleGetRestrictionTypes', array( $this, &$types ) );
2545
2546 wfDebug( __METHOD__ . ': applicable restrictions to [[' .
2547 $this->getPrefixedText() . ']] are {' . implode( ',', $types ) . "}\n" );
2548
2549 return $types;
2550 }
2551
2552 /**
2553 * Is this title subject to title protection?
2554 * Title protection is the one applied against creation of such title.
2555 *
2556 * @return array|bool An associative array representing any existent title
2557 * protection, or false if there's none.
2558 */
2559 public function getTitleProtection() {
2560 // Can't protect pages in special namespaces
2561 if ( $this->getNamespace() < 0 ) {
2562 return false;
2563 }
2564
2565 // Can't protect pages that exist.
2566 if ( $this->exists() ) {
2567 return false;
2568 }
2569
2570 if ( $this->mTitleProtection === null ) {
2571 $dbr = wfGetDB( DB_SLAVE );
2572 $res = $dbr->select(
2573 'protected_titles',
2574 array(
2575 'user' => 'pt_user',
2576 'reason' => 'pt_reason',
2577 'expiry' => 'pt_expiry',
2578 'permission' => 'pt_create_perm'
2579 ),
2580 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
2581 __METHOD__
2582 );
2583
2584 // fetchRow returns false if there are no rows.
2585 $row = $dbr->fetchRow( $res );
2586 if ( $row ) {
2587 if ( $row['permission'] == 'sysop' ) {
2588 $row['permission'] = 'editprotected'; // B/C
2589 }
2590 if ( $row['permission'] == 'autoconfirmed' ) {
2591 $row['permission'] = 'editsemiprotected'; // B/C
2592 }
2593 }
2594 $this->mTitleProtection = $row;
2595 }
2596 return $this->mTitleProtection;
2597 }
2598
2599 /**
2600 * Remove any title protection due to page existing
2601 */
2602 public function deleteTitleProtection() {
2603 $dbw = wfGetDB( DB_MASTER );
2604
2605 $dbw->delete(
2606 'protected_titles',
2607 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
2608 __METHOD__
2609 );
2610 $this->mTitleProtection = false;
2611 }
2612
2613 /**
2614 * Is this page "semi-protected" - the *only* protection levels are listed
2615 * in $wgSemiprotectedRestrictionLevels?
2616 *
2617 * @param string $action Action to check (default: edit)
2618 * @return bool
2619 */
2620 public function isSemiProtected( $action = 'edit' ) {
2621 global $wgSemiprotectedRestrictionLevels;
2622
2623 $restrictions = $this->getRestrictions( $action );
2624 $semi = $wgSemiprotectedRestrictionLevels;
2625 if ( !$restrictions || !$semi ) {
2626 // Not protected, or all protection is full protection
2627 return false;
2628 }
2629
2630 // Remap autoconfirmed to editsemiprotected for BC
2631 foreach ( array_keys( $semi, 'autoconfirmed' ) as $key ) {
2632 $semi[$key] = 'editsemiprotected';
2633 }
2634 foreach ( array_keys( $restrictions, 'autoconfirmed' ) as $key ) {
2635 $restrictions[$key] = 'editsemiprotected';
2636 }
2637
2638 return !array_diff( $restrictions, $semi );
2639 }
2640
2641 /**
2642 * Does the title correspond to a protected article?
2643 *
2644 * @param string $action The action the page is protected from,
2645 * by default checks all actions.
2646 * @return bool
2647 */
2648 public function isProtected( $action = '' ) {
2649 global $wgRestrictionLevels;
2650
2651 $restrictionTypes = $this->getRestrictionTypes();
2652
2653 # Special pages have inherent protection
2654 if ( $this->isSpecialPage() ) {
2655 return true;
2656 }
2657
2658 # Check regular protection levels
2659 foreach ( $restrictionTypes as $type ) {
2660 if ( $action == $type || $action == '' ) {
2661 $r = $this->getRestrictions( $type );
2662 foreach ( $wgRestrictionLevels as $level ) {
2663 if ( in_array( $level, $r ) && $level != '' ) {
2664 return true;
2665 }
2666 }
2667 }
2668 }
2669
2670 return false;
2671 }
2672
2673 /**
2674 * Determines if $user is unable to edit this page because it has been protected
2675 * by $wgNamespaceProtection.
2676 *
2677 * @param User $user User object to check permissions
2678 * @return bool
2679 */
2680 public function isNamespaceProtected( User $user ) {
2681 global $wgNamespaceProtection;
2682
2683 if ( isset( $wgNamespaceProtection[$this->mNamespace] ) ) {
2684 foreach ( (array)$wgNamespaceProtection[$this->mNamespace] as $right ) {
2685 if ( $right != '' && !$user->isAllowed( $right ) ) {
2686 return true;
2687 }
2688 }
2689 }
2690 return false;
2691 }
2692
2693 /**
2694 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
2695 *
2696 * @return bool If the page is subject to cascading restrictions.
2697 */
2698 public function isCascadeProtected() {
2699 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
2700 return ( $sources > 0 );
2701 }
2702
2703 /**
2704 * Determines whether cascading protection sources have already been loaded from
2705 * the database.
2706 *
2707 * @param bool $getPages True to check if the pages are loaded, or false to check
2708 * if the status is loaded.
2709 * @return bool Whether or not the specified information has been loaded
2710 * @since 1.23
2711 */
2712 public function areCascadeProtectionSourcesLoaded( $getPages = true ) {
2713 return $getPages ? $this->mCascadeSources !== null : $this->mHasCascadingRestrictions !== null;
2714 }
2715
2716 /**
2717 * Cascading protection: Get the source of any cascading restrictions on this page.
2718 *
2719 * @param bool $getPages Whether or not to retrieve the actual pages
2720 * that the restrictions have come from and the actual restrictions
2721 * themselves.
2722 * @return array Two elements: First is an array of Title objects of the
2723 * pages from which cascading restrictions have come, false for
2724 * none, or true if such restrictions exist but $getPages was not
2725 * set. Second is an array like that returned by
2726 * Title::getAllRestrictions(), or an empty array if $getPages is
2727 * false.
2728 */
2729 public function getCascadeProtectionSources( $getPages = true ) {
2730 global $wgContLang;
2731 $pagerestrictions = array();
2732
2733 if ( $this->mCascadeSources !== null && $getPages ) {
2734 return array( $this->mCascadeSources, $this->mCascadingRestrictions );
2735 } elseif ( $this->mHasCascadingRestrictions !== null && !$getPages ) {
2736 return array( $this->mHasCascadingRestrictions, $pagerestrictions );
2737 }
2738
2739 wfProfileIn( __METHOD__ );
2740
2741 $dbr = wfGetDB( DB_SLAVE );
2742
2743 if ( $this->getNamespace() == NS_FILE ) {
2744 $tables = array( 'imagelinks', 'page_restrictions' );
2745 $where_clauses = array(
2746 'il_to' => $this->getDBkey(),
2747 'il_from=pr_page',
2748 'pr_cascade' => 1
2749 );
2750 } else {
2751 $tables = array( 'templatelinks', 'page_restrictions' );
2752 $where_clauses = array(
2753 'tl_namespace' => $this->getNamespace(),
2754 'tl_title' => $this->getDBkey(),
2755 'tl_from=pr_page',
2756 'pr_cascade' => 1
2757 );
2758 }
2759
2760 if ( $getPages ) {
2761 $cols = array( 'pr_page', 'page_namespace', 'page_title',
2762 'pr_expiry', 'pr_type', 'pr_level' );
2763 $where_clauses[] = 'page_id=pr_page';
2764 $tables[] = 'page';
2765 } else {
2766 $cols = array( 'pr_expiry' );
2767 }
2768
2769 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__ );
2770
2771 $sources = $getPages ? array() : false;
2772 $now = wfTimestampNow();
2773 $purgeExpired = false;
2774
2775 foreach ( $res as $row ) {
2776 $expiry = $wgContLang->formatExpiry( $row->pr_expiry, TS_MW );
2777 if ( $expiry > $now ) {
2778 if ( $getPages ) {
2779 $page_id = $row->pr_page;
2780 $page_ns = $row->page_namespace;
2781 $page_title = $row->page_title;
2782 $sources[$page_id] = Title::makeTitle( $page_ns, $page_title );
2783 # Add groups needed for each restriction type if its not already there
2784 # Make sure this restriction type still exists
2785
2786 if ( !isset( $pagerestrictions[$row->pr_type] ) ) {
2787 $pagerestrictions[$row->pr_type] = array();
2788 }
2789
2790 if (
2791 isset( $pagerestrictions[$row->pr_type] )
2792 && !in_array( $row->pr_level, $pagerestrictions[$row->pr_type] )
2793 ) {
2794 $pagerestrictions[$row->pr_type][] = $row->pr_level;
2795 }
2796 } else {
2797 $sources = true;
2798 }
2799 } else {
2800 // Trigger lazy purge of expired restrictions from the db
2801 $purgeExpired = true;
2802 }
2803 }
2804 if ( $purgeExpired ) {
2805 Title::purgeExpiredRestrictions();
2806 }
2807
2808 if ( $getPages ) {
2809 $this->mCascadeSources = $sources;
2810 $this->mCascadingRestrictions = $pagerestrictions;
2811 } else {
2812 $this->mHasCascadingRestrictions = $sources;
2813 }
2814
2815 wfProfileOut( __METHOD__ );
2816 return array( $sources, $pagerestrictions );
2817 }
2818
2819 /**
2820 * Accessor for mRestrictionsLoaded
2821 *
2822 * @return bool Whether or not the page's restrictions have already been
2823 * loaded from the database
2824 * @since 1.23
2825 */
2826 public function areRestrictionsLoaded() {
2827 return $this->mRestrictionsLoaded;
2828 }
2829
2830 /**
2831 * Accessor/initialisation for mRestrictions
2832 *
2833 * @param string $action Action that permission needs to be checked for
2834 * @return array Restriction levels needed to take the action. All levels are
2835 * required. Note that restriction levels are normally user rights, but 'sysop'
2836 * and 'autoconfirmed' are also allowed for backwards compatibility. These should
2837 * be mapped to 'editprotected' and 'editsemiprotected' respectively.
2838 */
2839 public function getRestrictions( $action ) {
2840 if ( !$this->mRestrictionsLoaded ) {
2841 $this->loadRestrictions();
2842 }
2843 return isset( $this->mRestrictions[$action] )
2844 ? $this->mRestrictions[$action]
2845 : array();
2846 }
2847
2848 /**
2849 * Accessor/initialisation for mRestrictions
2850 *
2851 * @return array Keys are actions, values are arrays as returned by
2852 * Title::getRestrictions()
2853 * @since 1.23
2854 */
2855 public function getAllRestrictions() {
2856 if ( !$this->mRestrictionsLoaded ) {
2857 $this->loadRestrictions();
2858 }
2859 return $this->mRestrictions;
2860 }
2861
2862 /**
2863 * Get the expiry time for the restriction against a given action
2864 *
2865 * @param string $action
2866 * @return string|bool 14-char timestamp, or 'infinity' if the page is protected forever
2867 * or not protected at all, or false if the action is not recognised.
2868 */
2869 public function getRestrictionExpiry( $action ) {
2870 if ( !$this->mRestrictionsLoaded ) {
2871 $this->loadRestrictions();
2872 }
2873 return isset( $this->mRestrictionsExpiry[$action] ) ? $this->mRestrictionsExpiry[$action] : false;
2874 }
2875
2876 /**
2877 * Returns cascading restrictions for the current article
2878 *
2879 * @return bool
2880 */
2881 function areRestrictionsCascading() {
2882 if ( !$this->mRestrictionsLoaded ) {
2883 $this->loadRestrictions();
2884 }
2885
2886 return $this->mCascadeRestriction;
2887 }
2888
2889 /**
2890 * Loads a string into mRestrictions array
2891 *
2892 * @param ResultWrapper $res Resource restrictions as an SQL result.
2893 * @param string $oldFashionedRestrictions Comma-separated list of page
2894 * restrictions from page table (pre 1.10)
2895 */
2896 private function loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions = null ) {
2897 $rows = array();
2898
2899 foreach ( $res as $row ) {
2900 $rows[] = $row;
2901 }
2902
2903 $this->loadRestrictionsFromRows( $rows, $oldFashionedRestrictions );
2904 }
2905
2906 /**
2907 * Compiles list of active page restrictions from both page table (pre 1.10)
2908 * and page_restrictions table for this existing page.
2909 * Public for usage by LiquidThreads.
2910 *
2911 * @param array $rows Array of db result objects
2912 * @param string $oldFashionedRestrictions Comma-separated list of page
2913 * restrictions from page table (pre 1.10)
2914 */
2915 public function loadRestrictionsFromRows( $rows, $oldFashionedRestrictions = null ) {
2916 global $wgContLang;
2917 $dbr = wfGetDB( DB_SLAVE );
2918
2919 $restrictionTypes = $this->getRestrictionTypes();
2920
2921 foreach ( $restrictionTypes as $type ) {
2922 $this->mRestrictions[$type] = array();
2923 $this->mRestrictionsExpiry[$type] = $wgContLang->formatExpiry( '', TS_MW );
2924 }
2925
2926 $this->mCascadeRestriction = false;
2927
2928 # Backwards-compatibility: also load the restrictions from the page record (old format).
2929
2930 if ( $oldFashionedRestrictions === null ) {
2931 $oldFashionedRestrictions = $dbr->selectField( 'page', 'page_restrictions',
2932 array( 'page_id' => $this->getArticleID() ), __METHOD__ );
2933 }
2934
2935 if ( $oldFashionedRestrictions != '' ) {
2936
2937 foreach ( explode( ':', trim( $oldFashionedRestrictions ) ) as $restrict ) {
2938 $temp = explode( '=', trim( $restrict ) );
2939 if ( count( $temp ) == 1 ) {
2940 // old old format should be treated as edit/move restriction
2941 $this->mRestrictions['edit'] = explode( ',', trim( $temp[0] ) );
2942 $this->mRestrictions['move'] = explode( ',', trim( $temp[0] ) );
2943 } else {
2944 $restriction = trim( $temp[1] );
2945 if ( $restriction != '' ) { //some old entries are empty
2946 $this->mRestrictions[$temp[0]] = explode( ',', $restriction );
2947 }
2948 }
2949 }
2950
2951 $this->mOldRestrictions = true;
2952
2953 }
2954
2955 if ( count( $rows ) ) {
2956 # Current system - load second to make them override.
2957 $now = wfTimestampNow();
2958 $purgeExpired = false;
2959
2960 # Cycle through all the restrictions.
2961 foreach ( $rows as $row ) {
2962
2963 // Don't take care of restrictions types that aren't allowed
2964 if ( !in_array( $row->pr_type, $restrictionTypes ) ) {
2965 continue;
2966 }
2967
2968 // This code should be refactored, now that it's being used more generally,
2969 // But I don't really see any harm in leaving it in Block for now -werdna
2970 $expiry = $wgContLang->formatExpiry( $row->pr_expiry, TS_MW );
2971
2972 // Only apply the restrictions if they haven't expired!
2973 if ( !$expiry || $expiry > $now ) {
2974 $this->mRestrictionsExpiry[$row->pr_type] = $expiry;
2975 $this->mRestrictions[$row->pr_type] = explode( ',', trim( $row->pr_level ) );
2976
2977 $this->mCascadeRestriction |= $row->pr_cascade;
2978 } else {
2979 // Trigger a lazy purge of expired restrictions
2980 $purgeExpired = true;
2981 }
2982 }
2983
2984 if ( $purgeExpired ) {
2985 Title::purgeExpiredRestrictions();
2986 }
2987 }
2988
2989 $this->mRestrictionsLoaded = true;
2990 }
2991
2992 /**
2993 * Load restrictions from the page_restrictions table
2994 *
2995 * @param string $oldFashionedRestrictions Comma-separated list of page
2996 * restrictions from page table (pre 1.10)
2997 */
2998 public function loadRestrictions( $oldFashionedRestrictions = null ) {
2999 global $wgContLang;
3000 if ( !$this->mRestrictionsLoaded ) {
3001 if ( $this->exists() ) {
3002 $dbr = wfGetDB( DB_SLAVE );
3003
3004 $res = $dbr->select(
3005 'page_restrictions',
3006 array( 'pr_type', 'pr_expiry', 'pr_level', 'pr_cascade' ),
3007 array( 'pr_page' => $this->getArticleID() ),
3008 __METHOD__
3009 );
3010
3011 $this->loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions );
3012 } else {
3013 $title_protection = $this->getTitleProtection();
3014
3015 if ( $title_protection ) {
3016 $now = wfTimestampNow();
3017 $expiry = $wgContLang->formatExpiry( $title_protection['expiry'], TS_MW );
3018
3019 if ( !$expiry || $expiry > $now ) {
3020 // Apply the restrictions
3021 $this->mRestrictionsExpiry['create'] = $expiry;
3022 $this->mRestrictions['create'] = explode( ',', trim( $title_protection['permission'] ) );
3023 } else { // Get rid of the old restrictions
3024 Title::purgeExpiredRestrictions();
3025 $this->mTitleProtection = false;
3026 }
3027 } else {
3028 $this->mRestrictionsExpiry['create'] = $wgContLang->formatExpiry( '', TS_MW );
3029 }
3030 $this->mRestrictionsLoaded = true;
3031 }
3032 }
3033 }
3034
3035 /**
3036 * Flush the protection cache in this object and force reload from the database.
3037 * This is used when updating protection from WikiPage::doUpdateRestrictions().
3038 */
3039 public function flushRestrictions() {
3040 $this->mRestrictionsLoaded = false;
3041 $this->mTitleProtection = null;
3042 }
3043
3044 /**
3045 * Purge expired restrictions from the page_restrictions table
3046 */
3047 static function purgeExpiredRestrictions() {
3048 if ( wfReadOnly() ) {
3049 return;
3050 }
3051
3052 $method = __METHOD__;
3053 $dbw = wfGetDB( DB_MASTER );
3054 $dbw->onTransactionIdle( function () use ( $dbw, $method ) {
3055 $dbw->delete(
3056 'page_restrictions',
3057 array( 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
3058 $method
3059 );
3060 $dbw->delete(
3061 'protected_titles',
3062 array( 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
3063 $method
3064 );
3065 } );
3066 }
3067
3068 /**
3069 * Does this have subpages? (Warning, usually requires an extra DB query.)
3070 *
3071 * @return bool
3072 */
3073 public function hasSubpages() {
3074 if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
3075 # Duh
3076 return false;
3077 }
3078
3079 # We dynamically add a member variable for the purpose of this method
3080 # alone to cache the result. There's no point in having it hanging
3081 # around uninitialized in every Title object; therefore we only add it
3082 # if needed and don't declare it statically.
3083 if ( $this->mHasSubpages === null ) {
3084 $this->mHasSubpages = false;
3085 $subpages = $this->getSubpages( 1 );
3086 if ( $subpages instanceof TitleArray ) {
3087 $this->mHasSubpages = (bool)$subpages->count();
3088 }
3089 }
3090
3091 return $this->mHasSubpages;
3092 }
3093
3094 /**
3095 * Get all subpages of this page.
3096 *
3097 * @param int $limit Maximum number of subpages to fetch; -1 for no limit
3098 * @return TitleArray|array TitleArray, or empty array if this page's namespace
3099 * doesn't allow subpages
3100 */
3101 public function getSubpages( $limit = -1 ) {
3102 if ( !MWNamespace::hasSubpages( $this->getNamespace() ) ) {
3103 return array();
3104 }
3105
3106 $dbr = wfGetDB( DB_SLAVE );
3107 $conds['page_namespace'] = $this->getNamespace();
3108 $conds[] = 'page_title ' . $dbr->buildLike( $this->getDBkey() . '/', $dbr->anyString() );
3109 $options = array();
3110 if ( $limit > -1 ) {
3111 $options['LIMIT'] = $limit;
3112 }
3113 $this->mSubpages = TitleArray::newFromResult(
3114 $dbr->select( 'page',
3115 array( 'page_id', 'page_namespace', 'page_title', 'page_is_redirect' ),
3116 $conds,
3117 __METHOD__,
3118 $options
3119 )
3120 );
3121 return $this->mSubpages;
3122 }
3123
3124 /**
3125 * Is there a version of this page in the deletion archive?
3126 *
3127 * @return int The number of archived revisions
3128 */
3129 public function isDeleted() {
3130 if ( $this->getNamespace() < 0 ) {
3131 $n = 0;
3132 } else {
3133 $dbr = wfGetDB( DB_SLAVE );
3134
3135 $n = $dbr->selectField( 'archive', 'COUNT(*)',
3136 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
3137 __METHOD__
3138 );
3139 if ( $this->getNamespace() == NS_FILE ) {
3140 $n += $dbr->selectField( 'filearchive', 'COUNT(*)',
3141 array( 'fa_name' => $this->getDBkey() ),
3142 __METHOD__
3143 );
3144 }
3145 }
3146 return (int)$n;
3147 }
3148
3149 /**
3150 * Is there a version of this page in the deletion archive?
3151 *
3152 * @return bool
3153 */
3154 public function isDeletedQuick() {
3155 if ( $this->getNamespace() < 0 ) {
3156 return false;
3157 }
3158 $dbr = wfGetDB( DB_SLAVE );
3159 $deleted = (bool)$dbr->selectField( 'archive', '1',
3160 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
3161 __METHOD__
3162 );
3163 if ( !$deleted && $this->getNamespace() == NS_FILE ) {
3164 $deleted = (bool)$dbr->selectField( 'filearchive', '1',
3165 array( 'fa_name' => $this->getDBkey() ),
3166 __METHOD__
3167 );
3168 }
3169 return $deleted;
3170 }
3171
3172 /**
3173 * Get the article ID for this Title from the link cache,
3174 * adding it if necessary
3175 *
3176 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select
3177 * for update
3178 * @return int The ID
3179 */
3180 public function getArticleID( $flags = 0 ) {
3181 if ( $this->getNamespace() < 0 ) {
3182 $this->mArticleID = 0;
3183 return $this->mArticleID;
3184 }
3185 $linkCache = LinkCache::singleton();
3186 if ( $flags & self::GAID_FOR_UPDATE ) {
3187 $oldUpdate = $linkCache->forUpdate( true );
3188 $linkCache->clearLink( $this );
3189 $this->mArticleID = $linkCache->addLinkObj( $this );
3190 $linkCache->forUpdate( $oldUpdate );
3191 } else {
3192 if ( -1 == $this->mArticleID ) {
3193 $this->mArticleID = $linkCache->addLinkObj( $this );
3194 }
3195 }
3196 return $this->mArticleID;
3197 }
3198
3199 /**
3200 * Is this an article that is a redirect page?
3201 * Uses link cache, adding it if necessary
3202 *
3203 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3204 * @return bool
3205 */
3206 public function isRedirect( $flags = 0 ) {
3207 if ( !is_null( $this->mRedirect ) ) {
3208 return $this->mRedirect;
3209 }
3210 # Calling getArticleID() loads the field from cache as needed
3211 if ( !$this->getArticleID( $flags ) ) {
3212 $this->mRedirect = false;
3213 return $this->mRedirect;
3214 }
3215
3216 $linkCache = LinkCache::singleton();
3217 $cached = $linkCache->getGoodLinkFieldObj( $this, 'redirect' );
3218 if ( $cached === null ) {
3219 # Trust LinkCache's state over our own
3220 # LinkCache is telling us that the page doesn't exist, despite there being cached
3221 # data relating to an existing page in $this->mArticleID. Updaters should clear
3222 # LinkCache as appropriate, or use $flags = Title::GAID_FOR_UPDATE. If that flag is
3223 # set, then LinkCache will definitely be up to date here, since getArticleID() forces
3224 # LinkCache to refresh its data from the master.
3225 $this->mRedirect = false;
3226 return $this->mRedirect;
3227 }
3228
3229 $this->mRedirect = (bool)$cached;
3230
3231 return $this->mRedirect;
3232 }
3233
3234 /**
3235 * What is the length of this page?
3236 * Uses link cache, adding it if necessary
3237 *
3238 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3239 * @return int
3240 */
3241 public function getLength( $flags = 0 ) {
3242 if ( $this->mLength != -1 ) {
3243 return $this->mLength;
3244 }
3245 # Calling getArticleID() loads the field from cache as needed
3246 if ( !$this->getArticleID( $flags ) ) {
3247 $this->mLength = 0;
3248 return $this->mLength;
3249 }
3250 $linkCache = LinkCache::singleton();
3251 $cached = $linkCache->getGoodLinkFieldObj( $this, 'length' );
3252 if ( $cached === null ) {
3253 # Trust LinkCache's state over our own, as for isRedirect()
3254 $this->mLength = 0;
3255 return $this->mLength;
3256 }
3257
3258 $this->mLength = intval( $cached );
3259
3260 return $this->mLength;
3261 }
3262
3263 /**
3264 * What is the page_latest field for this page?
3265 *
3266 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3267 * @return int Int or 0 if the page doesn't exist
3268 */
3269 public function getLatestRevID( $flags = 0 ) {
3270 if ( !( $flags & Title::GAID_FOR_UPDATE ) && $this->mLatestID !== false ) {
3271 return intval( $this->mLatestID );
3272 }
3273 # Calling getArticleID() loads the field from cache as needed
3274 if ( !$this->getArticleID( $flags ) ) {
3275 $this->mLatestID = 0;
3276 return $this->mLatestID;
3277 }
3278 $linkCache = LinkCache::singleton();
3279 $linkCache->addLinkObj( $this );
3280 $cached = $linkCache->getGoodLinkFieldObj( $this, 'revision' );
3281 if ( $cached === null ) {
3282 # Trust LinkCache's state over our own, as for isRedirect()
3283 $this->mLatestID = 0;
3284 return $this->mLatestID;
3285 }
3286
3287 $this->mLatestID = intval( $cached );
3288
3289 return $this->mLatestID;
3290 }
3291
3292 /**
3293 * This clears some fields in this object, and clears any associated
3294 * keys in the "bad links" section of the link cache.
3295 *
3296 * - This is called from WikiPage::doEdit() and WikiPage::insertOn() to allow
3297 * loading of the new page_id. It's also called from
3298 * WikiPage::doDeleteArticleReal()
3299 *
3300 * @param int $newid The new Article ID
3301 */
3302 public function resetArticleID( $newid ) {
3303 $linkCache = LinkCache::singleton();
3304 $linkCache->clearLink( $this );
3305
3306 if ( $newid === false ) {
3307 $this->mArticleID = -1;
3308 } else {
3309 $this->mArticleID = intval( $newid );
3310 }
3311 $this->mRestrictionsLoaded = false;
3312 $this->mRestrictions = array();
3313 $this->mRedirect = null;
3314 $this->mLength = -1;
3315 $this->mLatestID = false;
3316 $this->mContentModel = false;
3317 $this->mEstimateRevisions = null;
3318 $this->mPageLanguage = false;
3319 $this->mDbPageLanguage = null;
3320 $this->mIsBigDeletion = null;
3321 }
3322
3323 /**
3324 * Capitalize a text string for a title if it belongs to a namespace that capitalizes
3325 *
3326 * @param string $text Containing title to capitalize
3327 * @param int $ns Namespace index, defaults to NS_MAIN
3328 * @return string Containing capitalized title
3329 */
3330 public static function capitalize( $text, $ns = NS_MAIN ) {
3331 global $wgContLang;
3332
3333 if ( MWNamespace::isCapitalized( $ns ) ) {
3334 return $wgContLang->ucfirst( $text );
3335 } else {
3336 return $text;
3337 }
3338 }
3339
3340 /**
3341 * Secure and split - main initialisation function for this object
3342 *
3343 * Assumes that mDbkeyform has been set, and is urldecoded
3344 * and uses underscores, but not otherwise munged. This function
3345 * removes illegal characters, splits off the interwiki and
3346 * namespace prefixes, sets the other forms, and canonicalizes
3347 * everything.
3348 *
3349 * @return bool True on success
3350 */
3351 private function secureAndSplit() {
3352 # Initialisation
3353 $this->mInterwiki = '';
3354 $this->mFragment = '';
3355 $this->mNamespace = $this->mDefaultNamespace; # Usually NS_MAIN
3356
3357 $dbkey = $this->mDbkeyform;
3358
3359 try {
3360 // @note: splitTitleString() is a temporary hack to allow MediaWikiTitleCodec to share
3361 // the parsing code with Title, while avoiding massive refactoring.
3362 // @todo: get rid of secureAndSplit, refactor parsing code.
3363 $titleParser = self::getTitleParser();
3364 $parts = $titleParser->splitTitleString( $dbkey, $this->getDefaultNamespace() );
3365 } catch ( MalformedTitleException $ex ) {
3366 return false;
3367 }
3368
3369 # Fill fields
3370 $this->setFragment( '#' . $parts['fragment'] );
3371 $this->mInterwiki = $parts['interwiki'];
3372 $this->mLocalInterwiki = $parts['local_interwiki'];
3373 $this->mNamespace = $parts['namespace'];
3374 $this->mUserCaseDBKey = $parts['user_case_dbkey'];
3375
3376 $this->mDbkeyform = $parts['dbkey'];
3377 $this->mUrlform = wfUrlencode( $this->mDbkeyform );
3378 $this->mTextform = str_replace( '_', ' ', $this->mDbkeyform );
3379
3380 # We already know that some pages won't be in the database!
3381 if ( $this->isExternal() || $this->mNamespace == NS_SPECIAL ) {
3382 $this->mArticleID = 0;
3383 }
3384
3385 return true;
3386 }
3387
3388 /**
3389 * Get an array of Title objects linking to this Title
3390 * Also stores the IDs in the link cache.
3391 *
3392 * WARNING: do not use this function on arbitrary user-supplied titles!
3393 * On heavily-used templates it will max out the memory.
3394 *
3395 * @param array $options May be FOR UPDATE
3396 * @param string $table Table name
3397 * @param string $prefix Fields prefix
3398 * @return Title[] Array of Title objects linking here
3399 */
3400 public function getLinksTo( $options = array(), $table = 'pagelinks', $prefix = 'pl' ) {
3401 if ( count( $options ) > 0 ) {
3402 $db = wfGetDB( DB_MASTER );
3403 } else {
3404 $db = wfGetDB( DB_SLAVE );
3405 }
3406
3407 $res = $db->select(
3408 array( 'page', $table ),
3409 self::getSelectFields(),
3410 array(
3411 "{$prefix}_from=page_id",
3412 "{$prefix}_namespace" => $this->getNamespace(),
3413 "{$prefix}_title" => $this->getDBkey() ),
3414 __METHOD__,
3415 $options
3416 );
3417
3418 $retVal = array();
3419 if ( $res->numRows() ) {
3420 $linkCache = LinkCache::singleton();
3421 foreach ( $res as $row ) {
3422 $titleObj = Title::makeTitle( $row->page_namespace, $row->page_title );
3423 if ( $titleObj ) {
3424 $linkCache->addGoodLinkObjFromRow( $titleObj, $row );
3425 $retVal[] = $titleObj;
3426 }
3427 }
3428 }
3429 return $retVal;
3430 }
3431
3432 /**
3433 * Get an array of Title objects using this Title as a template
3434 * Also stores the IDs in the link cache.
3435 *
3436 * WARNING: do not use this function on arbitrary user-supplied titles!
3437 * On heavily-used templates it will max out the memory.
3438 *
3439 * @param array $options May be FOR UPDATE
3440 * @return Title[] Array of Title the Title objects linking here
3441 */
3442 public function getTemplateLinksTo( $options = array() ) {
3443 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
3444 }
3445
3446 /**
3447 * Get an array of Title objects linked from this Title
3448 * Also stores the IDs in the link cache.
3449 *
3450 * WARNING: do not use this function on arbitrary user-supplied titles!
3451 * On heavily-used templates it will max out the memory.
3452 *
3453 * @param array $options May be FOR UPDATE
3454 * @param string $table Table name
3455 * @param string $prefix Fields prefix
3456 * @return array Array of Title objects linking here
3457 */
3458 public function getLinksFrom( $options = array(), $table = 'pagelinks', $prefix = 'pl' ) {
3459 global $wgContentHandlerUseDB;
3460
3461 $id = $this->getArticleID();
3462
3463 # If the page doesn't exist; there can't be any link from this page
3464 if ( !$id ) {
3465 return array();
3466 }
3467
3468 if ( count( $options ) > 0 ) {
3469 $db = wfGetDB( DB_MASTER );
3470 } else {
3471 $db = wfGetDB( DB_SLAVE );
3472 }
3473
3474 $namespaceFiled = "{$prefix}_namespace";
3475 $titleField = "{$prefix}_title";
3476
3477 $fields = array(
3478 $namespaceFiled,
3479 $titleField,
3480 'page_id',
3481 'page_len',
3482 'page_is_redirect',
3483 'page_latest'
3484 );
3485
3486 if ( $wgContentHandlerUseDB ) {
3487 $fields[] = 'page_content_model';
3488 }
3489
3490 $res = $db->select(
3491 array( $table, 'page' ),
3492 $fields,
3493 array( "{$prefix}_from" => $id ),
3494 __METHOD__,
3495 $options,
3496 array( 'page' => array(
3497 'LEFT JOIN',
3498 array( "page_namespace=$namespaceFiled", "page_title=$titleField" )
3499 ) )
3500 );
3501
3502 $retVal = array();
3503 if ( $res->numRows() ) {
3504 $linkCache = LinkCache::singleton();
3505 foreach ( $res as $row ) {
3506 $titleObj = Title::makeTitle( $row->$namespaceFiled, $row->$titleField );
3507 if ( $titleObj ) {
3508 if ( $row->page_id ) {
3509 $linkCache->addGoodLinkObjFromRow( $titleObj, $row );
3510 } else {
3511 $linkCache->addBadLinkObj( $titleObj );
3512 }
3513 $retVal[] = $titleObj;
3514 }
3515 }
3516 }
3517 return $retVal;
3518 }
3519
3520 /**
3521 * Get an array of Title objects used on this Title as a template
3522 * Also stores the IDs in the link cache.
3523 *
3524 * WARNING: do not use this function on arbitrary user-supplied titles!
3525 * On heavily-used templates it will max out the memory.
3526 *
3527 * @param array $options May be FOR UPDATE
3528 * @return Title[] Array of Title the Title objects used here
3529 */
3530 public function getTemplateLinksFrom( $options = array() ) {
3531 return $this->getLinksFrom( $options, 'templatelinks', 'tl' );
3532 }
3533
3534 /**
3535 * Get an array of Title objects referring to non-existent articles linked
3536 * from this page.
3537 *
3538 * @todo check if needed (used only in SpecialBrokenRedirects.php, and
3539 * should use redirect table in this case).
3540 * @return Title[] Array of Title the Title objects
3541 */
3542 public function getBrokenLinksFrom() {
3543 if ( $this->getArticleID() == 0 ) {
3544 # All links from article ID 0 are false positives
3545 return array();
3546 }
3547
3548 $dbr = wfGetDB( DB_SLAVE );
3549 $res = $dbr->select(
3550 array( 'page', 'pagelinks' ),
3551 array( 'pl_namespace', 'pl_title' ),
3552 array(
3553 'pl_from' => $this->getArticleID(),
3554 'page_namespace IS NULL'
3555 ),
3556 __METHOD__, array(),
3557 array(
3558 'page' => array(
3559 'LEFT JOIN',
3560 array( 'pl_namespace=page_namespace', 'pl_title=page_title' )
3561 )
3562 )
3563 );
3564
3565 $retVal = array();
3566 foreach ( $res as $row ) {
3567 $retVal[] = Title::makeTitle( $row->pl_namespace, $row->pl_title );
3568 }
3569 return $retVal;
3570 }
3571
3572 /**
3573 * Get a list of URLs to purge from the Squid cache when this
3574 * page changes
3575 *
3576 * @return string[] Array of String the URLs
3577 */
3578 public function getSquidURLs() {
3579 $urls = array(
3580 $this->getInternalURL(),
3581 $this->getInternalURL( 'action=history' )
3582 );
3583
3584 $pageLang = $this->getPageLanguage();
3585 if ( $pageLang->hasVariants() ) {
3586 $variants = $pageLang->getVariants();
3587 foreach ( $variants as $vCode ) {
3588 $urls[] = $this->getInternalURL( '', $vCode );
3589 }
3590 }
3591
3592 // If we are looking at a css/js user subpage, purge the action=raw.
3593 if ( $this->isJsSubpage() ) {
3594 $urls[] = $this->getInternalUrl( 'action=raw&ctype=text/javascript' );
3595 } elseif ( $this->isCssSubpage() ) {
3596 $urls[] = $this->getInternalUrl( 'action=raw&ctype=text/css' );
3597 }
3598
3599 Hooks::run( 'TitleSquidURLs', array( $this, &$urls ) );
3600 return $urls;
3601 }
3602
3603 /**
3604 * Purge all applicable Squid URLs
3605 */
3606 public function purgeSquid() {
3607 global $wgUseSquid;
3608 if ( $wgUseSquid ) {
3609 $urls = $this->getSquidURLs();
3610 $u = new SquidUpdate( $urls );
3611 $u->doUpdate();
3612 }
3613 }
3614
3615 /**
3616 * Move this page without authentication
3617 *
3618 * @deprecated since 1.25 use MovePage class instead
3619 * @param Title $nt The new page Title
3620 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
3621 */
3622 public function moveNoAuth( &$nt ) {
3623 wfDeprecated( __METHOD__, '1.25' );
3624 return $this->moveTo( $nt, false );
3625 }
3626
3627 /**
3628 * Check whether a given move operation would be valid.
3629 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
3630 *
3631 * @deprecated since 1.25, use MovePage's methods instead
3632 * @param Title $nt The new title
3633 * @param bool $auth Ignored
3634 * @param string $reason Is the log summary of the move, used for spam checking
3635 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
3636 */
3637 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
3638 global $wgUser;
3639
3640 if ( !( $nt instanceof Title ) ) {
3641 // Normally we'd add this to $errors, but we'll get
3642 // lots of syntax errors if $nt is not an object
3643 return array( array( 'badtitletext' ) );
3644 }
3645
3646 $mp = new MovePage( $this, $nt );
3647 $errors = wfMergeErrorArrays(
3648 $mp->isValidMove()->getErrorsArray(),
3649 $mp->checkPermissions( $wgUser, $reason )->getErrorsArray()
3650 );
3651
3652 return $errors ? : true;
3653 }
3654
3655 /**
3656 * Check if the requested move target is a valid file move target
3657 * @todo move this to MovePage
3658 * @param Title $nt Target title
3659 * @return array List of errors
3660 */
3661 protected function validateFileMoveOperation( $nt ) {
3662 global $wgUser;
3663
3664 $errors = array();
3665
3666 $destFile = wfLocalFile( $nt );
3667 if ( !$wgUser->isAllowed( 'reupload-shared' ) && !$destFile->exists() && wfFindFile( $nt ) ) {
3668 $errors[] = array( 'file-exists-sharedrepo' );
3669 }
3670
3671 return $errors;
3672 }
3673
3674 /**
3675 * Move a title to a new location
3676 *
3677 * @deprecated since 1.25, use the MovePage class instead
3678 * @param Title $nt The new title
3679 * @param bool $auth Indicates whether $wgUser's permissions
3680 * should be checked
3681 * @param string $reason The reason for the move
3682 * @param bool $createRedirect Whether to create a redirect from the old title to the new title.
3683 * Ignored if the user doesn't have the suppressredirect right.
3684 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
3685 */
3686 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true ) {
3687 global $wgUser;
3688 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
3689 if ( is_array( $err ) ) {
3690 // Auto-block user's IP if the account was "hard" blocked
3691 $wgUser->spreadAnyEditBlock();
3692 return $err;
3693 }
3694 // Check suppressredirect permission
3695 if ( $auth && !$wgUser->isAllowed( 'suppressredirect' ) ) {
3696 $createRedirect = true;
3697 }
3698
3699 $mp = new MovePage( $this, $nt );
3700 $status = $mp->move( $wgUser, $reason, $createRedirect );
3701 if ( $status->isOK() ) {
3702 return true;
3703 } else {
3704 return $status->getErrorsArray();
3705 }
3706 }
3707
3708 /**
3709 * Move this page's subpages to be subpages of $nt
3710 *
3711 * @param Title $nt Move target
3712 * @param bool $auth Whether $wgUser's permissions should be checked
3713 * @param string $reason The reason for the move
3714 * @param bool $createRedirect Whether to create redirects from the old subpages to
3715 * the new ones Ignored if the user doesn't have the 'suppressredirect' right
3716 * @return array Array with old page titles as keys, and strings (new page titles) or
3717 * arrays (errors) as values, or an error array with numeric indices if no pages
3718 * were moved
3719 */
3720 public function moveSubpages( $nt, $auth = true, $reason = '', $createRedirect = true ) {
3721 global $wgMaximumMovedPages;
3722 // Check permissions
3723 if ( !$this->userCan( 'move-subpages' ) ) {
3724 return array( 'cant-move-subpages' );
3725 }
3726 // Do the source and target namespaces support subpages?
3727 if ( !MWNamespace::hasSubpages( $this->getNamespace() ) ) {
3728 return array( 'namespace-nosubpages',
3729 MWNamespace::getCanonicalName( $this->getNamespace() ) );
3730 }
3731 if ( !MWNamespace::hasSubpages( $nt->getNamespace() ) ) {
3732 return array( 'namespace-nosubpages',
3733 MWNamespace::getCanonicalName( $nt->getNamespace() ) );
3734 }
3735
3736 $subpages = $this->getSubpages( $wgMaximumMovedPages + 1 );
3737 $retval = array();
3738 $count = 0;
3739 foreach ( $subpages as $oldSubpage ) {
3740 $count++;
3741 if ( $count > $wgMaximumMovedPages ) {
3742 $retval[$oldSubpage->getPrefixedText()] =
3743 array( 'movepage-max-pages',
3744 $wgMaximumMovedPages );
3745 break;
3746 }
3747
3748 // We don't know whether this function was called before
3749 // or after moving the root page, so check both
3750 // $this and $nt
3751 if ( $oldSubpage->getArticleID() == $this->getArticleID()
3752 || $oldSubpage->getArticleID() == $nt->getArticleID()
3753 ) {
3754 // When moving a page to a subpage of itself,
3755 // don't move it twice
3756 continue;
3757 }
3758 $newPageName = preg_replace(
3759 '#^' . preg_quote( $this->getDBkey(), '#' ) . '#',
3760 StringUtils::escapeRegexReplacement( $nt->getDBkey() ), # bug 21234
3761 $oldSubpage->getDBkey() );
3762 if ( $oldSubpage->isTalkPage() ) {
3763 $newNs = $nt->getTalkPage()->getNamespace();
3764 } else {
3765 $newNs = $nt->getSubjectPage()->getNamespace();
3766 }
3767 # Bug 14385: we need makeTitleSafe because the new page names may
3768 # be longer than 255 characters.
3769 $newSubpage = Title::makeTitleSafe( $newNs, $newPageName );
3770
3771 $success = $oldSubpage->moveTo( $newSubpage, $auth, $reason, $createRedirect );
3772 if ( $success === true ) {
3773 $retval[$oldSubpage->getPrefixedText()] = $newSubpage->getPrefixedText();
3774 } else {
3775 $retval[$oldSubpage->getPrefixedText()] = $success;
3776 }
3777 }
3778 return $retval;
3779 }
3780
3781 /**
3782 * Checks if this page is just a one-rev redirect.
3783 * Adds lock, so don't use just for light purposes.
3784 *
3785 * @return bool
3786 */
3787 public function isSingleRevRedirect() {
3788 global $wgContentHandlerUseDB;
3789
3790 $dbw = wfGetDB( DB_MASTER );
3791
3792 # Is it a redirect?
3793 $fields = array( 'page_is_redirect', 'page_latest', 'page_id' );
3794 if ( $wgContentHandlerUseDB ) {
3795 $fields[] = 'page_content_model';
3796 }
3797
3798 $row = $dbw->selectRow( 'page',
3799 $fields,
3800 $this->pageCond(),
3801 __METHOD__,
3802 array( 'FOR UPDATE' )
3803 );
3804 # Cache some fields we may want
3805 $this->mArticleID = $row ? intval( $row->page_id ) : 0;
3806 $this->mRedirect = $row ? (bool)$row->page_is_redirect : false;
3807 $this->mLatestID = $row ? intval( $row->page_latest ) : false;
3808 $this->mContentModel = $row && isset( $row->page_content_model )
3809 ? strval( $row->page_content_model )
3810 : false;
3811
3812 if ( !$this->mRedirect ) {
3813 return false;
3814 }
3815 # Does the article have a history?
3816 $row = $dbw->selectField( array( 'page', 'revision' ),
3817 'rev_id',
3818 array( 'page_namespace' => $this->getNamespace(),
3819 'page_title' => $this->getDBkey(),
3820 'page_id=rev_page',
3821 'page_latest != rev_id'
3822 ),
3823 __METHOD__,
3824 array( 'FOR UPDATE' )
3825 );
3826 # Return true if there was no history
3827 return ( $row === false );
3828 }
3829
3830 /**
3831 * Checks if $this can be moved to a given Title
3832 * - Selects for update, so don't call it unless you mean business
3833 *
3834 * @deprecated since 1.25, use MovePage's methods instead
3835 * @param Title $nt The new title to check
3836 * @return bool
3837 */
3838 public function isValidMoveTarget( $nt ) {
3839 # Is it an existing file?
3840 if ( $nt->getNamespace() == NS_FILE ) {
3841 $file = wfLocalFile( $nt );
3842 if ( $file->exists() ) {
3843 wfDebug( __METHOD__ . ": file exists\n" );
3844 return false;
3845 }
3846 }
3847 # Is it a redirect with no history?
3848 if ( !$nt->isSingleRevRedirect() ) {
3849 wfDebug( __METHOD__ . ": not a one-rev redirect\n" );
3850 return false;
3851 }
3852 # Get the article text
3853 $rev = Revision::newFromTitle( $nt, false, Revision::READ_LATEST );
3854 if ( !is_object( $rev ) ) {
3855 return false;
3856 }
3857 $content = $rev->getContent();
3858 # Does the redirect point to the source?
3859 # Or is it a broken self-redirect, usually caused by namespace collisions?
3860 $redirTitle = $content ? $content->getRedirectTarget() : null;
3861
3862 if ( $redirTitle ) {
3863 if ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
3864 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) {
3865 wfDebug( __METHOD__ . ": redirect points to other page\n" );
3866 return false;
3867 } else {
3868 return true;
3869 }
3870 } else {
3871 # Fail safe (not a redirect after all. strange.)
3872 wfDebug( __METHOD__ . ": failsafe: database sais " . $nt->getPrefixedDBkey() .
3873 " is a redirect, but it doesn't contain a valid redirect.\n" );
3874 return false;
3875 }
3876 }
3877
3878 /**
3879 * Get categories to which this Title belongs and return an array of
3880 * categories' names.
3881 *
3882 * @return array Array of parents in the form:
3883 * $parent => $currentarticle
3884 */
3885 public function getParentCategories() {
3886 global $wgContLang;
3887
3888 $data = array();
3889
3890 $titleKey = $this->getArticleID();
3891
3892 if ( $titleKey === 0 ) {
3893 return $data;
3894 }
3895
3896 $dbr = wfGetDB( DB_SLAVE );
3897
3898 $res = $dbr->select(
3899 'categorylinks',
3900 'cl_to',
3901 array( 'cl_from' => $titleKey ),
3902 __METHOD__
3903 );
3904
3905 if ( $res->numRows() > 0 ) {
3906 foreach ( $res as $row ) {
3907 // $data[] = Title::newFromText($wgContLang->getNsText ( NS_CATEGORY ).':'.$row->cl_to);
3908 $data[$wgContLang->getNsText( NS_CATEGORY ) . ':' . $row->cl_to] = $this->getFullText();
3909 }
3910 }
3911 return $data;
3912 }
3913
3914 /**
3915 * Get a tree of parent categories
3916 *
3917 * @param array $children Array with the children in the keys, to check for circular refs
3918 * @return array Tree of parent categories
3919 */
3920 public function getParentCategoryTree( $children = array() ) {
3921 $stack = array();
3922 $parents = $this->getParentCategories();
3923
3924 if ( $parents ) {
3925 foreach ( $parents as $parent => $current ) {
3926 if ( array_key_exists( $parent, $children ) ) {
3927 # Circular reference
3928 $stack[$parent] = array();
3929 } else {
3930 $nt = Title::newFromText( $parent );
3931 if ( $nt ) {
3932 $stack[$parent] = $nt->getParentCategoryTree( $children + array( $parent => 1 ) );
3933 }
3934 }
3935 }
3936 }
3937
3938 return $stack;
3939 }
3940
3941 /**
3942 * Get an associative array for selecting this title from
3943 * the "page" table
3944 *
3945 * @return array Array suitable for the $where parameter of DB::select()
3946 */
3947 public function pageCond() {
3948 if ( $this->mArticleID > 0 ) {
3949 // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs
3950 return array( 'page_id' => $this->mArticleID );
3951 } else {
3952 return array( 'page_namespace' => $this->mNamespace, 'page_title' => $this->mDbkeyform );
3953 }
3954 }
3955
3956 /**
3957 * Get the revision ID of the previous revision
3958 *
3959 * @param int $revId Revision ID. Get the revision that was before this one.
3960 * @param int $flags Title::GAID_FOR_UPDATE
3961 * @return int|bool Old revision ID, or false if none exists
3962 */
3963 public function getPreviousRevisionID( $revId, $flags = 0 ) {
3964 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
3965 $revId = $db->selectField( 'revision', 'rev_id',
3966 array(
3967 'rev_page' => $this->getArticleID( $flags ),
3968 'rev_id < ' . intval( $revId )
3969 ),
3970 __METHOD__,
3971 array( 'ORDER BY' => 'rev_id DESC' )
3972 );
3973
3974 if ( $revId === false ) {
3975 return false;
3976 } else {
3977 return intval( $revId );
3978 }
3979 }
3980
3981 /**
3982 * Get the revision ID of the next revision
3983 *
3984 * @param int $revId Revision ID. Get the revision that was after this one.
3985 * @param int $flags Title::GAID_FOR_UPDATE
3986 * @return int|bool Next revision ID, or false if none exists
3987 */
3988 public function getNextRevisionID( $revId, $flags = 0 ) {
3989 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
3990 $revId = $db->selectField( 'revision', 'rev_id',
3991 array(
3992 'rev_page' => $this->getArticleID( $flags ),
3993 'rev_id > ' . intval( $revId )
3994 ),
3995 __METHOD__,
3996 array( 'ORDER BY' => 'rev_id' )
3997 );
3998
3999 if ( $revId === false ) {
4000 return false;
4001 } else {
4002 return intval( $revId );
4003 }
4004 }
4005
4006 /**
4007 * Get the first revision of the page
4008 *
4009 * @param int $flags Title::GAID_FOR_UPDATE
4010 * @return Revision|null If page doesn't exist
4011 */
4012 public function getFirstRevision( $flags = 0 ) {
4013 $pageId = $this->getArticleID( $flags );
4014 if ( $pageId ) {
4015 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
4016 $row = $db->selectRow( 'revision', Revision::selectFields(),
4017 array( 'rev_page' => $pageId ),
4018 __METHOD__,
4019 array( 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 1 )
4020 );
4021 if ( $row ) {
4022 return new Revision( $row );
4023 }
4024 }
4025 return null;
4026 }
4027
4028 /**
4029 * Get the oldest revision timestamp of this page
4030 *
4031 * @param int $flags Title::GAID_FOR_UPDATE
4032 * @return string MW timestamp
4033 */
4034 public function getEarliestRevTime( $flags = 0 ) {
4035 $rev = $this->getFirstRevision( $flags );
4036 return $rev ? $rev->getTimestamp() : null;
4037 }
4038
4039 /**
4040 * Check if this is a new page
4041 *
4042 * @return bool
4043 */
4044 public function isNewPage() {
4045 $dbr = wfGetDB( DB_SLAVE );
4046 return (bool)$dbr->selectField( 'page', 'page_is_new', $this->pageCond(), __METHOD__ );
4047 }
4048
4049 /**
4050 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
4051 *
4052 * @return bool
4053 */
4054 public function isBigDeletion() {
4055 global $wgDeleteRevisionsLimit;
4056
4057 if ( !$wgDeleteRevisionsLimit ) {
4058 return false;
4059 }
4060
4061 if ( $this->mIsBigDeletion === null ) {
4062 $dbr = wfGetDB( DB_SLAVE );
4063
4064 $innerQuery = $dbr->selectSQLText(
4065 'revision',
4066 '1',
4067 array( 'rev_page' => $this->getArticleID() ),
4068 __METHOD__,
4069 array( 'LIMIT' => $wgDeleteRevisionsLimit + 1 )
4070 );
4071
4072 $revCount = $dbr->query(
4073 'SELECT COUNT(*) FROM (' . $innerQuery . ') AS innerQuery',
4074 __METHOD__
4075 );
4076 $revCount = $revCount->fetchRow();
4077 $revCount = $revCount['COUNT(*)'];
4078
4079 $this->mIsBigDeletion = $revCount > $wgDeleteRevisionsLimit;
4080 }
4081
4082 return $this->mIsBigDeletion;
4083 }
4084
4085 /**
4086 * Get the approximate revision count of this page.
4087 *
4088 * @return int
4089 */
4090 public function estimateRevisionCount() {
4091 if ( !$this->exists() ) {
4092 return 0;
4093 }
4094
4095 if ( $this->mEstimateRevisions === null ) {
4096 $dbr = wfGetDB( DB_SLAVE );
4097 $this->mEstimateRevisions = $dbr->estimateRowCount( 'revision', '*',
4098 array( 'rev_page' => $this->getArticleID() ), __METHOD__ );
4099 }
4100
4101 return $this->mEstimateRevisions;
4102 }
4103
4104 /**
4105 * Get the number of revisions between the given revision.
4106 * Used for diffs and other things that really need it.
4107 *
4108 * @param int|Revision $old Old revision or rev ID (first before range)
4109 * @param int|Revision $new New revision or rev ID (first after range)
4110 * @param int|null $max Limit of Revisions to count, will be incremented to detect truncations
4111 * @return int Number of revisions between these revisions.
4112 */
4113 public function countRevisionsBetween( $old, $new, $max = null ) {
4114 if ( !( $old instanceof Revision ) ) {
4115 $old = Revision::newFromTitle( $this, (int)$old );
4116 }
4117 if ( !( $new instanceof Revision ) ) {
4118 $new = Revision::newFromTitle( $this, (int)$new );
4119 }
4120 if ( !$old || !$new ) {
4121 return 0; // nothing to compare
4122 }
4123 $dbr = wfGetDB( DB_SLAVE );
4124 $conds = array(
4125 'rev_page' => $this->getArticleID(),
4126 'rev_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4127 'rev_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4128 );
4129 if ( $max !== null ) {
4130 $res = $dbr->select( 'revision', '1',
4131 $conds,
4132 __METHOD__,
4133 array( 'LIMIT' => $max + 1 ) // extra to detect truncation
4134 );
4135 return $res->numRows();
4136 } else {
4137 return (int)$dbr->selectField( 'revision', 'count(*)', $conds, __METHOD__ );
4138 }
4139 }
4140
4141 /**
4142 * Get the authors between the given revisions or revision IDs.
4143 * Used for diffs and other things that really need it.
4144 *
4145 * @since 1.23
4146 *
4147 * @param int|Revision $old Old revision or rev ID (first before range by default)
4148 * @param int|Revision $new New revision or rev ID (first after range by default)
4149 * @param int $limit Maximum number of authors
4150 * @param string|array $options (Optional): Single option, or an array of options:
4151 * 'include_old' Include $old in the range; $new is excluded.
4152 * 'include_new' Include $new in the range; $old is excluded.
4153 * 'include_both' Include both $old and $new in the range.
4154 * Unknown option values are ignored.
4155 * @return array|null Names of revision authors in the range; null if not both revisions exist
4156 */
4157 public function getAuthorsBetween( $old, $new, $limit, $options = array() ) {
4158 if ( !( $old instanceof Revision ) ) {
4159 $old = Revision::newFromTitle( $this, (int)$old );
4160 }
4161 if ( !( $new instanceof Revision ) ) {
4162 $new = Revision::newFromTitle( $this, (int)$new );
4163 }
4164 // XXX: what if Revision objects are passed in, but they don't refer to this title?
4165 // Add $old->getPage() != $new->getPage() || $old->getPage() != $this->getArticleID()
4166 // in the sanity check below?
4167 if ( !$old || !$new ) {
4168 return null; // nothing to compare
4169 }
4170 $authors = array();
4171 $old_cmp = '>';
4172 $new_cmp = '<';
4173 $options = (array)$options;
4174 if ( in_array( 'include_old', $options ) ) {
4175 $old_cmp = '>=';
4176 }
4177 if ( in_array( 'include_new', $options ) ) {
4178 $new_cmp = '<=';
4179 }
4180 if ( in_array( 'include_both', $options ) ) {
4181 $old_cmp = '>=';
4182 $new_cmp = '<=';
4183 }
4184 // No DB query needed if $old and $new are the same or successive revisions:
4185 if ( $old->getId() === $new->getId() ) {
4186 return ( $old_cmp === '>' && $new_cmp === '<' ) ? array() : array( $old->getRawUserText() );
4187 } elseif ( $old->getId() === $new->getParentId() ) {
4188 if ( $old_cmp === '>=' && $new_cmp === '<=' ) {
4189 $authors[] = $old->getRawUserText();
4190 if ( $old->getRawUserText() != $new->getRawUserText() ) {
4191 $authors[] = $new->getRawUserText();
4192 }
4193 } elseif ( $old_cmp === '>=' ) {
4194 $authors[] = $old->getRawUserText();
4195 } elseif ( $new_cmp === '<=' ) {
4196 $authors[] = $new->getRawUserText();
4197 }
4198 return $authors;
4199 }
4200 $dbr = wfGetDB( DB_SLAVE );
4201 $res = $dbr->select( 'revision', 'DISTINCT rev_user_text',
4202 array(
4203 'rev_page' => $this->getArticleID(),
4204 "rev_timestamp $old_cmp " . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4205 "rev_timestamp $new_cmp " . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4206 ), __METHOD__,
4207 array( 'LIMIT' => $limit + 1 ) // add one so caller knows it was truncated
4208 );
4209 foreach ( $res as $row ) {
4210 $authors[] = $row->rev_user_text;
4211 }
4212 return $authors;
4213 }
4214
4215 /**
4216 * Get the number of authors between the given revisions or revision IDs.
4217 * Used for diffs and other things that really need it.
4218 *
4219 * @param int|Revision $old Old revision or rev ID (first before range by default)
4220 * @param int|Revision $new New revision or rev ID (first after range by default)
4221 * @param int $limit Maximum number of authors
4222 * @param string|array $options (Optional): Single option, or an array of options:
4223 * 'include_old' Include $old in the range; $new is excluded.
4224 * 'include_new' Include $new in the range; $old is excluded.
4225 * 'include_both' Include both $old and $new in the range.
4226 * Unknown option values are ignored.
4227 * @return int Number of revision authors in the range; zero if not both revisions exist
4228 */
4229 public function countAuthorsBetween( $old, $new, $limit, $options = array() ) {
4230 $authors = $this->getAuthorsBetween( $old, $new, $limit, $options );
4231 return $authors ? count( $authors ) : 0;
4232 }
4233
4234 /**
4235 * Compare with another title.
4236 *
4237 * @param Title $title
4238 * @return bool
4239 */
4240 public function equals( Title $title ) {
4241 // Note: === is necessary for proper matching of number-like titles.
4242 return $this->getInterwiki() === $title->getInterwiki()
4243 && $this->getNamespace() == $title->getNamespace()
4244 && $this->getDBkey() === $title->getDBkey();
4245 }
4246
4247 /**
4248 * Check if this title is a subpage of another title
4249 *
4250 * @param Title $title
4251 * @return bool
4252 */
4253 public function isSubpageOf( Title $title ) {
4254 return $this->getInterwiki() === $title->getInterwiki()
4255 && $this->getNamespace() == $title->getNamespace()
4256 && strpos( $this->getDBkey(), $title->getDBkey() . '/' ) === 0;
4257 }
4258
4259 /**
4260 * Check if page exists. For historical reasons, this function simply
4261 * checks for the existence of the title in the page table, and will
4262 * thus return false for interwiki links, special pages and the like.
4263 * If you want to know if a title can be meaningfully viewed, you should
4264 * probably call the isKnown() method instead.
4265 *
4266 * @return bool
4267 */
4268 public function exists() {
4269 $exists = $this->getArticleID() != 0;
4270 Hooks::run( 'TitleExists', array( $this, &$exists ) );
4271 return $exists;
4272 }
4273
4274 /**
4275 * Should links to this title be shown as potentially viewable (i.e. as
4276 * "bluelinks"), even if there's no record by this title in the page
4277 * table?
4278 *
4279 * This function is semi-deprecated for public use, as well as somewhat
4280 * misleadingly named. You probably just want to call isKnown(), which
4281 * calls this function internally.
4282 *
4283 * (ISSUE: Most of these checks are cheap, but the file existence check
4284 * can potentially be quite expensive. Including it here fixes a lot of
4285 * existing code, but we might want to add an optional parameter to skip
4286 * it and any other expensive checks.)
4287 *
4288 * @return bool
4289 */
4290 public function isAlwaysKnown() {
4291 $isKnown = null;
4292
4293 /**
4294 * Allows overriding default behavior for determining if a page exists.
4295 * If $isKnown is kept as null, regular checks happen. If it's
4296 * a boolean, this value is returned by the isKnown method.
4297 *
4298 * @since 1.20
4299 *
4300 * @param Title $title
4301 * @param bool|null $isKnown
4302 */
4303 Hooks::run( 'TitleIsAlwaysKnown', array( $this, &$isKnown ) );
4304
4305 if ( !is_null( $isKnown ) ) {
4306 return $isKnown;
4307 }
4308
4309 if ( $this->isExternal() ) {
4310 return true; // any interwiki link might be viewable, for all we know
4311 }
4312
4313 switch ( $this->mNamespace ) {
4314 case NS_MEDIA:
4315 case NS_FILE:
4316 // file exists, possibly in a foreign repo
4317 return (bool)wfFindFile( $this );
4318 case NS_SPECIAL:
4319 // valid special page
4320 return SpecialPageFactory::exists( $this->getDBkey() );
4321 case NS_MAIN:
4322 // selflink, possibly with fragment
4323 return $this->mDbkeyform == '';
4324 case NS_MEDIAWIKI:
4325 // known system message
4326 return $this->hasSourceText() !== false;
4327 default:
4328 return false;
4329 }
4330 }
4331
4332 /**
4333 * Does this title refer to a page that can (or might) be meaningfully
4334 * viewed? In particular, this function may be used to determine if
4335 * links to the title should be rendered as "bluelinks" (as opposed to
4336 * "redlinks" to non-existent pages).
4337 * Adding something else to this function will cause inconsistency
4338 * since LinkHolderArray calls isAlwaysKnown() and does its own
4339 * page existence check.
4340 *
4341 * @return bool
4342 */
4343 public function isKnown() {
4344 return $this->isAlwaysKnown() || $this->exists();
4345 }
4346
4347 /**
4348 * Does this page have source text?
4349 *
4350 * @return bool
4351 */
4352 public function hasSourceText() {
4353 if ( $this->exists() ) {
4354 return true;
4355 }
4356
4357 if ( $this->mNamespace == NS_MEDIAWIKI ) {
4358 // If the page doesn't exist but is a known system message, default
4359 // message content will be displayed, same for language subpages-
4360 // Use always content language to avoid loading hundreds of languages
4361 // to get the link color.
4362 global $wgContLang;
4363 list( $name, ) = MessageCache::singleton()->figureMessage(
4364 $wgContLang->lcfirst( $this->getText() )
4365 );
4366 $message = wfMessage( $name )->inLanguage( $wgContLang )->useDatabase( false );
4367 return $message->exists();
4368 }
4369
4370 return false;
4371 }
4372
4373 /**
4374 * Get the default message text or false if the message doesn't exist
4375 *
4376 * @return string|bool
4377 */
4378 public function getDefaultMessageText() {
4379 global $wgContLang;
4380
4381 if ( $this->getNamespace() != NS_MEDIAWIKI ) { // Just in case
4382 return false;
4383 }
4384
4385 list( $name, $lang ) = MessageCache::singleton()->figureMessage(
4386 $wgContLang->lcfirst( $this->getText() )
4387 );
4388 $message = wfMessage( $name )->inLanguage( $lang )->useDatabase( false );
4389
4390 if ( $message->exists() ) {
4391 return $message->plain();
4392 } else {
4393 return false;
4394 }
4395 }
4396
4397 /**
4398 * Updates page_touched for this page; called from LinksUpdate.php
4399 *
4400 * @return bool True if the update succeeded
4401 */
4402 public function invalidateCache() {
4403 if ( wfReadOnly() ) {
4404 return false;
4405 }
4406
4407 if ( $this->mArticleID === 0 ) {
4408 return true; // avoid gap locking if we know it's not there
4409 }
4410
4411 $method = __METHOD__;
4412 $dbw = wfGetDB( DB_MASTER );
4413 $conds = $this->pageCond();
4414 $dbw->onTransactionIdle( function () use ( $dbw, $conds, $method ) {
4415 $dbw->update(
4416 'page',
4417 array( 'page_touched' => $dbw->timestamp() ),
4418 $conds,
4419 $method
4420 );
4421 } );
4422
4423 return true;
4424 }
4425
4426 /**
4427 * Update page_touched timestamps and send squid purge messages for
4428 * pages linking to this title. May be sent to the job queue depending
4429 * on the number of links. Typically called on create and delete.
4430 */
4431 public function touchLinks() {
4432 $u = new HTMLCacheUpdate( $this, 'pagelinks' );
4433 $u->doUpdate();
4434
4435 if ( $this->getNamespace() == NS_CATEGORY ) {
4436 $u = new HTMLCacheUpdate( $this, 'categorylinks' );
4437 $u->doUpdate();
4438 }
4439 }
4440
4441 /**
4442 * Get the last touched timestamp
4443 *
4444 * @param DatabaseBase $db Optional db
4445 * @return string Last-touched timestamp
4446 */
4447 public function getTouched( $db = null ) {
4448 if ( $db === null ) {
4449 $db = wfGetDB( DB_SLAVE );
4450 }
4451 $touched = $db->selectField( 'page', 'page_touched', $this->pageCond(), __METHOD__ );
4452 return $touched;
4453 }
4454
4455 /**
4456 * Get the timestamp when this page was updated since the user last saw it.
4457 *
4458 * @param User $user
4459 * @return string|null
4460 */
4461 public function getNotificationTimestamp( $user = null ) {
4462 global $wgUser, $wgShowUpdatedMarker;
4463 // Assume current user if none given
4464 if ( !$user ) {
4465 $user = $wgUser;
4466 }
4467 // Check cache first
4468 $uid = $user->getId();
4469 // avoid isset here, as it'll return false for null entries
4470 if ( array_key_exists( $uid, $this->mNotificationTimestamp ) ) {
4471 return $this->mNotificationTimestamp[$uid];
4472 }
4473 if ( !$uid || !$wgShowUpdatedMarker || !$user->isAllowed( 'viewmywatchlist' ) ) {
4474 $this->mNotificationTimestamp[$uid] = false;
4475 return $this->mNotificationTimestamp[$uid];
4476 }
4477 // Don't cache too much!
4478 if ( count( $this->mNotificationTimestamp ) >= self::CACHE_MAX ) {
4479 $this->mNotificationTimestamp = array();
4480 }
4481 $dbr = wfGetDB( DB_SLAVE );
4482 $this->mNotificationTimestamp[$uid] = $dbr->selectField( 'watchlist',
4483 'wl_notificationtimestamp',
4484 array(
4485 'wl_user' => $user->getId(),
4486 'wl_namespace' => $this->getNamespace(),
4487 'wl_title' => $this->getDBkey(),
4488 ),
4489 __METHOD__
4490 );
4491 return $this->mNotificationTimestamp[$uid];
4492 }
4493
4494 /**
4495 * Generate strings used for xml 'id' names in monobook tabs
4496 *
4497 * @param string $prepend Defaults to 'nstab-'
4498 * @return string XML 'id' name
4499 */
4500 public function getNamespaceKey( $prepend = 'nstab-' ) {
4501 global $wgContLang;
4502 // Gets the subject namespace if this title
4503 $namespace = MWNamespace::getSubject( $this->getNamespace() );
4504 // Checks if canonical namespace name exists for namespace
4505 if ( MWNamespace::exists( $this->getNamespace() ) ) {
4506 // Uses canonical namespace name
4507 $namespaceKey = MWNamespace::getCanonicalName( $namespace );
4508 } else {
4509 // Uses text of namespace
4510 $namespaceKey = $this->getSubjectNsText();
4511 }
4512 // Makes namespace key lowercase
4513 $namespaceKey = $wgContLang->lc( $namespaceKey );
4514 // Uses main
4515 if ( $namespaceKey == '' ) {
4516 $namespaceKey = 'main';
4517 }
4518 // Changes file to image for backwards compatibility
4519 if ( $namespaceKey == 'file' ) {
4520 $namespaceKey = 'image';
4521 }
4522 return $prepend . $namespaceKey;
4523 }
4524
4525 /**
4526 * Get all extant redirects to this Title
4527 *
4528 * @param int|null $ns Single namespace to consider; null to consider all namespaces
4529 * @return Title[] Array of Title redirects to this title
4530 */
4531 public function getRedirectsHere( $ns = null ) {
4532 $redirs = array();
4533
4534 $dbr = wfGetDB( DB_SLAVE );
4535 $where = array(
4536 'rd_namespace' => $this->getNamespace(),
4537 'rd_title' => $this->getDBkey(),
4538 'rd_from = page_id'
4539 );
4540 if ( $this->isExternal() ) {
4541 $where['rd_interwiki'] = $this->getInterwiki();
4542 } else {
4543 $where[] = 'rd_interwiki = ' . $dbr->addQuotes( '' ) . ' OR rd_interwiki IS NULL';
4544 }
4545 if ( !is_null( $ns ) ) {
4546 $where['page_namespace'] = $ns;
4547 }
4548
4549 $res = $dbr->select(
4550 array( 'redirect', 'page' ),
4551 array( 'page_namespace', 'page_title' ),
4552 $where,
4553 __METHOD__
4554 );
4555
4556 foreach ( $res as $row ) {
4557 $redirs[] = self::newFromRow( $row );
4558 }
4559 return $redirs;
4560 }
4561
4562 /**
4563 * Check if this Title is a valid redirect target
4564 *
4565 * @return bool
4566 */
4567 public function isValidRedirectTarget() {
4568 global $wgInvalidRedirectTargets;
4569
4570 // invalid redirect targets are stored in a global array, but explicitly disallow Userlogout here
4571 if ( $this->isSpecial( 'Userlogout' ) ) {
4572 return false;
4573 }
4574
4575 foreach ( $wgInvalidRedirectTargets as $target ) {
4576 if ( $this->isSpecial( $target ) ) {
4577 return false;
4578 }
4579 }
4580
4581 return true;
4582 }
4583
4584 /**
4585 * Get a backlink cache object
4586 *
4587 * @return BacklinkCache
4588 */
4589 public function getBacklinkCache() {
4590 return BacklinkCache::get( $this );
4591 }
4592
4593 /**
4594 * Whether the magic words __INDEX__ and __NOINDEX__ function for this page.
4595 *
4596 * @return bool
4597 */
4598 public function canUseNoindex() {
4599 global $wgContentNamespaces, $wgExemptFromUserRobotsControl;
4600
4601 $bannedNamespaces = is_null( $wgExemptFromUserRobotsControl )
4602 ? $wgContentNamespaces
4603 : $wgExemptFromUserRobotsControl;
4604
4605 return !in_array( $this->mNamespace, $bannedNamespaces );
4606
4607 }
4608
4609 /**
4610 * Returns the raw sort key to be used for categories, with the specified
4611 * prefix. This will be fed to Collation::getSortKey() to get a
4612 * binary sortkey that can be used for actual sorting.
4613 *
4614 * @param string $prefix The prefix to be used, specified using
4615 * {{defaultsort:}} or like [[Category:Foo|prefix]]. Empty for no
4616 * prefix.
4617 * @return string
4618 */
4619 public function getCategorySortkey( $prefix = '' ) {
4620 $unprefixed = $this->getText();
4621
4622 // Anything that uses this hook should only depend
4623 // on the Title object passed in, and should probably
4624 // tell the users to run updateCollations.php --force
4625 // in order to re-sort existing category relations.
4626 Hooks::run( 'GetDefaultSortkey', array( $this, &$unprefixed ) );
4627 if ( $prefix !== '' ) {
4628 # Separate with a line feed, so the unprefixed part is only used as
4629 # a tiebreaker when two pages have the exact same prefix.
4630 # In UCA, tab is the only character that can sort above LF
4631 # so we strip both of them from the original prefix.
4632 $prefix = strtr( $prefix, "\n\t", ' ' );
4633 return "$prefix\n$unprefixed";
4634 }
4635 return $unprefixed;
4636 }
4637
4638 /**
4639 * Get the language in which the content of this page is written in
4640 * wikitext. Defaults to $wgContLang, but in certain cases it can be
4641 * e.g. $wgLang (such as special pages, which are in the user language).
4642 *
4643 * @since 1.18
4644 * @return Language
4645 */
4646 public function getPageLanguage() {
4647 global $wgLang, $wgLanguageCode;
4648 wfProfileIn( __METHOD__ );
4649 if ( $this->isSpecialPage() ) {
4650 // special pages are in the user language
4651 wfProfileOut( __METHOD__ );
4652 return $wgLang;
4653 }
4654
4655 // Checking if DB language is set
4656 if ( $this->mDbPageLanguage ) {
4657 wfProfileOut( __METHOD__ );
4658 return wfGetLangObj( $this->mDbPageLanguage );
4659 }
4660
4661 if ( !$this->mPageLanguage || $this->mPageLanguage[1] !== $wgLanguageCode ) {
4662 // Note that this may depend on user settings, so the cache should
4663 // be only per-request.
4664 // NOTE: ContentHandler::getPageLanguage() may need to load the
4665 // content to determine the page language!
4666 // Checking $wgLanguageCode hasn't changed for the benefit of unit
4667 // tests.
4668 $contentHandler = ContentHandler::getForTitle( $this );
4669 $langObj = wfGetLangObj( $contentHandler->getPageLanguage( $this ) );
4670 $this->mPageLanguage = array( $langObj->getCode(), $wgLanguageCode );
4671 } else {
4672 $langObj = wfGetLangObj( $this->mPageLanguage[0] );
4673 }
4674
4675 wfProfileOut( __METHOD__ );
4676 return $langObj;
4677 }
4678
4679 /**
4680 * Get the language in which the content of this page is written when
4681 * viewed by user. Defaults to $wgContLang, but in certain cases it can be
4682 * e.g. $wgLang (such as special pages, which are in the user language).
4683 *
4684 * @since 1.20
4685 * @return Language
4686 */
4687 public function getPageViewLanguage() {
4688 global $wgLang;
4689
4690 if ( $this->isSpecialPage() ) {
4691 // If the user chooses a variant, the content is actually
4692 // in a language whose code is the variant code.
4693 $variant = $wgLang->getPreferredVariant();
4694 if ( $wgLang->getCode() !== $variant ) {
4695 return Language::factory( $variant );
4696 }
4697
4698 return $wgLang;
4699 }
4700
4701 // @note Can't be cached persistently, depends on user settings.
4702 // @note ContentHandler::getPageViewLanguage() may need to load the
4703 // content to determine the page language!
4704 $contentHandler = ContentHandler::getForTitle( $this );
4705 $pageLang = $contentHandler->getPageViewLanguage( $this );
4706 return $pageLang;
4707 }
4708
4709 /**
4710 * Get a list of rendered edit notices for this page.
4711 *
4712 * Array is keyed by the original message key, and values are rendered using parseAsBlock, so
4713 * they will already be wrapped in paragraphs.
4714 *
4715 * @since 1.21
4716 * @param int $oldid Revision ID that's being edited
4717 * @return array
4718 */
4719 public function getEditNotices( $oldid = 0 ) {
4720 $notices = array();
4721
4722 # Optional notices on a per-namespace and per-page basis
4723 $editnotice_ns = 'editnotice-' . $this->getNamespace();
4724 $editnotice_ns_message = wfMessage( $editnotice_ns );
4725 if ( $editnotice_ns_message->exists() ) {
4726 $notices[$editnotice_ns] = $editnotice_ns_message->parseAsBlock();
4727 }
4728 if ( MWNamespace::hasSubpages( $this->getNamespace() ) ) {
4729 $parts = explode( '/', $this->getDBkey() );
4730 $editnotice_base = $editnotice_ns;
4731 while ( count( $parts ) > 0 ) {
4732 $editnotice_base .= '-' . array_shift( $parts );
4733 $editnotice_base_msg = wfMessage( $editnotice_base );
4734 if ( $editnotice_base_msg->exists() ) {
4735 $notices[$editnotice_base] = $editnotice_base_msg->parseAsBlock();
4736 }
4737 }
4738 } else {
4739 # Even if there are no subpages in namespace, we still don't want / in MW ns.
4740 $editnoticeText = $editnotice_ns . '-' . str_replace( '/', '-', $this->getDBkey() );
4741 $editnoticeMsg = wfMessage( $editnoticeText );
4742 if ( $editnoticeMsg->exists() ) {
4743 $notices[$editnoticeText] = $editnoticeMsg->parseAsBlock();
4744 }
4745 }
4746
4747 Hooks::run( 'TitleGetEditNotices', array( $this, $oldid, &$notices ) );
4748 return $notices;
4749 }
4750 }