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