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