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