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