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