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