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