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