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