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