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