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