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