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