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