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