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