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