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