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