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