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