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