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