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