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