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