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