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