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