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