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