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