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