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