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