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