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