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