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