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