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