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