* (bug 34937) Fix for r107636: call WikiPage::onArticleCreate() when moving a page...
[lhc/web/wiklou.git] / includes / Title.php
1 <?php
2 /**
3 * See title.txt
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 */
22
23 /**
24 * Represents a title within MediaWiki.
25 * Optionally may contain an interwiki designation or namespace.
26 * @note This class can fetch various kinds of data from the database;
27 * however, it does so inefficiently.
28 *
29 * @internal documentation reviewed 15 Mar 2010
30 */
31 class Title {
32 /** @name Static cache variables */
33 // @{
34 static private $titleCache = array();
35 // @}
36
37 /**
38 * Title::newFromText maintains a cache to avoid expensive re-normalization of
39 * commonly used titles. On a batch operation this can become a memory leak
40 * if not bounded. After hitting this many titles reset the cache.
41 */
42 const CACHE_MAX = 1000;
43
44 /**
45 * Used to be GAID_FOR_UPDATE define. Used with getArticleID() and friends
46 * to use the master DB
47 */
48 const GAID_FOR_UPDATE = 1;
49
50 /**
51 * @name Private member variables
52 * Please use the accessor functions instead.
53 * @private
54 */
55 // @{
56
57 var $mTextform = ''; // /< Text form (spaces not underscores) of the main part
58 var $mUrlform = ''; // /< URL-encoded form of the main part
59 var $mDbkeyform = ''; // /< Main part with underscores
60 var $mUserCaseDBKey; // /< DB key with the initial letter in the case specified by the user
61 var $mNamespace = NS_MAIN; // /< Namespace index, i.e. one of the NS_xxxx constants
62 var $mInterwiki = ''; // /< Interwiki prefix (or null string)
63 var $mFragment; // /< Title fragment (i.e. the bit after the #)
64 var $mArticleID = -1; // /< Article ID, fetched from the link cache on demand
65 var $mLatestID = false; // /< ID of most recent revision
66 private $mEstimateRevisions; // /< Estimated number of revisions; null of not loaded
67 var $mRestrictions = array(); // /< Array of groups allowed to edit this article
68 var $mOldRestrictions = false;
69 var $mCascadeRestriction; ///< Cascade restrictions on this page to included templates and images?
70 var $mCascadingRestrictions; // Caching the results of getCascadeProtectionSources
71 var $mRestrictionsExpiry = array(); ///< When do the restrictions on this page expire?
72 var $mHasCascadingRestrictions; ///< Are cascading restrictions in effect on this page?
73 var $mCascadeSources; ///< Where are the cascading restrictions coming from on this page?
74 var $mRestrictionsLoaded = false; ///< Boolean for initialisation on demand
75 var $mPrefixedText; ///< Text form including namespace/interwiki, initialised on demand
76 var $mTitleProtection; ///< Cached value for getTitleProtection (create protection)
77 # Don't change the following default, NS_MAIN is hardcoded in several
78 # places. See bug 696.
79 var $mDefaultNamespace = NS_MAIN; // /< Namespace index when there is no namespace
80 # Zero except in {{transclusion}} tags
81 var $mWatched = null; // /< Is $wgUser watching this page? null if unfilled, accessed through userIsWatching()
82 var $mLength = -1; // /< The page length, 0 for special pages
83 var $mRedirect = null; // /< Is the article at this title a redirect?
84 var $mNotificationTimestamp = array(); // /< Associative array of user ID -> timestamp/false
85 var $mBacklinkCache = null; // /< Cache of links to this title
86 // @}
87
88
89 /**
90 * Constructor
91 */
92 /*protected*/ function __construct() { }
93
94 /**
95 * Create a new Title from a prefixed DB key
96 *
97 * @param $key String the database key, which has underscores
98 * instead of spaces, possibly including namespace and
99 * interwiki prefixes
100 * @return Title, or NULL on an error
101 */
102 public static function newFromDBkey( $key ) {
103 $t = new Title();
104 $t->mDbkeyform = $key;
105 if ( $t->secureAndSplit() ) {
106 return $t;
107 } else {
108 return null;
109 }
110 }
111
112 /**
113 * Create a new Title from text, such as what one would find in a link. De-
114 * codes any HTML entities in the text.
115 *
116 * @param $text String the link text; spaces, prefixes, and an
117 * initial ':' indicating the main namespace are accepted.
118 * @param $defaultNamespace Int the namespace to use if none is speci-
119 * fied by a prefix. If you want to force a specific namespace even if
120 * $text might begin with a namespace prefix, use makeTitle() or
121 * makeTitleSafe().
122 * @return Title, or null on an error.
123 */
124 public static function newFromText( $text, $defaultNamespace = NS_MAIN ) {
125 if ( is_object( $text ) ) {
126 throw new MWException( 'Title::newFromText given an object' );
127 }
128
129 /**
130 * Wiki pages often contain multiple links to the same page.
131 * Title normalization and parsing can become expensive on
132 * pages with many links, so we can save a little time by
133 * caching them.
134 *
135 * In theory these are value objects and won't get changed...
136 */
137 if ( $defaultNamespace == NS_MAIN && isset( Title::$titleCache[$text] ) ) {
138 return Title::$titleCache[$text];
139 }
140
141 # Convert things like &eacute; &#257; or &#x3017; into normalized (bug 14952) text
142 $filteredText = Sanitizer::decodeCharReferencesAndNormalize( $text );
143
144 $t = new Title();
145 $t->mDbkeyform = str_replace( ' ', '_', $filteredText );
146 $t->mDefaultNamespace = $defaultNamespace;
147
148 static $cachedcount = 0 ;
149 if ( $t->secureAndSplit() ) {
150 if ( $defaultNamespace == NS_MAIN ) {
151 if ( $cachedcount >= self::CACHE_MAX ) {
152 # Avoid memory leaks on mass operations...
153 Title::$titleCache = array();
154 $cachedcount = 0;
155 }
156 $cachedcount++;
157 Title::$titleCache[$text] =& $t;
158 }
159 return $t;
160 } else {
161 $ret = null;
162 return $ret;
163 }
164 }
165
166 /**
167 * THIS IS NOT THE FUNCTION YOU WANT. Use Title::newFromText().
168 *
169 * Example of wrong and broken code:
170 * $title = Title::newFromURL( $wgRequest->getVal( 'title' ) );
171 *
172 * Example of right code:
173 * $title = Title::newFromText( $wgRequest->getVal( 'title' ) );
174 *
175 * Create a new Title from URL-encoded text. Ensures that
176 * the given title's length does not exceed the maximum.
177 *
178 * @param $url String the title, as might be taken from a URL
179 * @return Title the new object, or NULL on an error
180 */
181 public static function newFromURL( $url ) {
182 global $wgLegalTitleChars;
183 $t = new Title();
184
185 # For compatibility with old buggy URLs. "+" is usually not valid in titles,
186 # but some URLs used it as a space replacement and they still come
187 # from some external search tools.
188 if ( strpos( $wgLegalTitleChars, '+' ) === false ) {
189 $url = str_replace( '+', ' ', $url );
190 }
191
192 $t->mDbkeyform = str_replace( ' ', '_', $url );
193 if ( $t->secureAndSplit() ) {
194 return $t;
195 } else {
196 return null;
197 }
198 }
199
200 /**
201 * Create a new Title from an article ID
202 *
203 * @param $id Int the page_id corresponding to the Title to create
204 * @param $flags Int use Title::GAID_FOR_UPDATE to use master
205 * @return Title the new object, or NULL on an error
206 */
207 public static function newFromID( $id, $flags = 0 ) {
208 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
209 $row = $db->selectRow( 'page', '*', array( 'page_id' => $id ), __METHOD__ );
210 if ( $row !== false ) {
211 $title = Title::newFromRow( $row );
212 } else {
213 $title = null;
214 }
215 return $title;
216 }
217
218 /**
219 * Make an array of titles from an array of IDs
220 *
221 * @param $ids Array of Int Array of IDs
222 * @return Array of Titles
223 */
224 public static function newFromIDs( $ids ) {
225 if ( !count( $ids ) ) {
226 return array();
227 }
228 $dbr = wfGetDB( DB_SLAVE );
229
230 $res = $dbr->select(
231 'page',
232 array(
233 'page_namespace', 'page_title', 'page_id',
234 'page_len', 'page_is_redirect', 'page_latest',
235 ),
236 array( 'page_id' => $ids ),
237 __METHOD__
238 );
239
240 $titles = array();
241 foreach ( $res as $row ) {
242 $titles[] = Title::newFromRow( $row );
243 }
244 return $titles;
245 }
246
247 /**
248 * Make a Title object from a DB row
249 *
250 * @param $row Object database row (needs at least page_title,page_namespace)
251 * @return Title corresponding Title
252 */
253 public static function newFromRow( $row ) {
254 $t = self::makeTitle( $row->page_namespace, $row->page_title );
255 $t->loadFromRow( $row );
256 return $t;
257 }
258
259 /**
260 * Load Title object fields from a DB row.
261 * If false is given, the title will be treated as non-existing.
262 *
263 * @param $row Object|bool database row
264 */
265 public function loadFromRow( $row ) {
266 if ( $row ) { // page found
267 if ( isset( $row->page_id ) )
268 $this->mArticleID = (int)$row->page_id;
269 if ( isset( $row->page_len ) )
270 $this->mLength = (int)$row->page_len;
271 if ( isset( $row->page_is_redirect ) )
272 $this->mRedirect = (bool)$row->page_is_redirect;
273 if ( isset( $row->page_latest ) )
274 $this->mLatestID = (int)$row->page_latest;
275 } else { // page not found
276 $this->mArticleID = 0;
277 $this->mLength = 0;
278 $this->mRedirect = false;
279 $this->mLatestID = 0;
280 }
281 }
282
283 /**
284 * Create a new Title from a namespace index and a DB key.
285 * It's assumed that $ns and $title are *valid*, for instance when
286 * they came directly from the database or a special page name.
287 * For convenience, spaces are converted to underscores so that
288 * eg user_text fields can be used directly.
289 *
290 * @param $ns Int the namespace of the article
291 * @param $title String the unprefixed database key form
292 * @param $fragment String the link fragment (after the "#")
293 * @param $interwiki String the interwiki prefix
294 * @return Title the new object
295 */
296 public static function &makeTitle( $ns, $title, $fragment = '', $interwiki = '' ) {
297 $t = new Title();
298 $t->mInterwiki = $interwiki;
299 $t->mFragment = $fragment;
300 $t->mNamespace = $ns = intval( $ns );
301 $t->mDbkeyform = str_replace( ' ', '_', $title );
302 $t->mArticleID = ( $ns >= 0 ) ? -1 : 0;
303 $t->mUrlform = wfUrlencode( $t->mDbkeyform );
304 $t->mTextform = str_replace( '_', ' ', $title );
305 return $t;
306 }
307
308 /**
309 * Create a new Title from a namespace index and a DB key.
310 * The parameters will be checked for validity, which is a bit slower
311 * than makeTitle() but safer for user-provided data.
312 *
313 * @param $ns Int the namespace of the article
314 * @param $title String database key form
315 * @param $fragment String the link fragment (after the "#")
316 * @param $interwiki String interwiki prefix
317 * @return Title the new object, or NULL on an error
318 */
319 public static function makeTitleSafe( $ns, $title, $fragment = '', $interwiki = '' ) {
320 $t = new Title();
321 $t->mDbkeyform = Title::makeName( $ns, $title, $fragment, $interwiki );
322 if ( $t->secureAndSplit() ) {
323 return $t;
324 } else {
325 return null;
326 }
327 }
328
329 /**
330 * Create a new Title for the Main Page
331 *
332 * @return Title the new object
333 */
334 public static function newMainPage() {
335 $title = Title::newFromText( wfMsgForContent( 'mainpage' ) );
336 // Don't give fatal errors if the message is broken
337 if ( !$title ) {
338 $title = Title::newFromText( 'Main Page' );
339 }
340 return $title;
341 }
342
343 /**
344 * Extract a redirect destination from a string and return the
345 * Title, or null if the text doesn't contain a valid redirect
346 * This will only return the very next target, useful for
347 * the redirect table and other checks that don't need full recursion
348 *
349 * @param $text String: Text with possible redirect
350 * @return Title: The corresponding Title
351 */
352 public static function newFromRedirect( $text ) {
353 return self::newFromRedirectInternal( $text );
354 }
355
356 /**
357 * Extract a redirect destination from a string and return the
358 * Title, or null if the text doesn't contain a valid redirect
359 * This will recurse down $wgMaxRedirects times or until a non-redirect target is hit
360 * in order to provide (hopefully) the Title of the final destination instead of another redirect
361 *
362 * @param $text String Text with possible redirect
363 * @return Title
364 */
365 public static function newFromRedirectRecurse( $text ) {
366 $titles = self::newFromRedirectArray( $text );
367 return $titles ? array_pop( $titles ) : null;
368 }
369
370 /**
371 * Extract a redirect destination from a string and return an
372 * array of Titles, or null if the text doesn't contain a valid redirect
373 * The last element in the array is the final destination after all redirects
374 * have been resolved (up to $wgMaxRedirects times)
375 *
376 * @param $text String Text with possible redirect
377 * @return Array of Titles, with the destination last
378 */
379 public static function newFromRedirectArray( $text ) {
380 global $wgMaxRedirects;
381 $title = self::newFromRedirectInternal( $text );
382 if ( is_null( $title ) ) {
383 return null;
384 }
385 // recursive check to follow double redirects
386 $recurse = $wgMaxRedirects;
387 $titles = array( $title );
388 while ( --$recurse > 0 ) {
389 if ( $title->isRedirect() ) {
390 $page = WikiPage::factory( $title );
391 $newtitle = $page->getRedirectTarget();
392 } else {
393 break;
394 }
395 // Redirects to some special pages are not permitted
396 if ( $newtitle instanceOf Title && $newtitle->isValidRedirectTarget() ) {
397 // the new title passes the checks, so make that our current title so that further recursion can be checked
398 $title = $newtitle;
399 $titles[] = $newtitle;
400 } else {
401 break;
402 }
403 }
404 return $titles;
405 }
406
407 /**
408 * Really extract the redirect destination
409 * Do not call this function directly, use one of the newFromRedirect* functions above
410 *
411 * @param $text String Text with possible redirect
412 * @return Title
413 */
414 protected static function newFromRedirectInternal( $text ) {
415 global $wgMaxRedirects;
416 if ( $wgMaxRedirects < 1 ) {
417 //redirects are disabled, so quit early
418 return null;
419 }
420 $redir = MagicWord::get( 'redirect' );
421 $text = trim( $text );
422 if ( $redir->matchStartAndRemove( $text ) ) {
423 // Extract the first link and see if it's usable
424 // Ensure that it really does come directly after #REDIRECT
425 // Some older redirects included a colon, so don't freak about that!
426 $m = array();
427 if ( preg_match( '!^\s*:?\s*\[{2}(.*?)(?:\|.*?)?\]{2}!', $text, $m ) ) {
428 // Strip preceding colon used to "escape" categories, etc.
429 // and URL-decode links
430 if ( strpos( $m[1], '%' ) !== false ) {
431 // Match behavior of inline link parsing here;
432 $m[1] = rawurldecode( ltrim( $m[1], ':' ) );
433 }
434 $title = Title::newFromText( $m[1] );
435 // If the title is a redirect to bad special pages or is invalid, return null
436 if ( !$title instanceof Title || !$title->isValidRedirectTarget() ) {
437 return null;
438 }
439 return $title;
440 }
441 }
442 return null;
443 }
444
445 /**
446 * Get the prefixed DB key associated with an ID
447 *
448 * @param $id Int the page_id of the article
449 * @return Title an object representing the article, or NULL if no such article was found
450 */
451 public static function nameOf( $id ) {
452 $dbr = wfGetDB( DB_SLAVE );
453
454 $s = $dbr->selectRow(
455 'page',
456 array( 'page_namespace', 'page_title' ),
457 array( 'page_id' => $id ),
458 __METHOD__
459 );
460 if ( $s === false ) {
461 return null;
462 }
463
464 $n = self::makeName( $s->page_namespace, $s->page_title );
465 return $n;
466 }
467
468 /**
469 * Get a regex character class describing the legal characters in a link
470 *
471 * @return String the list of characters, not delimited
472 */
473 public static function legalChars() {
474 global $wgLegalTitleChars;
475 return $wgLegalTitleChars;
476 }
477
478 /**
479 * Returns a simple regex that will match on characters and sequences invalid in titles.
480 * Note that this doesn't pick up many things that could be wrong with titles, but that
481 * replacing this regex with something valid will make many titles valid.
482 *
483 * @return String regex string
484 */
485 static function getTitleInvalidRegex() {
486 static $rxTc = false;
487 if ( !$rxTc ) {
488 # Matching titles will be held as illegal.
489 $rxTc = '/' .
490 # Any character not allowed is forbidden...
491 '[^' . self::legalChars() . ']' .
492 # URL percent encoding sequences interfere with the ability
493 # to round-trip titles -- you can't link to them consistently.
494 '|%[0-9A-Fa-f]{2}' .
495 # XML/HTML character references produce similar issues.
496 '|&[A-Za-z0-9\x80-\xff]+;' .
497 '|&#[0-9]+;' .
498 '|&#x[0-9A-Fa-f]+;' .
499 '/S';
500 }
501
502 return $rxTc;
503 }
504
505 /**
506 * Get a string representation of a title suitable for
507 * including in a search index
508 *
509 * @param $ns Int a namespace index
510 * @param $title String text-form main part
511 * @return String a stripped-down title string ready for the search index
512 */
513 public static function indexTitle( $ns, $title ) {
514 global $wgContLang;
515
516 $lc = SearchEngine::legalSearchChars() . '&#;';
517 $t = $wgContLang->normalizeForSearch( $title );
518 $t = preg_replace( "/[^{$lc}]+/", ' ', $t );
519 $t = $wgContLang->lc( $t );
520
521 # Handle 's, s'
522 $t = preg_replace( "/([{$lc}]+)'s( |$)/", "\\1 \\1's ", $t );
523 $t = preg_replace( "/([{$lc}]+)s'( |$)/", "\\1s ", $t );
524
525 $t = preg_replace( "/\\s+/", ' ', $t );
526
527 if ( $ns == NS_FILE ) {
528 $t = preg_replace( "/ (png|gif|jpg|jpeg|ogg)$/", "", $t );
529 }
530 return trim( $t );
531 }
532
533 /**
534 * Make a prefixed DB key from a DB key and a namespace index
535 *
536 * @param $ns Int numerical representation of the namespace
537 * @param $title String the DB key form the title
538 * @param $fragment String The link fragment (after the "#")
539 * @param $interwiki String The interwiki prefix
540 * @return String the prefixed form of the title
541 */
542 public static function makeName( $ns, $title, $fragment = '', $interwiki = '' ) {
543 global $wgContLang;
544
545 $namespace = $wgContLang->getNsText( $ns );
546 $name = $namespace == '' ? $title : "$namespace:$title";
547 if ( strval( $interwiki ) != '' ) {
548 $name = "$interwiki:$name";
549 }
550 if ( strval( $fragment ) != '' ) {
551 $name .= '#' . $fragment;
552 }
553 return $name;
554 }
555
556 /**
557 * Escape a text fragment, say from a link, for a URL
558 *
559 * @param $fragment string containing a URL or link fragment (after the "#")
560 * @return String: escaped string
561 */
562 static function escapeFragmentForURL( $fragment ) {
563 # Note that we don't urlencode the fragment. urlencoded Unicode
564 # fragments appear not to work in IE (at least up to 7) or in at least
565 # one version of Opera 9.x. The W3C validator, for one, doesn't seem
566 # to care if they aren't encoded.
567 return Sanitizer::escapeId( $fragment, 'noninitial' );
568 }
569
570 /**
571 * Callback for usort() to do title sorts by (namespace, title)
572 *
573 * @param $a Title
574 * @param $b Title
575 *
576 * @return Integer: result of string comparison, or namespace comparison
577 */
578 public static function compare( $a, $b ) {
579 if ( $a->getNamespace() == $b->getNamespace() ) {
580 return strcmp( $a->getText(), $b->getText() );
581 } else {
582 return $a->getNamespace() - $b->getNamespace();
583 }
584 }
585
586 /**
587 * Determine whether the object refers to a page within
588 * this project.
589 *
590 * @return Bool TRUE if this is an in-project interwiki link or a wikilink, FALSE otherwise
591 */
592 public function isLocal() {
593 if ( $this->mInterwiki != '' ) {
594 return Interwiki::fetch( $this->mInterwiki )->isLocal();
595 } else {
596 return true;
597 }
598 }
599
600 /**
601 * Is this Title interwiki?
602 *
603 * @return Bool
604 */
605 public function isExternal() {
606 return ( $this->mInterwiki != '' );
607 }
608
609 /**
610 * Get the interwiki prefix (or null string)
611 *
612 * @return String Interwiki prefix
613 */
614 public function getInterwiki() {
615 return $this->mInterwiki;
616 }
617
618 /**
619 * Determine whether the object refers to a page within
620 * this project and is transcludable.
621 *
622 * @return Bool TRUE if this is transcludable
623 */
624 public function isTrans() {
625 if ( $this->mInterwiki == '' ) {
626 return false;
627 }
628
629 return Interwiki::fetch( $this->mInterwiki )->isTranscludable();
630 }
631
632 /**
633 * Returns the DB name of the distant wiki which owns the object.
634 *
635 * @return String the DB name
636 */
637 public function getTransWikiID() {
638 if ( $this->mInterwiki == '' ) {
639 return false;
640 }
641
642 return Interwiki::fetch( $this->mInterwiki )->getWikiID();
643 }
644
645 /**
646 * Get the text form (spaces not underscores) of the main part
647 *
648 * @return String Main part of the title
649 */
650 public function getText() {
651 return $this->mTextform;
652 }
653
654 /**
655 * Get the URL-encoded form of the main part
656 *
657 * @return String Main part of the title, URL-encoded
658 */
659 public function getPartialURL() {
660 return $this->mUrlform;
661 }
662
663 /**
664 * Get the main part with underscores
665 *
666 * @return String: Main part of the title, with underscores
667 */
668 public function getDBkey() {
669 return $this->mDbkeyform;
670 }
671
672 /**
673 * Get the DB key with the initial letter case as specified by the user
674 *
675 * @return String DB key
676 */
677 function getUserCaseDBKey() {
678 return $this->mUserCaseDBKey;
679 }
680
681 /**
682 * Get the namespace index, i.e. one of the NS_xxxx constants.
683 *
684 * @return Integer: Namespace index
685 */
686 public function getNamespace() {
687 return $this->mNamespace;
688 }
689
690 /**
691 * Get the namespace text
692 *
693 * @return String: Namespace text
694 */
695 public function getNsText() {
696 global $wgContLang;
697
698 if ( $this->mInterwiki != '' ) {
699 // This probably shouldn't even happen. ohh man, oh yuck.
700 // But for interwiki transclusion it sometimes does.
701 // Shit. Shit shit shit.
702 //
703 // Use the canonical namespaces if possible to try to
704 // resolve a foreign namespace.
705 if ( MWNamespace::exists( $this->mNamespace ) ) {
706 return MWNamespace::getCanonicalName( $this->mNamespace );
707 }
708 }
709
710 // Strip off subpages
711 $pagename = $this->getText();
712 if ( strpos( $pagename, '/' ) !== false ) {
713 list( $username , ) = explode( '/', $pagename, 2 );
714 } else {
715 $username = $pagename;
716 }
717
718 if ( $wgContLang->needsGenderDistinction() &&
719 MWNamespace::hasGenderDistinction( $this->mNamespace ) ) {
720 $gender = GenderCache::singleton()->getGenderOf( $username, __METHOD__ );
721 return $wgContLang->getGenderNsText( $this->mNamespace, $gender );
722 }
723
724 return $wgContLang->getNsText( $this->mNamespace );
725 }
726
727 /**
728 * Get the namespace text of the subject (rather than talk) page
729 *
730 * @return String Namespace text
731 */
732 public function getSubjectNsText() {
733 global $wgContLang;
734 return $wgContLang->getNsText( MWNamespace::getSubject( $this->mNamespace ) );
735 }
736
737 /**
738 * Get the namespace text of the talk page
739 *
740 * @return String Namespace text
741 */
742 public function getTalkNsText() {
743 global $wgContLang;
744 return( $wgContLang->getNsText( MWNamespace::getTalk( $this->mNamespace ) ) );
745 }
746
747 /**
748 * Could this title have a corresponding talk page?
749 *
750 * @return Bool TRUE or FALSE
751 */
752 public function canTalk() {
753 return( MWNamespace::canTalk( $this->mNamespace ) );
754 }
755
756 /**
757 * Is this in a namespace that allows actual pages?
758 *
759 * @return Bool
760 * @internal note -- uses hardcoded namespace index instead of constants
761 */
762 public function canExist() {
763 return $this->mNamespace >= NS_MAIN;
764 }
765
766 /**
767 * Can this title be added to a user's watchlist?
768 *
769 * @return Bool TRUE or FALSE
770 */
771 public function isWatchable() {
772 return !$this->isExternal() && MWNamespace::isWatchable( $this->getNamespace() );
773 }
774
775 /**
776 * Returns true if this is a special page.
777 *
778 * @return boolean
779 */
780 public function isSpecialPage() {
781 return $this->getNamespace() == NS_SPECIAL;
782 }
783
784 /**
785 * Returns true if this title resolves to the named special page
786 *
787 * @param $name String The special page name
788 * @return boolean
789 */
790 public function isSpecial( $name ) {
791 if ( $this->isSpecialPage() ) {
792 list( $thisName, /* $subpage */ ) = SpecialPageFactory::resolveAlias( $this->getDBkey() );
793 if ( $name == $thisName ) {
794 return true;
795 }
796 }
797 return false;
798 }
799
800 /**
801 * If the Title refers to a special page alias which is not the local default, resolve
802 * the alias, and localise the name as necessary. Otherwise, return $this
803 *
804 * @return Title
805 */
806 public function fixSpecialName() {
807 if ( $this->isSpecialPage() ) {
808 list( $canonicalName, $par ) = SpecialPageFactory::resolveAlias( $this->mDbkeyform );
809 if ( $canonicalName ) {
810 $localName = SpecialPageFactory::getLocalNameFor( $canonicalName, $par );
811 if ( $localName != $this->mDbkeyform ) {
812 return Title::makeTitle( NS_SPECIAL, $localName );
813 }
814 }
815 }
816 return $this;
817 }
818
819 /**
820 * Returns true if the title is inside the specified namespace.
821 *
822 * Please make use of this instead of comparing to getNamespace()
823 * This function is much more resistant to changes we may make
824 * to namespaces than code that makes direct comparisons.
825 * @param $ns int The namespace
826 * @return bool
827 * @since 1.19
828 */
829 public function inNamespace( $ns ) {
830 return MWNamespace::equals( $this->getNamespace(), $ns );
831 }
832
833 /**
834 * Returns true if the title is inside one of the specified namespaces.
835 *
836 * @param ...$namespaces The namespaces to check for
837 * @return bool
838 * @since 1.19
839 */
840 public function inNamespaces( /* ... */ ) {
841 $namespaces = func_get_args();
842 if ( count( $namespaces ) > 0 && is_array( $namespaces[0] ) ) {
843 $namespaces = $namespaces[0];
844 }
845
846 foreach ( $namespaces as $ns ) {
847 if ( $this->inNamespace( $ns ) ) {
848 return true;
849 }
850 }
851
852 return false;
853 }
854
855 /**
856 * Returns true if the title has the same subject namespace as the
857 * namespace specified.
858 * For example this method will take NS_USER and return true if namespace
859 * is either NS_USER or NS_USER_TALK since both of them have NS_USER
860 * as their subject namespace.
861 *
862 * This is MUCH simpler than individually testing for equivilance
863 * against both NS_USER and NS_USER_TALK, and is also forward compatible.
864 * @since 1.19
865 * @return bool
866 */
867 public function hasSubjectNamespace( $ns ) {
868 return MWNamespace::subjectEquals( $this->getNamespace(), $ns );
869 }
870
871 /**
872 * Is this Title in a namespace which contains content?
873 * In other words, is this a content page, for the purposes of calculating
874 * statistics, etc?
875 *
876 * @return Boolean
877 */
878 public function isContentPage() {
879 return MWNamespace::isContent( $this->getNamespace() );
880 }
881
882 /**
883 * Would anybody with sufficient privileges be able to move this page?
884 * Some pages just aren't movable.
885 *
886 * @return Bool TRUE or FALSE
887 */
888 public function isMovable() {
889 if ( !MWNamespace::isMovable( $this->getNamespace() ) || $this->getInterwiki() != '' ) {
890 // Interwiki title or immovable namespace. Hooks don't get to override here
891 return false;
892 }
893
894 $result = true;
895 wfRunHooks( 'TitleIsMovable', array( $this, &$result ) );
896 return $result;
897 }
898
899 /**
900 * Is this the mainpage?
901 * @note Title::newFromText seams to be sufficiently optimized by the title
902 * cache that we don't need to over-optimize by doing direct comparisons and
903 * acidentally creating new bugs where $title->equals( Title::newFromText() )
904 * ends up reporting something differently than $title->isMainPage();
905 *
906 * @since 1.18
907 * @return Bool
908 */
909 public function isMainPage() {
910 return $this->equals( Title::newMainPage() );
911 }
912
913 /**
914 * Is this a subpage?
915 *
916 * @return Bool
917 */
918 public function isSubpage() {
919 return MWNamespace::hasSubpages( $this->mNamespace )
920 ? strpos( $this->getText(), '/' ) !== false
921 : false;
922 }
923
924 /**
925 * Is this a conversion table for the LanguageConverter?
926 *
927 * @return Bool
928 */
929 public function isConversionTable() {
930 return $this->getNamespace() == NS_MEDIAWIKI &&
931 strpos( $this->getText(), 'Conversiontable' ) !== false;
932 }
933
934 /**
935 * Does that page contain wikitext, or it is JS, CSS or whatever?
936 *
937 * @return Bool
938 */
939 public function isWikitextPage() {
940 $retval = !$this->isCssOrJsPage() && !$this->isCssJsSubpage();
941 wfRunHooks( 'TitleIsWikitextPage', array( $this, &$retval ) );
942 return $retval;
943 }
944
945 /**
946 * Could this page contain custom CSS or JavaScript, based
947 * on the title?
948 *
949 * @return Bool
950 */
951 public function isCssOrJsPage() {
952 $retval = $this->mNamespace == NS_MEDIAWIKI
953 && preg_match( '!\.(?:css|js)$!u', $this->mTextform ) > 0;
954 wfRunHooks( 'TitleIsCssOrJsPage', array( $this, &$retval ) );
955 return $retval;
956 }
957
958 /**
959 * Is this a .css or .js subpage of a user page?
960 * @return Bool
961 */
962 public function isCssJsSubpage() {
963 return ( NS_USER == $this->mNamespace and preg_match( "/\\/.*\\.(?:css|js)$/", $this->mTextform ) );
964 }
965
966 /**
967 * Trim down a .css or .js subpage title to get the corresponding skin name
968 *
969 * @return string containing skin name from .css or .js subpage title
970 */
971 public function getSkinFromCssJsSubpage() {
972 $subpage = explode( '/', $this->mTextform );
973 $subpage = $subpage[ count( $subpage ) - 1 ];
974 $lastdot = strrpos( $subpage, '.' );
975 if ( $lastdot === false )
976 return $subpage; # Never happens: only called for names ending in '.css' or '.js'
977 return substr( $subpage, 0, $lastdot );
978 }
979
980 /**
981 * Is this a .css subpage of a user page?
982 *
983 * @return Bool
984 */
985 public function isCssSubpage() {
986 return ( NS_USER == $this->mNamespace && preg_match( "/\\/.*\\.css$/", $this->mTextform ) );
987 }
988
989 /**
990 * Is this a .js subpage of a user page?
991 *
992 * @return Bool
993 */
994 public function isJsSubpage() {
995 return ( NS_USER == $this->mNamespace && preg_match( "/\\/.*\\.js$/", $this->mTextform ) );
996 }
997
998 /**
999 * Is this a talk page of some sort?
1000 *
1001 * @return Bool
1002 */
1003 public function isTalkPage() {
1004 return MWNamespace::isTalk( $this->getNamespace() );
1005 }
1006
1007 /**
1008 * Get a Title object associated with the talk page of this article
1009 *
1010 * @return Title the object for the talk page
1011 */
1012 public function getTalkPage() {
1013 return Title::makeTitle( MWNamespace::getTalk( $this->getNamespace() ), $this->getDBkey() );
1014 }
1015
1016 /**
1017 * Get a title object associated with the subject page of this
1018 * talk page
1019 *
1020 * @return Title the object for the subject page
1021 */
1022 public function getSubjectPage() {
1023 // Is this the same title?
1024 $subjectNS = MWNamespace::getSubject( $this->getNamespace() );
1025 if ( $this->getNamespace() == $subjectNS ) {
1026 return $this;
1027 }
1028 return Title::makeTitle( $subjectNS, $this->getDBkey() );
1029 }
1030
1031 /**
1032 * Get the default namespace index, for when there is no namespace
1033 *
1034 * @return Int Default namespace index
1035 */
1036 public function getDefaultNamespace() {
1037 return $this->mDefaultNamespace;
1038 }
1039
1040 /**
1041 * Get title for search index
1042 *
1043 * @return String a stripped-down title string ready for the
1044 * search index
1045 */
1046 public function getIndexTitle() {
1047 return Title::indexTitle( $this->mNamespace, $this->mTextform );
1048 }
1049
1050 /**
1051 * Get the Title fragment (i.e.\ the bit after the #) in text form
1052 *
1053 * @return String Title fragment
1054 */
1055 public function getFragment() {
1056 return $this->mFragment;
1057 }
1058
1059 /**
1060 * Get the fragment in URL form, including the "#" character if there is one
1061 * @return String Fragment in URL form
1062 */
1063 public function getFragmentForURL() {
1064 if ( $this->mFragment == '' ) {
1065 return '';
1066 } else {
1067 return '#' . Title::escapeFragmentForURL( $this->mFragment );
1068 }
1069 }
1070
1071 /**
1072 * Set the fragment for this title. Removes the first character from the
1073 * specified fragment before setting, so it assumes you're passing it with
1074 * an initial "#".
1075 *
1076 * Deprecated for public use, use Title::makeTitle() with fragment parameter.
1077 * Still in active use privately.
1078 *
1079 * @param $fragment String text
1080 */
1081 public function setFragment( $fragment ) {
1082 $this->mFragment = str_replace( '_', ' ', substr( $fragment, 1 ) );
1083 }
1084
1085 /**
1086 * Prefix some arbitrary text with the namespace or interwiki prefix
1087 * of this object
1088 *
1089 * @param $name String the text
1090 * @return String the prefixed text
1091 * @private
1092 */
1093 private function prefix( $name ) {
1094 $p = '';
1095 if ( $this->mInterwiki != '' ) {
1096 $p = $this->mInterwiki . ':';
1097 }
1098
1099 if ( 0 != $this->mNamespace ) {
1100 $p .= $this->getNsText() . ':';
1101 }
1102 return $p . $name;
1103 }
1104
1105 /**
1106 * Get the prefixed database key form
1107 *
1108 * @return String the prefixed title, with underscores and
1109 * any interwiki and namespace prefixes
1110 */
1111 public function getPrefixedDBkey() {
1112 $s = $this->prefix( $this->mDbkeyform );
1113 $s = str_replace( ' ', '_', $s );
1114 return $s;
1115 }
1116
1117 /**
1118 * Get the prefixed title with spaces.
1119 * This is the form usually used for display
1120 *
1121 * @return String the prefixed title, with spaces
1122 */
1123 public function getPrefixedText() {
1124 // @todo FIXME: Bad usage of empty() ?
1125 if ( empty( $this->mPrefixedText ) ) {
1126 $s = $this->prefix( $this->mTextform );
1127 $s = str_replace( '_', ' ', $s );
1128 $this->mPrefixedText = $s;
1129 }
1130 return $this->mPrefixedText;
1131 }
1132
1133 /**
1134 * Return a string representation of this title
1135 *
1136 * @return String representation of this title
1137 */
1138 public function __toString() {
1139 return $this->getPrefixedText();
1140 }
1141
1142 /**
1143 * Get the prefixed title with spaces, plus any fragment
1144 * (part beginning with '#')
1145 *
1146 * @return String the prefixed title, with spaces and the fragment, including '#'
1147 */
1148 public function getFullText() {
1149 $text = $this->getPrefixedText();
1150 if ( $this->mFragment != '' ) {
1151 $text .= '#' . $this->mFragment;
1152 }
1153 return $text;
1154 }
1155
1156 /**
1157 * Get the base page name, i.e. the leftmost part before any slashes
1158 *
1159 * @return String Base name
1160 */
1161 public function getBaseText() {
1162 if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
1163 return $this->getText();
1164 }
1165
1166 $parts = explode( '/', $this->getText() );
1167 # Don't discard the real title if there's no subpage involved
1168 if ( count( $parts ) > 1 ) {
1169 unset( $parts[count( $parts ) - 1] );
1170 }
1171 return implode( '/', $parts );
1172 }
1173
1174 /**
1175 * Get the lowest-level subpage name, i.e. the rightmost part after any slashes
1176 *
1177 * @return String Subpage name
1178 */
1179 public function getSubpageText() {
1180 if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
1181 return( $this->mTextform );
1182 }
1183 $parts = explode( '/', $this->mTextform );
1184 return( $parts[count( $parts ) - 1] );
1185 }
1186
1187 /**
1188 * Get the HTML-escaped displayable text form.
1189 * Used for the title field in <a> tags.
1190 *
1191 * @return String the text, including any prefixes
1192 */
1193 public function getEscapedText() {
1194 wfDeprecated( __METHOD__, '1.19' );
1195 return htmlspecialchars( $this->getPrefixedText() );
1196 }
1197
1198 /**
1199 * Get a URL-encoded form of the subpage text
1200 *
1201 * @return String URL-encoded subpage name
1202 */
1203 public function getSubpageUrlForm() {
1204 $text = $this->getSubpageText();
1205 $text = wfUrlencode( str_replace( ' ', '_', $text ) );
1206 return( $text );
1207 }
1208
1209 /**
1210 * Get a URL-encoded title (not an actual URL) including interwiki
1211 *
1212 * @return String the URL-encoded form
1213 */
1214 public function getPrefixedURL() {
1215 $s = $this->prefix( $this->mDbkeyform );
1216 $s = wfUrlencode( str_replace( ' ', '_', $s ) );
1217 return $s;
1218 }
1219
1220 /**
1221 * Helper to fix up the get{Local,Full,Link,Canonical}URL args
1222 * get{Canonical,Full,Link,Local}URL methods accepted an optional
1223 * second argument named variant. This was deprecated in favor
1224 * of passing an array of option with a "variant" key
1225 * Once $query2 is removed for good, this helper can be dropped
1226 * andthe wfArrayToCGI moved to getLocalURL();
1227 *
1228 * @since 1.19 (r105919)
1229 * @return String
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 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 * @return string
1483 */
1484 public function escapeCanonicalURL( $query = '', $query2 = false ) {
1485 wfDeprecated( __METHOD__, '1.19' );
1486 return htmlspecialchars( $this->getCanonicalURL( $query, $query2 ) );
1487 }
1488
1489 /**
1490 * Get the edit URL for this Title
1491 *
1492 * @return String the URL, or a null string if this is an
1493 * interwiki link
1494 */
1495 public function getEditURL() {
1496 if ( $this->mInterwiki != '' ) {
1497 return '';
1498 }
1499 $s = $this->getLocalURL( 'action=edit' );
1500
1501 return $s;
1502 }
1503
1504 /**
1505 * Is $wgUser watching this page?
1506 *
1507 * @return Bool
1508 */
1509 public function userIsWatching() {
1510 global $wgUser;
1511
1512 if ( is_null( $this->mWatched ) ) {
1513 if ( NS_SPECIAL == $this->mNamespace || !$wgUser->isLoggedIn() ) {
1514 $this->mWatched = false;
1515 } else {
1516 $this->mWatched = $wgUser->isWatched( $this );
1517 }
1518 }
1519 return $this->mWatched;
1520 }
1521
1522 /**
1523 * Can $wgUser read this page?
1524 *
1525 * @deprecated in 1.19; use userCan(), quickUserCan() or getUserPermissionsErrors() instead
1526 * @return Bool
1527 * @todo fold these checks into userCan()
1528 */
1529 public function userCanRead() {
1530 wfDeprecated( __METHOD__, '1.19' );
1531 return $this->userCan( 'read' );
1532 }
1533
1534 /**
1535 * Can $user perform $action on this page?
1536 * This skips potentially expensive cascading permission checks
1537 * as well as avoids expensive error formatting
1538 *
1539 * Suitable for use for nonessential UI controls in common cases, but
1540 * _not_ for functional access control.
1541 *
1542 * May provide false positives, but should never provide a false negative.
1543 *
1544 * @param $action String action that permission needs to be checked for
1545 * @param $user User to check (since 1.19); $wgUser will be used if not
1546 * provided.
1547 * @return Bool
1548 */
1549 public function quickUserCan( $action, $user = null ) {
1550 return $this->userCan( $action, $user, false );
1551 }
1552
1553 /**
1554 * Can $user perform $action on this page?
1555 *
1556 * @param $action String action that permission needs to be checked for
1557 * @param $user User to check (since 1.19); $wgUser will be used if not
1558 * provided.
1559 * @param $doExpensiveQueries Bool Set this to false to avoid doing
1560 * unnecessary queries.
1561 * @return Bool
1562 */
1563 public function userCan( $action, $user = null, $doExpensiveQueries = true ) {
1564 if ( !$user instanceof User ) {
1565 global $wgUser;
1566 $user = $wgUser;
1567 }
1568 return !count( $this->getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries, true ) );
1569 }
1570
1571 /**
1572 * Can $user perform $action on this page?
1573 *
1574 * @todo FIXME: This *does not* check throttles (User::pingLimiter()).
1575 *
1576 * @param $action String action that permission needs to be checked for
1577 * @param $user User to check
1578 * @param $doExpensiveQueries Bool Set this to false to avoid doing unnecessary
1579 * queries by skipping checks for cascading protections and user blocks.
1580 * @param $ignoreErrors Array of Strings Set this to a list of message keys
1581 * whose corresponding errors may be ignored.
1582 * @return Array of arguments to wfMsg to explain permissions problems.
1583 */
1584 public function getUserPermissionsErrors( $action, $user, $doExpensiveQueries = true, $ignoreErrors = array() ) {
1585 $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries );
1586
1587 // Remove the errors being ignored.
1588 foreach ( $errors as $index => $error ) {
1589 $error_key = is_array( $error ) ? $error[0] : $error;
1590
1591 if ( in_array( $error_key, $ignoreErrors ) ) {
1592 unset( $errors[$index] );
1593 }
1594 }
1595
1596 return $errors;
1597 }
1598
1599 /**
1600 * Permissions checks that fail most often, and which are easiest to test.
1601 *
1602 * @param $action String the action to check
1603 * @param $user User user to check
1604 * @param $errors Array list of current errors
1605 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1606 * @param $short Boolean short circuit on first error
1607 *
1608 * @return Array list of errors
1609 */
1610 private function checkQuickPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1611 if ( $action == 'create' ) {
1612 if ( ( $this->isTalkPage() && !$user->isAllowed( 'createtalk' ) ) ||
1613 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage' ) ) ) {
1614 $errors[] = $user->isAnon() ? array( 'nocreatetext' ) : array( 'nocreate-loggedin' );
1615 }
1616 } elseif ( $action == 'move' ) {
1617 if ( !$user->isAllowed( 'move-rootuserpages' )
1618 && $this->mNamespace == NS_USER && !$this->isSubpage() ) {
1619 // Show user page-specific message only if the user can move other pages
1620 $errors[] = array( 'cant-move-user-page' );
1621 }
1622
1623 // Check if user is allowed to move files if it's a file
1624 if ( $this->mNamespace == NS_FILE && !$user->isAllowed( 'movefile' ) ) {
1625 $errors[] = array( 'movenotallowedfile' );
1626 }
1627
1628 if ( !$user->isAllowed( 'move' ) ) {
1629 // User can't move anything
1630 global $wgGroupPermissions;
1631 $userCanMove = false;
1632 if ( isset( $wgGroupPermissions['user']['move'] ) ) {
1633 $userCanMove = $wgGroupPermissions['user']['move'];
1634 }
1635 $autoconfirmedCanMove = false;
1636 if ( isset( $wgGroupPermissions['autoconfirmed']['move'] ) ) {
1637 $autoconfirmedCanMove = $wgGroupPermissions['autoconfirmed']['move'];
1638 }
1639 if ( $user->isAnon() && ( $userCanMove || $autoconfirmedCanMove ) ) {
1640 // custom message if logged-in users without any special rights can move
1641 $errors[] = array( 'movenologintext' );
1642 } else {
1643 $errors[] = array( 'movenotallowed' );
1644 }
1645 }
1646 } elseif ( $action == 'move-target' ) {
1647 if ( !$user->isAllowed( 'move' ) ) {
1648 // User can't move anything
1649 $errors[] = array( 'movenotallowed' );
1650 } elseif ( !$user->isAllowed( 'move-rootuserpages' )
1651 && $this->mNamespace == NS_USER && !$this->isSubpage() ) {
1652 // Show user page-specific message only if the user can move other pages
1653 $errors[] = array( 'cant-move-to-user-page' );
1654 }
1655 } elseif ( !$user->isAllowed( $action ) ) {
1656 $errors[] = $this->missingPermissionError( $action, $short );
1657 }
1658
1659 return $errors;
1660 }
1661
1662 /**
1663 * Add the resulting error code to the errors array
1664 *
1665 * @param $errors Array list of current errors
1666 * @param $result Mixed result of errors
1667 *
1668 * @return Array list of errors
1669 */
1670 private function resultToError( $errors, $result ) {
1671 if ( is_array( $result ) && count( $result ) && !is_array( $result[0] ) ) {
1672 // A single array representing an error
1673 $errors[] = $result;
1674 } elseif ( is_array( $result ) && is_array( $result[0] ) ) {
1675 // A nested array representing multiple errors
1676 $errors = array_merge( $errors, $result );
1677 } elseif ( $result !== '' && is_string( $result ) ) {
1678 // A string representing a message-id
1679 $errors[] = array( $result );
1680 } elseif ( $result === false ) {
1681 // a generic "We don't want them to do that"
1682 $errors[] = array( 'badaccess-group0' );
1683 }
1684 return $errors;
1685 }
1686
1687 /**
1688 * Check various permission hooks
1689 *
1690 * @param $action String the action to check
1691 * @param $user User user to check
1692 * @param $errors Array list of current errors
1693 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1694 * @param $short Boolean short circuit on first error
1695 *
1696 * @return Array list of errors
1697 */
1698 private function checkPermissionHooks( $action, $user, $errors, $doExpensiveQueries, $short ) {
1699 // Use getUserPermissionsErrors instead
1700 $result = '';
1701 if ( !wfRunHooks( 'userCan', array( &$this, &$user, $action, &$result ) ) ) {
1702 return $result ? array() : array( array( 'badaccess-group0' ) );
1703 }
1704 // Check getUserPermissionsErrors hook
1705 if ( !wfRunHooks( 'getUserPermissionsErrors', array( &$this, &$user, $action, &$result ) ) ) {
1706 $errors = $this->resultToError( $errors, $result );
1707 }
1708 // Check getUserPermissionsErrorsExpensive hook
1709 if ( $doExpensiveQueries && !( $short && count( $errors ) > 0 ) &&
1710 !wfRunHooks( 'getUserPermissionsErrorsExpensive', array( &$this, &$user, $action, &$result ) ) ) {
1711 $errors = $this->resultToError( $errors, $result );
1712 }
1713
1714 return $errors;
1715 }
1716
1717 /**
1718 * Check permissions on special pages & namespaces
1719 *
1720 * @param $action String the action to check
1721 * @param $user User user to check
1722 * @param $errors Array list of current errors
1723 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1724 * @param $short Boolean short circuit on first error
1725 *
1726 * @return Array list of errors
1727 */
1728 private function checkSpecialsAndNSPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1729 # Only 'createaccount' and 'execute' can be performed on
1730 # special pages, which don't actually exist in the DB.
1731 $specialOKActions = array( 'createaccount', 'execute', 'read' );
1732 if ( NS_SPECIAL == $this->mNamespace && !in_array( $action, $specialOKActions ) ) {
1733 $errors[] = array( 'ns-specialprotected' );
1734 }
1735
1736 # Check $wgNamespaceProtection for restricted namespaces
1737 if ( $this->isNamespaceProtected( $user ) ) {
1738 $ns = $this->mNamespace == NS_MAIN ?
1739 wfMsg( 'nstab-main' ) : $this->getNsText();
1740 $errors[] = $this->mNamespace == NS_MEDIAWIKI ?
1741 array( 'protectedinterface' ) : array( 'namespaceprotected', $ns );
1742 }
1743
1744 return $errors;
1745 }
1746
1747 /**
1748 * Check CSS/JS sub-page permissions
1749 *
1750 * @param $action String the action to check
1751 * @param $user User user to check
1752 * @param $errors Array list of current errors
1753 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1754 * @param $short Boolean short circuit on first error
1755 *
1756 * @return Array list of errors
1757 */
1758 private function checkCSSandJSPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1759 # Protect css/js subpages of user pages
1760 # XXX: this might be better using restrictions
1761 # XXX: right 'editusercssjs' is deprecated, for backward compatibility only
1762 if ( $action != 'patrol' && !$user->isAllowed( 'editusercssjs' )
1763 && !preg_match( '/^' . preg_quote( $user->getName(), '/' ) . '\//', $this->mTextform ) ) {
1764 if ( $this->isCssSubpage() && !$user->isAllowed( 'editusercss' ) ) {
1765 $errors[] = array( 'customcssprotected' );
1766 } elseif ( $this->isJsSubpage() && !$user->isAllowed( 'edituserjs' ) ) {
1767 $errors[] = array( 'customjsprotected' );
1768 }
1769 }
1770
1771 return $errors;
1772 }
1773
1774 /**
1775 * Check against page_restrictions table requirements on this
1776 * page. The user must possess all required rights for this
1777 * action.
1778 *
1779 * @param $action String the action to check
1780 * @param $user User user to check
1781 * @param $errors Array list of current errors
1782 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1783 * @param $short Boolean short circuit on first error
1784 *
1785 * @return Array list of errors
1786 */
1787 private function checkPageRestrictions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1788 foreach ( $this->getRestrictions( $action ) as $right ) {
1789 // Backwards compatibility, rewrite sysop -> protect
1790 if ( $right == 'sysop' ) {
1791 $right = 'protect';
1792 }
1793 if ( $right != '' && !$user->isAllowed( $right ) ) {
1794 // Users with 'editprotected' permission can edit protected pages
1795 // without cascading option turned on.
1796 if ( $action != 'edit' || !$user->isAllowed( 'editprotected' )
1797 || $this->mCascadeRestriction )
1798 {
1799 $errors[] = array( 'protectedpagetext', $right );
1800 }
1801 }
1802 }
1803
1804 return $errors;
1805 }
1806
1807 /**
1808 * Check restrictions on cascading pages.
1809 *
1810 * @param $action String the action to check
1811 * @param $user User to check
1812 * @param $errors Array list of current errors
1813 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1814 * @param $short Boolean short circuit on first error
1815 *
1816 * @return Array list of errors
1817 */
1818 private function checkCascadingSourcesRestrictions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1819 if ( $doExpensiveQueries && !$this->isCssJsSubpage() ) {
1820 # We /could/ use the protection level on the source page, but it's
1821 # fairly ugly as we have to establish a precedence hierarchy for pages
1822 # included by multiple cascade-protected pages. So just restrict
1823 # it to people with 'protect' permission, as they could remove the
1824 # protection anyway.
1825 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
1826 # Cascading protection depends on more than this page...
1827 # Several cascading protected pages may include this page...
1828 # Check each cascading level
1829 # This is only for protection restrictions, not for all actions
1830 if ( isset( $restrictions[$action] ) ) {
1831 foreach ( $restrictions[$action] as $right ) {
1832 $right = ( $right == 'sysop' ) ? 'protect' : $right;
1833 if ( $right != '' && !$user->isAllowed( $right ) ) {
1834 $pages = '';
1835 foreach ( $cascadingSources as $page )
1836 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
1837 $errors[] = array( 'cascadeprotected', count( $cascadingSources ), $pages );
1838 }
1839 }
1840 }
1841 }
1842
1843 return $errors;
1844 }
1845
1846 /**
1847 * Check action permissions not already checked in checkQuickPermissions
1848 *
1849 * @param $action String the action to check
1850 * @param $user User to check
1851 * @param $errors Array list of current errors
1852 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1853 * @param $short Boolean short circuit on first error
1854 *
1855 * @return Array list of errors
1856 */
1857 private function checkActionPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1858 global $wgDeleteRevisionsLimit, $wgLang;
1859
1860 if ( $action == 'protect' ) {
1861 if ( count( $this->getUserPermissionsErrorsInternal( 'edit', $user, $doExpensiveQueries, true ) ) ) {
1862 // If they can't edit, they shouldn't protect.
1863 $errors[] = array( 'protect-cantedit' );
1864 }
1865 } elseif ( $action == 'create' ) {
1866 $title_protection = $this->getTitleProtection();
1867 if( $title_protection ) {
1868 if( $title_protection['pt_create_perm'] == 'sysop' ) {
1869 $title_protection['pt_create_perm'] = 'protect'; // B/C
1870 }
1871 if( $title_protection['pt_create_perm'] == '' ||
1872 !$user->isAllowed( $title_protection['pt_create_perm'] ) )
1873 {
1874 $errors[] = array( 'titleprotected', User::whoIs( $title_protection['pt_user'] ), $title_protection['pt_reason'] );
1875 }
1876 }
1877 } elseif ( $action == 'move' ) {
1878 // Check for immobile pages
1879 if ( !MWNamespace::isMovable( $this->mNamespace ) ) {
1880 // Specific message for this case
1881 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
1882 } elseif ( !$this->isMovable() ) {
1883 // Less specific message for rarer cases
1884 $errors[] = array( 'immobile-source-page' );
1885 }
1886 } elseif ( $action == 'move-target' ) {
1887 if ( !MWNamespace::isMovable( $this->mNamespace ) ) {
1888 $errors[] = array( 'immobile-target-namespace', $this->getNsText() );
1889 } elseif ( !$this->isMovable() ) {
1890 $errors[] = array( 'immobile-target-page' );
1891 }
1892 } elseif ( $action == 'delete' ) {
1893 if ( $doExpensiveQueries && $wgDeleteRevisionsLimit
1894 && !$this->userCan( 'bigdelete', $user ) && $this->isBigDeletion() )
1895 {
1896 $errors[] = array( 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) );
1897 }
1898 }
1899 return $errors;
1900 }
1901
1902 /**
1903 * Check that the user isn't blocked from editting.
1904 *
1905 * @param $action String the action to check
1906 * @param $user User to check
1907 * @param $errors Array list of current errors
1908 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1909 * @param $short Boolean short circuit on first error
1910 *
1911 * @return Array list of errors
1912 */
1913 private function checkUserBlock( $action, $user, $errors, $doExpensiveQueries, $short ) {
1914 // Account creation blocks handled at userlogin.
1915 // Unblocking handled in SpecialUnblock
1916 if( !$doExpensiveQueries || in_array( $action, array( 'createaccount', 'unblock' ) ) ) {
1917 return $errors;
1918 }
1919
1920 global $wgContLang, $wgLang, $wgEmailConfirmToEdit;
1921
1922 if ( $wgEmailConfirmToEdit && !$user->isEmailConfirmed() ) {
1923 $errors[] = array( 'confirmedittext' );
1924 }
1925
1926 if ( ( $action == 'edit' || $action == 'create' ) && !$user->isBlockedFrom( $this ) ) {
1927 // Don't block the user from editing their own talk page unless they've been
1928 // explicitly blocked from that too.
1929 } elseif( $user->isBlocked() && $user->mBlock->prevents( $action ) !== false ) {
1930 $block = $user->getBlock();
1931
1932 // This is from OutputPage::blockedPage
1933 // Copied at r23888 by werdna
1934
1935 $id = $user->blockedBy();
1936 $reason = $user->blockedFor();
1937 if ( $reason == '' ) {
1938 $reason = wfMsg( 'blockednoreason' );
1939 }
1940 $ip = $user->getRequest()->getIP();
1941
1942 if ( is_numeric( $id ) ) {
1943 $name = User::whoIs( $id );
1944 } else {
1945 $name = $id;
1946 }
1947
1948 $link = '[[' . $wgContLang->getNsText( NS_USER ) . ":{$name}|{$name}]]";
1949 $blockid = $block->getId();
1950 $blockExpiry = $block->getExpiry();
1951 $blockTimestamp = $wgLang->timeanddate( wfTimestamp( TS_MW, $block->mTimestamp ), true );
1952 if ( $blockExpiry == 'infinity' ) {
1953 $blockExpiry = wfMessage( 'infiniteblock' )->text();
1954 } else {
1955 $blockExpiry = $wgLang->timeanddate( wfTimestamp( TS_MW, $blockExpiry ), true );
1956 }
1957
1958 $intended = strval( $block->getTarget() );
1959
1960 $errors[] = array( ( $block->mAuto ? 'autoblockedtext' : 'blockedtext' ), $link, $reason, $ip, $name,
1961 $blockid, $blockExpiry, $intended, $blockTimestamp );
1962 }
1963
1964 return $errors;
1965 }
1966
1967 /**
1968 * Check that the user is allowed to read this page.
1969 *
1970 * @param $action String the action to check
1971 * @param $user User to check
1972 * @param $errors Array list of current errors
1973 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1974 * @param $short Boolean short circuit on first error
1975 *
1976 * @return Array list of errors
1977 */
1978 private function checkReadPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1979 global $wgWhitelistRead, $wgGroupPermissions, $wgRevokePermissions;
1980 static $useShortcut = null;
1981
1982 # Initialize the $useShortcut boolean, to determine if we can skip quite a bit of code below
1983 if ( is_null( $useShortcut ) ) {
1984 $useShortcut = true;
1985 if ( empty( $wgGroupPermissions['*']['read'] ) ) {
1986 # Not a public wiki, so no shortcut
1987 $useShortcut = false;
1988 } elseif ( !empty( $wgRevokePermissions ) ) {
1989 /**
1990 * Iterate through each group with permissions being revoked (key not included since we don't care
1991 * what the group name is), then check if the read permission is being revoked. If it is, then
1992 * we don't use the shortcut below since the user might not be able to read, even though anon
1993 * reading is allowed.
1994 */
1995 foreach ( $wgRevokePermissions as $perms ) {
1996 if ( !empty( $perms['read'] ) ) {
1997 # We might be removing the read right from the user, so no shortcut
1998 $useShortcut = false;
1999 break;
2000 }
2001 }
2002 }
2003 }
2004
2005 $whitelisted = false;
2006 if ( $useShortcut ) {
2007 # Shortcut for public wikis, allows skipping quite a bit of code
2008 $whitelisted = true;
2009 } elseif ( $user->isAllowed( 'read' ) ) {
2010 # If the user is allowed to read pages, he is allowed to read all pages
2011 $whitelisted = true;
2012 } elseif ( $this->isSpecial( 'Userlogin' )
2013 || $this->isSpecial( 'ChangePassword' )
2014 || $this->isSpecial( 'PasswordReset' )
2015 ) {
2016 # Always grant access to the login page.
2017 # Even anons need to be able to log in.
2018 $whitelisted = true;
2019 } elseif ( is_array( $wgWhitelistRead ) && count( $wgWhitelistRead ) ) {
2020 # Time to check the whitelist
2021 # Only do these checks is there's something to check against
2022 $name = $this->getPrefixedText();
2023 $dbName = $this->getPrefixedDBKey();
2024
2025 // Check for explicit whitelisting with and without underscores
2026 if ( in_array( $name, $wgWhitelistRead, true ) || in_array( $dbName, $wgWhitelistRead, true ) ) {
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( __METHOD__ ); # 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( __METHOD__ );
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( __METHOD__ );
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
3599 $dbw = wfGetDB( DB_MASTER );
3600
3601 $newpage = WikiPage::factory( $nt );
3602
3603 if ( $moveOverRedirect ) {
3604 $newid = $nt->getArticleID();
3605
3606 # Delete the old redirect. We don't save it to history since
3607 # by definition if we've got here it's rather uninteresting.
3608 # We have to remove it so that the next step doesn't trigger
3609 # a conflict on the unique namespace+title index...
3610 $dbw->delete( 'page', array( 'page_id' => $newid ), __METHOD__ );
3611
3612 $newpage->doDeleteUpdates( $newid );
3613 }
3614
3615 # Save a null revision in the page's history notifying of the move
3616 $nullRevision = Revision::newNullRevision( $dbw, $oldid, $comment, true );
3617 if ( !is_object( $nullRevision ) ) {
3618 throw new MWException( 'No valid null revision produced in ' . __METHOD__ );
3619 }
3620 $nullRevId = $nullRevision->insertOn( $dbw );
3621
3622 # Change the name of the target page:
3623 $dbw->update( 'page',
3624 /* SET */ array(
3625 'page_namespace' => $nt->getNamespace(),
3626 'page_title' => $nt->getDBkey(),
3627 ),
3628 /* WHERE */ array( 'page_id' => $oldid ),
3629 __METHOD__
3630 );
3631
3632 $this->resetArticleID( 0 );
3633 $nt->resetArticleID( $oldid );
3634
3635 $newpage->updateRevisionOn( $dbw, $nullRevision );
3636
3637 wfRunHooks( 'NewRevisionFromEditComplete',
3638 array( $newpage, $nullRevision, $nullRevision->getParentId(), $wgUser ) );
3639
3640 $newpage->doEditUpdates( $nullRevision, $wgUser, array( 'changed' => false ) );
3641
3642 if ( !$moveOverRedirect ) {
3643 WikiPage::onArticleCreate( $nt );
3644 }
3645
3646 # Recreate the redirect, this time in the other direction.
3647 if ( $redirectSuppressed ) {
3648 WikiPage::onArticleDelete( $this );
3649 } else {
3650 $mwRedir = MagicWord::get( 'redirect' );
3651 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
3652 $redirectArticle = WikiPage::factory( $this );
3653 $newid = $redirectArticle->insertOn( $dbw );
3654 if ( $newid ) { // sanity
3655 $redirectRevision = new Revision( array(
3656 'page' => $newid,
3657 'comment' => $comment,
3658 'text' => $redirectText ) );
3659 $redirectRevision->insertOn( $dbw );
3660 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
3661
3662 wfRunHooks( 'NewRevisionFromEditComplete',
3663 array( $redirectArticle, $redirectRevision, false, $wgUser ) );
3664
3665 $redirectArticle->doEditUpdates( $redirectRevision, $wgUser, array( 'created' => true ) );
3666 }
3667 }
3668
3669 # Log the move
3670 $logid = $logEntry->insert();
3671 $logEntry->publish( $logid );
3672 }
3673
3674 /**
3675 * Move this page's subpages to be subpages of $nt
3676 *
3677 * @param $nt Title Move target
3678 * @param $auth bool Whether $wgUser's permissions should be checked
3679 * @param $reason string The reason for the move
3680 * @param $createRedirect bool Whether to create redirects from the old subpages to
3681 * the new ones Ignored if the user doesn't have the 'suppressredirect' right
3682 * @return mixed array with old page titles as keys, and strings (new page titles) or
3683 * arrays (errors) as values, or an error array with numeric indices if no pages
3684 * were moved
3685 */
3686 public function moveSubpages( $nt, $auth = true, $reason = '', $createRedirect = true ) {
3687 global $wgMaximumMovedPages;
3688 // Check permissions
3689 if ( !$this->userCan( 'move-subpages' ) ) {
3690 return array( 'cant-move-subpages' );
3691 }
3692 // Do the source and target namespaces support subpages?
3693 if ( !MWNamespace::hasSubpages( $this->getNamespace() ) ) {
3694 return array( 'namespace-nosubpages',
3695 MWNamespace::getCanonicalName( $this->getNamespace() ) );
3696 }
3697 if ( !MWNamespace::hasSubpages( $nt->getNamespace() ) ) {
3698 return array( 'namespace-nosubpages',
3699 MWNamespace::getCanonicalName( $nt->getNamespace() ) );
3700 }
3701
3702 $subpages = $this->getSubpages( $wgMaximumMovedPages + 1 );
3703 $retval = array();
3704 $count = 0;
3705 foreach ( $subpages as $oldSubpage ) {
3706 $count++;
3707 if ( $count > $wgMaximumMovedPages ) {
3708 $retval[$oldSubpage->getPrefixedTitle()] =
3709 array( 'movepage-max-pages',
3710 $wgMaximumMovedPages );
3711 break;
3712 }
3713
3714 // We don't know whether this function was called before
3715 // or after moving the root page, so check both
3716 // $this and $nt
3717 if ( $oldSubpage->getArticleId() == $this->getArticleId() ||
3718 $oldSubpage->getArticleID() == $nt->getArticleId() )
3719 {
3720 // When moving a page to a subpage of itself,
3721 // don't move it twice
3722 continue;
3723 }
3724 $newPageName = preg_replace(
3725 '#^' . preg_quote( $this->getDBkey(), '#' ) . '#',
3726 StringUtils::escapeRegexReplacement( $nt->getDBkey() ), # bug 21234
3727 $oldSubpage->getDBkey() );
3728 if ( $oldSubpage->isTalkPage() ) {
3729 $newNs = $nt->getTalkPage()->getNamespace();
3730 } else {
3731 $newNs = $nt->getSubjectPage()->getNamespace();
3732 }
3733 # Bug 14385: we need makeTitleSafe because the new page names may
3734 # be longer than 255 characters.
3735 $newSubpage = Title::makeTitleSafe( $newNs, $newPageName );
3736
3737 $success = $oldSubpage->moveTo( $newSubpage, $auth, $reason, $createRedirect );
3738 if ( $success === true ) {
3739 $retval[$oldSubpage->getPrefixedText()] = $newSubpage->getPrefixedText();
3740 } else {
3741 $retval[$oldSubpage->getPrefixedText()] = $success;
3742 }
3743 }
3744 return $retval;
3745 }
3746
3747 /**
3748 * Checks if this page is just a one-rev redirect.
3749 * Adds lock, so don't use just for light purposes.
3750 *
3751 * @return Bool
3752 */
3753 public function isSingleRevRedirect() {
3754 $dbw = wfGetDB( DB_MASTER );
3755 # Is it a redirect?
3756 $row = $dbw->selectRow( 'page',
3757 array( 'page_is_redirect', 'page_latest', 'page_id' ),
3758 $this->pageCond(),
3759 __METHOD__,
3760 array( 'FOR UPDATE' )
3761 );
3762 # Cache some fields we may want
3763 $this->mArticleID = $row ? intval( $row->page_id ) : 0;
3764 $this->mRedirect = $row ? (bool)$row->page_is_redirect : false;
3765 $this->mLatestID = $row ? intval( $row->page_latest ) : false;
3766 if ( !$this->mRedirect ) {
3767 return false;
3768 }
3769 # Does the article have a history?
3770 $row = $dbw->selectField( array( 'page', 'revision' ),
3771 'rev_id',
3772 array( 'page_namespace' => $this->getNamespace(),
3773 'page_title' => $this->getDBkey(),
3774 'page_id=rev_page',
3775 'page_latest != rev_id'
3776 ),
3777 __METHOD__,
3778 array( 'FOR UPDATE' )
3779 );
3780 # Return true if there was no history
3781 return ( $row === false );
3782 }
3783
3784 /**
3785 * Checks if $this can be moved to a given Title
3786 * - Selects for update, so don't call it unless you mean business
3787 *
3788 * @param $nt Title the new title to check
3789 * @return Bool
3790 */
3791 public function isValidMoveTarget( $nt ) {
3792 # Is it an existing file?
3793 if ( $nt->getNamespace() == NS_FILE ) {
3794 $file = wfLocalFile( $nt );
3795 if ( $file->exists() ) {
3796 wfDebug( __METHOD__ . ": file exists\n" );
3797 return false;
3798 }
3799 }
3800 # Is it a redirect with no history?
3801 if ( !$nt->isSingleRevRedirect() ) {
3802 wfDebug( __METHOD__ . ": not a one-rev redirect\n" );
3803 return false;
3804 }
3805 # Get the article text
3806 $rev = Revision::newFromTitle( $nt );
3807 if( !is_object( $rev ) ){
3808 return false;
3809 }
3810 $text = $rev->getText();
3811 # Does the redirect point to the source?
3812 # Or is it a broken self-redirect, usually caused by namespace collisions?
3813 $m = array();
3814 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $text, $m ) ) {
3815 $redirTitle = Title::newFromText( $m[1] );
3816 if ( !is_object( $redirTitle ) ||
3817 ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
3818 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) ) {
3819 wfDebug( __METHOD__ . ": redirect points to other page\n" );
3820 return false;
3821 }
3822 } else {
3823 # Fail safe
3824 wfDebug( __METHOD__ . ": failsafe\n" );
3825 return false;
3826 }
3827 return true;
3828 }
3829
3830 /**
3831 * Get categories to which this Title belongs and return an array of
3832 * categories' names.
3833 *
3834 * @return Array of parents in the form:
3835 * $parent => $currentarticle
3836 */
3837 public function getParentCategories() {
3838 global $wgContLang;
3839
3840 $data = array();
3841
3842 $titleKey = $this->getArticleId();
3843
3844 if ( $titleKey === 0 ) {
3845 return $data;
3846 }
3847
3848 $dbr = wfGetDB( DB_SLAVE );
3849
3850 $res = $dbr->select( 'categorylinks', '*',
3851 array(
3852 'cl_from' => $titleKey,
3853 ),
3854 __METHOD__,
3855 array()
3856 );
3857
3858 if ( $dbr->numRows( $res ) > 0 ) {
3859 foreach ( $res as $row ) {
3860 // $data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$row->cl_to);
3861 $data[$wgContLang->getNSText( NS_CATEGORY ) . ':' . $row->cl_to] = $this->getFullText();
3862 }
3863 }
3864 return $data;
3865 }
3866
3867 /**
3868 * Get a tree of parent categories
3869 *
3870 * @param $children Array with the children in the keys, to check for circular refs
3871 * @return Array Tree of parent categories
3872 */
3873 public function getParentCategoryTree( $children = array() ) {
3874 $stack = array();
3875 $parents = $this->getParentCategories();
3876
3877 if ( $parents ) {
3878 foreach ( $parents as $parent => $current ) {
3879 if ( array_key_exists( $parent, $children ) ) {
3880 # Circular reference
3881 $stack[$parent] = array();
3882 } else {
3883 $nt = Title::newFromText( $parent );
3884 if ( $nt ) {
3885 $stack[$parent] = $nt->getParentCategoryTree( $children + array( $parent => 1 ) );
3886 }
3887 }
3888 }
3889 }
3890
3891 return $stack;
3892 }
3893
3894 /**
3895 * Get an associative array for selecting this title from
3896 * the "page" table
3897 *
3898 * @return Array suitable for the $where parameter of DB::select()
3899 */
3900 public function pageCond() {
3901 if ( $this->mArticleID > 0 ) {
3902 // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs
3903 return array( 'page_id' => $this->mArticleID );
3904 } else {
3905 return array( 'page_namespace' => $this->mNamespace, 'page_title' => $this->mDbkeyform );
3906 }
3907 }
3908
3909 /**
3910 * Get the revision ID of the previous revision
3911 *
3912 * @param $revId Int Revision ID. Get the revision that was before this one.
3913 * @param $flags Int Title::GAID_FOR_UPDATE
3914 * @return Int|Bool Old revision ID, or FALSE if none exists
3915 */
3916 public function getPreviousRevisionID( $revId, $flags = 0 ) {
3917 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
3918 return $db->selectField( 'revision', 'rev_id',
3919 array(
3920 'rev_page' => $this->getArticleId( $flags ),
3921 'rev_id < ' . intval( $revId )
3922 ),
3923 __METHOD__,
3924 array( 'ORDER BY' => 'rev_id DESC' )
3925 );
3926 }
3927
3928 /**
3929 * Get the revision ID of the next revision
3930 *
3931 * @param $revId Int Revision ID. Get the revision that was after this one.
3932 * @param $flags Int Title::GAID_FOR_UPDATE
3933 * @return Int|Bool Next revision ID, or FALSE if none exists
3934 */
3935 public function getNextRevisionID( $revId, $flags = 0 ) {
3936 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
3937 return $db->selectField( 'revision', 'rev_id',
3938 array(
3939 'rev_page' => $this->getArticleId( $flags ),
3940 'rev_id > ' . intval( $revId )
3941 ),
3942 __METHOD__,
3943 array( 'ORDER BY' => 'rev_id' )
3944 );
3945 }
3946
3947 /**
3948 * Get the first revision of the page
3949 *
3950 * @param $flags Int Title::GAID_FOR_UPDATE
3951 * @return Revision|Null if page doesn't exist
3952 */
3953 public function getFirstRevision( $flags = 0 ) {
3954 $pageId = $this->getArticleId( $flags );
3955 if ( $pageId ) {
3956 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
3957 $row = $db->selectRow( 'revision', '*',
3958 array( 'rev_page' => $pageId ),
3959 __METHOD__,
3960 array( 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 1 )
3961 );
3962 if ( $row ) {
3963 return new Revision( $row );
3964 }
3965 }
3966 return null;
3967 }
3968
3969 /**
3970 * Get the oldest revision timestamp of this page
3971 *
3972 * @param $flags Int Title::GAID_FOR_UPDATE
3973 * @return String: MW timestamp
3974 */
3975 public function getEarliestRevTime( $flags = 0 ) {
3976 $rev = $this->getFirstRevision( $flags );
3977 return $rev ? $rev->getTimestamp() : null;
3978 }
3979
3980 /**
3981 * Check if this is a new page
3982 *
3983 * @return bool
3984 */
3985 public function isNewPage() {
3986 $dbr = wfGetDB( DB_SLAVE );
3987 return (bool)$dbr->selectField( 'page', 'page_is_new', $this->pageCond(), __METHOD__ );
3988 }
3989
3990 /**
3991 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
3992 *
3993 * @return bool
3994 */
3995 public function isBigDeletion() {
3996 global $wgDeleteRevisionsLimit;
3997
3998 if ( !$wgDeleteRevisionsLimit ) {
3999 return false;
4000 }
4001
4002 $revCount = $this->estimateRevisionCount();
4003 return $revCount > $wgDeleteRevisionsLimit;
4004 }
4005
4006 /**
4007 * Get the approximate revision count of this page.
4008 *
4009 * @return int
4010 */
4011 public function estimateRevisionCount() {
4012 if ( !$this->exists() ) {
4013 return 0;
4014 }
4015
4016 if ( $this->mEstimateRevisions === null ) {
4017 $dbr = wfGetDB( DB_SLAVE );
4018 $this->mEstimateRevisions = $dbr->estimateRowCount( 'revision', '*',
4019 array( 'rev_page' => $this->getArticleId() ), __METHOD__ );
4020 }
4021
4022 return $this->mEstimateRevisions;
4023 }
4024
4025 /**
4026 * Get the number of revisions between the given revision.
4027 * Used for diffs and other things that really need it.
4028 *
4029 * @param $old int|Revision Old revision or rev ID (first before range)
4030 * @param $new int|Revision New revision or rev ID (first after range)
4031 * @return Int Number of revisions between these revisions.
4032 */
4033 public function countRevisionsBetween( $old, $new ) {
4034 if ( !( $old instanceof Revision ) ) {
4035 $old = Revision::newFromTitle( $this, (int)$old );
4036 }
4037 if ( !( $new instanceof Revision ) ) {
4038 $new = Revision::newFromTitle( $this, (int)$new );
4039 }
4040 if ( !$old || !$new ) {
4041 return 0; // nothing to compare
4042 }
4043 $dbr = wfGetDB( DB_SLAVE );
4044 return (int)$dbr->selectField( 'revision', 'count(*)',
4045 array(
4046 'rev_page' => $this->getArticleId(),
4047 'rev_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4048 'rev_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4049 ),
4050 __METHOD__
4051 );
4052 }
4053
4054 /**
4055 * Get the number of authors between the given revision IDs.
4056 * Used for diffs and other things that really need it.
4057 *
4058 * @param $old int|Revision Old revision or rev ID (first before range)
4059 * @param $new int|Revision New revision or rev ID (first after range)
4060 * @param $limit Int Maximum number of authors
4061 * @return Int Number of revision authors between these revisions.
4062 */
4063 public function countAuthorsBetween( $old, $new, $limit ) {
4064 if ( !( $old instanceof Revision ) ) {
4065 $old = Revision::newFromTitle( $this, (int)$old );
4066 }
4067 if ( !( $new instanceof Revision ) ) {
4068 $new = Revision::newFromTitle( $this, (int)$new );
4069 }
4070 if ( !$old || !$new ) {
4071 return 0; // nothing to compare
4072 }
4073 $dbr = wfGetDB( DB_SLAVE );
4074 $res = $dbr->select( 'revision', 'DISTINCT rev_user_text',
4075 array(
4076 'rev_page' => $this->getArticleID(),
4077 'rev_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4078 'rev_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4079 ), __METHOD__,
4080 array( 'LIMIT' => $limit + 1 ) // add one so caller knows it was truncated
4081 );
4082 return (int)$dbr->numRows( $res );
4083 }
4084
4085 /**
4086 * Compare with another title.
4087 *
4088 * @param $title Title
4089 * @return Bool
4090 */
4091 public function equals( Title $title ) {
4092 // Note: === is necessary for proper matching of number-like titles.
4093 return $this->getInterwiki() === $title->getInterwiki()
4094 && $this->getNamespace() == $title->getNamespace()
4095 && $this->getDBkey() === $title->getDBkey();
4096 }
4097
4098 /**
4099 * Check if this title is a subpage of another title
4100 *
4101 * @param $title Title
4102 * @return Bool
4103 */
4104 public function isSubpageOf( Title $title ) {
4105 return $this->getInterwiki() === $title->getInterwiki()
4106 && $this->getNamespace() == $title->getNamespace()
4107 && strpos( $this->getDBkey(), $title->getDBkey() . '/' ) === 0;
4108 }
4109
4110 /**
4111 * Check if page exists. For historical reasons, this function simply
4112 * checks for the existence of the title in the page table, and will
4113 * thus return false for interwiki links, special pages and the like.
4114 * If you want to know if a title can be meaningfully viewed, you should
4115 * probably call the isKnown() method instead.
4116 *
4117 * @return Bool
4118 */
4119 public function exists() {
4120 return $this->getArticleId() != 0;
4121 }
4122
4123 /**
4124 * Should links to this title be shown as potentially viewable (i.e. as
4125 * "bluelinks"), even if there's no record by this title in the page
4126 * table?
4127 *
4128 * This function is semi-deprecated for public use, as well as somewhat
4129 * misleadingly named. You probably just want to call isKnown(), which
4130 * calls this function internally.
4131 *
4132 * (ISSUE: Most of these checks are cheap, but the file existence check
4133 * can potentially be quite expensive. Including it here fixes a lot of
4134 * existing code, but we might want to add an optional parameter to skip
4135 * it and any other expensive checks.)
4136 *
4137 * @return Bool
4138 */
4139 public function isAlwaysKnown() {
4140 $isKnown = null;
4141
4142 /**
4143 * Allows overriding default behaviour for determining if a page exists.
4144 * If $isKnown is kept as null, regular checks happen. If it's
4145 * a boolean, this value is returned by the isKnown method.
4146 *
4147 * @since 1.20
4148 *
4149 * @param Title $title
4150 * @param boolean|null $isKnown
4151 */
4152 wfRunHooks( 'TitleIsAlwaysKnown', array( $this, &$isKnown ) );
4153
4154 if ( !is_null( $isKnown ) ) {
4155 return $isKnown;
4156 }
4157
4158 if ( $this->mInterwiki != '' ) {
4159 return true; // any interwiki link might be viewable, for all we know
4160 }
4161
4162 switch( $this->mNamespace ) {
4163 case NS_MEDIA:
4164 case NS_FILE:
4165 // file exists, possibly in a foreign repo
4166 return (bool)wfFindFile( $this );
4167 case NS_SPECIAL:
4168 // valid special page
4169 return SpecialPageFactory::exists( $this->getDBkey() );
4170 case NS_MAIN:
4171 // selflink, possibly with fragment
4172 return $this->mDbkeyform == '';
4173 case NS_MEDIAWIKI:
4174 // known system message
4175 return $this->hasSourceText() !== false;
4176 default:
4177 return false;
4178 }
4179 }
4180
4181 /**
4182 * Does this title refer to a page that can (or might) be meaningfully
4183 * viewed? In particular, this function may be used to determine if
4184 * links to the title should be rendered as "bluelinks" (as opposed to
4185 * "redlinks" to non-existent pages).
4186 * Adding something else to this function will cause inconsistency
4187 * since LinkHolderArray calls isAlwaysKnown() and does its own
4188 * page existence check.
4189 *
4190 * @return Bool
4191 */
4192 public function isKnown() {
4193 return $this->isAlwaysKnown() || $this->exists();
4194 }
4195
4196 /**
4197 * Does this page have source text?
4198 *
4199 * @return Boolean
4200 */
4201 public function hasSourceText() {
4202 if ( $this->exists() ) {
4203 return true;
4204 }
4205
4206 if ( $this->mNamespace == NS_MEDIAWIKI ) {
4207 // If the page doesn't exist but is a known system message, default
4208 // message content will be displayed, same for language subpages-
4209 // Use always content language to avoid loading hundreds of languages
4210 // to get the link color.
4211 global $wgContLang;
4212 list( $name, $lang ) = MessageCache::singleton()->figureMessage( $wgContLang->lcfirst( $this->getText() ) );
4213 $message = wfMessage( $name )->inLanguage( $wgContLang )->useDatabase( false );
4214 return $message->exists();
4215 }
4216
4217 return false;
4218 }
4219
4220 /**
4221 * Get the default message text or false if the message doesn't exist
4222 *
4223 * @return String or false
4224 */
4225 public function getDefaultMessageText() {
4226 global $wgContLang;
4227
4228 if ( $this->getNamespace() != NS_MEDIAWIKI ) { // Just in case
4229 return false;
4230 }
4231
4232 list( $name, $lang ) = MessageCache::singleton()->figureMessage( $wgContLang->lcfirst( $this->getText() ) );
4233 $message = wfMessage( $name )->inLanguage( $lang )->useDatabase( false );
4234
4235 if ( $message->exists() ) {
4236 return $message->plain();
4237 } else {
4238 return false;
4239 }
4240 }
4241
4242 /**
4243 * Updates page_touched for this page; called from LinksUpdate.php
4244 *
4245 * @return Bool true if the update succeded
4246 */
4247 public function invalidateCache() {
4248 if ( wfReadOnly() ) {
4249 return false;
4250 }
4251 $dbw = wfGetDB( DB_MASTER );
4252 $success = $dbw->update(
4253 'page',
4254 array( 'page_touched' => $dbw->timestamp() ),
4255 $this->pageCond(),
4256 __METHOD__
4257 );
4258 HTMLFileCache::clearFileCache( $this );
4259 return $success;
4260 }
4261
4262 /**
4263 * Update page_touched timestamps and send squid purge messages for
4264 * pages linking to this title. May be sent to the job queue depending
4265 * on the number of links. Typically called on create and delete.
4266 */
4267 public function touchLinks() {
4268 $u = new HTMLCacheUpdate( $this, 'pagelinks' );
4269 $u->doUpdate();
4270
4271 if ( $this->getNamespace() == NS_CATEGORY ) {
4272 $u = new HTMLCacheUpdate( $this, 'categorylinks' );
4273 $u->doUpdate();
4274 }
4275 }
4276
4277 /**
4278 * Get the last touched timestamp
4279 *
4280 * @param $db DatabaseBase: optional db
4281 * @return String last-touched timestamp
4282 */
4283 public function getTouched( $db = null ) {
4284 $db = isset( $db ) ? $db : wfGetDB( DB_SLAVE );
4285 $touched = $db->selectField( 'page', 'page_touched', $this->pageCond(), __METHOD__ );
4286 return $touched;
4287 }
4288
4289 /**
4290 * Get the timestamp when this page was updated since the user last saw it.
4291 *
4292 * @param $user User
4293 * @return String|Null
4294 */
4295 public function getNotificationTimestamp( $user = null ) {
4296 global $wgUser, $wgShowUpdatedMarker;
4297 // Assume current user if none given
4298 if ( !$user ) {
4299 $user = $wgUser;
4300 }
4301 // Check cache first
4302 $uid = $user->getId();
4303 // avoid isset here, as it'll return false for null entries
4304 if ( array_key_exists( $uid, $this->mNotificationTimestamp ) ) {
4305 return $this->mNotificationTimestamp[$uid];
4306 }
4307 if ( !$uid || !$wgShowUpdatedMarker ) {
4308 return $this->mNotificationTimestamp[$uid] = false;
4309 }
4310 // Don't cache too much!
4311 if ( count( $this->mNotificationTimestamp ) >= self::CACHE_MAX ) {
4312 $this->mNotificationTimestamp = array();
4313 }
4314 $dbr = wfGetDB( DB_SLAVE );
4315 $this->mNotificationTimestamp[$uid] = $dbr->selectField( 'watchlist',
4316 'wl_notificationtimestamp',
4317 array( 'wl_namespace' => $this->getNamespace(),
4318 'wl_title' => $this->getDBkey(),
4319 'wl_user' => $user->getId()
4320 ),
4321 __METHOD__
4322 );
4323 return $this->mNotificationTimestamp[$uid];
4324 }
4325
4326 /**
4327 * Generate strings used for xml 'id' names in monobook tabs
4328 *
4329 * @param $prepend string defaults to 'nstab-'
4330 * @return String XML 'id' name
4331 */
4332 public function getNamespaceKey( $prepend = 'nstab-' ) {
4333 global $wgContLang;
4334 // Gets the subject namespace if this title
4335 $namespace = MWNamespace::getSubject( $this->getNamespace() );
4336 // Checks if cononical namespace name exists for namespace
4337 if ( MWNamespace::exists( $this->getNamespace() ) ) {
4338 // Uses canonical namespace name
4339 $namespaceKey = MWNamespace::getCanonicalName( $namespace );
4340 } else {
4341 // Uses text of namespace
4342 $namespaceKey = $this->getSubjectNsText();
4343 }
4344 // Makes namespace key lowercase
4345 $namespaceKey = $wgContLang->lc( $namespaceKey );
4346 // Uses main
4347 if ( $namespaceKey == '' ) {
4348 $namespaceKey = 'main';
4349 }
4350 // Changes file to image for backwards compatibility
4351 if ( $namespaceKey == 'file' ) {
4352 $namespaceKey = 'image';
4353 }
4354 return $prepend . $namespaceKey;
4355 }
4356
4357 /**
4358 * Get all extant redirects to this Title
4359 *
4360 * @param $ns Int|Null Single namespace to consider; NULL to consider all namespaces
4361 * @return Array of Title redirects to this title
4362 */
4363 public function getRedirectsHere( $ns = null ) {
4364 $redirs = array();
4365
4366 $dbr = wfGetDB( DB_SLAVE );
4367 $where = array(
4368 'rd_namespace' => $this->getNamespace(),
4369 'rd_title' => $this->getDBkey(),
4370 'rd_from = page_id'
4371 );
4372 if ( !is_null( $ns ) ) {
4373 $where['page_namespace'] = $ns;
4374 }
4375
4376 $res = $dbr->select(
4377 array( 'redirect', 'page' ),
4378 array( 'page_namespace', 'page_title' ),
4379 $where,
4380 __METHOD__
4381 );
4382
4383 foreach ( $res as $row ) {
4384 $redirs[] = self::newFromRow( $row );
4385 }
4386 return $redirs;
4387 }
4388
4389 /**
4390 * Check if this Title is a valid redirect target
4391 *
4392 * @return Bool
4393 */
4394 public function isValidRedirectTarget() {
4395 global $wgInvalidRedirectTargets;
4396
4397 // invalid redirect targets are stored in a global array, but explicity disallow Userlogout here
4398 if ( $this->isSpecial( 'Userlogout' ) ) {
4399 return false;
4400 }
4401
4402 foreach ( $wgInvalidRedirectTargets as $target ) {
4403 if ( $this->isSpecial( $target ) ) {
4404 return false;
4405 }
4406 }
4407
4408 return true;
4409 }
4410
4411 /**
4412 * Get a backlink cache object
4413 *
4414 * @return BacklinkCache
4415 */
4416 function getBacklinkCache() {
4417 if ( is_null( $this->mBacklinkCache ) ) {
4418 $this->mBacklinkCache = new BacklinkCache( $this );
4419 }
4420 return $this->mBacklinkCache;
4421 }
4422
4423 /**
4424 * Whether the magic words __INDEX__ and __NOINDEX__ function for this page.
4425 *
4426 * @return Boolean
4427 */
4428 public function canUseNoindex() {
4429 global $wgContentNamespaces, $wgExemptFromUserRobotsControl;
4430
4431 $bannedNamespaces = is_null( $wgExemptFromUserRobotsControl )
4432 ? $wgContentNamespaces
4433 : $wgExemptFromUserRobotsControl;
4434
4435 return !in_array( $this->mNamespace, $bannedNamespaces );
4436
4437 }
4438
4439 /**
4440 * Returns the raw sort key to be used for categories, with the specified
4441 * prefix. This will be fed to Collation::getSortKey() to get a
4442 * binary sortkey that can be used for actual sorting.
4443 *
4444 * @param $prefix string The prefix to be used, specified using
4445 * {{defaultsort:}} or like [[Category:Foo|prefix]]. Empty for no
4446 * prefix.
4447 * @return string
4448 */
4449 public function getCategorySortkey( $prefix = '' ) {
4450 $unprefixed = $this->getText();
4451
4452 // Anything that uses this hook should only depend
4453 // on the Title object passed in, and should probably
4454 // tell the users to run updateCollations.php --force
4455 // in order to re-sort existing category relations.
4456 wfRunHooks( 'GetDefaultSortkey', array( $this, &$unprefixed ) );
4457 if ( $prefix !== '' ) {
4458 # Separate with a line feed, so the unprefixed part is only used as
4459 # a tiebreaker when two pages have the exact same prefix.
4460 # In UCA, tab is the only character that can sort above LF
4461 # so we strip both of them from the original prefix.
4462 $prefix = strtr( $prefix, "\n\t", ' ' );
4463 return "$prefix\n$unprefixed";
4464 }
4465 return $unprefixed;
4466 }
4467
4468 /**
4469 * Get the language in which the content of this page is written.
4470 * Defaults to $wgContLang, but in certain cases it can be e.g.
4471 * $wgLang (such as special pages, which are in the user language).
4472 *
4473 * @since 1.18
4474 * @return object Language
4475 */
4476 public function getPageLanguage() {
4477 global $wgLang;
4478 if ( $this->isSpecialPage() ) {
4479 // special pages are in the user language
4480 return $wgLang;
4481 } elseif ( $this->isCssOrJsPage() || $this->isCssJsSubpage() ) {
4482 // css/js should always be LTR and is, in fact, English
4483 return wfGetLangObj( 'en' );
4484 } elseif ( $this->getNamespace() == NS_MEDIAWIKI ) {
4485 // Parse mediawiki messages with correct target language
4486 list( /* $unused */, $lang ) = MessageCache::singleton()->figureMessage( $this->getText() );
4487 return wfGetLangObj( $lang );
4488 }
4489 global $wgContLang;
4490 // If nothing special, it should be in the wiki content language
4491 $pageLang = $wgContLang;
4492 // Hook at the end because we don't want to override the above stuff
4493 wfRunHooks( 'PageContentLanguage', array( $this, &$pageLang, $wgLang ) );
4494 return wfGetLangObj( $pageLang );
4495 }
4496 }