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