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