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