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