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