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