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