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