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