baea55ef5704d2d2cc3cea30cb31cde181e4de98
[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 global $wgGroupPermissions;
1175 if( $user->isAnon() && ( $wgGroupPermissions['user']['move']
1176 || $wgGroupPermissions['autoconfirmed']['move'] ) ) {
1177 // custom message if logged-in users without any special rights can move
1178 $errors[] = array ( 'movenologintext' );
1179 } else {
1180 $errors[] = array ('movenotallowed');
1181 }
1182 }
1183 } elseif ( $action == 'create' ) {
1184 if( ( $this->isTalkPage() && !$user->isAllowed( 'createtalk' ) ) ||
1185 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage' ) ) )
1186 {
1187 $errors[] = $user->isAnon() ? array ('nocreatetext') : array ('nocreate-loggedin');
1188 }
1189 } elseif( $action == 'move-target' ) {
1190 if( !$user->isAllowed( 'move' ) ) {
1191 // User can't move anything
1192 $errors[] = array ('movenotallowed');
1193 } elseif( !$user->isAllowed( 'move-rootuserpages' )
1194 && $this->getNamespace() == NS_USER && !$this->isSubpage() )
1195 {
1196 // Show user page-specific message only if the user can move other pages
1197 $errors[] = array( 'cant-move-to-user-page' );
1198 }
1199 } elseif( !$user->isAllowed( $action ) ) {
1200 $return = null;
1201 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
1202 User::getGroupsWithPermission( $action ) );
1203 if( $groups ) {
1204 $return = array( 'badaccess-groups',
1205 array( implode( ', ', $groups ), count( $groups ) ) );
1206 } else {
1207 $return = array( "badaccess-group0" );
1208 }
1209 $errors[] = $return;
1210 }
1211
1212 # Short-circuit point
1213 if( $short && count($errors) > 0 ) {
1214 wfProfileOut( __METHOD__ );
1215 return $errors;
1216 }
1217
1218 // Use getUserPermissionsErrors instead
1219 if( !wfRunHooks( 'userCan', array( &$this, &$user, $action, &$result ) ) ) {
1220 wfProfileOut( __METHOD__ );
1221 return $result ? array() : array( array( 'badaccess-group0' ) );
1222 }
1223 // Check getUserPermissionsErrors hook
1224 if( !wfRunHooks( 'getUserPermissionsErrors', array(&$this,&$user,$action,&$result) ) ) {
1225 if( is_array($result) && count($result) && !is_array($result[0]) )
1226 $errors[] = $result; # A single array representing an error
1227 else if( is_array($result) && is_array($result[0]) )
1228 $errors = array_merge( $errors, $result ); # A nested array representing multiple errors
1229 else if( $result !== '' && is_string($result) )
1230 $errors[] = array($result); # A string representing a message-id
1231 else if( $result === false )
1232 $errors[] = array('badaccess-group0'); # a generic "We don't want them to do that"
1233 }
1234 # Short-circuit point
1235 if( $short && count($errors) > 0 ) {
1236 wfProfileOut( __METHOD__ );
1237 return $errors;
1238 }
1239 // Check getUserPermissionsErrorsExpensive hook
1240 if( $doExpensiveQueries && !wfRunHooks( 'getUserPermissionsErrorsExpensive', array(&$this,&$user,$action,&$result) ) ) {
1241 if( is_array($result) && count($result) && !is_array($result[0]) )
1242 $errors[] = $result; # A single array representing an error
1243 else if( is_array($result) && is_array($result[0]) )
1244 $errors = array_merge( $errors, $result ); # A nested array representing multiple errors
1245 else if( $result !== '' && is_string($result) )
1246 $errors[] = array($result); # A string representing a message-id
1247 else if( $result === false )
1248 $errors[] = array('badaccess-group0'); # a generic "We don't want them to do that"
1249 }
1250 # Short-circuit point
1251 if( $short && count($errors) > 0 ) {
1252 wfProfileOut( __METHOD__ );
1253 return $errors;
1254 }
1255
1256 # Only 'createaccount' and 'execute' can be performed on
1257 # special pages, which don't actually exist in the DB.
1258 $specialOKActions = array( 'createaccount', 'execute' );
1259 if( NS_SPECIAL == $this->mNamespace && !in_array( $action, $specialOKActions) ) {
1260 $errors[] = array('ns-specialprotected');
1261 }
1262
1263 # Check $wgNamespaceProtection for restricted namespaces
1264 if( $this->isNamespaceProtected() ) {
1265 $ns = $this->getNamespace() == NS_MAIN ?
1266 wfMsg( 'nstab-main' ) : $this->getNsText();
1267 $errors[] = NS_MEDIAWIKI == $this->mNamespace ?
1268 array('protectedinterface') : array( 'namespaceprotected', $ns );
1269 }
1270
1271 # Protect css/js subpages of user pages
1272 # XXX: this might be better using restrictions
1273 # XXX: Find a way to work around the php bug that prevents using $this->userCanEditCssJsSubpage() from working
1274 if( $this->isCssJsSubpage() && !$user->isAllowed('editusercssjs')
1275 && !preg_match('/^'.preg_quote($user->getName(), '/').'\//', $this->mTextform) )
1276 {
1277 $errors[] = array('customcssjsprotected');
1278 }
1279
1280 # Check against page_restrictions table requirements on this
1281 # page. The user must possess all required rights for this action.
1282 foreach( $this->getRestrictions($action) as $right ) {
1283 // Backwards compatibility, rewrite sysop -> protect
1284 if( $right == 'sysop' ) {
1285 $right = 'protect';
1286 }
1287 if( '' != $right && !$user->isAllowed( $right ) ) {
1288 // Users with 'editprotected' permission can edit protected pages
1289 if( $action=='edit' && $user->isAllowed( 'editprotected' ) ) {
1290 // Users with 'editprotected' permission cannot edit protected pages
1291 // with cascading option turned on.
1292 if( $this->mCascadeRestriction ) {
1293 $errors[] = array( 'protectedpagetext', $right );
1294 }
1295 } else {
1296 $errors[] = array( 'protectedpagetext', $right );
1297 }
1298 }
1299 }
1300 # Short-circuit point
1301 if( $short && count($errors) > 0 ) {
1302 wfProfileOut( __METHOD__ );
1303 return $errors;
1304 }
1305
1306 if( $doExpensiveQueries && !$this->isCssJsSubpage() ) {
1307 # We /could/ use the protection level on the source page, but it's fairly ugly
1308 # as we have to establish a precedence hierarchy for pages included by multiple
1309 # cascade-protected pages. So just restrict it to people with 'protect' permission,
1310 # as they could remove the protection anyway.
1311 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
1312 # Cascading protection depends on more than this page...
1313 # Several cascading protected pages may include this page...
1314 # Check each cascading level
1315 # This is only for protection restrictions, not for all actions
1316 if( $cascadingSources > 0 && isset($restrictions[$action]) ) {
1317 foreach( $restrictions[$action] as $right ) {
1318 $right = ( $right == 'sysop' ) ? 'protect' : $right;
1319 if( '' != $right && !$user->isAllowed( $right ) ) {
1320 $pages = '';
1321 foreach( $cascadingSources as $page )
1322 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
1323 $errors[] = array( 'cascadeprotected', count( $cascadingSources ), $pages );
1324 }
1325 }
1326 }
1327 }
1328 # Short-circuit point
1329 if( $short && count($errors) > 0 ) {
1330 wfProfileOut( __METHOD__ );
1331 return $errors;
1332 }
1333
1334 if( $action == 'protect' ) {
1335 if( $this->getUserPermissionsErrors('edit', $user) != array() ) {
1336 $errors[] = array( 'protect-cantedit' ); // If they can't edit, they shouldn't protect.
1337 }
1338 }
1339
1340 if( $action == 'create' ) {
1341 $title_protection = $this->getTitleProtection();
1342 if( is_array($title_protection) ) {
1343 extract($title_protection); // is this extract() really needed?
1344
1345 if( $pt_create_perm == 'sysop' ) {
1346 $pt_create_perm = 'protect'; // B/C
1347 }
1348 if( $pt_create_perm == '' || !$user->isAllowed($pt_create_perm) ) {
1349 $errors[] = array( 'titleprotected', User::whoIs($pt_user), $pt_reason );
1350 }
1351 }
1352 } elseif( $action == 'move' ) {
1353 // Check for immobile pages
1354 if( !MWNamespace::isMovable( $this->getNamespace() ) ) {
1355 // Specific message for this case
1356 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
1357 } elseif( !$this->isMovable() ) {
1358 // Less specific message for rarer cases
1359 $errors[] = array( 'immobile-page' );
1360 }
1361 } elseif( $action == 'move-target' ) {
1362 if( !MWNamespace::isMovable( $this->getNamespace() ) ) {
1363 $errors[] = array( 'immobile-target-namespace', $this->getNsText() );
1364 } elseif( !$this->isMovable() ) {
1365 $errors[] = array( 'immobile-target-page' );
1366 }
1367 }
1368
1369 wfProfileOut( __METHOD__ );
1370 return $errors;
1371 }
1372
1373 /**
1374 * Is this title subject to title protection?
1375 * @return \type{\mixed} An associative array representing any existent title
1376 * protection, or false if there's none.
1377 */
1378 private function getTitleProtection() {
1379 // Can't protect pages in special namespaces
1380 if ( $this->getNamespace() < 0 ) {
1381 return false;
1382 }
1383
1384 $dbr = wfGetDB( DB_SLAVE );
1385 $res = $dbr->select( 'protected_titles', '*',
1386 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
1387 __METHOD__ );
1388
1389 if ($row = $dbr->fetchRow( $res )) {
1390 return $row;
1391 } else {
1392 return false;
1393 }
1394 }
1395
1396 /**
1397 * Update the title protection status
1398 * @param $create_perm \type{\string} Permission required for creation
1399 * @param $reason \type{\string} Reason for protection
1400 * @param $expiry \type{\string} Expiry timestamp
1401 */
1402 public function updateTitleProtection( $create_perm, $reason, $expiry ) {
1403 global $wgUser,$wgContLang;
1404
1405 if ($create_perm == implode(',',$this->getRestrictions('create'))
1406 && $expiry == $this->mRestrictionsExpiry['create']) {
1407 // No change
1408 return true;
1409 }
1410
1411 list ($namespace, $title) = array( $this->getNamespace(), $this->getDBkey() );
1412
1413 $dbw = wfGetDB( DB_MASTER );
1414
1415 $encodedExpiry = Block::encodeExpiry($expiry, $dbw );
1416
1417 $expiry_description = '';
1418 if ( $encodedExpiry != 'infinity' ) {
1419 $expiry_description = ' (' . wfMsgForContent( 'protect-expiring', $wgContLang->timeanddate( $expiry ) , $wgContLang->date( $expiry ) , $wgContLang->time( $expiry ) ).')';
1420 }
1421 else {
1422 $expiry_description .= ' (' . wfMsgForContent( 'protect-expiry-indefinite' ).')';
1423 }
1424
1425 # Update protection table
1426 if ($create_perm != '' ) {
1427 $dbw->replace( 'protected_titles', array(array('pt_namespace', 'pt_title')),
1428 array( 'pt_namespace' => $namespace, 'pt_title' => $title
1429 , 'pt_create_perm' => $create_perm
1430 , 'pt_timestamp' => Block::encodeExpiry(wfTimestampNow(), $dbw)
1431 , 'pt_expiry' => $encodedExpiry
1432 , 'pt_user' => $wgUser->getId(), 'pt_reason' => $reason ), __METHOD__ );
1433 } else {
1434 $dbw->delete( 'protected_titles', array( 'pt_namespace' => $namespace,
1435 'pt_title' => $title ), __METHOD__ );
1436 }
1437 # Update the protection log
1438 $log = new LogPage( 'protect' );
1439
1440 if( $create_perm ) {
1441 $params = array("[create=$create_perm] $expiry_description",'');
1442 $log->addEntry( $this->mRestrictions['create'] ? 'modify' : 'protect', $this, trim( $reason ), $params );
1443 } else {
1444 $log->addEntry( 'unprotect', $this, $reason );
1445 }
1446
1447 return true;
1448 }
1449
1450 /**
1451 * Remove any title protection due to page existing
1452 */
1453 public function deleteTitleProtection() {
1454 $dbw = wfGetDB( DB_MASTER );
1455
1456 $dbw->delete( 'protected_titles',
1457 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
1458 __METHOD__ );
1459 }
1460
1461 /**
1462 * Would anybody with sufficient privileges be able to move this page?
1463 * Some pages just aren't movable.
1464 *
1465 * @return \type{\bool} TRUE or FALSE
1466 */
1467 public function isMovable() {
1468 return MWNamespace::isMovable( $this->getNamespace() ) && $this->getInterwiki() == '';
1469 }
1470
1471 /**
1472 * Can $wgUser read this page?
1473 * @return \type{\bool} TRUE or FALSE
1474 * @todo fold these checks into userCan()
1475 */
1476 public function userCanRead() {
1477 global $wgUser, $wgGroupPermissions;
1478
1479 $result = null;
1480 wfRunHooks( 'userCan', array( &$this, &$wgUser, 'read', &$result ) );
1481 if ( $result !== null ) {
1482 return $result;
1483 }
1484
1485 # Shortcut for public wikis, allows skipping quite a bit of code
1486 if ( !empty( $wgGroupPermissions['*']['read'] ) )
1487 return true;
1488
1489 if( $wgUser->isAllowed( 'read' ) ) {
1490 return true;
1491 } else {
1492 global $wgWhitelistRead;
1493
1494 /**
1495 * Always grant access to the login page.
1496 * Even anons need to be able to log in.
1497 */
1498 if( $this->isSpecial( 'Userlogin' ) || $this->isSpecial( 'Resetpass' ) ) {
1499 return true;
1500 }
1501
1502 /**
1503 * Bail out if there isn't whitelist
1504 */
1505 if( !is_array($wgWhitelistRead) ) {
1506 return false;
1507 }
1508
1509 /**
1510 * Check for explicit whitelisting
1511 */
1512 $name = $this->getPrefixedText();
1513 $dbName = $this->getPrefixedDBKey();
1514 // Check with and without underscores
1515 if( in_array($name,$wgWhitelistRead,true) || in_array($dbName,$wgWhitelistRead,true) )
1516 return true;
1517
1518 /**
1519 * Old settings might have the title prefixed with
1520 * a colon for main-namespace pages
1521 */
1522 if( $this->getNamespace() == NS_MAIN ) {
1523 if( in_array( ':' . $name, $wgWhitelistRead ) )
1524 return true;
1525 }
1526
1527 /**
1528 * If it's a special page, ditch the subpage bit
1529 * and check again
1530 */
1531 if( $this->getNamespace() == NS_SPECIAL ) {
1532 $name = $this->getDBkey();
1533 list( $name, /* $subpage */) = SpecialPage::resolveAliasWithSubpage( $name );
1534 if ( $name === false ) {
1535 # Invalid special page, but we show standard login required message
1536 return false;
1537 }
1538
1539 $pure = SpecialPage::getTitleFor( $name )->getPrefixedText();
1540 if( in_array( $pure, $wgWhitelistRead, true ) )
1541 return true;
1542 }
1543
1544 }
1545 return false;
1546 }
1547
1548 /**
1549 * Is this a talk page of some sort?
1550 * @return \type{\bool} TRUE or FALSE
1551 */
1552 public function isTalkPage() {
1553 return MWNamespace::isTalk( $this->getNamespace() );
1554 }
1555
1556 /**
1557 * Is this a subpage?
1558 * @return \type{\bool} TRUE or FALSE
1559 */
1560 public function isSubpage() {
1561 return MWNamespace::hasSubpages( $this->mNamespace )
1562 ? strpos( $this->getText(), '/' ) !== false
1563 : false;
1564 }
1565
1566 /**
1567 * Does this have subpages? (Warning, usually requires an extra DB query.)
1568 * @return \type{\bool} TRUE or FALSE
1569 */
1570 public function hasSubpages() {
1571 if( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
1572 # Duh
1573 return false;
1574 }
1575
1576 # We dynamically add a member variable for the purpose of this method
1577 # alone to cache the result. There's no point in having it hanging
1578 # around uninitialized in every Title object; therefore we only add it
1579 # if needed and don't declare it statically.
1580 if( isset( $this->mHasSubpages ) ) {
1581 return $this->mHasSubpages;
1582 }
1583
1584 $subpages = $this->getSubpages( 1 );
1585 if( $subpages instanceof TitleArray )
1586 return $this->mHasSubpages = (bool)$subpages->count();
1587 return $this->mHasSubpages = false;
1588 }
1589
1590 /**
1591 * Get all subpages of this page.
1592 * @param $limit Maximum number of subpages to fetch; -1 for no limit
1593 * @return mixed TitleArray, or empty array if this page's namespace
1594 * doesn't allow subpages
1595 */
1596 public function getSubpages( $limit = -1 ) {
1597 if( !MWNamespace::hasSubpages( $this->getNamespace() ) )
1598 return array();
1599
1600 $dbr = wfGetDB( DB_SLAVE );
1601 $conds['page_namespace'] = $this->getNamespace();
1602 $conds[] = 'page_title LIKE ' . $dbr->addQuotes(
1603 $dbr->escapeLike( $this->getDBkey() ) . '/%' );
1604 $options = array();
1605 if( $limit > -1 )
1606 $options['LIMIT'] = $limit;
1607 return $this->mSubpages = TitleArray::newFromResult(
1608 $dbr->select( 'page',
1609 array( 'page_id', 'page_namespace', 'page_title', 'page_is_redirect' ),
1610 $conds,
1611 __METHOD__,
1612 $options
1613 )
1614 );
1615 }
1616
1617 /**
1618 * Could this page contain custom CSS or JavaScript, based
1619 * on the title?
1620 *
1621 * @return \type{\bool} TRUE or FALSE
1622 */
1623 public function isCssOrJsPage() {
1624 return $this->mNamespace == NS_MEDIAWIKI
1625 && preg_match( '!\.(?:css|js)$!u', $this->mTextform ) > 0;
1626 }
1627
1628 /**
1629 * Is this a .css or .js subpage of a user page?
1630 * @return \type{\bool} TRUE or FALSE
1631 */
1632 public function isCssJsSubpage() {
1633 return ( NS_USER == $this->mNamespace and preg_match("/\\/.*\\.(?:css|js)$/", $this->mTextform ) );
1634 }
1635 /**
1636 * Is this a *valid* .css or .js subpage of a user page?
1637 * Check that the corresponding skin exists
1638 * @return \type{\bool} TRUE or FALSE
1639 */
1640 public function isValidCssJsSubpage() {
1641 if ( $this->isCssJsSubpage() ) {
1642 $skinNames = Skin::getSkinNames();
1643 return array_key_exists( $this->getSkinFromCssJsSubpage(), $skinNames );
1644 } else {
1645 return false;
1646 }
1647 }
1648 /**
1649 * Trim down a .css or .js subpage title to get the corresponding skin name
1650 */
1651 public function getSkinFromCssJsSubpage() {
1652 $subpage = explode( '/', $this->mTextform );
1653 $subpage = $subpage[ count( $subpage ) - 1 ];
1654 return( str_replace( array( '.css', '.js' ), array( '', '' ), $subpage ) );
1655 }
1656 /**
1657 * Is this a .css subpage of a user page?
1658 * @return \type{\bool} TRUE or FALSE
1659 */
1660 public function isCssSubpage() {
1661 return ( NS_USER == $this->mNamespace && preg_match("/\\/.*\\.css$/", $this->mTextform ) );
1662 }
1663 /**
1664 * Is this a .js subpage of a user page?
1665 * @return \type{\bool} TRUE or FALSE
1666 */
1667 public function isJsSubpage() {
1668 return ( NS_USER == $this->mNamespace && preg_match("/\\/.*\\.js$/", $this->mTextform ) );
1669 }
1670 /**
1671 * Protect css/js subpages of user pages: can $wgUser edit
1672 * this page?
1673 *
1674 * @return \type{\bool} TRUE or FALSE
1675 * @todo XXX: this might be better using restrictions
1676 */
1677 public function userCanEditCssJsSubpage() {
1678 global $wgUser;
1679 return ( $wgUser->isAllowed('editusercssjs') || preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform) );
1680 }
1681
1682 /**
1683 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
1684 *
1685 * @return \type{\bool} If the page is subject to cascading restrictions.
1686 */
1687 public function isCascadeProtected() {
1688 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
1689 return ( $sources > 0 );
1690 }
1691
1692 /**
1693 * Cascading protection: Get the source of any cascading restrictions on this page.
1694 *
1695 * @param $get_pages \type{\bool} Whether or not to retrieve the actual pages that the restrictions have come from.
1696 * @return \type{\arrayof{mixed title array, restriction array}} Array of the Title objects of the pages from
1697 * which cascading restrictions have come, false for none, or true if such restrictions exist, but $get_pages was not set.
1698 * The restriction array is an array of each type, each of which contains an array of unique groups.
1699 */
1700 public function getCascadeProtectionSources( $get_pages = true ) {
1701 global $wgRestrictionTypes;
1702
1703 # Define our dimension of restrictions types
1704 $pagerestrictions = array();
1705 foreach( $wgRestrictionTypes as $action )
1706 $pagerestrictions[$action] = array();
1707
1708 if ( isset( $this->mCascadeSources ) && $get_pages ) {
1709 return array( $this->mCascadeSources, $this->mCascadingRestrictions );
1710 } else if ( isset( $this->mHasCascadingRestrictions ) && !$get_pages ) {
1711 return array( $this->mHasCascadingRestrictions, $pagerestrictions );
1712 }
1713
1714 wfProfileIn( __METHOD__ );
1715
1716 $dbr = wfGetDB( DB_SLAVE );
1717
1718 if ( $this->getNamespace() == NS_FILE ) {
1719 $tables = array ('imagelinks', 'page_restrictions');
1720 $where_clauses = array(
1721 'il_to' => $this->getDBkey(),
1722 'il_from=pr_page',
1723 'pr_cascade' => 1 );
1724 } else {
1725 $tables = array ('templatelinks', 'page_restrictions');
1726 $where_clauses = array(
1727 'tl_namespace' => $this->getNamespace(),
1728 'tl_title' => $this->getDBkey(),
1729 'tl_from=pr_page',
1730 'pr_cascade' => 1 );
1731 }
1732
1733 if ( $get_pages ) {
1734 $cols = array('pr_page', 'page_namespace', 'page_title', 'pr_expiry', 'pr_type', 'pr_level' );
1735 $where_clauses[] = 'page_id=pr_page';
1736 $tables[] = 'page';
1737 } else {
1738 $cols = array( 'pr_expiry' );
1739 }
1740
1741 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__ );
1742
1743 $sources = $get_pages ? array() : false;
1744 $now = wfTimestampNow();
1745 $purgeExpired = false;
1746
1747 foreach( $res as $row ) {
1748 $expiry = Block::decodeExpiry( $row->pr_expiry );
1749 if( $expiry > $now ) {
1750 if ($get_pages) {
1751 $page_id = $row->pr_page;
1752 $page_ns = $row->page_namespace;
1753 $page_title = $row->page_title;
1754 $sources[$page_id] = Title::makeTitle($page_ns, $page_title);
1755 # Add groups needed for each restriction type if its not already there
1756 # Make sure this restriction type still exists
1757 if ( isset($pagerestrictions[$row->pr_type]) && !in_array($row->pr_level, $pagerestrictions[$row->pr_type]) ) {
1758 $pagerestrictions[$row->pr_type][]=$row->pr_level;
1759 }
1760 } else {
1761 $sources = true;
1762 }
1763 } else {
1764 // Trigger lazy purge of expired restrictions from the db
1765 $purgeExpired = true;
1766 }
1767 }
1768 if( $purgeExpired ) {
1769 Title::purgeExpiredRestrictions();
1770 }
1771
1772 wfProfileOut( __METHOD__ );
1773
1774 if ( $get_pages ) {
1775 $this->mCascadeSources = $sources;
1776 $this->mCascadingRestrictions = $pagerestrictions;
1777 } else {
1778 $this->mHasCascadingRestrictions = $sources;
1779 }
1780 return array( $sources, $pagerestrictions );
1781 }
1782
1783 function areRestrictionsCascading() {
1784 if (!$this->mRestrictionsLoaded) {
1785 $this->loadRestrictions();
1786 }
1787
1788 return $this->mCascadeRestriction;
1789 }
1790
1791 /**
1792 * Loads a string into mRestrictions array
1793 * @param $res \type{Resource} restrictions as an SQL result.
1794 */
1795 private function loadRestrictionsFromRow( $res, $oldFashionedRestrictions = NULL ) {
1796 global $wgRestrictionTypes;
1797 $dbr = wfGetDB( DB_SLAVE );
1798
1799 foreach( $wgRestrictionTypes as $type ){
1800 $this->mRestrictions[$type] = array();
1801 $this->mRestrictionsExpiry[$type] = Block::decodeExpiry('');
1802 }
1803
1804 $this->mCascadeRestriction = false;
1805
1806 # Backwards-compatibility: also load the restrictions from the page record (old format).
1807
1808 if ( $oldFashionedRestrictions === NULL ) {
1809 $oldFashionedRestrictions = $dbr->selectField( 'page', 'page_restrictions',
1810 array( 'page_id' => $this->getArticleId() ), __METHOD__ );
1811 }
1812
1813 if ($oldFashionedRestrictions != '') {
1814
1815 foreach( explode( ':', trim( $oldFashionedRestrictions ) ) as $restrict ) {
1816 $temp = explode( '=', trim( $restrict ) );
1817 if(count($temp) == 1) {
1818 // old old format should be treated as edit/move restriction
1819 $this->mRestrictions['edit'] = explode( ',', trim( $temp[0] ) );
1820 $this->mRestrictions['move'] = explode( ',', trim( $temp[0] ) );
1821 } else {
1822 $this->mRestrictions[$temp[0]] = explode( ',', trim( $temp[1] ) );
1823 }
1824 }
1825
1826 $this->mOldRestrictions = true;
1827
1828 }
1829
1830 if( $dbr->numRows( $res ) ) {
1831 # Current system - load second to make them override.
1832 $now = wfTimestampNow();
1833 $purgeExpired = false;
1834
1835 foreach( $res as $row ) {
1836 # Cycle through all the restrictions.
1837
1838 // Don't take care of restrictions types that aren't in $wgRestrictionTypes
1839 if( !in_array( $row->pr_type, $wgRestrictionTypes ) )
1840 continue;
1841
1842 // This code should be refactored, now that it's being used more generally,
1843 // But I don't really see any harm in leaving it in Block for now -werdna
1844 $expiry = Block::decodeExpiry( $row->pr_expiry );
1845
1846 // Only apply the restrictions if they haven't expired!
1847 if ( !$expiry || $expiry > $now ) {
1848 $this->mRestrictionsExpiry[$row->pr_type] = $expiry;
1849 $this->mRestrictions[$row->pr_type] = explode( ',', trim( $row->pr_level ) );
1850
1851 $this->mCascadeRestriction |= $row->pr_cascade;
1852 } else {
1853 // Trigger a lazy purge of expired restrictions
1854 $purgeExpired = true;
1855 }
1856 }
1857
1858 if( $purgeExpired ) {
1859 Title::purgeExpiredRestrictions();
1860 }
1861 }
1862
1863 $this->mRestrictionsLoaded = true;
1864 }
1865
1866 /**
1867 * Load restrictions from the page_restrictions table
1868 */
1869 public function loadRestrictions( $oldFashionedRestrictions = NULL ) {
1870 if( !$this->mRestrictionsLoaded ) {
1871 if ($this->exists()) {
1872 $dbr = wfGetDB( DB_SLAVE );
1873
1874 $res = $dbr->select( 'page_restrictions', '*',
1875 array ( 'pr_page' => $this->getArticleId() ), __METHOD__ );
1876
1877 $this->loadRestrictionsFromRow( $res, $oldFashionedRestrictions );
1878 } else {
1879 $title_protection = $this->getTitleProtection();
1880
1881 if (is_array($title_protection)) {
1882 extract($title_protection);
1883
1884 $now = wfTimestampNow();
1885 $expiry = Block::decodeExpiry($pt_expiry);
1886
1887 if (!$expiry || $expiry > $now) {
1888 // Apply the restrictions
1889 $this->mRestrictionsExpiry['create'] = $expiry;
1890 $this->mRestrictions['create'] = explode(',', trim($pt_create_perm) );
1891 } else { // Get rid of the old restrictions
1892 Title::purgeExpiredRestrictions();
1893 }
1894 } else {
1895 $this->mRestrictionsExpiry['create'] = Block::decodeExpiry('');
1896 }
1897 $this->mRestrictionsLoaded = true;
1898 }
1899 }
1900 }
1901
1902 /**
1903 * Purge expired restrictions from the page_restrictions table
1904 */
1905 static function purgeExpiredRestrictions() {
1906 $dbw = wfGetDB( DB_MASTER );
1907 $dbw->delete( 'page_restrictions',
1908 array( 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
1909 __METHOD__ );
1910
1911 $dbw->delete( 'protected_titles',
1912 array( 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
1913 __METHOD__ );
1914 }
1915
1916 /**
1917 * Accessor/initialisation for mRestrictions
1918 *
1919 * @param $action \type{\string} action that permission needs to be checked for
1920 * @return \type{\arrayof{\string}} the array of groups allowed to edit this article
1921 */
1922 public function getRestrictions( $action ) {
1923 if( !$this->mRestrictionsLoaded ) {
1924 $this->loadRestrictions();
1925 }
1926 return isset( $this->mRestrictions[$action] )
1927 ? $this->mRestrictions[$action]
1928 : array();
1929 }
1930
1931 /**
1932 * Get the expiry time for the restriction against a given action
1933 * @return 14-char timestamp, or 'infinity' if the page is protected forever
1934 * or not protected at all, or false if the action is not recognised.
1935 */
1936 public function getRestrictionExpiry( $action ) {
1937 if( !$this->mRestrictionsLoaded ) {
1938 $this->loadRestrictions();
1939 }
1940 return isset( $this->mRestrictionsExpiry[$action] ) ? $this->mRestrictionsExpiry[$action] : false;
1941 }
1942
1943 /**
1944 * Is there a version of this page in the deletion archive?
1945 * @return \type{\int} the number of archived revisions
1946 */
1947 public function isDeleted() {
1948 if( $this->getNamespace() < 0 ) {
1949 $n = 0;
1950 } else {
1951 $dbr = wfGetDB( DB_SLAVE );
1952 $n = $dbr->selectField( 'archive', 'COUNT(*)',
1953 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
1954 __METHOD__
1955 );
1956 if( $this->getNamespace() == NS_FILE ) {
1957 $n += $dbr->selectField( 'filearchive', 'COUNT(*)',
1958 array( 'fa_name' => $this->getDBkey() ),
1959 __METHOD__
1960 );
1961 }
1962 }
1963 return (int)$n;
1964 }
1965
1966 /**
1967 * Is there a version of this page in the deletion archive?
1968 * @return bool
1969 */
1970 public function isDeletedQuick() {
1971 if( $this->getNamespace() < 0 ) {
1972 return false;
1973 }
1974 $dbr = wfGetDB( DB_SLAVE );
1975 $deleted = (bool)$dbr->selectField( 'archive', '1',
1976 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
1977 __METHOD__
1978 );
1979 if( !$deleted && $this->getNamespace() == NS_FILE ) {
1980 $deleted = (bool)$dbr->selectField( 'filearchive', '1',
1981 array( 'fa_name' => $this->getDBkey() ),
1982 __METHOD__
1983 );
1984 }
1985 return $deleted;
1986 }
1987
1988 /**
1989 * Get the article ID for this Title from the link cache,
1990 * adding it if necessary
1991 * @param $flags \type{\int} a bit field; may be GAID_FOR_UPDATE to select
1992 * for update
1993 * @return \type{\int} the ID
1994 */
1995 public function getArticleID( $flags = 0 ) {
1996 if( $this->getNamespace() < 0 ) {
1997 return $this->mArticleID = 0;
1998 }
1999 $linkCache = LinkCache::singleton();
2000 if( $flags & GAID_FOR_UPDATE ) {
2001 $oldUpdate = $linkCache->forUpdate( true );
2002 $linkCache->clearLink( $this );
2003 $this->mArticleID = $linkCache->addLinkObj( $this );
2004 $linkCache->forUpdate( $oldUpdate );
2005 } else {
2006 if( -1 == $this->mArticleID ) {
2007 $this->mArticleID = $linkCache->addLinkObj( $this );
2008 }
2009 }
2010 return $this->mArticleID;
2011 }
2012
2013 /**
2014 * Is this an article that is a redirect page?
2015 * Uses link cache, adding it if necessary
2016 * @param $flags \type{\int} a bit field; may be GAID_FOR_UPDATE to select for update
2017 * @return \type{\bool}
2018 */
2019 public function isRedirect( $flags = 0 ) {
2020 if( !is_null($this->mRedirect) )
2021 return $this->mRedirect;
2022 # Calling getArticleID() loads the field from cache as needed
2023 if( !$this->getArticleID($flags) ) {
2024 return $this->mRedirect = false;
2025 }
2026 $linkCache = LinkCache::singleton();
2027 $this->mRedirect = (bool)$linkCache->getGoodLinkFieldObj( $this, 'redirect' );
2028
2029 return $this->mRedirect;
2030 }
2031
2032 /**
2033 * What is the length of this page?
2034 * Uses link cache, adding it if necessary
2035 * @param $flags \type{\int} a bit field; may be GAID_FOR_UPDATE to select for update
2036 * @return \type{\bool}
2037 */
2038 public function getLength( $flags = 0 ) {
2039 if( $this->mLength != -1 )
2040 return $this->mLength;
2041 # Calling getArticleID() loads the field from cache as needed
2042 if( !$this->getArticleID($flags) ) {
2043 return $this->mLength = 0;
2044 }
2045 $linkCache = LinkCache::singleton();
2046 $this->mLength = intval( $linkCache->getGoodLinkFieldObj( $this, 'length' ) );
2047
2048 return $this->mLength;
2049 }
2050
2051 /**
2052 * What is the page_latest field for this page?
2053 * @param $flags \type{\int} a bit field; may be GAID_FOR_UPDATE to select for update
2054 * @return \type{\int}
2055 */
2056 public function getLatestRevID( $flags = 0 ) {
2057 if( $this->mLatestID !== false )
2058 return $this->mLatestID;
2059
2060 $db = ($flags & GAID_FOR_UPDATE) ? wfGetDB(DB_MASTER) : wfGetDB(DB_SLAVE);
2061 $this->mLatestID = $db->selectField( 'page', 'page_latest', $this->pageCond(), __METHOD__ );
2062 return $this->mLatestID;
2063 }
2064
2065 /**
2066 * This clears some fields in this object, and clears any associated
2067 * keys in the "bad links" section of the link cache.
2068 *
2069 * - This is called from Article::insertNewArticle() to allow
2070 * loading of the new page_id. It's also called from
2071 * Article::doDeleteArticle()
2072 *
2073 * @param $newid \type{\int} the new Article ID
2074 */
2075 public function resetArticleID( $newid ) {
2076 $linkCache = LinkCache::singleton();
2077 $linkCache->clearBadLink( $this->getPrefixedDBkey() );
2078
2079 if ( $newid === false ) { $this->mArticleID = -1; }
2080 else { $this->mArticleID = $newid; }
2081 $this->mRestrictionsLoaded = false;
2082 $this->mRestrictions = array();
2083 }
2084
2085 /**
2086 * Updates page_touched for this page; called from LinksUpdate.php
2087 * @return \type{\bool} true if the update succeded
2088 */
2089 public function invalidateCache() {
2090 if( wfReadOnly() ) {
2091 return;
2092 }
2093 $dbw = wfGetDB( DB_MASTER );
2094 $success = $dbw->update( 'page',
2095 array( 'page_touched' => $dbw->timestamp() ),
2096 $this->pageCond(),
2097 __METHOD__
2098 );
2099 HTMLFileCache::clearFileCache( $this );
2100 return $success;
2101 }
2102
2103 /**
2104 * Prefix some arbitrary text with the namespace or interwiki prefix
2105 * of this object
2106 *
2107 * @param $name \type{\string} the text
2108 * @return \type{\string} the prefixed text
2109 * @private
2110 */
2111 /* private */ function prefix( $name ) {
2112 $p = '';
2113 if ( '' != $this->mInterwiki ) {
2114 $p = $this->mInterwiki . ':';
2115 }
2116 if ( 0 != $this->mNamespace ) {
2117 $p .= $this->getNsText() . ':';
2118 }
2119 return $p . $name;
2120 }
2121
2122 /**
2123 * Secure and split - main initialisation function for this object
2124 *
2125 * Assumes that mDbkeyform has been set, and is urldecoded
2126 * and uses underscores, but not otherwise munged. This function
2127 * removes illegal characters, splits off the interwiki and
2128 * namespace prefixes, sets the other forms, and canonicalizes
2129 * everything.
2130 * @return \type{\bool} true on success
2131 */
2132 private function secureAndSplit() {
2133 global $wgContLang, $wgLocalInterwiki, $wgCapitalLinks;
2134
2135 # Initialisation
2136 static $rxTc = false;
2137 if( !$rxTc ) {
2138 # Matching titles will be held as illegal.
2139 $rxTc = '/' .
2140 # Any character not allowed is forbidden...
2141 '[^' . Title::legalChars() . ']' .
2142 # URL percent encoding sequences interfere with the ability
2143 # to round-trip titles -- you can't link to them consistently.
2144 '|%[0-9A-Fa-f]{2}' .
2145 # XML/HTML character references produce similar issues.
2146 '|&[A-Za-z0-9\x80-\xff]+;' .
2147 '|&#[0-9]+;' .
2148 '|&#x[0-9A-Fa-f]+;' .
2149 '/S';
2150 }
2151
2152 $this->mInterwiki = $this->mFragment = '';
2153 $this->mNamespace = $this->mDefaultNamespace; # Usually NS_MAIN
2154
2155 $dbkey = $this->mDbkeyform;
2156
2157 # Strip Unicode bidi override characters.
2158 # Sometimes they slip into cut-n-pasted page titles, where the
2159 # override chars get included in list displays.
2160 $dbkey = preg_replace( '/\xE2\x80[\x8E\x8F\xAA-\xAE]/S', '', $dbkey );
2161
2162 # Clean up whitespace
2163 #
2164 $dbkey = preg_replace( '/[ _]+/', '_', $dbkey );
2165 $dbkey = trim( $dbkey, '_' );
2166
2167 if ( '' == $dbkey ) {
2168 return false;
2169 }
2170
2171 if( false !== strpos( $dbkey, UTF8_REPLACEMENT ) ) {
2172 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
2173 return false;
2174 }
2175
2176 $this->mDbkeyform = $dbkey;
2177
2178 # Initial colon indicates main namespace rather than specified default
2179 # but should not create invalid {ns,title} pairs such as {0,Project:Foo}
2180 if ( ':' == $dbkey{0} ) {
2181 $this->mNamespace = NS_MAIN;
2182 $dbkey = substr( $dbkey, 1 ); # remove the colon but continue processing
2183 $dbkey = trim( $dbkey, '_' ); # remove any subsequent whitespace
2184 }
2185
2186 # Namespace or interwiki prefix
2187 $firstPass = true;
2188 $prefixRegexp = "/^(.+?)_*:_*(.*)$/S";
2189 do {
2190 $m = array();
2191 if ( preg_match( $prefixRegexp, $dbkey, $m ) ) {
2192 $p = $m[1];
2193 if ( $ns = $wgContLang->getNsIndex( $p ) ) {
2194 # Ordinary namespace
2195 $dbkey = $m[2];
2196 $this->mNamespace = $ns;
2197 # For Talk:X pages, check if X has a "namespace" prefix
2198 if( $ns == NS_TALK && preg_match( $prefixRegexp, $dbkey, $x ) ) {
2199 if( $wgContLang->getNsIndex( $x[1] ) )
2200 return false; # Disallow Talk:File:x type titles...
2201 else if( Interwiki::isValidInterwiki( $x[1] ) )
2202 return false; # Disallow Talk:Interwiki:x type titles...
2203 }
2204 } elseif( Interwiki::isValidInterwiki( $p ) ) {
2205 if( !$firstPass ) {
2206 # Can't make a local interwiki link to an interwiki link.
2207 # That's just crazy!
2208 return false;
2209 }
2210
2211 # Interwiki link
2212 $dbkey = $m[2];
2213 $this->mInterwiki = $wgContLang->lc( $p );
2214
2215 # Redundant interwiki prefix to the local wiki
2216 if ( 0 == strcasecmp( $this->mInterwiki, $wgLocalInterwiki ) ) {
2217 if( $dbkey == '' ) {
2218 # Can't have an empty self-link
2219 return false;
2220 }
2221 $this->mInterwiki = '';
2222 $firstPass = false;
2223 # Do another namespace split...
2224 continue;
2225 }
2226
2227 # If there's an initial colon after the interwiki, that also
2228 # resets the default namespace
2229 if ( $dbkey !== '' && $dbkey[0] == ':' ) {
2230 $this->mNamespace = NS_MAIN;
2231 $dbkey = substr( $dbkey, 1 );
2232 }
2233 }
2234 # If there's no recognized interwiki or namespace,
2235 # then let the colon expression be part of the title.
2236 }
2237 break;
2238 } while( true );
2239
2240 # We already know that some pages won't be in the database!
2241 #
2242 if ( '' != $this->mInterwiki || NS_SPECIAL == $this->mNamespace ) {
2243 $this->mArticleID = 0;
2244 }
2245 $fragment = strstr( $dbkey, '#' );
2246 if ( false !== $fragment ) {
2247 $this->setFragment( $fragment );
2248 $dbkey = substr( $dbkey, 0, strlen( $dbkey ) - strlen( $fragment ) );
2249 # remove whitespace again: prevents "Foo_bar_#"
2250 # becoming "Foo_bar_"
2251 $dbkey = preg_replace( '/_*$/', '', $dbkey );
2252 }
2253
2254 # Reject illegal characters.
2255 #
2256 if( preg_match( $rxTc, $dbkey ) ) {
2257 return false;
2258 }
2259
2260 /**
2261 * Pages with "/./" or "/../" appearing in the URLs will often be un-
2262 * reachable due to the way web browsers deal with 'relative' URLs.
2263 * Also, they conflict with subpage syntax. Forbid them explicitly.
2264 */
2265 if ( strpos( $dbkey, '.' ) !== false &&
2266 ( $dbkey === '.' || $dbkey === '..' ||
2267 strpos( $dbkey, './' ) === 0 ||
2268 strpos( $dbkey, '../' ) === 0 ||
2269 strpos( $dbkey, '/./' ) !== false ||
2270 strpos( $dbkey, '/../' ) !== false ||
2271 substr( $dbkey, -2 ) == '/.' ||
2272 substr( $dbkey, -3 ) == '/..' ) )
2273 {
2274 return false;
2275 }
2276
2277 /**
2278 * Magic tilde sequences? Nu-uh!
2279 */
2280 if( strpos( $dbkey, '~~~' ) !== false ) {
2281 return false;
2282 }
2283
2284 /**
2285 * Limit the size of titles to 255 bytes.
2286 * This is typically the size of the underlying database field.
2287 * We make an exception for special pages, which don't need to be stored
2288 * in the database, and may edge over 255 bytes due to subpage syntax
2289 * for long titles, e.g. [[Special:Block/Long name]]
2290 */
2291 if ( ( $this->mNamespace != NS_SPECIAL && strlen( $dbkey ) > 255 ) ||
2292 strlen( $dbkey ) > 512 )
2293 {
2294 return false;
2295 }
2296
2297 /**
2298 * Normally, all wiki links are forced to have
2299 * an initial capital letter so [[foo]] and [[Foo]]
2300 * point to the same place.
2301 *
2302 * Don't force it for interwikis, since the other
2303 * site might be case-sensitive.
2304 */
2305 $this->mUserCaseDBKey = $dbkey;
2306 if( $wgCapitalLinks && $this->mInterwiki == '') {
2307 $dbkey = $wgContLang->ucfirst( $dbkey );
2308 }
2309
2310 /**
2311 * Can't make a link to a namespace alone...
2312 * "empty" local links can only be self-links
2313 * with a fragment identifier.
2314 */
2315 if( $dbkey == '' &&
2316 $this->mInterwiki == '' &&
2317 $this->mNamespace != NS_MAIN ) {
2318 return false;
2319 }
2320 // Allow IPv6 usernames to start with '::' by canonicalizing IPv6 titles.
2321 // IP names are not allowed for accounts, and can only be referring to
2322 // edits from the IP. Given '::' abbreviations and caps/lowercaps,
2323 // there are numerous ways to present the same IP. Having sp:contribs scan
2324 // them all is silly and having some show the edits and others not is
2325 // inconsistent. Same for talk/userpages. Keep them normalized instead.
2326 $dbkey = ($this->mNamespace == NS_USER || $this->mNamespace == NS_USER_TALK) ?
2327 IP::sanitizeIP( $dbkey ) : $dbkey;
2328 // Any remaining initial :s are illegal.
2329 if ( $dbkey !== '' && ':' == $dbkey{0} ) {
2330 return false;
2331 }
2332
2333 # Fill fields
2334 $this->mDbkeyform = $dbkey;
2335 $this->mUrlform = wfUrlencode( $dbkey );
2336
2337 $this->mTextform = str_replace( '_', ' ', $dbkey );
2338
2339 return true;
2340 }
2341
2342 /**
2343 * Set the fragment for this title. Removes the first character from the
2344 * specified fragment before setting, so it assumes you're passing it with
2345 * an initial "#".
2346 *
2347 * Deprecated for public use, use Title::makeTitle() with fragment parameter.
2348 * Still in active use privately.
2349 *
2350 * @param $fragment \type{\string} text
2351 */
2352 public function setFragment( $fragment ) {
2353 $this->mFragment = str_replace( '_', ' ', substr( $fragment, 1 ) );
2354 }
2355
2356 /**
2357 * Get a Title object associated with the talk page of this article
2358 * @return \type{Title} the object for the talk page
2359 */
2360 public function getTalkPage() {
2361 return Title::makeTitle( MWNamespace::getTalk( $this->getNamespace() ), $this->getDBkey() );
2362 }
2363
2364 /**
2365 * Get a title object associated with the subject page of this
2366 * talk page
2367 *
2368 * @return \type{Title} the object for the subject page
2369 */
2370 public function getSubjectPage() {
2371 // Is this the same title?
2372 $subjectNS = MWNamespace::getSubject( $this->getNamespace() );
2373 if( $this->getNamespace() == $subjectNS ) {
2374 return $this;
2375 }
2376 return Title::makeTitle( $subjectNS, $this->getDBkey() );
2377 }
2378
2379 /**
2380 * Get an array of Title objects linking to this Title
2381 * Also stores the IDs in the link cache.
2382 *
2383 * WARNING: do not use this function on arbitrary user-supplied titles!
2384 * On heavily-used templates it will max out the memory.
2385 *
2386 * @param array $options may be FOR UPDATE
2387 * @return \type{\arrayof{Title}} the Title objects linking here
2388 */
2389 public function getLinksTo( $options = array(), $table = 'pagelinks', $prefix = 'pl' ) {
2390 $linkCache = LinkCache::singleton();
2391
2392 if ( count( $options ) > 0 ) {
2393 $db = wfGetDB( DB_MASTER );
2394 } else {
2395 $db = wfGetDB( DB_SLAVE );
2396 }
2397
2398 $res = $db->select( array( 'page', $table ),
2399 array( 'page_namespace', 'page_title', 'page_id', 'page_len', 'page_is_redirect' ),
2400 array(
2401 "{$prefix}_from=page_id",
2402 "{$prefix}_namespace" => $this->getNamespace(),
2403 "{$prefix}_title" => $this->getDBkey() ),
2404 __METHOD__,
2405 $options );
2406
2407 $retVal = array();
2408 if ( $db->numRows( $res ) ) {
2409 foreach( $res as $row ) {
2410 if ( $titleObj = Title::makeTitle( $row->page_namespace, $row->page_title ) ) {
2411 $linkCache->addGoodLinkObj( $row->page_id, $titleObj, $row->page_len, $row->page_is_redirect );
2412 $retVal[] = $titleObj;
2413 }
2414 }
2415 }
2416 $db->freeResult( $res );
2417 return $retVal;
2418 }
2419
2420 /**
2421 * Get an array of Title objects using this Title as a template
2422 * Also stores the IDs in the link cache.
2423 *
2424 * WARNING: do not use this function on arbitrary user-supplied titles!
2425 * On heavily-used templates it will max out the memory.
2426 *
2427 * @param array $options may be FOR UPDATE
2428 * @return \type{\arrayof{Title}} the Title objects linking here
2429 */
2430 public function getTemplateLinksTo( $options = array() ) {
2431 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
2432 }
2433
2434 /**
2435 * Get an array of Title objects referring to non-existent articles linked from this page
2436 *
2437 * @todo check if needed (used only in SpecialBrokenRedirects.php, and should use redirect table in this case)
2438 * @return \type{\arrayof{Title}} the Title objects
2439 */
2440 public function getBrokenLinksFrom() {
2441 if ( $this->getArticleId() == 0 ) {
2442 # All links from article ID 0 are false positives
2443 return array();
2444 }
2445
2446 $dbr = wfGetDB( DB_SLAVE );
2447 $res = $dbr->select(
2448 array( 'page', 'pagelinks' ),
2449 array( 'pl_namespace', 'pl_title' ),
2450 array(
2451 'pl_from' => $this->getArticleId(),
2452 'page_namespace IS NULL'
2453 ),
2454 __METHOD__, array(),
2455 array(
2456 'page' => array(
2457 'LEFT JOIN',
2458 array( 'pl_namespace=page_namespace', 'pl_title=page_title' )
2459 )
2460 )
2461 );
2462
2463 $retVal = array();
2464 foreach( $res as $row ) {
2465 $retVal[] = Title::makeTitle( $row->pl_namespace, $row->pl_title );
2466 }
2467 return $retVal;
2468 }
2469
2470
2471 /**
2472 * Get a list of URLs to purge from the Squid cache when this
2473 * page changes
2474 *
2475 * @return \type{\arrayof{\string}} the URLs
2476 */
2477 public function getSquidURLs() {
2478 global $wgContLang;
2479
2480 $urls = array(
2481 $this->getInternalURL(),
2482 $this->getInternalURL( 'action=history' )
2483 );
2484
2485 // purge variant urls as well
2486 if($wgContLang->hasVariants()){
2487 $variants = $wgContLang->getVariants();
2488 foreach($variants as $vCode){
2489 if($vCode==$wgContLang->getCode()) continue; // we don't want default variant
2490 $urls[] = $this->getInternalURL('',$vCode);
2491 }
2492 }
2493
2494 return $urls;
2495 }
2496
2497 /**
2498 * Purge all applicable Squid URLs
2499 */
2500 public function purgeSquid() {
2501 global $wgUseSquid;
2502 if ( $wgUseSquid ) {
2503 $urls = $this->getSquidURLs();
2504 $u = new SquidUpdate( $urls );
2505 $u->doUpdate();
2506 }
2507 }
2508
2509 /**
2510 * Move this page without authentication
2511 * @param &$nt \type{Title} the new page Title
2512 */
2513 public function moveNoAuth( &$nt ) {
2514 return $this->moveTo( $nt, false );
2515 }
2516
2517 /**
2518 * Check whether a given move operation would be valid.
2519 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
2520 * @param &$nt \type{Title} the new title
2521 * @param $auth \type{\bool} indicates whether $wgUser's permissions
2522 * should be checked
2523 * @param $reason \type{\string} is the log summary of the move, used for spam checking
2524 * @return \type{\mixed} True on success, getUserPermissionsErrors()-like array on failure
2525 */
2526 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
2527 global $wgUser;
2528
2529 $errors = array();
2530 if( !$nt ) {
2531 // Normally we'd add this to $errors, but we'll get
2532 // lots of syntax errors if $nt is not an object
2533 return array(array('badtitletext'));
2534 }
2535 if( $this->equals( $nt ) ) {
2536 $errors[] = array('selfmove');
2537 }
2538 if( !$this->isMovable() ) {
2539 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
2540 }
2541 if ( $nt->getInterwiki() != '' ) {
2542 $errors[] = array( 'immobile-target-namespace-iw' );
2543 }
2544 if ( !$nt->isMovable() ) {
2545 $errors[] = array('immobile-target-namespace', $nt->getNsText() );
2546 }
2547
2548 $oldid = $this->getArticleID();
2549 $newid = $nt->getArticleID();
2550
2551 if ( strlen( $nt->getDBkey() ) < 1 ) {
2552 $errors[] = array('articleexists');
2553 }
2554 if ( ( '' == $this->getDBkey() ) ||
2555 ( !$oldid ) ||
2556 ( '' == $nt->getDBkey() ) ) {
2557 $errors[] = array('badarticleerror');
2558 }
2559
2560 // Image-specific checks
2561 if( $this->getNamespace() == NS_FILE ) {
2562 $file = wfLocalFile( $this );
2563 if( $file->exists() ) {
2564 if( $nt->getNamespace() != NS_FILE ) {
2565 $errors[] = array('imagenocrossnamespace');
2566 }
2567 if( $nt->getText() != wfStripIllegalFilenameChars( $nt->getText() ) ) {
2568 $errors[] = array('imageinvalidfilename');
2569 }
2570 if( !File::checkExtensionCompatibility( $file, $nt->getDBkey() ) ) {
2571 $errors[] = array('imagetypemismatch');
2572 }
2573 }
2574 }
2575
2576 if ( $auth ) {
2577 $errors = wfMergeErrorArrays( $errors,
2578 $this->getUserPermissionsErrors('move', $wgUser),
2579 $this->getUserPermissionsErrors('edit', $wgUser),
2580 $nt->getUserPermissionsErrors('move-target', $wgUser),
2581 $nt->getUserPermissionsErrors('edit', $wgUser) );
2582 }
2583
2584 $match = EditPage::matchSummarySpamRegex( $reason );
2585 if( $match !== false ) {
2586 // This is kind of lame, won't display nice
2587 $errors[] = array('spamprotectiontext');
2588 }
2589
2590 $err = null;
2591 if( !wfRunHooks( 'AbortMove', array( $this, $nt, $wgUser, &$err, $reason ) ) ) {
2592 $errors[] = array('hookaborted', $err);
2593 }
2594
2595 # The move is allowed only if (1) the target doesn't exist, or
2596 # (2) the target is a redirect to the source, and has no history
2597 # (so we can undo bad moves right after they're done).
2598
2599 if ( 0 != $newid ) { # Target exists; check for validity
2600 if ( ! $this->isValidMoveTarget( $nt ) ) {
2601 $errors[] = array('articleexists');
2602 }
2603 } else {
2604 $tp = $nt->getTitleProtection();
2605 $right = ( $tp['pt_create_perm'] == 'sysop' ) ? 'protect' : $tp['pt_create_perm'];
2606 if ( $tp and !$wgUser->isAllowed( $right ) ) {
2607 $errors[] = array('cantmove-titleprotected');
2608 }
2609 }
2610 if(empty($errors))
2611 return true;
2612 return $errors;
2613 }
2614
2615 /**
2616 * Move a title to a new location
2617 * @param &$nt \type{Title} the new title
2618 * @param $auth \type{\bool} indicates whether $wgUser's permissions
2619 * should be checked
2620 * @param $reason \type{\string} The reason for the move
2621 * @param $createRedirect \type{\bool} Whether to create a redirect from the old title to the new title.
2622 * Ignored if the user doesn't have the suppressredirect right.
2623 * @return \type{\mixed} true on success, getUserPermissionsErrors()-like array on failure
2624 */
2625 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true ) {
2626 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
2627 if( is_array( $err ) ) {
2628 return $err;
2629 }
2630
2631 // If it is a file, more it first. It is done before all other moving stuff is done because it's hard to revert
2632 $dbw = wfGetDB( DB_MASTER );
2633 if( $this->getNamespace() == NS_FILE ) {
2634 $file = wfLocalFile( $this );
2635 if( $file->exists() ) {
2636 $status = $file->move( $nt );
2637 if( !$status->isOk() ) {
2638 return $status->getErrorsArray();
2639 }
2640 }
2641 }
2642
2643 $pageid = $this->getArticleID();
2644 $protected = $this->isProtected();
2645 if( $nt->exists() ) {
2646 $err = $this->moveOverExistingRedirect( $nt, $reason, $createRedirect );
2647 $pageCountChange = ($createRedirect ? 0 : -1);
2648 } else { # Target didn't exist, do normal move.
2649 $err = $this->moveToNewTitle( $nt, $reason, $createRedirect );
2650 $pageCountChange = ($createRedirect ? 1 : 0);
2651 }
2652
2653 if( is_array( $err ) ) {
2654 return $err;
2655 }
2656 $redirid = $this->getArticleID();
2657
2658 // Category memberships include a sort key which may be customized.
2659 // If it's left as the default (the page title), we need to update
2660 // the sort key to match the new title.
2661 //
2662 // Be careful to avoid resetting cl_timestamp, which may disturb
2663 // time-based lists on some sites.
2664 //
2665 // Warning -- if the sort key is *explicitly* set to the old title,
2666 // we can't actually distinguish it from a default here, and it'll
2667 // be set to the new title even though it really shouldn't.
2668 // It'll get corrected on the next edit, but resetting cl_timestamp.
2669 $dbw->update( 'categorylinks',
2670 array(
2671 'cl_sortkey' => $nt->getPrefixedText(),
2672 'cl_timestamp=cl_timestamp' ),
2673 array(
2674 'cl_from' => $pageid,
2675 'cl_sortkey' => $this->getPrefixedText() ),
2676 __METHOD__ );
2677
2678 if( $protected ) {
2679 # Protect the redirect title as the title used to be...
2680 $dbw->insertSelect( 'page_restrictions', 'page_restrictions',
2681 array(
2682 'pr_page' => $redirid,
2683 'pr_type' => 'pr_type',
2684 'pr_level' => 'pr_level',
2685 'pr_cascade' => 'pr_cascade',
2686 'pr_user' => 'pr_user',
2687 'pr_expiry' => 'pr_expiry'
2688 ),
2689 array( 'pr_page' => $pageid ),
2690 __METHOD__,
2691 array( 'IGNORE' )
2692 );
2693 # Update the protection log
2694 $log = new LogPage( 'protect' );
2695 $comment = wfMsgForContent( 'prot_1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
2696 if( $reason ) $comment .= wfMsgForContent( 'colon-separator' ) . $reason;
2697 $log->addEntry( 'move_prot', $nt, $comment, array($this->getPrefixedText()) ); // FIXME: $params?
2698 }
2699
2700 # Update watchlists
2701 $oldnamespace = $this->getNamespace() & ~1;
2702 $newnamespace = $nt->getNamespace() & ~1;
2703 $oldtitle = $this->getDBkey();
2704 $newtitle = $nt->getDBkey();
2705
2706 if( $oldnamespace != $newnamespace || $oldtitle != $newtitle ) {
2707 WatchedItem::duplicateEntries( $this, $nt );
2708 }
2709
2710 # Update search engine
2711 $u = new SearchUpdate( $pageid, $nt->getPrefixedDBkey() );
2712 $u->doUpdate();
2713 $u = new SearchUpdate( $redirid, $this->getPrefixedDBkey(), '' );
2714 $u->doUpdate();
2715
2716 # Update site_stats
2717 if( $this->isContentPage() && !$nt->isContentPage() ) {
2718 # No longer a content page
2719 # Not viewed, edited, removing
2720 $u = new SiteStatsUpdate( 0, 1, -1, $pageCountChange );
2721 } elseif( !$this->isContentPage() && $nt->isContentPage() ) {
2722 # Now a content page
2723 # Not viewed, edited, adding
2724 $u = new SiteStatsUpdate( 0, 1, +1, $pageCountChange );
2725 } elseif( $pageCountChange ) {
2726 # Redirect added
2727 $u = new SiteStatsUpdate( 0, 0, 0, 1 );
2728 } else {
2729 # Nothing special
2730 $u = false;
2731 }
2732 if( $u )
2733 $u->doUpdate();
2734 # Update message cache for interface messages
2735 if( $nt->getNamespace() == NS_MEDIAWIKI ) {
2736 global $wgMessageCache;
2737
2738 # @bug 17860: old article can be deleted, if this the case,
2739 # delete it from message cache
2740 if ( $this->getArticleID() === 0 ) {
2741 $wgMessageCache->replace( $this->getDBkey(), false );
2742 } else {
2743 $oldarticle = new Article( $this );
2744 $wgMessageCache->replace( $this->getDBkey(), $oldarticle->getContent() );
2745 }
2746
2747 $newarticle = new Article( $nt );
2748 $wgMessageCache->replace( $nt->getDBkey(), $newarticle->getContent() );
2749 }
2750
2751 global $wgUser;
2752 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) );
2753 return true;
2754 }
2755
2756 /**
2757 * Move page to a title which is at present a redirect to the
2758 * source page
2759 *
2760 * @param &$nt \type{Title} the page to move to, which should currently
2761 * be a redirect
2762 * @param $reason \type{\string} The reason for the move
2763 * @param $createRedirect \type{\bool} Whether to leave a redirect at the old title.
2764 * Ignored if the user doesn't have the suppressredirect right
2765 */
2766 private function moveOverExistingRedirect( &$nt, $reason = '', $createRedirect = true ) {
2767 global $wgUseSquid, $wgUser;
2768 $fname = 'Title::moveOverExistingRedirect';
2769 $comment = wfMsgForContent( '1movedto2_redir', $this->getPrefixedText(), $nt->getPrefixedText() );
2770
2771 if ( $reason ) {
2772 $comment .= ": $reason";
2773 }
2774
2775 $now = wfTimestampNow();
2776 $newid = $nt->getArticleID();
2777 $oldid = $this->getArticleID();
2778 $latest = $this->getLatestRevID();
2779
2780 $dbw = wfGetDB( DB_MASTER );
2781
2782 # Delete the old redirect. We don't save it to history since
2783 # by definition if we've got here it's rather uninteresting.
2784 # We have to remove it so that the next step doesn't trigger
2785 # a conflict on the unique namespace+title index...
2786 $dbw->delete( 'page', array( 'page_id' => $newid ), $fname );
2787 if ( !$dbw->cascadingDeletes() ) {
2788 $dbw->delete( 'revision', array( 'rev_page' => $newid ), __METHOD__ );
2789 global $wgUseTrackbacks;
2790 if ($wgUseTrackbacks)
2791 $dbw->delete( 'trackbacks', array( 'tb_page' => $newid ), __METHOD__ );
2792 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), __METHOD__ );
2793 $dbw->delete( 'imagelinks', array( 'il_from' => $newid ), __METHOD__ );
2794 $dbw->delete( 'categorylinks', array( 'cl_from' => $newid ), __METHOD__ );
2795 $dbw->delete( 'templatelinks', array( 'tl_from' => $newid ), __METHOD__ );
2796 $dbw->delete( 'externallinks', array( 'el_from' => $newid ), __METHOD__ );
2797 $dbw->delete( 'langlinks', array( 'll_from' => $newid ), __METHOD__ );
2798 $dbw->delete( 'redirect', array( 'rd_from' => $newid ), __METHOD__ );
2799 }
2800
2801 # Save a null revision in the page's history notifying of the move
2802 $nullRevision = Revision::newNullRevision( $dbw, $oldid, $comment, true );
2803 $nullRevId = $nullRevision->insertOn( $dbw );
2804
2805 $article = new Article( $this );
2806 wfRunHooks( 'NewRevisionFromEditComplete', array($article, $nullRevision, $latest, $wgUser) );
2807
2808 # Change the name of the target page:
2809 $dbw->update( 'page',
2810 /* SET */ array(
2811 'page_touched' => $dbw->timestamp($now),
2812 'page_namespace' => $nt->getNamespace(),
2813 'page_title' => $nt->getDBkey(),
2814 'page_latest' => $nullRevId,
2815 ),
2816 /* WHERE */ array( 'page_id' => $oldid ),
2817 $fname
2818 );
2819 $nt->resetArticleID( $oldid );
2820
2821 # Recreate the redirect, this time in the other direction.
2822 if( $createRedirect || !$wgUser->isAllowed('suppressredirect') ) {
2823 $mwRedir = MagicWord::get( 'redirect' );
2824 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
2825 $redirectArticle = new Article( $this );
2826 $newid = $redirectArticle->insertOn( $dbw );
2827 $redirectRevision = new Revision( array(
2828 'page' => $newid,
2829 'comment' => $comment,
2830 'text' => $redirectText ) );
2831 $redirectRevision->insertOn( $dbw );
2832 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
2833
2834 wfRunHooks( 'NewRevisionFromEditComplete', array($redirectArticle, $redirectRevision, false, $wgUser) );
2835
2836 # Now, we record the link from the redirect to the new title.
2837 # It should have no other outgoing links...
2838 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), $fname );
2839 $dbw->insert( 'pagelinks',
2840 array(
2841 'pl_from' => $newid,
2842 'pl_namespace' => $nt->getNamespace(),
2843 'pl_title' => $nt->getDBkey() ),
2844 $fname );
2845 $redirectSuppressed = false;
2846 } else {
2847 $this->resetArticleID( 0 );
2848 $redirectSuppressed = true;
2849 }
2850
2851 # Log the move
2852 $log = new LogPage( 'move' );
2853 $log->addEntry( 'move_redir', $this, $reason, array( 1 => $nt->getPrefixedText(), 2 => $redirectSuppressed ) );
2854
2855 # Purge squid
2856 if ( $wgUseSquid ) {
2857 $urls = array_merge( $nt->getSquidURLs(), $this->getSquidURLs() );
2858 $u = new SquidUpdate( $urls );
2859 $u->doUpdate();
2860 }
2861
2862 }
2863
2864 /**
2865 * Move page to non-existing title.
2866 * @param &$nt \type{Title} the new Title
2867 * @param $reason \type{\string} The reason for the move
2868 * @param $createRedirect \type{\bool} Whether to create a redirect from the old title to the new title
2869 * Ignored if the user doesn't have the suppressredirect right
2870 */
2871 private function moveToNewTitle( &$nt, $reason = '', $createRedirect = true ) {
2872 global $wgUseSquid, $wgUser;
2873 $fname = 'MovePageForm::moveToNewTitle';
2874 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
2875 if ( $reason ) {
2876 $comment .= wfMsgExt( 'colon-separator',
2877 array( 'escapenoentities', 'content' ) );
2878 $comment .= $reason;
2879 }
2880
2881 $newid = $nt->getArticleID();
2882 $oldid = $this->getArticleID();
2883 $latest = $this->getLatestRevId();
2884
2885 $dbw = wfGetDB( DB_MASTER );
2886 $now = $dbw->timestamp();
2887
2888 # Save a null revision in the page's history notifying of the move
2889 $nullRevision = Revision::newNullRevision( $dbw, $oldid, $comment, true );
2890 $nullRevId = $nullRevision->insertOn( $dbw );
2891
2892 $article = new Article( $this );
2893 wfRunHooks( 'NewRevisionFromEditComplete', array($article, $nullRevision, $latest, $wgUser) );
2894
2895 # Rename page entry
2896 $dbw->update( 'page',
2897 /* SET */ array(
2898 'page_touched' => $now,
2899 'page_namespace' => $nt->getNamespace(),
2900 'page_title' => $nt->getDBkey(),
2901 'page_latest' => $nullRevId,
2902 ),
2903 /* WHERE */ array( 'page_id' => $oldid ),
2904 $fname
2905 );
2906 $nt->resetArticleID( $oldid );
2907
2908 if( $createRedirect || !$wgUser->isAllowed('suppressredirect') ) {
2909 # Insert redirect
2910 $mwRedir = MagicWord::get( 'redirect' );
2911 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
2912 $redirectArticle = new Article( $this );
2913 $newid = $redirectArticle->insertOn( $dbw );
2914 $redirectRevision = new Revision( array(
2915 'page' => $newid,
2916 'comment' => $comment,
2917 'text' => $redirectText ) );
2918 $redirectRevision->insertOn( $dbw );
2919 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
2920
2921 wfRunHooks( 'NewRevisionFromEditComplete', array($redirectArticle, $redirectRevision, false, $wgUser) );
2922
2923 # Record the just-created redirect's linking to the page
2924 $dbw->insert( 'pagelinks',
2925 array(
2926 'pl_from' => $newid,
2927 'pl_namespace' => $nt->getNamespace(),
2928 'pl_title' => $nt->getDBkey() ),
2929 $fname );
2930 $redirectSuppressed = false;
2931 } else {
2932 $this->resetArticleID( 0 );
2933 $redirectSuppressed = true;
2934 }
2935
2936 # Log the move
2937 $log = new LogPage( 'move' );
2938 $log->addEntry( 'move', $this, $reason, array( 1 => $nt->getPrefixedText(), 2 => $redirectSuppressed ) );
2939
2940 # Purge caches as per article creation
2941 Article::onArticleCreate( $nt );
2942
2943 # Purge old title from squid
2944 # The new title, and links to the new title, are purged in Article::onArticleCreate()
2945 $this->purgeSquid();
2946
2947 }
2948
2949 /**
2950 * Move this page's subpages to be subpages of $nt
2951 * @param $nt Title Move target
2952 * @param $auth bool Whether $wgUser's permissions should be checked
2953 * @param $reason string The reason for the move
2954 * @param $createRedirect bool Whether to create redirects from the old subpages to the new ones
2955 * Ignored if the user doesn't have the 'suppressredirect' right
2956 * @return mixed array with old page titles as keys, and strings (new page titles) or
2957 * arrays (errors) as values, or an error array with numeric indices if no pages were moved
2958 */
2959 public function moveSubpages( $nt, $auth = true, $reason = '', $createRedirect = true ) {
2960 global $wgMaximumMovedPages;
2961 // Check permissions
2962 if( !$this->userCan( 'move-subpages' ) )
2963 return array( 'cant-move-subpages' );
2964 // Do the source and target namespaces support subpages?
2965 if( !MWNamespace::hasSubpages( $this->getNamespace() ) )
2966 return array( 'namespace-nosubpages',
2967 MWNamespace::getCanonicalName( $this->getNamespace() ) );
2968 if( !MWNamespace::hasSubpages( $nt->getNamespace() ) )
2969 return array( 'namespace-nosubpages',
2970 MWNamespace::getCanonicalName( $nt->getNamespace() ) );
2971
2972 $subpages = $this->getSubpages($wgMaximumMovedPages + 1);
2973 $retval = array();
2974 $count = 0;
2975 foreach( $subpages as $oldSubpage ) {
2976 $count++;
2977 if( $count > $wgMaximumMovedPages ) {
2978 $retval[$oldSubpage->getPrefixedTitle()] =
2979 array( 'movepage-max-pages',
2980 $wgMaximumMovedPages );
2981 break;
2982 }
2983
2984 if( $oldSubpage->getArticleId() == $this->getArticleId() )
2985 // When moving a page to a subpage of itself,
2986 // don't move it twice
2987 continue;
2988 $newPageName = preg_replace(
2989 '#^'.preg_quote( $this->getDBkey(), '#' ).'#',
2990 $nt->getDBkey(), $oldSubpage->getDBkey() );
2991 if( $oldSubpage->isTalkPage() ) {
2992 $newNs = $nt->getTalkPage()->getNamespace();
2993 } else {
2994 $newNs = $nt->getSubjectPage()->getNamespace();
2995 }
2996 # Bug 14385: we need makeTitleSafe because the new page names may
2997 # be longer than 255 characters.
2998 $newSubpage = Title::makeTitleSafe( $newNs, $newPageName );
2999
3000 $success = $oldSubpage->moveTo( $newSubpage, $auth, $reason, $createRedirect );
3001 if( $success === true ) {
3002 $retval[$oldSubpage->getPrefixedText()] = $newSubpage->getPrefixedText();
3003 } else {
3004 $retval[$oldSubpage->getPrefixedText()] = $success;
3005 }
3006 }
3007 return $retval;
3008 }
3009
3010 /**
3011 * Checks if this page is just a one-rev redirect.
3012 * Adds lock, so don't use just for light purposes.
3013 *
3014 * @return \type{\bool} TRUE or FALSE
3015 */
3016 public function isSingleRevRedirect() {
3017 $dbw = wfGetDB( DB_MASTER );
3018 # Is it a redirect?
3019 $row = $dbw->selectRow( 'page',
3020 array( 'page_is_redirect', 'page_latest', 'page_id' ),
3021 $this->pageCond(),
3022 __METHOD__,
3023 array( 'FOR UPDATE' )
3024 );
3025 # Cache some fields we may want
3026 $this->mArticleID = $row ? intval($row->page_id) : 0;
3027 $this->mRedirect = $row ? (bool)$row->page_is_redirect : false;
3028 $this->mLatestID = $row ? intval($row->page_latest) : false;
3029 if( !$this->mRedirect ) {
3030 return false;
3031 }
3032 # Does the article have a history?
3033 $row = $dbw->selectField( array( 'page', 'revision'),
3034 'rev_id',
3035 array( 'page_namespace' => $this->getNamespace(),
3036 'page_title' => $this->getDBkey(),
3037 'page_id=rev_page',
3038 'page_latest != rev_id'
3039 ),
3040 __METHOD__,
3041 array( 'FOR UPDATE' )
3042 );
3043 # Return true if there was no history
3044 return ($row === false);
3045 }
3046
3047 /**
3048 * Checks if $this can be moved to a given Title
3049 * - Selects for update, so don't call it unless you mean business
3050 *
3051 * @param &$nt \type{Title} the new title to check
3052 * @return \type{\bool} TRUE or FALSE
3053 */
3054 public function isValidMoveTarget( $nt ) {
3055 $dbw = wfGetDB( DB_MASTER );
3056 # Is it an existsing file?
3057 if( $nt->getNamespace() == NS_FILE ) {
3058 $file = wfLocalFile( $nt );
3059 if( $file->exists() ) {
3060 wfDebug( __METHOD__ . ": file exists\n" );
3061 return false;
3062 }
3063 }
3064 # Is it a redirect with no history?
3065 if( !$nt->isSingleRevRedirect() ) {
3066 wfDebug( __METHOD__ . ": not a one-rev redirect\n" );
3067 return false;
3068 }
3069 # Get the article text
3070 $rev = Revision::newFromTitle( $nt );
3071 $text = $rev->getText();
3072 # Does the redirect point to the source?
3073 # Or is it a broken self-redirect, usually caused by namespace collisions?
3074 $m = array();
3075 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $text, $m ) ) {
3076 $redirTitle = Title::newFromText( $m[1] );
3077 if( !is_object( $redirTitle ) ||
3078 ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
3079 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) ) {
3080 wfDebug( __METHOD__ . ": redirect points to other page\n" );
3081 return false;
3082 }
3083 } else {
3084 # Fail safe
3085 wfDebug( __METHOD__ . ": failsafe\n" );
3086 return false;
3087 }
3088 return true;
3089 }
3090
3091 /**
3092 * Can this title be added to a user's watchlist?
3093 *
3094 * @return \type{\bool} TRUE or FALSE
3095 */
3096 public function isWatchable() {
3097 return !$this->isExternal() && MWNamespace::isWatchable( $this->getNamespace() );
3098 }
3099
3100 /**
3101 * Get categories to which this Title belongs and return an array of
3102 * categories' names.
3103 *
3104 * @return \type{\array} array an array of parents in the form:
3105 * $parent => $currentarticle
3106 */
3107 public function getParentCategories() {
3108 global $wgContLang;
3109
3110 $titlekey = $this->getArticleId();
3111 $dbr = wfGetDB( DB_SLAVE );
3112 $categorylinks = $dbr->tableName( 'categorylinks' );
3113
3114 # NEW SQL
3115 $sql = "SELECT * FROM $categorylinks"
3116 ." WHERE cl_from='$titlekey'"
3117 ." AND cl_from <> '0'"
3118 ." ORDER BY cl_sortkey";
3119
3120 $res = $dbr->query( $sql );
3121
3122 if( $dbr->numRows( $res ) > 0 ) {
3123 foreach( $res as $row )
3124 //$data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$row->cl_to);
3125 $data[$wgContLang->getNSText( NS_CATEGORY ).':'.$row->cl_to] = $this->getFullText();
3126 $dbr->freeResult( $res );
3127 } else {
3128 $data = array();
3129 }
3130 return $data;
3131 }
3132
3133 /**
3134 * Get a tree of parent categories
3135 * @param $children \type{\array} an array with the children in the keys, to check for circular refs
3136 * @return \type{\array} Tree of parent categories
3137 */
3138 public function getParentCategoryTree( $children = array() ) {
3139 $stack = array();
3140 $parents = $this->getParentCategories();
3141
3142 if( $parents ) {
3143 foreach( $parents as $parent => $current ) {
3144 if ( array_key_exists( $parent, $children ) ) {
3145 # Circular reference
3146 $stack[$parent] = array();
3147 } else {
3148 $nt = Title::newFromText($parent);
3149 if ( $nt ) {
3150 $stack[$parent] = $nt->getParentCategoryTree( $children + array($parent => 1) );
3151 }
3152 }
3153 }
3154 return $stack;
3155 } else {
3156 return array();
3157 }
3158 }
3159
3160
3161 /**
3162 * Get an associative array for selecting this title from
3163 * the "page" table
3164 *
3165 * @return \type{\array} Selection array
3166 */
3167 public function pageCond() {
3168 if( $this->mArticleID > 0 ) {
3169 // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs
3170 return array( 'page_id' => $this->mArticleID );
3171 } else {
3172 return array( 'page_namespace' => $this->mNamespace, 'page_title' => $this->mDbkeyform );
3173 }
3174 }
3175
3176 /**
3177 * Get the revision ID of the previous revision
3178 *
3179 * @param $revId \type{\int} Revision ID. Get the revision that was before this one.
3180 * @param $flags \type{\int} GAID_FOR_UPDATE
3181 * @return \twotypes{\int,\bool} Old revision ID, or FALSE if none exists
3182 */
3183 public function getPreviousRevisionID( $revId, $flags=0 ) {
3184 $db = ($flags & GAID_FOR_UPDATE) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
3185 return $db->selectField( 'revision', 'rev_id',
3186 array(
3187 'rev_page' => $this->getArticleId($flags),
3188 'rev_id < ' . intval( $revId )
3189 ),
3190 __METHOD__,
3191 array( 'ORDER BY' => 'rev_id DESC' )
3192 );
3193 }
3194
3195 /**
3196 * Get the revision ID of the next revision
3197 *
3198 * @param $revId \type{\int} Revision ID. Get the revision that was after this one.
3199 * @param $flags \type{\int} GAID_FOR_UPDATE
3200 * @return \twotypes{\int,\bool} Next revision ID, or FALSE if none exists
3201 */
3202 public function getNextRevisionID( $revId, $flags=0 ) {
3203 $db = ($flags & GAID_FOR_UPDATE) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
3204 return $db->selectField( 'revision', 'rev_id',
3205 array(
3206 'rev_page' => $this->getArticleId($flags),
3207 'rev_id > ' . intval( $revId )
3208 ),
3209 __METHOD__,
3210 array( 'ORDER BY' => 'rev_id' )
3211 );
3212 }
3213
3214 /**
3215 * Get the first revision of the page
3216 *
3217 * @param $flags \type{\int} GAID_FOR_UPDATE
3218 * @return Revision (or NULL if page doesn't exist)
3219 */
3220 public function getFirstRevision( $flags=0 ) {
3221 $db = ($flags & GAID_FOR_UPDATE) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
3222 $pageId = $this->getArticleId($flags);
3223 if( !$pageId ) return NULL;
3224 $row = $db->selectRow( 'revision', '*',
3225 array( 'rev_page' => $pageId ),
3226 __METHOD__,
3227 array( 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 1 )
3228 );
3229 if( !$row ) {
3230 return NULL;
3231 } else {
3232 return new Revision( $row );
3233 }
3234 }
3235
3236 /**
3237 * Check if this is a new page
3238 *
3239 * @return bool
3240 */
3241 public function isNewPage() {
3242 $dbr = wfGetDB( DB_SLAVE );
3243 return (bool)$dbr->selectField( 'page', 'page_is_new', $this->pageCond(), __METHOD__ );
3244 }
3245
3246 /**
3247 * Get the oldest revision timestamp of this page
3248 *
3249 * @return string, MW timestamp
3250 */
3251 public function getEarliestRevTime() {
3252 $dbr = wfGetDB( DB_SLAVE );
3253 if( $this->exists() ) {
3254 $min = $dbr->selectField( 'revision',
3255 'MIN(rev_timestamp)',
3256 array( 'rev_page' => $this->getArticleId() ),
3257 __METHOD__ );
3258 return wfTimestampOrNull( TS_MW, $min );
3259 }
3260 return null;
3261 }
3262
3263 /**
3264 * Get the number of revisions between the given revision IDs.
3265 * Used for diffs and other things that really need it.
3266 *
3267 * @param $old \type{\int} Revision ID.
3268 * @param $new \type{\int} Revision ID.
3269 * @return \type{\int} Number of revisions between these IDs.
3270 */
3271 public function countRevisionsBetween( $old, $new ) {
3272 $dbr = wfGetDB( DB_SLAVE );
3273 return $dbr->selectField( 'revision', 'count(*)',
3274 'rev_page = ' . intval( $this->getArticleId() ) .
3275 ' AND rev_id > ' . intval( $old ) .
3276 ' AND rev_id < ' . intval( $new ),
3277 __METHOD__
3278 );
3279 }
3280
3281 /**
3282 * Compare with another title.
3283 *
3284 * @param \type{Title} $title
3285 * @return \type{\bool} TRUE or FALSE
3286 */
3287 public function equals( Title $title ) {
3288 // Note: === is necessary for proper matching of number-like titles.
3289 return $this->getInterwiki() === $title->getInterwiki()
3290 && $this->getNamespace() == $title->getNamespace()
3291 && $this->getDBkey() === $title->getDBkey();
3292 }
3293
3294 /**
3295 * Callback for usort() to do title sorts by (namespace, title)
3296 */
3297 public static function compare( $a, $b ) {
3298 if( $a->getNamespace() == $b->getNamespace() ) {
3299 return strcmp( $a->getText(), $b->getText() );
3300 } else {
3301 return $a->getNamespace() - $b->getNamespace();
3302 }
3303 }
3304
3305 /**
3306 * Return a string representation of this title
3307 *
3308 * @return \type{\string} String representation of this title
3309 */
3310 public function __toString() {
3311 return $this->getPrefixedText();
3312 }
3313
3314 /**
3315 * Check if page exists. For historical reasons, this function simply
3316 * checks for the existence of the title in the page table, and will
3317 * thus return false for interwiki links, special pages and the like.
3318 * If you want to know if a title can be meaningfully viewed, you should
3319 * probably call the isKnown() method instead.
3320 *
3321 * @return \type{\bool} TRUE or FALSE
3322 */
3323 public function exists() {
3324 return $this->getArticleId() != 0;
3325 }
3326
3327 /**
3328 * Should links to this title be shown as potentially viewable (i.e. as
3329 * "bluelinks"), even if there's no record by this title in the page
3330 * table?
3331 *
3332 * This function is semi-deprecated for public use, as well as somewhat
3333 * misleadingly named. You probably just want to call isKnown(), which
3334 * calls this function internally.
3335 *
3336 * (ISSUE: Most of these checks are cheap, but the file existence check
3337 * can potentially be quite expensive. Including it here fixes a lot of
3338 * existing code, but we might want to add an optional parameter to skip
3339 * it and any other expensive checks.)
3340 *
3341 * @return \type{\bool} TRUE or FALSE
3342 */
3343 public function isAlwaysKnown() {
3344 if( $this->mInterwiki != '' ) {
3345 return true; // any interwiki link might be viewable, for all we know
3346 }
3347 switch( $this->mNamespace ) {
3348 case NS_MEDIA:
3349 case NS_FILE:
3350 return wfFindFile( $this ); // file exists, possibly in a foreign repo
3351 case NS_SPECIAL:
3352 return SpecialPage::exists( $this->getDBkey() ); // valid special page
3353 case NS_MAIN:
3354 return $this->mDbkeyform == ''; // selflink, possibly with fragment
3355 case NS_MEDIAWIKI:
3356 // If the page is form Mediawiki:message/lang, calling wfMsgWeirdKey causes
3357 // the full l10n of that language to be loaded. That takes much memory and
3358 // isn't needed. So we strip the language part away.
3359 // Also, extension messages which are not loaded, are shown as red, because
3360 // we don't call MessageCache::loadAllMessages.
3361 list( $basename, /* rest */ ) = explode( '/', $this->mDbkeyform, 2 );
3362 return wfMsgWeirdKey( $basename ); // known system message
3363 default:
3364 return false;
3365 }
3366 }
3367
3368 /**
3369 * Does this title refer to a page that can (or might) be meaningfully
3370 * viewed? In particular, this function may be used to determine if
3371 * links to the title should be rendered as "bluelinks" (as opposed to
3372 * "redlinks" to non-existent pages).
3373 *
3374 * @return \type{\bool} TRUE or FALSE
3375 */
3376 public function isKnown() {
3377 return $this->exists() || $this->isAlwaysKnown();
3378 }
3379
3380 /**
3381 * Is this in a namespace that allows actual pages?
3382 *
3383 * @return \type{\bool} TRUE or FALSE
3384 */
3385 public function canExist() {
3386 return $this->mNamespace >= 0 && $this->mNamespace != NS_MEDIA;
3387 }
3388
3389 /**
3390 * Update page_touched timestamps and send squid purge messages for
3391 * pages linking to this title. May be sent to the job queue depending
3392 * on the number of links. Typically called on create and delete.
3393 */
3394 public function touchLinks() {
3395 $u = new HTMLCacheUpdate( $this, 'pagelinks' );
3396 $u->doUpdate();
3397
3398 if ( $this->getNamespace() == NS_CATEGORY ) {
3399 $u = new HTMLCacheUpdate( $this, 'categorylinks' );
3400 $u->doUpdate();
3401 }
3402 }
3403
3404 /**
3405 * Get the last touched timestamp
3406 * @param Database $db, optional db
3407 * @return \type{\string} Last touched timestamp
3408 */
3409 public function getTouched( $db = NULL ) {
3410 $db = isset($db) ? $db : wfGetDB( DB_SLAVE );
3411 $touched = $db->selectField( 'page', 'page_touched', $this->pageCond(), __METHOD__ );
3412 return $touched;
3413 }
3414
3415 /**
3416 * Get the timestamp when this page was updated since the user last saw it.
3417 * @param User $user
3418 * @return mixed string/NULL
3419 */
3420 public function getNotificationTimestamp( $user = NULL ) {
3421 global $wgUser, $wgShowUpdatedMarker;
3422 // Assume current user if none given
3423 if( !$user ) $user = $wgUser;
3424 // Check cache first
3425 $uid = $user->getId();
3426 if( isset($this->mNotificationTimestamp[$uid]) ) {
3427 return $this->mNotificationTimestamp[$uid];
3428 }
3429 if( !$uid || !$wgShowUpdatedMarker ) {
3430 return $this->mNotificationTimestamp[$uid] = false;
3431 }
3432 // Don't cache too much!
3433 if( count($this->mNotificationTimestamp) >= self::CACHE_MAX ) {
3434 $this->mNotificationTimestamp = array();
3435 }
3436 $dbr = wfGetDB( DB_SLAVE );
3437 $this->mNotificationTimestamp[$uid] = $dbr->selectField( 'watchlist',
3438 'wl_notificationtimestamp',
3439 array( 'wl_namespace' => $this->getNamespace(),
3440 'wl_title' => $this->getDBkey(),
3441 'wl_user' => $user->getId()
3442 ),
3443 __METHOD__
3444 );
3445 return $this->mNotificationTimestamp[$uid];
3446 }
3447
3448 /**
3449 * Get the trackback URL for this page
3450 * @return \type{\string} Trackback URL
3451 */
3452 public function trackbackURL() {
3453 global $wgScriptPath, $wgServer, $wgScriptExtension;
3454
3455 return "$wgServer$wgScriptPath/trackback$wgScriptExtension?article="
3456 . htmlspecialchars(urlencode($this->getPrefixedDBkey()));
3457 }
3458
3459 /**
3460 * Get the trackback RDF for this page
3461 * @return \type{\string} Trackback RDF
3462 */
3463 public function trackbackRDF() {
3464 $url = htmlspecialchars($this->getFullURL());
3465 $title = htmlspecialchars($this->getText());
3466 $tburl = $this->trackbackURL();
3467
3468 // Autodiscovery RDF is placed in comments so HTML validator
3469 // won't barf. This is a rather icky workaround, but seems
3470 // frequently used by this kind of RDF thingy.
3471 //
3472 // Spec: http://www.sixapart.com/pronet/docs/trackback_spec
3473 return "<!--
3474 <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"
3475 xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
3476 xmlns:trackback=\"http://madskills.com/public/xml/rss/module/trackback/\">
3477 <rdf:Description
3478 rdf:about=\"$url\"
3479 dc:identifier=\"$url\"
3480 dc:title=\"$title\"
3481 trackback:ping=\"$tburl\" />
3482 </rdf:RDF>
3483 -->";
3484 }
3485
3486 /**
3487 * Generate strings used for xml 'id' names in monobook tabs
3488 * @return \type{\string} XML 'id' name
3489 */
3490 public function getNamespaceKey() {
3491 global $wgContLang;
3492 switch ($this->getNamespace()) {
3493 case NS_MAIN:
3494 case NS_TALK:
3495 return 'nstab-main';
3496 case NS_USER:
3497 case NS_USER_TALK:
3498 return 'nstab-user';
3499 case NS_MEDIA:
3500 return 'nstab-media';
3501 case NS_SPECIAL:
3502 return 'nstab-special';
3503 case NS_PROJECT:
3504 case NS_PROJECT_TALK:
3505 return 'nstab-project';
3506 case NS_FILE:
3507 case NS_FILE_TALK:
3508 return 'nstab-image';
3509 case NS_MEDIAWIKI:
3510 case NS_MEDIAWIKI_TALK:
3511 return 'nstab-mediawiki';
3512 case NS_TEMPLATE:
3513 case NS_TEMPLATE_TALK:
3514 return 'nstab-template';
3515 case NS_HELP:
3516 case NS_HELP_TALK:
3517 return 'nstab-help';
3518 case NS_CATEGORY:
3519 case NS_CATEGORY_TALK:
3520 return 'nstab-category';
3521 default:
3522 return 'nstab-' . $wgContLang->lc( $this->getSubjectNsText() );
3523 }
3524 }
3525
3526 /**
3527 * Returns true if this title resolves to the named special page
3528 * @param $name \type{\string} The special page name
3529 */
3530 public function isSpecial( $name ) {
3531 if ( $this->getNamespace() == NS_SPECIAL ) {
3532 list( $thisName, /* $subpage */ ) = SpecialPage::resolveAliasWithSubpage( $this->getDBkey() );
3533 if ( $name == $thisName ) {
3534 return true;
3535 }
3536 }
3537 return false;
3538 }
3539
3540 /**
3541 * If the Title refers to a special page alias which is not the local default,
3542 * @return \type{Title} A new Title which points to the local default. Otherwise, returns $this.
3543 */
3544 public function fixSpecialName() {
3545 if ( $this->getNamespace() == NS_SPECIAL ) {
3546 $canonicalName = SpecialPage::resolveAlias( $this->mDbkeyform );
3547 if ( $canonicalName ) {
3548 $localName = SpecialPage::getLocalNameFor( $canonicalName );
3549 if ( $localName != $this->mDbkeyform ) {
3550 return Title::makeTitle( NS_SPECIAL, $localName );
3551 }
3552 }
3553 }
3554 return $this;
3555 }
3556
3557 /**
3558 * Is this Title in a namespace which contains content?
3559 * In other words, is this a content page, for the purposes of calculating
3560 * statistics, etc?
3561 *
3562 * @return \type{\bool} TRUE or FALSE
3563 */
3564 public function isContentPage() {
3565 return MWNamespace::isContent( $this->getNamespace() );
3566 }
3567
3568 /**
3569 * Get all extant redirects to this Title
3570 *
3571 * @param $ns \twotypes{\int,\null} Single namespace to consider;
3572 * NULL to consider all namespaces
3573 * @return \type{\arrayof{Title}} Redirects to this title
3574 */
3575 public function getRedirectsHere( $ns = null ) {
3576 $redirs = array();
3577
3578 $dbr = wfGetDB( DB_SLAVE );
3579 $where = array(
3580 'rd_namespace' => $this->getNamespace(),
3581 'rd_title' => $this->getDBkey(),
3582 'rd_from = page_id'
3583 );
3584 if ( !is_null($ns) ) $where['page_namespace'] = $ns;
3585
3586 $res = $dbr->select(
3587 array( 'redirect', 'page' ),
3588 array( 'page_namespace', 'page_title' ),
3589 $where,
3590 __METHOD__
3591 );
3592
3593
3594 foreach( $res as $row ) {
3595 $redirs[] = self::newFromRow( $row );
3596 }
3597 return $redirs;
3598 }
3599
3600 /**
3601 * Check if this Title is a valid redirect target
3602 *
3603 * @return \type{\bool} TRUE or FALSE
3604 */
3605 public function isValidRedirectTarget() {
3606 global $wgInvalidRedirectTargets;
3607
3608 // invalid redirect targets are stored in a global array, but explicity disallow Userlogout here
3609 if( $this->isSpecial( 'Userlogout' ) ) {
3610 return false;
3611 }
3612
3613 foreach( $wgInvalidRedirectTargets as $target ) {
3614 if( $this->isSpecial( $target ) ) {
3615 return false;
3616 }
3617 }
3618
3619 return true;
3620 }
3621
3622 /**
3623 * Get a backlink cache object
3624 */
3625 function getBacklinkCache() {
3626 if ( is_null( $this->mBacklinkCache ) ) {
3627 $this->mBacklinkCache = new BacklinkCache( $this );
3628 }
3629 return $this->mBacklinkCache;
3630 }
3631 }