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