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