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