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