Make getSubjectPage return $this if the title is the same. This avoids process cache...
[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 //@}
72
73
74 /**
75 * Constructor
76 * @private
77 */
78 /* private */ function __construct() {}
79
80 /**
81 * Create a new Title from a prefixed DB key
82 * @param $key \type{\string} The database key, which has underscores
83 * instead of spaces, possibly including namespace and
84 * interwiki prefixes
85 * @return \type{Title} the new object, or NULL on an error
86 */
87 public static function newFromDBkey( $key ) {
88 $t = new Title();
89 $t->mDbkeyform = $key;
90 if( $t->secureAndSplit() )
91 return $t;
92 else
93 return NULL;
94 }
95
96 /**
97 * Create a new Title from text, such as what one would find in a link. De-
98 * codes any HTML entities in the text.
99 *
100 * @param $text string The link text; spaces, prefixes, and an
101 * initial ':' indicating the main namespace are accepted.
102 * @param $defaultNamespace int The namespace to use if none is speci-
103 * fied by a prefix. If you want to force a specific namespace even if
104 * $text might begin with a namespace prefix, use makeTitle() or
105 * makeTitleSafe().
106 * @return Title The new object, or null on an error.
107 */
108 public static function newFromText( $text, $defaultNamespace = NS_MAIN ) {
109 if( is_object( $text ) ) {
110 throw new MWException( 'Title::newFromText given an object' );
111 }
112
113 /**
114 * Wiki pages often contain multiple links to the same page.
115 * Title normalization and parsing can become expensive on
116 * pages with many links, so we can save a little time by
117 * caching them.
118 *
119 * In theory these are value objects and won't get changed...
120 */
121 if( $defaultNamespace == NS_MAIN && isset( Title::$titleCache[$text] ) ) {
122 return Title::$titleCache[$text];
123 }
124
125 /**
126 * Convert things like &eacute; &#257; or &#x3017; into real text...
127 */
128 $filteredText = Sanitizer::decodeCharReferences( $text );
129
130 $t = new Title();
131 $t->mDbkeyform = str_replace( ' ', '_', $filteredText );
132 $t->mDefaultNamespace = $defaultNamespace;
133
134 static $cachedcount = 0 ;
135 if( $t->secureAndSplit() ) {
136 if( $defaultNamespace == NS_MAIN ) {
137 if( $cachedcount >= self::CACHE_MAX ) {
138 # Avoid memory leaks on mass operations...
139 Title::$titleCache = array();
140 $cachedcount=0;
141 }
142 $cachedcount++;
143 Title::$titleCache[$text] =& $t;
144 }
145 return $t;
146 } else {
147 $ret = NULL;
148 return $ret;
149 }
150 }
151
152 /**
153 * Create a new Title from URL-encoded text. Ensures that
154 * the given title's length does not exceed the maximum.
155 * @param $url \type{\string} the title, as might be taken from a URL
156 * @return \type{Title} the new object, or NULL on an error
157 */
158 public static function newFromURL( $url ) {
159 global $wgLegalTitleChars;
160 $t = new Title();
161
162 # For compatibility with old buggy URLs. "+" is usually not valid in titles,
163 # but some URLs used it as a space replacement and they still come
164 # from some external search tools.
165 if ( strpos( $wgLegalTitleChars, '+' ) === false ) {
166 $url = str_replace( '+', ' ', $url );
167 }
168
169 $t->mDbkeyform = str_replace( ' ', '_', $url );
170 if( $t->secureAndSplit() ) {
171 return $t;
172 } else {
173 return NULL;
174 }
175 }
176
177 /**
178 * Create a new Title from an article ID
179 *
180 * @todo This is inefficiently implemented, the page row is requested
181 * but not used for anything else
182 *
183 * @param $id \type{\int} the page_id corresponding to the Title to create
184 * @param $flags \type{\int} use GAID_FOR_UPDATE to use master
185 * @return \type{Title} the new object, or NULL on an error
186 */
187 public static function newFromID( $id, $flags = 0 ) {
188 $fname = 'Title::newFromID';
189 $db = ($flags & GAID_FOR_UPDATE) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
190 $row = $db->selectRow( 'page', array( 'page_namespace', 'page_title' ),
191 array( 'page_id' => $id ), $fname );
192 if ( $row !== false ) {
193 $title = Title::makeTitle( $row->page_namespace, $row->page_title );
194 } else {
195 $title = NULL;
196 }
197 return $title;
198 }
199
200 /**
201 * Make an array of titles from an array of IDs
202 * @param $ids \type{\arrayof{\int}} Array of IDs
203 * @return \type{\arrayof{Title}} Array of Titles
204 */
205 public static function newFromIDs( $ids ) {
206 if ( !count( $ids ) ) {
207 return array();
208 }
209 $dbr = wfGetDB( DB_SLAVE );
210 $res = $dbr->select( 'page', array( 'page_namespace', 'page_title' ),
211 'page_id IN (' . $dbr->makeList( $ids ) . ')', __METHOD__ );
212
213 $titles = array();
214 foreach( $res as $row ) {
215 $titles[] = Title::makeTitle( $row->page_namespace, $row->page_title );
216 }
217 return $titles;
218 }
219
220 /**
221 * Make a Title object from a DB row
222 * @param $row \type{Row} (needs at least page_title,page_namespace)
223 * @return \type{Title} corresponding Title
224 */
225 public static function newFromRow( $row ) {
226 $t = self::makeTitle( $row->page_namespace, $row->page_title );
227
228 $t->mArticleID = isset($row->page_id) ? intval($row->page_id) : -1;
229 $t->mLength = isset($row->page_len) ? intval($row->page_len) : -1;
230 $t->mRedirect = isset($row->page_is_redirect) ? (bool)$row->page_is_redirect : NULL;
231 $t->mLatestID = isset($row->page_latest) ? $row->page_latest : false;
232
233 return $t;
234 }
235
236 /**
237 * Create a new Title from a namespace index and a DB key.
238 * It's assumed that $ns and $title are *valid*, for instance when
239 * they came directly from the database or a special page name.
240 * For convenience, spaces are converted to underscores so that
241 * eg user_text fields can be used directly.
242 *
243 * @param $ns \type{\int} the namespace of the article
244 * @param $title \type{\string} the unprefixed database key form
245 * @param $fragment \type{\string} The link fragment (after the "#")
246 * @return \type{Title} the new object
247 */
248 public static function &makeTitle( $ns, $title, $fragment = '' ) {
249 $t = new Title();
250 $t->mInterwiki = '';
251 $t->mFragment = $fragment;
252 $t->mNamespace = $ns = intval( $ns );
253 $t->mDbkeyform = str_replace( ' ', '_', $title );
254 $t->mArticleID = ( $ns >= 0 ) ? -1 : 0;
255 $t->mUrlform = wfUrlencode( $t->mDbkeyform );
256 $t->mTextform = str_replace( '_', ' ', $title );
257 return $t;
258 }
259
260 /**
261 * Create a new Title from a namespace index and a DB key.
262 * The parameters will be checked for validity, which is a bit slower
263 * than makeTitle() but safer for user-provided data.
264 *
265 * @param $ns \type{\int} the namespace of the article
266 * @param $title \type{\string} the database key form
267 * @param $fragment \type{\string} The link fragment (after the "#")
268 * @return \type{Title} the new object, or NULL on an error
269 */
270 public static function makeTitleSafe( $ns, $title, $fragment = '' ) {
271 $t = new Title();
272 $t->mDbkeyform = Title::makeName( $ns, $title, $fragment );
273 if( $t->secureAndSplit() ) {
274 return $t;
275 } else {
276 return NULL;
277 }
278 }
279
280 /**
281 * Create a new Title for the Main Page
282 * @return \type{Title} the new object
283 */
284 public static function newMainPage() {
285 $title = Title::newFromText( wfMsgForContent( 'mainpage' ) );
286 // Don't give fatal errors if the message is broken
287 if ( !$title ) {
288 $title = Title::newFromText( 'Main Page' );
289 }
290 return $title;
291 }
292
293 /**
294 * Extract a redirect destination from a string and return the
295 * Title, or null if the text doesn't contain a valid redirect
296 *
297 * @param $text \type{String} Text with possible redirect
298 * @return \type{Title} The corresponding Title
299 */
300 public static function newFromRedirect( $text ) {
301 $redir = MagicWord::get( 'redirect' );
302 $text = trim($text);
303 if( $redir->matchStartAndRemove( $text ) ) {
304 // Extract the first link and see if it's usable
305 // Ensure that it really does come directly after #REDIRECT
306 // Some older redirects included a colon, so don't freak about that!
307 $m = array();
308 if( preg_match( '!^\s*:?\s*\[{2}(.*?)(?:\|.*?)?\]{2}!', $text, $m ) ) {
309 // Strip preceding colon used to "escape" categories, etc.
310 // and URL-decode links
311 if( strpos( $m[1], '%' ) !== false ) {
312 // Match behavior of inline link parsing here;
313 // don't interpret + as " " most of the time!
314 // It might be safe to just use rawurldecode instead, though.
315 $m[1] = urldecode( ltrim( $m[1], ':' ) );
316 }
317 $title = Title::newFromText( $m[1] );
318 // Redirects to Special:Userlogout are not permitted
319 if( $title instanceof Title && !$title->isSpecial( 'Userlogout' ) )
320 return $title;
321 }
322 }
323 return null;
324 }
325
326 #----------------------------------------------------------------------------
327 # Static functions
328 #----------------------------------------------------------------------------
329
330 /**
331 * Get the prefixed DB key associated with an ID
332 * @param $id \type{\int} the page_id of the article
333 * @return \type{Title} an object representing the article, or NULL
334 * if no such article was found
335 */
336 public static function nameOf( $id ) {
337 $dbr = wfGetDB( DB_SLAVE );
338
339 $s = $dbr->selectRow( 'page', array( 'page_namespace','page_title' ), array( 'page_id' => $id ), __METHOD__ );
340 if ( $s === false ) { return NULL; }
341
342 $n = self::makeName( $s->page_namespace, $s->page_title );
343 return $n;
344 }
345
346 /**
347 * Get a regex character class describing the legal characters in a link
348 * @return \type{\string} the list of characters, not delimited
349 */
350 public static function legalChars() {
351 global $wgLegalTitleChars;
352 return $wgLegalTitleChars;
353 }
354
355 /**
356 * Get a string representation of a title suitable for
357 * including in a search index
358 *
359 * @param $ns \type{\int} a namespace index
360 * @param $title \type{\string} text-form main part
361 * @return \type{\string} a stripped-down title string ready for the
362 * search index
363 */
364 public static function indexTitle( $ns, $title ) {
365 global $wgContLang;
366
367 $lc = SearchEngine::legalSearchChars() . '&#;';
368 $t = $wgContLang->stripForSearch( $title );
369 $t = preg_replace( "/[^{$lc}]+/", ' ', $t );
370 $t = $wgContLang->lc( $t );
371
372 # Handle 's, s'
373 $t = preg_replace( "/([{$lc}]+)'s( |$)/", "\\1 \\1's ", $t );
374 $t = preg_replace( "/([{$lc}]+)s'( |$)/", "\\1s ", $t );
375
376 $t = preg_replace( "/\\s+/", ' ', $t );
377
378 if ( $ns == NS_IMAGE ) {
379 $t = preg_replace( "/ (png|gif|jpg|jpeg|ogg)$/", "", $t );
380 }
381 return trim( $t );
382 }
383
384 /*
385 * Make a prefixed DB key from a DB key and a namespace index
386 * @param $ns \type{\int} numerical representation of the namespace
387 * @param $title \type{\string} the DB key form the title
388 * @param $fragment \type{\string} The link fragment (after the "#")
389 * @return \type{\string} the prefixed form of the title
390 */
391 public static function makeName( $ns, $title, $fragment = '' ) {
392 global $wgContLang;
393
394 $namespace = $wgContLang->getNsText( $ns );
395 $name = $namespace == '' ? $title : "$namespace:$title";
396 if ( strval( $fragment ) != '' ) {
397 $name .= '#' . $fragment;
398 }
399 return $name;
400 }
401
402 /**
403 * Returns the URL associated with an interwiki prefix
404 * @param $key \type{\string} the interwiki prefix (e.g. "MeatBall")
405 * @return \type{\string} the associated URL, containing "$1",
406 * which should be replaced by an article title
407 * @static (arguably)
408 * @deprecated See Interwiki class
409 */
410 public function getInterwikiLink( $key ) {
411 return Interwiki::fetch( $key )->getURL( );
412 }
413
414 /**
415 * Determine whether the object refers to a page within
416 * this project.
417 *
418 * @return \type{\bool} TRUE if this is an in-project interwiki link
419 * or a wikilink, FALSE otherwise
420 */
421 public function isLocal() {
422 if ( $this->mInterwiki != '' ) {
423 return Interwiki::fetch( $this->mInterwiki )->isLocal();
424 } else {
425 return true;
426 }
427 }
428
429 /**
430 * Determine whether the object refers to a page within
431 * this project and is transcludable.
432 *
433 * @return \type{\bool} TRUE if this is transcludable
434 */
435 public function isTrans() {
436 if ($this->mInterwiki == '')
437 return false;
438
439 return Interwiki::fetch( $this->mInterwiki )->isTranscludable();
440 }
441
442 /**
443 * Escape a text fragment, say from a link, for a URL
444 */
445 static function escapeFragmentForURL( $fragment ) {
446 $fragment = str_replace( ' ', '_', $fragment );
447 $fragment = urlencode( Sanitizer::decodeCharReferences( $fragment ) );
448 $replaceArray = array(
449 '%3A' => ':',
450 '%' => '.'
451 );
452 return strtr( $fragment, $replaceArray );
453 }
454
455 #----------------------------------------------------------------------------
456 # Other stuff
457 #----------------------------------------------------------------------------
458
459 /** Simple accessors */
460 /**
461 * Get the text form (spaces not underscores) of the main part
462 * @return \type{\string} Main part of the title
463 */
464 public function getText() { return $this->mTextform; }
465 /**
466 * Get the URL-encoded form of the main part
467 * @return \type{\string} Main part of the title, URL-encoded
468 */
469 public function getPartialURL() { return $this->mUrlform; }
470 /**
471 * Get the main part with underscores
472 * @return \type{\string} Main part of the title, with underscores
473 */
474 public function getDBkey() { return $this->mDbkeyform; }
475 /**
476 * Get the namespace index, i.e.\ one of the NS_xxxx constants.
477 * @return \type{\int} Namespace index
478 */
479 public function getNamespace() { return $this->mNamespace; }
480 /**
481 * Get the namespace text
482 * @return \type{\string} Namespace text
483 */
484 public function getNsText() {
485 global $wgContLang, $wgCanonicalNamespaceNames;
486
487 if ( '' != $this->mInterwiki ) {
488 // This probably shouldn't even happen. ohh man, oh yuck.
489 // But for interwiki transclusion it sometimes does.
490 // Shit. Shit shit shit.
491 //
492 // Use the canonical namespaces if possible to try to
493 // resolve a foreign namespace.
494 if( isset( $wgCanonicalNamespaceNames[$this->mNamespace] ) ) {
495 return $wgCanonicalNamespaceNames[$this->mNamespace];
496 }
497 }
498 return $wgContLang->getNsText( $this->mNamespace );
499 }
500 /**
501 * Get the DB key with the initial letter case as specified by the user
502 * @return \type{\string} DB key
503 */
504 function getUserCaseDBKey() {
505 return $this->mUserCaseDBKey;
506 }
507 /**
508 * Get the namespace text of the subject (rather than talk) page
509 * @return \type{\string} Namespace text
510 */
511 public function getSubjectNsText() {
512 global $wgContLang;
513 return $wgContLang->getNsText( MWNamespace::getSubject( $this->mNamespace ) );
514 }
515 /**
516 * Get the namespace text of the talk page
517 * @return \type{\string} Namespace text
518 */
519 public function getTalkNsText() {
520 global $wgContLang;
521 return( $wgContLang->getNsText( MWNamespace::getTalk( $this->mNamespace ) ) );
522 }
523 /**
524 * Could this title have a corresponding talk page?
525 * @return \type{\bool} TRUE or FALSE
526 */
527 public function canTalk() {
528 return( MWNamespace::canTalk( $this->mNamespace ) );
529 }
530 /**
531 * Get the interwiki prefix (or null string)
532 * @return \type{\string} Interwiki prefix
533 */
534 public function getInterwiki() { return $this->mInterwiki; }
535 /**
536 * Get the Title fragment (i.e.\ the bit after the #) in text form
537 * @return \type{\string} Title fragment
538 */
539 public function getFragment() { return $this->mFragment; }
540 /**
541 * Get the fragment in URL form, including the "#" character if there is one
542 * @return \type{\string} Fragment in URL form
543 */
544 public function getFragmentForURL() {
545 if ( $this->mFragment == '' ) {
546 return '';
547 } else {
548 return '#' . Title::escapeFragmentForURL( $this->mFragment );
549 }
550 }
551 /**
552 * Get the default namespace index, for when there is no namespace
553 * @return \type{\int} Default namespace index
554 */
555 public function getDefaultNamespace() { return $this->mDefaultNamespace; }
556
557 /**
558 * Get title for search index
559 * @return \type{\string} a stripped-down title string ready for the
560 * search index
561 */
562 public function getIndexTitle() {
563 return Title::indexTitle( $this->mNamespace, $this->mTextform );
564 }
565
566 /**
567 * Get the prefixed database key form
568 * @return \type{\string} the prefixed title, with underscores and
569 * any interwiki and namespace prefixes
570 */
571 public function getPrefixedDBkey() {
572 $s = $this->prefix( $this->mDbkeyform );
573 $s = str_replace( ' ', '_', $s );
574 return $s;
575 }
576
577 /**
578 * Get the prefixed title with spaces.
579 * This is the form usually used for display
580 * @return \type{\string} the prefixed title, with spaces
581 */
582 public function getPrefixedText() {
583 if ( empty( $this->mPrefixedText ) ) { // FIXME: bad usage of empty() ?
584 $s = $this->prefix( $this->mTextform );
585 $s = str_replace( '_', ' ', $s );
586 $this->mPrefixedText = $s;
587 }
588 return $this->mPrefixedText;
589 }
590
591 /**
592 * Get the prefixed title with spaces, plus any fragment
593 * (part beginning with '#')
594 * @return \type{\string} the prefixed title, with spaces and
595 * the fragment, including '#'
596 */
597 public function getFullText() {
598 $text = $this->getPrefixedText();
599 if( '' != $this->mFragment ) {
600 $text .= '#' . $this->mFragment;
601 }
602 return $text;
603 }
604
605 /**
606 * Get the base name, i.e. the leftmost parts before the /
607 * @return \type{\string} Base name
608 */
609 public function getBaseText() {
610 if( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
611 return $this->getText();
612 }
613
614 $parts = explode( '/', $this->getText() );
615 # Don't discard the real title if there's no subpage involved
616 if( count( $parts ) > 1 )
617 unset( $parts[ count( $parts ) - 1 ] );
618 return implode( '/', $parts );
619 }
620
621 /**
622 * Get the lowest-level subpage name, i.e. the rightmost part after /
623 * @return \type{\string} Subpage name
624 */
625 public function getSubpageText() {
626 if( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
627 return( $this->mTextform );
628 }
629 $parts = explode( '/', $this->mTextform );
630 return( $parts[ count( $parts ) - 1 ] );
631 }
632
633 /**
634 * Get a URL-encoded form of the subpage text
635 * @return \type{\string} URL-encoded subpage name
636 */
637 public function getSubpageUrlForm() {
638 $text = $this->getSubpageText();
639 $text = wfUrlencode( str_replace( ' ', '_', $text ) );
640 $text = str_replace( '%28', '(', str_replace( '%29', ')', $text ) ); # Clean up the URL; per below, this might not be safe
641 return( $text );
642 }
643
644 /**
645 * Get a URL-encoded title (not an actual URL) including interwiki
646 * @return \type{\string} the URL-encoded form
647 */
648 public function getPrefixedURL() {
649 $s = $this->prefix( $this->mDbkeyform );
650 $s = str_replace( ' ', '_', $s );
651
652 $s = wfUrlencode ( $s ) ;
653
654 # Cleaning up URL to make it look nice -- is this safe?
655 $s = str_replace( '%28', '(', $s );
656 $s = str_replace( '%29', ')', $s );
657
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
1297 if ($row = $dbr->fetchRow( $res )) {
1298 return $row;
1299 } else {
1300 return false;
1301 }
1302 }
1303
1304 /**
1305 * Update the title protection status
1306 * @param $create_perm \type{\string} Permission required for creation
1307 * @param $reason \type{\string} Reason for protection
1308 * @param $expiry \type{\string} Expiry timestamp
1309 */
1310 public function updateTitleProtection( $create_perm, $reason, $expiry ) {
1311 global $wgUser,$wgContLang;
1312
1313 if ($create_perm == implode(',',$this->getRestrictions('create'))
1314 && $expiry == $this->mRestrictionsExpiry['create']) {
1315 // No change
1316 return true;
1317 }
1318
1319 list ($namespace, $title) = array( $this->getNamespace(), $this->getDBkey() );
1320
1321 $dbw = wfGetDB( DB_MASTER );
1322
1323 $encodedExpiry = Block::encodeExpiry($expiry, $dbw );
1324
1325 $expiry_description = '';
1326 if ( $encodedExpiry != 'infinity' ) {
1327 $expiry_description = ' (' . wfMsgForContent( 'protect-expiring', $wgContLang->timeanddate( $expiry ) ).')';
1328 }
1329 else {
1330 $expiry_description .= ' (' . wfMsgForContent( 'protect-expiry-indefinite' ).')';
1331 }
1332
1333 # Update protection table
1334 if ($create_perm != '' ) {
1335 $dbw->replace( 'protected_titles', array(array('pt_namespace', 'pt_title')),
1336 array( 'pt_namespace' => $namespace, 'pt_title' => $title
1337 , 'pt_create_perm' => $create_perm
1338 , 'pt_timestamp' => Block::encodeExpiry(wfTimestampNow(), $dbw)
1339 , 'pt_expiry' => $encodedExpiry
1340 , 'pt_user' => $wgUser->getId(), 'pt_reason' => $reason ), __METHOD__ );
1341 } else {
1342 $dbw->delete( 'protected_titles', array( 'pt_namespace' => $namespace,
1343 'pt_title' => $title ), __METHOD__ );
1344 }
1345 # Update the protection log
1346 $log = new LogPage( 'protect' );
1347
1348 if( $create_perm ) {
1349 $params = array("[create=$create_perm] $expiry_description",'');
1350 $log->addEntry( $this->mRestrictions['create'] ? 'modify' : 'protect', $this, trim( $reason ), $params );
1351 } else {
1352 $log->addEntry( 'unprotect', $this, $reason );
1353 }
1354
1355 return true;
1356 }
1357
1358 /**
1359 * Remove any title protection due to page existing
1360 */
1361 public function deleteTitleProtection() {
1362 $dbw = wfGetDB( DB_MASTER );
1363
1364 $dbw->delete( 'protected_titles',
1365 array ('pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey()), __METHOD__ );
1366 }
1367
1368 /**
1369 * Can $wgUser edit this page?
1370 * @return \type{\bool} TRUE or FALSE
1371 * @deprecated use userCan('edit')
1372 */
1373 public function userCanEdit( $doExpensiveQueries = true ) {
1374 return $this->userCan( 'edit', $doExpensiveQueries );
1375 }
1376
1377 /**
1378 * Can $wgUser create this page?
1379 * @return \type{\bool} TRUE or FALSE
1380 * @deprecated use userCan('create')
1381 */
1382 public function userCanCreate( $doExpensiveQueries = true ) {
1383 return $this->userCan( 'create', $doExpensiveQueries );
1384 }
1385
1386 /**
1387 * Can $wgUser move this page?
1388 * @return \type{\bool} TRUE or FALSE
1389 * @deprecated use userCan('move')
1390 */
1391 public function userCanMove( $doExpensiveQueries = true ) {
1392 return $this->userCan( 'move', $doExpensiveQueries );
1393 }
1394
1395 /**
1396 * Would anybody with sufficient privileges be able to move this page?
1397 * Some pages just aren't movable.
1398 *
1399 * @return \type{\bool} TRUE or FALSE
1400 */
1401 public function isMovable() {
1402 return MWNamespace::isMovable( $this->getNamespace() )
1403 && $this->getInterwiki() == '';
1404 }
1405
1406 /**
1407 * Can $wgUser read this page?
1408 * @return \type{\bool} TRUE or FALSE
1409 * @todo fold these checks into userCan()
1410 */
1411 public function userCanRead() {
1412 global $wgUser, $wgGroupPermissions;
1413
1414 $result = null;
1415 wfRunHooks( 'userCan', array( &$this, &$wgUser, 'read', &$result ) );
1416 if ( $result !== null ) {
1417 return $result;
1418 }
1419
1420 # Shortcut for public wikis, allows skipping quite a bit of code
1421 if ($wgGroupPermissions['*']['read'])
1422 return true;
1423
1424 if( $wgUser->isAllowed( 'read' ) ) {
1425 return true;
1426 } else {
1427 global $wgWhitelistRead;
1428
1429 /**
1430 * Always grant access to the login page.
1431 * Even anons need to be able to log in.
1432 */
1433 if( $this->isSpecial( 'Userlogin' ) || $this->isSpecial( 'Resetpass' ) ) {
1434 return true;
1435 }
1436
1437 /**
1438 * Bail out if there isn't whitelist
1439 */
1440 if( !is_array($wgWhitelistRead) ) {
1441 return false;
1442 }
1443
1444 /**
1445 * Check for explicit whitelisting
1446 */
1447 $name = $this->getPrefixedText();
1448 $dbName = $this->getPrefixedDBKey();
1449 // Check with and without underscores
1450 if( in_array($name,$wgWhitelistRead,true) || in_array($dbName,$wgWhitelistRead,true) )
1451 return true;
1452
1453 /**
1454 * Old settings might have the title prefixed with
1455 * a colon for main-namespace pages
1456 */
1457 if( $this->getNamespace() == NS_MAIN ) {
1458 if( in_array( ':' . $name, $wgWhitelistRead ) )
1459 return true;
1460 }
1461
1462 /**
1463 * If it's a special page, ditch the subpage bit
1464 * and check again
1465 */
1466 if( $this->getNamespace() == NS_SPECIAL ) {
1467 $name = $this->getDBkey();
1468 list( $name, /* $subpage */) = SpecialPage::resolveAliasWithSubpage( $name );
1469 if ( $name === false ) {
1470 # Invalid special page, but we show standard login required message
1471 return false;
1472 }
1473
1474 $pure = SpecialPage::getTitleFor( $name )->getPrefixedText();
1475 if( in_array( $pure, $wgWhitelistRead, true ) )
1476 return true;
1477 }
1478
1479 }
1480 return false;
1481 }
1482
1483 /**
1484 * Is this a talk page of some sort?
1485 * @return \type{\bool} TRUE or FALSE
1486 */
1487 public function isTalkPage() {
1488 return MWNamespace::isTalk( $this->getNamespace() );
1489 }
1490
1491 /**
1492 * Is this a subpage?
1493 * @return \type{\bool} TRUE or FALSE
1494 */
1495 public function isSubpage() {
1496 return MWNamespace::hasSubpages( $this->mNamespace )
1497 ? strpos( $this->getText(), '/' ) !== false
1498 : false;
1499 }
1500
1501 /**
1502 * Does this have subpages? (Warning, usually requires an extra DB query.)
1503 * @return \type{\bool} TRUE or FALSE
1504 */
1505 public function hasSubpages() {
1506 if( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
1507 # Duh
1508 return false;
1509 }
1510
1511 # We dynamically add a member variable for the purpose of this method
1512 # alone to cache the result. There's no point in having it hanging
1513 # around uninitialized in every Title object; therefore we only add it
1514 # if needed and don't declare it statically.
1515 if( isset( $this->mHasSubpages ) ) {
1516 return $this->mHasSubpages;
1517 }
1518
1519 $db = wfGetDB( DB_SLAVE );
1520 return $this->mHasSubpages = (bool)$db->selectField( 'page', '1',
1521 "page_namespace = {$this->mNamespace} AND page_title LIKE '"
1522 . $db->escapeLike( $this->mDbkeyform ) . "/%'",
1523 __METHOD__
1524 );
1525 }
1526
1527 /**
1528 * Could this page contain custom CSS or JavaScript, based
1529 * on the title?
1530 *
1531 * @return \type{\bool} TRUE or FALSE
1532 */
1533 public function isCssOrJsPage() {
1534 return $this->mNamespace == NS_MEDIAWIKI
1535 && preg_match( '!\.(?:css|js)$!u', $this->mTextform ) > 0;
1536 }
1537
1538 /**
1539 * Is this a .css or .js subpage of a user page?
1540 * @return \type{\bool} TRUE or FALSE
1541 */
1542 public function isCssJsSubpage() {
1543 return ( NS_USER == $this->mNamespace and preg_match("/\\/.*\\.(?:css|js)$/", $this->mTextform ) );
1544 }
1545 /**
1546 * Is this a *valid* .css or .js subpage of a user page?
1547 * Check that the corresponding skin exists
1548 * @return \type{\bool} TRUE or FALSE
1549 */
1550 public function isValidCssJsSubpage() {
1551 if ( $this->isCssJsSubpage() ) {
1552 $skinNames = Skin::getSkinNames();
1553 return array_key_exists( $this->getSkinFromCssJsSubpage(), $skinNames );
1554 } else {
1555 return false;
1556 }
1557 }
1558 /**
1559 * Trim down a .css or .js subpage title to get the corresponding skin name
1560 */
1561 public function getSkinFromCssJsSubpage() {
1562 $subpage = explode( '/', $this->mTextform );
1563 $subpage = $subpage[ count( $subpage ) - 1 ];
1564 return( str_replace( array( '.css', '.js' ), array( '', '' ), $subpage ) );
1565 }
1566 /**
1567 * Is this a .css subpage of a user page?
1568 * @return \type{\bool} TRUE or FALSE
1569 */
1570 public function isCssSubpage() {
1571 return ( NS_USER == $this->mNamespace && preg_match("/\\/.*\\.css$/", $this->mTextform ) );
1572 }
1573 /**
1574 * Is this a .js subpage of a user page?
1575 * @return \type{\bool} TRUE or FALSE
1576 */
1577 public function isJsSubpage() {
1578 return ( NS_USER == $this->mNamespace && preg_match("/\\/.*\\.js$/", $this->mTextform ) );
1579 }
1580 /**
1581 * Protect css/js subpages of user pages: can $wgUser edit
1582 * this page?
1583 *
1584 * @return \type{\bool} TRUE or FALSE
1585 * @todo XXX: this might be better using restrictions
1586 */
1587 public function userCanEditCssJsSubpage() {
1588 global $wgUser;
1589 return ( $wgUser->isAllowed('editusercssjs') || preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform) );
1590 }
1591
1592 /**
1593 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
1594 *
1595 * @return \type{\bool} If the page is subject to cascading restrictions.
1596 */
1597 public function isCascadeProtected() {
1598 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
1599 return ( $sources > 0 );
1600 }
1601
1602 /**
1603 * Cascading protection: Get the source of any cascading restrictions on this page.
1604 *
1605 * @param $get_pages \type{\bool} Whether or not to retrieve the actual pages that the restrictions have come from.
1606 * @return \type{\arrayof{mixed title array, restriction array}} Array of the Title objects of the pages from
1607 * which cascading restrictions have come, false for none, or true if such restrictions exist, but $get_pages was not set.
1608 * The restriction array is an array of each type, each of which contains an array of unique groups.
1609 */
1610 public function getCascadeProtectionSources( $get_pages = true ) {
1611 global $wgRestrictionTypes;
1612
1613 # Define our dimension of restrictions types
1614 $pagerestrictions = array();
1615 foreach( $wgRestrictionTypes as $action )
1616 $pagerestrictions[$action] = array();
1617
1618 if ( isset( $this->mCascadeSources ) && $get_pages ) {
1619 return array( $this->mCascadeSources, $this->mCascadingRestrictions );
1620 } else if ( isset( $this->mHasCascadingRestrictions ) && !$get_pages ) {
1621 return array( $this->mHasCascadingRestrictions, $pagerestrictions );
1622 }
1623
1624 wfProfileIn( __METHOD__ );
1625
1626 $dbr = wfGetDb( DB_SLAVE );
1627
1628 if ( $this->getNamespace() == NS_IMAGE ) {
1629 $tables = array ('imagelinks', 'page_restrictions');
1630 $where_clauses = array(
1631 'il_to' => $this->getDBkey(),
1632 'il_from=pr_page',
1633 'pr_cascade' => 1 );
1634 } else {
1635 $tables = array ('templatelinks', 'page_restrictions');
1636 $where_clauses = array(
1637 'tl_namespace' => $this->getNamespace(),
1638 'tl_title' => $this->getDBkey(),
1639 'tl_from=pr_page',
1640 'pr_cascade' => 1 );
1641 }
1642
1643 if ( $get_pages ) {
1644 $cols = array('pr_page', 'page_namespace', 'page_title', 'pr_expiry', 'pr_type', 'pr_level' );
1645 $where_clauses[] = 'page_id=pr_page';
1646 $tables[] = 'page';
1647 } else {
1648 $cols = array( 'pr_expiry' );
1649 }
1650
1651 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__ );
1652
1653 $sources = $get_pages ? array() : false;
1654 $now = wfTimestampNow();
1655 $purgeExpired = false;
1656
1657 foreach( $res as $row ) {
1658 $expiry = Block::decodeExpiry( $row->pr_expiry );
1659 if( $expiry > $now ) {
1660 if ($get_pages) {
1661 $page_id = $row->pr_page;
1662 $page_ns = $row->page_namespace;
1663 $page_title = $row->page_title;
1664 $sources[$page_id] = Title::makeTitle($page_ns, $page_title);
1665 # Add groups needed for each restriction type if its not already there
1666 # Make sure this restriction type still exists
1667 if ( isset($pagerestrictions[$row->pr_type]) && !in_array($row->pr_level, $pagerestrictions[$row->pr_type]) ) {
1668 $pagerestrictions[$row->pr_type][]=$row->pr_level;
1669 }
1670 } else {
1671 $sources = true;
1672 }
1673 } else {
1674 // Trigger lazy purge of expired restrictions from the db
1675 $purgeExpired = true;
1676 }
1677 }
1678 if( $purgeExpired ) {
1679 Title::purgeExpiredRestrictions();
1680 }
1681
1682 wfProfileOut( __METHOD__ );
1683
1684 if ( $get_pages ) {
1685 $this->mCascadeSources = $sources;
1686 $this->mCascadingRestrictions = $pagerestrictions;
1687 } else {
1688 $this->mHasCascadingRestrictions = $sources;
1689 }
1690 return array( $sources, $pagerestrictions );
1691 }
1692
1693 function areRestrictionsCascading() {
1694 if (!$this->mRestrictionsLoaded) {
1695 $this->loadRestrictions();
1696 }
1697
1698 return $this->mCascadeRestriction;
1699 }
1700
1701 /**
1702 * Loads a string into mRestrictions array
1703 * @param $res \type{Resource} restrictions as an SQL result.
1704 */
1705 private function loadRestrictionsFromRow( $res, $oldFashionedRestrictions = NULL ) {
1706 global $wgRestrictionTypes;
1707 $dbr = wfGetDB( DB_SLAVE );
1708
1709 foreach( $wgRestrictionTypes as $type ){
1710 $this->mRestrictions[$type] = array();
1711 $this->mRestrictionsExpiry[$type] = Block::decodeExpiry('');
1712 }
1713
1714 $this->mCascadeRestriction = false;
1715
1716 # Backwards-compatibility: also load the restrictions from the page record (old format).
1717
1718 if ( $oldFashionedRestrictions === NULL ) {
1719 $oldFashionedRestrictions = $dbr->selectField( 'page', 'page_restrictions',
1720 array( 'page_id' => $this->getArticleId() ), __METHOD__ );
1721 }
1722
1723 if ($oldFashionedRestrictions != '') {
1724
1725 foreach( explode( ':', trim( $oldFashionedRestrictions ) ) as $restrict ) {
1726 $temp = explode( '=', trim( $restrict ) );
1727 if(count($temp) == 1) {
1728 // old old format should be treated as edit/move restriction
1729 $this->mRestrictions['edit'] = explode( ',', trim( $temp[0] ) );
1730 $this->mRestrictions['move'] = explode( ',', trim( $temp[0] ) );
1731 } else {
1732 $this->mRestrictions[$temp[0]] = explode( ',', trim( $temp[1] ) );
1733 }
1734 }
1735
1736 $this->mOldRestrictions = true;
1737
1738 }
1739
1740 if( $dbr->numRows( $res ) ) {
1741 # Current system - load second to make them override.
1742 $now = wfTimestampNow();
1743 $purgeExpired = false;
1744
1745 foreach( $res as $row ) {
1746 # Cycle through all the restrictions.
1747
1748 // Don't take care of restrictions types that aren't in $wgRestrictionTypes
1749 if( !in_array( $row->pr_type, $wgRestrictionTypes ) )
1750 continue;
1751
1752 // This code should be refactored, now that it's being used more generally,
1753 // But I don't really see any harm in leaving it in Block for now -werdna
1754 $expiry = Block::decodeExpiry( $row->pr_expiry );
1755
1756 // Only apply the restrictions if they haven't expired!
1757 if ( !$expiry || $expiry > $now ) {
1758 $this->mRestrictionsExpiry[$row->pr_type] = $expiry;
1759 $this->mRestrictions[$row->pr_type] = explode( ',', trim( $row->pr_level ) );
1760
1761 $this->mCascadeRestriction |= $row->pr_cascade;
1762 } else {
1763 // Trigger a lazy purge of expired restrictions
1764 $purgeExpired = true;
1765 }
1766 }
1767
1768 if( $purgeExpired ) {
1769 Title::purgeExpiredRestrictions();
1770 }
1771 }
1772
1773 $this->mRestrictionsLoaded = true;
1774 }
1775
1776 /**
1777 * Load restrictions from the page_restrictions table
1778 */
1779 public function loadRestrictions( $oldFashionedRestrictions = NULL ) {
1780 if( !$this->mRestrictionsLoaded ) {
1781 if ($this->exists()) {
1782 $dbr = wfGetDB( DB_SLAVE );
1783
1784 $res = $dbr->select( 'page_restrictions', '*',
1785 array ( 'pr_page' => $this->getArticleId() ), __METHOD__ );
1786
1787 $this->loadRestrictionsFromRow( $res, $oldFashionedRestrictions );
1788 } else {
1789 $title_protection = $this->getTitleProtection();
1790
1791 if (is_array($title_protection)) {
1792 extract($title_protection);
1793
1794 $now = wfTimestampNow();
1795 $expiry = Block::decodeExpiry($pt_expiry);
1796
1797 if (!$expiry || $expiry > $now) {
1798 // Apply the restrictions
1799 $this->mRestrictionsExpiry['create'] = $expiry;
1800 $this->mRestrictions['create'] = explode(',', trim($pt_create_perm) );
1801 } else { // Get rid of the old restrictions
1802 Title::purgeExpiredRestrictions();
1803 }
1804 } else {
1805 $this->mRestrictionsExpiry['create'] = Block::decodeExpiry('');
1806 }
1807 $this->mRestrictionsLoaded = true;
1808 }
1809 }
1810 }
1811
1812 /**
1813 * Purge expired restrictions from the page_restrictions table
1814 */
1815 static function purgeExpiredRestrictions() {
1816 $dbw = wfGetDB( DB_MASTER );
1817 $dbw->delete( 'page_restrictions',
1818 array( 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
1819 __METHOD__ );
1820
1821 $dbw->delete( 'protected_titles',
1822 array( 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
1823 __METHOD__ );
1824 }
1825
1826 /**
1827 * Accessor/initialisation for mRestrictions
1828 *
1829 * @param $action \type{\string} action that permission needs to be checked for
1830 * @return \type{\arrayof{\string}} the array of groups allowed to edit this article
1831 */
1832 public function getRestrictions( $action ) {
1833 if( !$this->mRestrictionsLoaded ) {
1834 $this->loadRestrictions();
1835 }
1836 return isset( $this->mRestrictions[$action] )
1837 ? $this->mRestrictions[$action]
1838 : array();
1839 }
1840
1841 /**
1842 * Get the expiry time for the restriction against a given action
1843 * @return 14-char timestamp, or 'infinity' if the page is protected forever
1844 * or not protected at all, or false if the action is not recognised.
1845 */
1846 public function getRestrictionExpiry( $action ) {
1847 if( !$this->mRestrictionsLoaded ) {
1848 $this->loadRestrictions();
1849 }
1850 return isset( $this->mRestrictionsExpiry[$action] ) ? $this->mRestrictionsExpiry[$action] : false;
1851 }
1852
1853 /**
1854 * Is there a version of this page in the deletion archive?
1855 * @return \type{\int} the number of archived revisions
1856 */
1857 public function isDeleted() {
1858 $fname = 'Title::isDeleted';
1859 if ( $this->getNamespace() < 0 ) {
1860 $n = 0;
1861 } else {
1862 $dbr = wfGetDB( DB_SLAVE );
1863 $n = $dbr->selectField( 'archive', 'COUNT(*)', array( 'ar_namespace' => $this->getNamespace(),
1864 'ar_title' => $this->getDBkey() ), $fname );
1865 if( $this->getNamespace() == NS_IMAGE ) {
1866 $n += $dbr->selectField( 'filearchive', 'COUNT(*)',
1867 array( 'fa_name' => $this->getDBkey() ), $fname );
1868 }
1869 }
1870 return (int)$n;
1871 }
1872
1873 /**
1874 * Get the article ID for this Title from the link cache,
1875 * adding it if necessary
1876 * @param $flags \type{\int} a bit field; may be GAID_FOR_UPDATE to select
1877 * for update
1878 * @return \type{\int} the ID
1879 */
1880 public function getArticleID( $flags = 0 ) {
1881 $linkCache = LinkCache::singleton();
1882 if( $flags & GAID_FOR_UPDATE ) {
1883 $oldUpdate = $linkCache->forUpdate( true );
1884 $linkCache->clearLink( $this );
1885 $this->mArticleID = $linkCache->addLinkObj( $this );
1886 $linkCache->forUpdate( $oldUpdate );
1887 } else {
1888 if( -1 == $this->mArticleID ) {
1889 $this->mArticleID = $linkCache->addLinkObj( $this );
1890 }
1891 }
1892 return $this->mArticleID;
1893 }
1894
1895 /**
1896 * Is this an article that is a redirect page?
1897 * Uses link cache, adding it if necessary
1898 * @param $flags \type{\int} a bit field; may be GAID_FOR_UPDATE to select for update
1899 * @return \type{\bool}
1900 */
1901 public function isRedirect( $flags = 0 ) {
1902 if( !is_null($this->mRedirect) )
1903 return $this->mRedirect;
1904 # Zero for special pages.
1905 # Also, calling getArticleID() loads the field from cache!
1906 if( !$this->getArticleID($flags) || $this->getNamespace() == NS_SPECIAL ) {
1907 return false;
1908 }
1909 $linkCache = LinkCache::singleton();
1910 $this->mRedirect = (bool)$linkCache->getGoodLinkFieldObj( $this, 'redirect' );
1911
1912 return $this->mRedirect;
1913 }
1914
1915 /**
1916 * What is the length of this page?
1917 * Uses link cache, adding it if necessary
1918 * @param $flags \type{\int} a bit field; may be GAID_FOR_UPDATE to select for update
1919 * @return \type{\bool}
1920 */
1921 public function getLength( $flags = 0 ) {
1922 if( $this->mLength != -1 )
1923 return $this->mLength;
1924 # Zero for special pages.
1925 # Also, calling getArticleID() loads the field from cache!
1926 if( !$this->getArticleID($flags) || $this->getNamespace() == NS_SPECIAL ) {
1927 return 0;
1928 }
1929 $linkCache = LinkCache::singleton();
1930 $this->mLength = intval( $linkCache->getGoodLinkFieldObj( $this, 'length' ) );
1931
1932 return $this->mLength;
1933 }
1934
1935 /**
1936 * What is the page_latest field for this page?
1937 * @param $flags \type{\int} a bit field; may be GAID_FOR_UPDATE to select for update
1938 * @return \type{\int}
1939 */
1940 public function getLatestRevID( $flags = 0 ) {
1941 if( $this->mLatestID !== false )
1942 return $this->mLatestID;
1943
1944 $db = ($flags & GAID_FOR_UPDATE) ? wfGetDB(DB_MASTER) : wfGetDB(DB_SLAVE);
1945 $this->mLatestID = $db->selectField( 'page', 'page_latest',
1946 array( 'page_namespace' => $this->getNamespace(), 'page_title' => $this->getDBKey() ),
1947 __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
1978 if ( wfReadOnly() ) {
1979 return;
1980 }
1981
1982 $dbw = wfGetDB( DB_MASTER );
1983 $success = $dbw->update( 'page',
1984 array( /* SET */
1985 'page_touched' => $dbw->timestamp()
1986 ), array( /* WHERE */
1987 'page_namespace' => $this->getNamespace() ,
1988 'page_title' => $this->getDBkey()
1989 ), 'Title::invalidateCache'
1990 );
1991
1992 if ($wgUseFileCache) {
1993 $cache = new HTMLFileCache($this);
1994 @unlink($cache->fileCacheName());
1995 }
1996
1997 return $success;
1998 }
1999
2000 /**
2001 * Prefix some arbitrary text with the namespace or interwiki prefix
2002 * of this object
2003 *
2004 * @param $name \type{\string} the text
2005 * @return \type{\string} the prefixed text
2006 * @private
2007 */
2008 /* private */ function prefix( $name ) {
2009 $p = '';
2010 if ( '' != $this->mInterwiki ) {
2011 $p = $this->mInterwiki . ':';
2012 }
2013 if ( 0 != $this->mNamespace ) {
2014 $p .= $this->getNsText() . ':';
2015 }
2016 return $p . $name;
2017 }
2018
2019 /**
2020 * Secure and split - main initialisation function for this object
2021 *
2022 * Assumes that mDbkeyform has been set, and is urldecoded
2023 * and uses underscores, but not otherwise munged. This function
2024 * removes illegal characters, splits off the interwiki and
2025 * namespace prefixes, sets the other forms, and canonicalizes
2026 * everything.
2027 * @return \type{\bool} true on success
2028 */
2029 private function secureAndSplit() {
2030 global $wgContLang, $wgLocalInterwiki, $wgCapitalLinks;
2031
2032 # Initialisation
2033 static $rxTc = false;
2034 if( !$rxTc ) {
2035 # Matching titles will be held as illegal.
2036 $rxTc = '/' .
2037 # Any character not allowed is forbidden...
2038 '[^' . Title::legalChars() . ']' .
2039 # URL percent encoding sequences interfere with the ability
2040 # to round-trip titles -- you can't link to them consistently.
2041 '|%[0-9A-Fa-f]{2}' .
2042 # XML/HTML character references produce similar issues.
2043 '|&[A-Za-z0-9\x80-\xff]+;' .
2044 '|&#[0-9]+;' .
2045 '|&#x[0-9A-Fa-f]+;' .
2046 '/S';
2047 }
2048
2049 $this->mInterwiki = $this->mFragment = '';
2050 $this->mNamespace = $this->mDefaultNamespace; # Usually NS_MAIN
2051
2052 $dbkey = $this->mDbkeyform;
2053
2054 # Strip Unicode bidi override characters.
2055 # Sometimes they slip into cut-n-pasted page titles, where the
2056 # override chars get included in list displays.
2057 $dbkey = str_replace( "\xE2\x80\x8E", '', $dbkey ); // 200E LEFT-TO-RIGHT MARK
2058 $dbkey = str_replace( "\xE2\x80\x8F", '', $dbkey ); // 200F RIGHT-TO-LEFT MARK
2059
2060 # Clean up whitespace
2061 #
2062 $dbkey = preg_replace( '/[ _]+/', '_', $dbkey );
2063 $dbkey = trim( $dbkey, '_' );
2064
2065 if ( '' == $dbkey ) {
2066 return false;
2067 }
2068
2069 if( false !== strpos( $dbkey, UTF8_REPLACEMENT ) ) {
2070 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
2071 return false;
2072 }
2073
2074 $this->mDbkeyform = $dbkey;
2075
2076 # Initial colon indicates main namespace rather than specified default
2077 # but should not create invalid {ns,title} pairs such as {0,Project:Foo}
2078 if ( ':' == $dbkey{0} ) {
2079 $this->mNamespace = NS_MAIN;
2080 $dbkey = substr( $dbkey, 1 ); # remove the colon but continue processing
2081 $dbkey = trim( $dbkey, '_' ); # remove any subsequent whitespace
2082 }
2083
2084 # Namespace or interwiki prefix
2085 $firstPass = true;
2086 do {
2087 $m = array();
2088 if ( preg_match( "/^(.+?)_*:_*(.*)$/S", $dbkey, $m ) ) {
2089 $p = $m[1];
2090 if ( $ns = $wgContLang->getNsIndex( $p )) {
2091 # Ordinary namespace
2092 $dbkey = $m[2];
2093 $this->mNamespace = $ns;
2094 } elseif( Interwiki::isValidInterwiki( $p ) ) {
2095 if( !$firstPass ) {
2096 # Can't make a local interwiki link to an interwiki link.
2097 # That's just crazy!
2098 return false;
2099 }
2100
2101 # Interwiki link
2102 $dbkey = $m[2];
2103 $this->mInterwiki = $wgContLang->lc( $p );
2104
2105 # Redundant interwiki prefix to the local wiki
2106 if ( 0 == strcasecmp( $this->mInterwiki, $wgLocalInterwiki ) ) {
2107 if( $dbkey == '' ) {
2108 # Can't have an empty self-link
2109 return false;
2110 }
2111 $this->mInterwiki = '';
2112 $firstPass = false;
2113 # Do another namespace split...
2114 continue;
2115 }
2116
2117 # If there's an initial colon after the interwiki, that also
2118 # resets the default namespace
2119 if ( $dbkey !== '' && $dbkey[0] == ':' ) {
2120 $this->mNamespace = NS_MAIN;
2121 $dbkey = substr( $dbkey, 1 );
2122 }
2123 }
2124 # If there's no recognized interwiki or namespace,
2125 # then let the colon expression be part of the title.
2126 }
2127 break;
2128 } while( true );
2129
2130 # We already know that some pages won't be in the database!
2131 #
2132 if ( '' != $this->mInterwiki || NS_SPECIAL == $this->mNamespace ) {
2133 $this->mArticleID = 0;
2134 }
2135 $fragment = strstr( $dbkey, '#' );
2136 if ( false !== $fragment ) {
2137 $this->setFragment( $fragment );
2138 $dbkey = substr( $dbkey, 0, strlen( $dbkey ) - strlen( $fragment ) );
2139 # remove whitespace again: prevents "Foo_bar_#"
2140 # becoming "Foo_bar_"
2141 $dbkey = preg_replace( '/_*$/', '', $dbkey );
2142 }
2143
2144 # Reject illegal characters.
2145 #
2146 if( preg_match( $rxTc, $dbkey ) ) {
2147 return false;
2148 }
2149
2150 /**
2151 * Pages with "/./" or "/../" appearing in the URLs will often be un-
2152 * reachable due to the way web browsers deal with 'relative' URLs.
2153 * Also, they conflict with subpage syntax. Forbid them explicitly.
2154 */
2155 if ( strpos( $dbkey, '.' ) !== false &&
2156 ( $dbkey === '.' || $dbkey === '..' ||
2157 strpos( $dbkey, './' ) === 0 ||
2158 strpos( $dbkey, '../' ) === 0 ||
2159 strpos( $dbkey, '/./' ) !== false ||
2160 strpos( $dbkey, '/../' ) !== false ||
2161 substr( $dbkey, -2 ) == '/.' ||
2162 substr( $dbkey, -3 ) == '/..' ) )
2163 {
2164 return false;
2165 }
2166
2167 /**
2168 * Magic tilde sequences? Nu-uh!
2169 */
2170 if( strpos( $dbkey, '~~~' ) !== false ) {
2171 return false;
2172 }
2173
2174 /**
2175 * Limit the size of titles to 255 bytes.
2176 * This is typically the size of the underlying database field.
2177 * We make an exception for special pages, which don't need to be stored
2178 * in the database, and may edge over 255 bytes due to subpage syntax
2179 * for long titles, e.g. [[Special:Block/Long name]]
2180 */
2181 if ( ( $this->mNamespace != NS_SPECIAL && strlen( $dbkey ) > 255 ) ||
2182 strlen( $dbkey ) > 512 )
2183 {
2184 return false;
2185 }
2186
2187 /**
2188 * Normally, all wiki links are forced to have
2189 * an initial capital letter so [[foo]] and [[Foo]]
2190 * point to the same place.
2191 *
2192 * Don't force it for interwikis, since the other
2193 * site might be case-sensitive.
2194 */
2195 $this->mUserCaseDBKey = $dbkey;
2196 if( $wgCapitalLinks && $this->mInterwiki == '') {
2197 $dbkey = $wgContLang->ucfirst( $dbkey );
2198 }
2199
2200 /**
2201 * Can't make a link to a namespace alone...
2202 * "empty" local links can only be self-links
2203 * with a fragment identifier.
2204 */
2205 if( $dbkey == '' &&
2206 $this->mInterwiki == '' &&
2207 $this->mNamespace != NS_MAIN ) {
2208 return false;
2209 }
2210 // Allow IPv6 usernames to start with '::' by canonicalizing IPv6 titles.
2211 // IP names are not allowed for accounts, and can only be referring to
2212 // edits from the IP. Given '::' abbreviations and caps/lowercaps,
2213 // there are numerous ways to present the same IP. Having sp:contribs scan
2214 // them all is silly and having some show the edits and others not is
2215 // inconsistent. Same for talk/userpages. Keep them normalized instead.
2216 $dbkey = ($this->mNamespace == NS_USER || $this->mNamespace == NS_USER_TALK) ?
2217 IP::sanitizeIP( $dbkey ) : $dbkey;
2218 // Any remaining initial :s are illegal.
2219 if ( $dbkey !== '' && ':' == $dbkey{0} ) {
2220 return false;
2221 }
2222
2223 # Fill fields
2224 $this->mDbkeyform = $dbkey;
2225 $this->mUrlform = wfUrlencode( $dbkey );
2226
2227 $this->mTextform = str_replace( '_', ' ', $dbkey );
2228
2229 return true;
2230 }
2231
2232 /**
2233 * Set the fragment for this title. Removes the first character from the
2234 * specified fragment before setting, so it assumes you're passing it with
2235 * an initial "#".
2236 *
2237 * Deprecated for public use, use Title::makeTitle() with fragment parameter.
2238 * Still in active use privately.
2239 *
2240 * @param $fragment \type{\string} text
2241 */
2242 public function setFragment( $fragment ) {
2243 $this->mFragment = str_replace( '_', ' ', substr( $fragment, 1 ) );
2244 }
2245
2246 /**
2247 * Get a Title object associated with the talk page of this article
2248 * @return \type{Title} the object for the talk page
2249 */
2250 public function getTalkPage() {
2251 return Title::makeTitle( MWNamespace::getTalk( $this->getNamespace() ), $this->getDBkey() );
2252 }
2253
2254 /**
2255 * Get a title object associated with the subject page of this
2256 * talk page
2257 *
2258 * @return \type{Title} the object for the subject page
2259 */
2260 public function getSubjectPage() {
2261 // Is this the same title?
2262 $subjectNS = MWNamespace::getSubject( $this->getNamespace() );
2263 if( $this->getNamespace() == $subjectNS ) {
2264 return $this;
2265 }
2266 return Title::makeTitle( $subjectNS, $this->getDBkey() );
2267 }
2268
2269 /**
2270 * Get an array of Title objects linking to this Title
2271 * Also stores the IDs in the link cache.
2272 *
2273 * WARNING: do not use this function on arbitrary user-supplied titles!
2274 * On heavily-used templates it will max out the memory.
2275 *
2276 * @param $options \type{\string} may be FOR UPDATE
2277 * @return \type{\arrayof{Title}} the Title objects linking here
2278 */
2279 public function getLinksTo( $options = '', $table = 'pagelinks', $prefix = 'pl' ) {
2280 $linkCache = LinkCache::singleton();
2281
2282 if ( $options ) {
2283 $db = wfGetDB( DB_MASTER );
2284 } else {
2285 $db = wfGetDB( DB_SLAVE );
2286 }
2287
2288 $res = $db->select( array( 'page', $table ),
2289 array( 'page_namespace', 'page_title', 'page_id', 'page_len', 'page_is_redirect' ),
2290 array(
2291 "{$prefix}_from=page_id",
2292 "{$prefix}_namespace" => $this->getNamespace(),
2293 "{$prefix}_title" => $this->getDBkey() ),
2294 __METHOD__,
2295 $options );
2296
2297 $retVal = array();
2298 if ( $db->numRows( $res ) ) {
2299 foreach( $res as $row ) {
2300 if ( $titleObj = Title::makeTitle( $row->page_namespace, $row->page_title ) ) {
2301 $linkCache->addGoodLinkObj( $row->page_id, $titleObj, $row->page_len, $row->page_is_redirect );
2302 $retVal[] = $titleObj;
2303 }
2304 }
2305 }
2306 $db->freeResult( $res );
2307 return $retVal;
2308 }
2309
2310 /**
2311 * Get an array of Title objects using this Title as a template
2312 * Also stores the IDs in the link cache.
2313 *
2314 * WARNING: do not use this function on arbitrary user-supplied titles!
2315 * On heavily-used templates it will max out the memory.
2316 *
2317 * @param $options \type{\string} may be FOR UPDATE
2318 * @return \type{\arrayof{Title}} the Title objects linking here
2319 */
2320 public function getTemplateLinksTo( $options = '' ) {
2321 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
2322 }
2323
2324 /**
2325 * Get an array of Title objects referring to non-existent articles linked from this page
2326 *
2327 * @todo check if needed (used only in SpecialBrokenRedirects.php, and should use redirect table in this case)
2328 * @param $options \type{\string} may be FOR UPDATE
2329 * @return \type{\arrayof{Title}} the Title objects
2330 */
2331 public function getBrokenLinksFrom( $options = '' ) {
2332 if ( $this->getArticleId() == 0 ) {
2333 # All links from article ID 0 are false positives
2334 return array();
2335 }
2336
2337 if ( $options ) {
2338 $db = wfGetDB( DB_MASTER );
2339 } else {
2340 $db = wfGetDB( DB_SLAVE );
2341 }
2342
2343 $res = $db->safeQuery(
2344 "SELECT pl_namespace, pl_title
2345 FROM !
2346 LEFT JOIN !
2347 ON pl_namespace=page_namespace
2348 AND pl_title=page_title
2349 WHERE pl_from=?
2350 AND page_namespace IS NULL
2351 !",
2352 $db->tableName( 'pagelinks' ),
2353 $db->tableName( 'page' ),
2354 $this->getArticleId(),
2355 $options );
2356
2357 $retVal = array();
2358 if ( $db->numRows( $res ) ) {
2359 foreach( $res as $row ) {
2360 $retVal[] = Title::makeTitle( $row->pl_namespace, $row->pl_title );
2361 }
2362 }
2363 $db->freeResult( $res );
2364 return $retVal;
2365 }
2366
2367
2368 /**
2369 * Get a list of URLs to purge from the Squid cache when this
2370 * page changes
2371 *
2372 * @return \type{\arrayof{\string}} the URLs
2373 */
2374 public function getSquidURLs() {
2375 global $wgContLang;
2376
2377 $urls = array(
2378 $this->getInternalURL(),
2379 $this->getInternalURL( 'action=history' )
2380 );
2381
2382 // purge variant urls as well
2383 if($wgContLang->hasVariants()){
2384 $variants = $wgContLang->getVariants();
2385 foreach($variants as $vCode){
2386 if($vCode==$wgContLang->getCode()) continue; // we don't want default variant
2387 $urls[] = $this->getInternalURL('',$vCode);
2388 }
2389 }
2390
2391 return $urls;
2392 }
2393
2394 /**
2395 * Purge all applicable Squid URLs
2396 */
2397 public function purgeSquid() {
2398 global $wgUseSquid;
2399 if ( $wgUseSquid ) {
2400 $urls = $this->getSquidURLs();
2401 $u = new SquidUpdate( $urls );
2402 $u->doUpdate();
2403 }
2404 }
2405
2406 /**
2407 * Move this page without authentication
2408 * @param &$nt \type{Title} the new page Title
2409 */
2410 public function moveNoAuth( &$nt ) {
2411 return $this->moveTo( $nt, false );
2412 }
2413
2414 /**
2415 * Check whether a given move operation would be valid.
2416 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
2417 * @param &$nt \type{Title} the new title
2418 * @param $auth \type{\bool} indicates whether $wgUser's permissions
2419 * should be checked
2420 * @param $reason \type{\string} is the log summary of the move, used for spam checking
2421 * @return \type{\mixed} True on success, getUserPermissionsErrors()-like array on failure
2422 */
2423 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
2424 global $wgUser;
2425
2426 $errors = array();
2427 if( !$nt ) {
2428 // Normally we'd add this to $errors, but we'll get
2429 // lots of syntax errors if $nt is not an object
2430 return array(array('badtitletext'));
2431 }
2432 if( $this->equals( $nt ) ) {
2433 $errors[] = array('selfmove');
2434 }
2435 if( !$this->isMovable() ) {
2436 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
2437 }
2438 if ( !$nt->isMovable() ) {
2439 $errors[] = array('immobile-target-namespace', $nt->getNsText() );
2440 }
2441
2442 $oldid = $this->getArticleID();
2443 $newid = $nt->getArticleID();
2444
2445 if ( strlen( $nt->getDBkey() ) < 1 ) {
2446 $errors[] = array('articleexists');
2447 }
2448 if ( ( '' == $this->getDBkey() ) ||
2449 ( !$oldid ) ||
2450 ( '' == $nt->getDBkey() ) ) {
2451 $errors[] = array('badarticleerror');
2452 }
2453
2454 // Image-specific checks
2455 if( $this->getNamespace() == NS_IMAGE ) {
2456 $file = wfLocalFile( $this );
2457 if( $file->exists() ) {
2458 if( $nt->getNamespace() != NS_IMAGE ) {
2459 $errors[] = array('imagenocrossnamespace');
2460 }
2461 if( $nt->getText() != wfStripIllegalFilenameChars( $nt->getText() ) ) {
2462 $errors[] = array('imageinvalidfilename');
2463 }
2464 if( !File::checkExtensionCompatibility( $file, $nt->getDbKey() ) ) {
2465 $errors[] = array('imagetypemismatch');
2466 }
2467 }
2468 }
2469
2470 if ( $auth ) {
2471 $errors = wfArrayMerge($errors,
2472 $this->getUserPermissionsErrors('move', $wgUser),
2473 $this->getUserPermissionsErrors('edit', $wgUser),
2474 $nt->getUserPermissionsErrors('move-target', $wgUser),
2475 $nt->getUserPermissionsErrors('edit', $wgUser));
2476 }
2477
2478 $match = EditPage::matchSpamRegex( $reason );
2479 if( $match !== false ) {
2480 // This is kind of lame, won't display nice
2481 $errors[] = array('spamprotectiontext');
2482 }
2483
2484 $err = null;
2485 if( !wfRunHooks( 'AbortMove', array( $this, $nt, $wgUser, &$err, $reason ) ) ) {
2486 $errors[] = array('hookaborted', $err);
2487 }
2488
2489 # The move is allowed only if (1) the target doesn't exist, or
2490 # (2) the target is a redirect to the source, and has no history
2491 # (so we can undo bad moves right after they're done).
2492
2493 if ( 0 != $newid ) { # Target exists; check for validity
2494 if ( ! $this->isValidMoveTarget( $nt ) ) {
2495 $errors[] = array('articleexists');
2496 }
2497 } else {
2498 $tp = $nt->getTitleProtection();
2499 $right = ( $tp['pt_create_perm'] == 'sysop' ) ? 'protect' : $tp['pt_create_perm'];
2500 if ( $tp and !$wgUser->isAllowed( $right ) ) {
2501 $errors[] = array('cantmove-titleprotected');
2502 }
2503 }
2504 if(empty($errors))
2505 return true;
2506 return $errors;
2507 }
2508
2509 /**
2510 * Move a title to a new location
2511 * @param &$nt \type{Title} the new title
2512 * @param $auth \type{\bool} indicates whether $wgUser's permissions
2513 * should be checked
2514 * @param $reason \type{\string} The reason for the move
2515 * @param $createRedirect \type{\bool} Whether to create a redirect from the old title to the new title.
2516 * Ignored if the user doesn't have the suppressredirect right.
2517 * @return \type{\mixed} true on success, getUserPermissionsErrors()-like array on failure
2518 */
2519 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true ) {
2520 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
2521 if( is_array( $err ) ) {
2522 return $err;
2523 }
2524
2525 $pageid = $this->getArticleID();
2526 $protected = $this->isProtected();
2527 if( $nt->exists() ) {
2528 $err = $this->moveOverExistingRedirect( $nt, $reason, $createRedirect );
2529 $pageCountChange = ($createRedirect ? 0 : -1);
2530 } else { # Target didn't exist, do normal move.
2531 $err = $this->moveToNewTitle( $nt, $reason, $createRedirect );
2532 $pageCountChange = ($createRedirect ? 1 : 0);
2533 }
2534
2535 if( is_array( $err ) ) {
2536 return $err;
2537 }
2538 $redirid = $this->getArticleID();
2539
2540 // Category memberships include a sort key which may be customized.
2541 // If it's left as the default (the page title), we need to update
2542 // the sort key to match the new title.
2543 //
2544 // Be careful to avoid resetting cl_timestamp, which may disturb
2545 // time-based lists on some sites.
2546 //
2547 // Warning -- if the sort key is *explicitly* set to the old title,
2548 // we can't actually distinguish it from a default here, and it'll
2549 // be set to the new title even though it really shouldn't.
2550 // It'll get corrected on the next edit, but resetting cl_timestamp.
2551 $dbw = wfGetDB( DB_MASTER );
2552 $dbw->update( 'categorylinks',
2553 array(
2554 'cl_sortkey' => $nt->getPrefixedText(),
2555 'cl_timestamp=cl_timestamp' ),
2556 array(
2557 'cl_from' => $pageid,
2558 'cl_sortkey' => $this->getPrefixedText() ),
2559 __METHOD__ );
2560
2561 if( $protected ) {
2562 # Protect the redirect title as the title used to be...
2563 $dbw->insertSelect( 'page_restrictions', 'page_restrictions',
2564 array(
2565 'pr_page' => $redirid,
2566 'pr_type' => 'pr_type',
2567 'pr_level' => 'pr_level',
2568 'pr_cascade' => 'pr_cascade',
2569 'pr_user' => 'pr_user',
2570 'pr_expiry' => 'pr_expiry'
2571 ),
2572 array( 'pr_page' => $pageid ),
2573 __METHOD__,
2574 array( 'IGNORE' )
2575 );
2576 # Update the protection log
2577 $log = new LogPage( 'protect' );
2578 $comment = wfMsgForContent('prot_1movedto2',$this->getPrefixedText(), $nt->getPrefixedText() );
2579 if( $reason ) $comment .= ': ' . $reason;
2580 $log->addEntry( 'move_prot', $nt, $comment, array($this->getPrefixedText()) ); // FIXME: $params?
2581 }
2582
2583 # Update watchlists
2584 $oldnamespace = $this->getNamespace() & ~1;
2585 $newnamespace = $nt->getNamespace() & ~1;
2586 $oldtitle = $this->getDBkey();
2587 $newtitle = $nt->getDBkey();
2588
2589 if( $oldnamespace != $newnamespace || $oldtitle != $newtitle ) {
2590 WatchedItem::duplicateEntries( $this, $nt );
2591 }
2592
2593 # Update search engine
2594 $u = new SearchUpdate( $pageid, $nt->getPrefixedDBkey() );
2595 $u->doUpdate();
2596 $u = new SearchUpdate( $redirid, $this->getPrefixedDBkey(), '' );
2597 $u->doUpdate();
2598
2599 # Update site_stats
2600 if( $this->isContentPage() && !$nt->isContentPage() ) {
2601 # No longer a content page
2602 # Not viewed, edited, removing
2603 $u = new SiteStatsUpdate( 0, 1, -1, $pageCountChange );
2604 } elseif( !$this->isContentPage() && $nt->isContentPage() ) {
2605 # Now a content page
2606 # Not viewed, edited, adding
2607 $u = new SiteStatsUpdate( 0, 1, +1, $pageCountChange );
2608 } elseif( $pageCountChange ) {
2609 # Redirect added
2610 $u = new SiteStatsUpdate( 0, 0, 0, 1 );
2611 } else {
2612 # Nothing special
2613 $u = false;
2614 }
2615 if( $u )
2616 $u->doUpdate();
2617 # Update message cache for interface messages
2618 if( $nt->getNamespace() == NS_MEDIAWIKI ) {
2619 global $wgMessageCache;
2620 $oldarticle = new Article( $this );
2621 $wgMessageCache->replace( $this->getDBkey(), $oldarticle->getContent() );
2622 $newarticle = new Article( $nt );
2623 $wgMessageCache->replace( $nt->getDBkey(), $newarticle->getContent() );
2624 }
2625
2626 global $wgUser;
2627 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) );
2628 return true;
2629 }
2630
2631 /**
2632 * Move page to a title which is at present a redirect to the
2633 * source page
2634 *
2635 * @param &$nt \type{Title} the page to move to, which should currently
2636 * be a redirect
2637 * @param $reason \type{\string} The reason for the move
2638 * @param $createRedirect \type{\bool} Whether to leave a redirect at the old title.
2639 * Ignored if the user doesn't have the suppressredirect right
2640 */
2641 private function moveOverExistingRedirect( &$nt, $reason = '', $createRedirect = true ) {
2642 global $wgUseSquid, $wgUser;
2643 $fname = 'Title::moveOverExistingRedirect';
2644 $comment = wfMsgForContent( '1movedto2_redir', $this->getPrefixedText(), $nt->getPrefixedText() );
2645
2646 if ( $reason ) {
2647 $comment .= ": $reason";
2648 }
2649
2650 $now = wfTimestampNow();
2651 $newid = $nt->getArticleID();
2652 $oldid = $this->getArticleID();
2653 $latest = $this->getLatestRevID();
2654
2655 $dbw = wfGetDB( DB_MASTER );
2656
2657 # Delete the old redirect. We don't save it to history since
2658 # by definition if we've got here it's rather uninteresting.
2659 # We have to remove it so that the next step doesn't trigger
2660 # a conflict on the unique namespace+title index...
2661 $dbw->delete( 'page', array( 'page_id' => $newid ), $fname );
2662 if ( !$dbw->cascadingDeletes() ) {
2663 $dbw->delete( 'revision', array( 'rev_page' => $newid ), __METHOD__ );
2664 global $wgUseTrackbacks;
2665 if ($wgUseTrackbacks)
2666 $dbw->delete( 'trackbacks', array( 'tb_page' => $newid ), __METHOD__ );
2667 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), __METHOD__ );
2668 $dbw->delete( 'imagelinks', array( 'il_from' => $newid ), __METHOD__ );
2669 $dbw->delete( 'categorylinks', array( 'cl_from' => $newid ), __METHOD__ );
2670 $dbw->delete( 'templatelinks', array( 'tl_from' => $newid ), __METHOD__ );
2671 $dbw->delete( 'externallinks', array( 'el_from' => $newid ), __METHOD__ );
2672 $dbw->delete( 'langlinks', array( 'll_from' => $newid ), __METHOD__ );
2673 $dbw->delete( 'redirect', array( 'rd_from' => $newid ), __METHOD__ );
2674 }
2675
2676 # Save a null revision in the page's history notifying of the move
2677 $nullRevision = Revision::newNullRevision( $dbw, $oldid, $comment, true );
2678 $nullRevId = $nullRevision->insertOn( $dbw );
2679
2680 $article = new Article( $this );
2681 wfRunHooks( 'NewRevisionFromEditComplete', array($article, $nullRevision, $latest) );
2682
2683 # Change the name of the target page:
2684 $dbw->update( 'page',
2685 /* SET */ array(
2686 'page_touched' => $dbw->timestamp($now),
2687 'page_namespace' => $nt->getNamespace(),
2688 'page_title' => $nt->getDBkey(),
2689 'page_latest' => $nullRevId,
2690 ),
2691 /* WHERE */ array( 'page_id' => $oldid ),
2692 $fname
2693 );
2694 $nt->resetArticleID( $oldid );
2695
2696 # Recreate the redirect, this time in the other direction.
2697 if( $createRedirect || !$wgUser->isAllowed('suppressredirect') ) {
2698 $mwRedir = MagicWord::get( 'redirect' );
2699 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
2700 $redirectArticle = new Article( $this );
2701 $newid = $redirectArticle->insertOn( $dbw );
2702 $redirectRevision = new Revision( array(
2703 'page' => $newid,
2704 'comment' => $comment,
2705 'text' => $redirectText ) );
2706 $redirectRevision->insertOn( $dbw );
2707 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
2708
2709 wfRunHooks( 'NewRevisionFromEditComplete', array($redirectArticle, $redirectRevision, false) );
2710
2711 # Now, we record the link from the redirect to the new title.
2712 # It should have no other outgoing links...
2713 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), $fname );
2714 $dbw->insert( 'pagelinks',
2715 array(
2716 'pl_from' => $newid,
2717 'pl_namespace' => $nt->getNamespace(),
2718 'pl_title' => $nt->getDBkey() ),
2719 $fname );
2720 } else {
2721 $this->resetArticleID( 0 );
2722 }
2723
2724 # Move an image if this is a file
2725 if( $this->getNamespace() == NS_IMAGE ) {
2726 $file = wfLocalFile( $this );
2727 if( $file->exists() ) {
2728 $status = $file->move( $nt );
2729 if( !$status->isOk() ) {
2730 $dbw->rollback();
2731 return $status->getErrorsArray();
2732 }
2733 }
2734 }
2735
2736 # Log the move
2737 $log = new LogPage( 'move' );
2738 $log->addEntry( 'move_redir', $this, $reason, array( 1 => $nt->getPrefixedText() ) );
2739
2740 # Purge squid
2741 if ( $wgUseSquid ) {
2742 $urls = array_merge( $nt->getSquidURLs(), $this->getSquidURLs() );
2743 $u = new SquidUpdate( $urls );
2744 $u->doUpdate();
2745 }
2746
2747 }
2748
2749 /**
2750 * Move page to non-existing title.
2751 * @param &$nt \type{Title} the new Title
2752 * @param $reason \type{\string} The reason for the move
2753 * @param $createRedirect \type{\bool} Whether to create a redirect from the old title to the new title
2754 * Ignored if the user doesn't have the suppressredirect right
2755 */
2756 private function moveToNewTitle( &$nt, $reason = '', $createRedirect = true ) {
2757 global $wgUseSquid, $wgUser;
2758 $fname = 'MovePageForm::moveToNewTitle';
2759 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
2760 if ( $reason ) {
2761 $comment .= wfMsgExt( 'colon-separator',
2762 array( 'escapenoentities', 'content' ) );
2763 $comment .= $reason;
2764 }
2765
2766 $newid = $nt->getArticleID();
2767 $oldid = $this->getArticleID();
2768 $latest = $this->getLatestRevId();
2769
2770 $dbw = wfGetDB( DB_MASTER );
2771 $now = $dbw->timestamp();
2772
2773 # Save a null revision in the page's history notifying of the move
2774 $nullRevision = Revision::newNullRevision( $dbw, $oldid, $comment, true );
2775 $nullRevId = $nullRevision->insertOn( $dbw );
2776
2777 $article = new Article( $this );
2778 wfRunHooks( 'NewRevisionFromEditComplete', array($article, $nullRevision, $latest) );
2779
2780 # Rename page entry
2781 $dbw->update( 'page',
2782 /* SET */ array(
2783 'page_touched' => $now,
2784 'page_namespace' => $nt->getNamespace(),
2785 'page_title' => $nt->getDBkey(),
2786 'page_latest' => $nullRevId,
2787 ),
2788 /* WHERE */ array( 'page_id' => $oldid ),
2789 $fname
2790 );
2791 $nt->resetArticleID( $oldid );
2792
2793 if( $createRedirect || !$wgUser->isAllowed('suppressredirect') ) {
2794 # Insert redirect
2795 $mwRedir = MagicWord::get( 'redirect' );
2796 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
2797 $redirectArticle = new Article( $this );
2798 $newid = $redirectArticle->insertOn( $dbw );
2799 $redirectRevision = new Revision( array(
2800 'page' => $newid,
2801 'comment' => $comment,
2802 'text' => $redirectText ) );
2803 $redirectRevision->insertOn( $dbw );
2804 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
2805
2806 wfRunHooks( 'NewRevisionFromEditComplete', array($redirectArticle, $redirectRevision, false) );
2807
2808 # Record the just-created redirect's linking to the page
2809 $dbw->insert( 'pagelinks',
2810 array(
2811 'pl_from' => $newid,
2812 'pl_namespace' => $nt->getNamespace(),
2813 'pl_title' => $nt->getDBkey() ),
2814 $fname );
2815 } else {
2816 $this->resetArticleID( 0 );
2817 }
2818
2819 # Move an image if this is a file
2820 if( $this->getNamespace() == NS_IMAGE ) {
2821 $file = wfLocalFile( $this );
2822 if( $file->exists() ) {
2823 $status = $file->move( $nt );
2824 if( !$status->isOk() ) {
2825 $dbw->rollback();
2826 return $status->getErrorsArray();
2827 }
2828 }
2829 }
2830
2831 # Log the move
2832 $log = new LogPage( 'move' );
2833 $log->addEntry( 'move', $this, $reason, array( 1 => $nt->getPrefixedText()) );
2834
2835 # Purge caches as per article creation
2836 Article::onArticleCreate( $nt );
2837
2838 # Purge old title from squid
2839 # The new title, and links to the new title, are purged in Article::onArticleCreate()
2840 $this->purgeSquid();
2841
2842 }
2843
2844 /**
2845 * Checks if $this can be moved to a given Title
2846 * - Selects for update, so don't call it unless you mean business
2847 *
2848 * @param &$nt \type{Title} the new title to check
2849 * @return \type{\bool} TRUE or FALSE
2850 */
2851 public function isValidMoveTarget( $nt ) {
2852
2853 $fname = 'Title::isValidMoveTarget';
2854 $dbw = wfGetDB( DB_MASTER );
2855
2856 # Is it an existsing file?
2857 if( $nt->getNamespace() == NS_IMAGE ) {
2858 $file = wfLocalFile( $nt );
2859 if( $file->exists() ) {
2860 wfDebug( __METHOD__ . ": file exists\n" );
2861 return false;
2862 }
2863 }
2864
2865 # Is it a redirect?
2866 $id = $nt->getArticleID();
2867 $obj = $dbw->selectRow( array( 'page', 'revision', 'text'),
2868 array( 'page_is_redirect','old_text','old_flags' ),
2869 array( 'page_id' => $id, 'page_latest=rev_id', 'rev_text_id=old_id' ),
2870 $fname, 'FOR UPDATE' );
2871
2872 if ( !$obj || 0 == $obj->page_is_redirect ) {
2873 # Not a redirect
2874 wfDebug( __METHOD__ . ": not a redirect\n" );
2875 return false;
2876 }
2877 $text = Revision::getRevisionText( $obj );
2878
2879 # Does the redirect point to the source?
2880 # Or is it a broken self-redirect, usually caused by namespace collisions?
2881 $m = array();
2882 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $text, $m ) ) {
2883 $redirTitle = Title::newFromText( $m[1] );
2884 if( !is_object( $redirTitle ) ||
2885 ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
2886 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) ) {
2887 wfDebug( __METHOD__ . ": redirect points to other page\n" );
2888 return false;
2889 }
2890 } else {
2891 # Fail safe
2892 wfDebug( __METHOD__ . ": failsafe\n" );
2893 return false;
2894 }
2895
2896 # Does the article have a history?
2897 $row = $dbw->selectRow( array( 'page', 'revision'),
2898 array( 'rev_id' ),
2899 array( 'page_namespace' => $nt->getNamespace(),
2900 'page_title' => $nt->getDBkey(),
2901 'page_id=rev_page AND page_latest != rev_id'
2902 ), $fname, 'FOR UPDATE'
2903 );
2904
2905 # Return true if there was no history
2906 return $row === false;
2907 }
2908
2909 /**
2910 * Can this title be added to a user's watchlist?
2911 *
2912 * @return \type{\bool} TRUE or FALSE
2913 */
2914 public function isWatchable() {
2915 return !$this->isExternal()
2916 && MWNamespace::isWatchable( $this->getNamespace() );
2917 }
2918
2919 /**
2920 * Get categories to which this Title belongs and return an array of
2921 * categories' names.
2922 *
2923 * @return \type{\array} array an array of parents in the form:
2924 * $parent => $currentarticle
2925 */
2926 public function getParentCategories() {
2927 global $wgContLang;
2928
2929 $titlekey = $this->getArticleId();
2930 $dbr = wfGetDB( DB_SLAVE );
2931 $categorylinks = $dbr->tableName( 'categorylinks' );
2932
2933 # NEW SQL
2934 $sql = "SELECT * FROM $categorylinks"
2935 ." WHERE cl_from='$titlekey'"
2936 ." AND cl_from <> '0'"
2937 ." ORDER BY cl_sortkey";
2938
2939 $res = $dbr->query( $sql );
2940
2941 if( $dbr->numRows( $res ) > 0 ) {
2942 foreach( $res as $row )
2943 //$data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$row->cl_to);
2944 $data[$wgContLang->getNSText( NS_CATEGORY ).':'.$row->cl_to] = $this->getFullText();
2945 $dbr->freeResult( $res );
2946 } else {
2947 $data = array();
2948 }
2949 return $data;
2950 }
2951
2952 /**
2953 * Get a tree of parent categories
2954 * @param $children \type{\array} an array with the children in the keys, to check for circular refs
2955 * @return \type{\array} Tree of parent categories
2956 */
2957 public function getParentCategoryTree( $children = array() ) {
2958 $stack = array();
2959 $parents = $this->getParentCategories();
2960
2961 if( $parents ) {
2962 foreach( $parents as $parent => $current ) {
2963 if ( array_key_exists( $parent, $children ) ) {
2964 # Circular reference
2965 $stack[$parent] = array();
2966 } else {
2967 $nt = Title::newFromText($parent);
2968 if ( $nt ) {
2969 $stack[$parent] = $nt->getParentCategoryTree( $children + array($parent => 1) );
2970 }
2971 }
2972 }
2973 return $stack;
2974 } else {
2975 return array();
2976 }
2977 }
2978
2979
2980 /**
2981 * Get an associative array for selecting this title from
2982 * the "page" table
2983 *
2984 * @return \type{\array} Selection array
2985 */
2986 public function pageCond() {
2987 return array( 'page_namespace' => $this->mNamespace, 'page_title' => $this->mDbkeyform );
2988 }
2989
2990 /**
2991 * Get the revision ID of the previous revision
2992 *
2993 * @param $revId \type{\int} Revision ID. Get the revision that was before this one.
2994 * @param $flags \type{\int} GAID_FOR_UPDATE
2995 * @return \twotypes{\int,\bool} Old revision ID, or FALSE if none exists
2996 */
2997 public function getPreviousRevisionID( $revId, $flags=0 ) {
2998 $db = ($flags & GAID_FOR_UPDATE) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
2999 return $db->selectField( 'revision', 'rev_id',
3000 array(
3001 'rev_page' => $this->getArticleId($flags),
3002 'rev_id < ' . intval( $revId )
3003 ),
3004 __METHOD__,
3005 array( 'ORDER BY' => 'rev_id DESC' )
3006 );
3007 }
3008
3009 /**
3010 * Get the revision ID of the next revision
3011 *
3012 * @param $revId \type{\int} Revision ID. Get the revision that was after this one.
3013 * @param $flags \type{\int} GAID_FOR_UPDATE
3014 * @return \twotypes{\int,\bool} Next revision ID, or FALSE if none exists
3015 */
3016 public function getNextRevisionID( $revId, $flags=0 ) {
3017 $db = ($flags & GAID_FOR_UPDATE) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
3018 return $db->selectField( 'revision', 'rev_id',
3019 array(
3020 'rev_page' => $this->getArticleId($flags),
3021 'rev_id > ' . intval( $revId )
3022 ),
3023 __METHOD__,
3024 array( 'ORDER BY' => 'rev_id' )
3025 );
3026 }
3027
3028 /**
3029 * Get the oldest revision timestamp of this page
3030 *
3031 * @return string, MW timestamp
3032 */
3033 public function getEarliestRevTime() {
3034 $dbr = wfGetDB( DB_SLAVE );
3035 if( $this->exists() ) {
3036 $min = $dbr->selectField( 'revision',
3037 'MIN(rev_timestamp)',
3038 array( 'rev_page' => $this->getArticleId() ),
3039 __METHOD__ );
3040 return wfTimestampOrNull( TS_MW, $min );
3041 }
3042 return null;
3043 }
3044
3045 /**
3046 * Get the number of revisions between the given revision IDs.
3047 * Used for diffs and other things that really need it.
3048 *
3049 * @param $old \type{\int} Revision ID.
3050 * @param $new \type{\int} Revision ID.
3051 * @return \type{\int} Number of revisions between these IDs.
3052 */
3053 public function countRevisionsBetween( $old, $new ) {
3054 $dbr = wfGetDB( DB_SLAVE );
3055 return $dbr->selectField( 'revision', 'count(*)',
3056 'rev_page = ' . intval( $this->getArticleId() ) .
3057 ' AND rev_id > ' . intval( $old ) .
3058 ' AND rev_id < ' . intval( $new ),
3059 __METHOD__,
3060 array( 'USE INDEX' => 'PRIMARY' ) );
3061 }
3062
3063 /**
3064 * Compare with another title.
3065 *
3066 * @param \type{Title} $title
3067 * @return \type{\bool} TRUE or FALSE
3068 */
3069 public function equals( Title $title ) {
3070 // Note: === is necessary for proper matching of number-like titles.
3071 return $this->getInterwiki() === $title->getInterwiki()
3072 && $this->getNamespace() == $title->getNamespace()
3073 && $this->getDBkey() === $title->getDBkey();
3074 }
3075
3076 /**
3077 * Callback for usort() to do title sorts by (namespace, title)
3078 */
3079 static function compare( $a, $b ) {
3080 if( $a->getNamespace() == $b->getNamespace() ) {
3081 return strcmp( $a->getText(), $b->getText() );
3082 } else {
3083 return $a->getNamespace() - $b->getNamespace();
3084 }
3085 }
3086
3087 /**
3088 * Return a string representation of this title
3089 *
3090 * @return \type{\string} String representation of this title
3091 */
3092 public function __toString() {
3093 return $this->getPrefixedText();
3094 }
3095
3096 /**
3097 * Check if page exists
3098 * @return \type{\bool} TRUE or FALSE
3099 */
3100 public function exists() {
3101 return $this->getArticleId() != 0;
3102 }
3103
3104 /**
3105 * Do we know that this title definitely exists, or should we otherwise
3106 * consider that it exists?
3107 *
3108 * @return \type{\bool} TRUE or FALSE
3109 */
3110 public function isAlwaysKnown() {
3111 // If the page is form Mediawiki:message/lang, calling wfMsgWeirdKey causes
3112 // the full l10n of that language to be loaded. That takes much memory and
3113 // isn't needed. So we strip the language part away.
3114 // Also, extension messages which are not loaded, are shown as red, because
3115 // we don't call MessageCache::loadAllMessages.
3116 list( $basename, /* rest */ ) = explode( '/', $this->mDbkeyform, 2 );
3117 return $this->isExternal()
3118 || ( $this->mNamespace == NS_MAIN && $this->mDbkeyform == '' )
3119 || ( $this->mNamespace == NS_MEDIAWIKI && wfMsgWeirdKey( $basename ) );
3120 }
3121
3122 /**
3123 * Update page_touched timestamps and send squid purge messages for
3124 * pages linking to this title. May be sent to the job queue depending
3125 * on the number of links. Typically called on create and delete.
3126 */
3127 public function touchLinks() {
3128 $u = new HTMLCacheUpdate( $this, 'pagelinks' );
3129 $u->doUpdate();
3130
3131 if ( $this->getNamespace() == NS_CATEGORY ) {
3132 $u = new HTMLCacheUpdate( $this, 'categorylinks' );
3133 $u->doUpdate();
3134 }
3135 }
3136
3137 /**
3138 * Get the last touched timestamp
3139 * @param Database $db, optional db
3140 * @return \type{\string} Last touched timestamp
3141 */
3142 public function getTouched( $db = NULL ) {
3143 $db = isset($db) ? $db : wfGetDB( DB_SLAVE );
3144 $touched = $db->selectField( 'page', 'page_touched',
3145 array(
3146 'page_namespace' => $this->getNamespace(),
3147 'page_title' => $this->getDBkey()
3148 ), __METHOD__
3149 );
3150 return $touched;
3151 }
3152
3153 /**
3154 * Get the trackback URL for this page
3155 * @return \type{\string} Trackback URL
3156 */
3157 public function trackbackURL() {
3158 global $wgScriptPath, $wgServer;
3159
3160 return "$wgServer$wgScriptPath/trackback.php?article="
3161 . htmlspecialchars(urlencode($this->getPrefixedDBkey()));
3162 }
3163
3164 /**
3165 * Get the trackback RDF for this page
3166 * @return \type{\string} Trackback RDF
3167 */
3168 public function trackbackRDF() {
3169 $url = htmlspecialchars($this->getFullURL());
3170 $title = htmlspecialchars($this->getText());
3171 $tburl = $this->trackbackURL();
3172
3173 // Autodiscovery RDF is placed in comments so HTML validator
3174 // won't barf. This is a rather icky workaround, but seems
3175 // frequently used by this kind of RDF thingy.
3176 //
3177 // Spec: http://www.sixapart.com/pronet/docs/trackback_spec
3178 return "<!--
3179 <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"
3180 xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
3181 xmlns:trackback=\"http://madskills.com/public/xml/rss/module/trackback/\">
3182 <rdf:Description
3183 rdf:about=\"$url\"
3184 dc:identifier=\"$url\"
3185 dc:title=\"$title\"
3186 trackback:ping=\"$tburl\" />
3187 </rdf:RDF>
3188 -->";
3189 }
3190
3191 /**
3192 * Generate strings used for xml 'id' names in monobook tabs
3193 * @return \type{\string} XML 'id' name
3194 */
3195 public function getNamespaceKey() {
3196 global $wgContLang;
3197 switch ($this->getNamespace()) {
3198 case NS_MAIN:
3199 case NS_TALK:
3200 return 'nstab-main';
3201 case NS_USER:
3202 case NS_USER_TALK:
3203 return 'nstab-user';
3204 case NS_MEDIA:
3205 return 'nstab-media';
3206 case NS_SPECIAL:
3207 return 'nstab-special';
3208 case NS_PROJECT:
3209 case NS_PROJECT_TALK:
3210 return 'nstab-project';
3211 case NS_IMAGE:
3212 case NS_IMAGE_TALK:
3213 return 'nstab-image';
3214 case NS_MEDIAWIKI:
3215 case NS_MEDIAWIKI_TALK:
3216 return 'nstab-mediawiki';
3217 case NS_TEMPLATE:
3218 case NS_TEMPLATE_TALK:
3219 return 'nstab-template';
3220 case NS_HELP:
3221 case NS_HELP_TALK:
3222 return 'nstab-help';
3223 case NS_CATEGORY:
3224 case NS_CATEGORY_TALK:
3225 return 'nstab-category';
3226 default:
3227 return 'nstab-' . $wgContLang->lc( $this->getSubjectNsText() );
3228 }
3229 }
3230
3231 /**
3232 * Returns true if this title resolves to the named special page
3233 * @param $name \type{\string} The special page name
3234 */
3235 public function isSpecial( $name ) {
3236 if ( $this->getNamespace() == NS_SPECIAL ) {
3237 list( $thisName, /* $subpage */ ) = SpecialPage::resolveAliasWithSubpage( $this->getDBkey() );
3238 if ( $name == $thisName ) {
3239 return true;
3240 }
3241 }
3242 return false;
3243 }
3244
3245 /**
3246 * If the Title refers to a special page alias which is not the local default,
3247 * @return \type{Title} A new Title which points to the local default. Otherwise, returns $this.
3248 */
3249 public function fixSpecialName() {
3250 if ( $this->getNamespace() == NS_SPECIAL ) {
3251 $canonicalName = SpecialPage::resolveAlias( $this->mDbkeyform );
3252 if ( $canonicalName ) {
3253 $localName = SpecialPage::getLocalNameFor( $canonicalName );
3254 if ( $localName != $this->mDbkeyform ) {
3255 return Title::makeTitle( NS_SPECIAL, $localName );
3256 }
3257 }
3258 }
3259 return $this;
3260 }
3261
3262 /**
3263 * Is this Title in a namespace which contains content?
3264 * In other words, is this a content page, for the purposes of calculating
3265 * statistics, etc?
3266 *
3267 * @return \type{\bool} TRUE or FALSE
3268 */
3269 public function isContentPage() {
3270 return MWNamespace::isContent( $this->getNamespace() );
3271 }
3272
3273 /**
3274 * Get all extant redirects to this Title
3275 *
3276 * @param $ns \twotypes{\int,\null} Single namespace to consider;
3277 * NULL to consider all namespaces
3278 * @return \type{\arrayof{Title}} Redirects to this title
3279 */
3280 public function getRedirectsHere( $ns = null ) {
3281 $redirs = array();
3282
3283 $dbr = wfGetDB( DB_SLAVE );
3284 $where = array(
3285 'rd_namespace' => $this->getNamespace(),
3286 'rd_title' => $this->getDBkey(),
3287 'rd_from = page_id'
3288 );
3289 if ( !is_null($ns) ) $where['page_namespace'] = $ns;
3290
3291 $res = $dbr->select(
3292 array( 'redirect', 'page' ),
3293 array( 'page_namespace', 'page_title' ),
3294 $where,
3295 __METHOD__
3296 );
3297
3298
3299 foreach( $res as $row ) {
3300 $redirs[] = self::newFromRow( $row );
3301 }
3302 return $redirs;
3303 }
3304 }