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