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