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