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