89e20b0f9561632b338417ac4740ff45e65aab64
[lhc/web/wiklou.git] / includes / Title.php
1 <?php
2 /**
3 * See title.txt
4 *
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 global $wgNamespacesWithSubpages;
701 if( !empty( $wgNamespacesWithSubpages[$this->mNamespace] ) ) {
702 $parts = explode( '/', $this->getText() );
703 # Don't discard the real title if there's no subpage involved
704 if( count( $parts ) > 1 )
705 unset( $parts[ count( $parts ) - 1 ] );
706 return implode( '/', $parts );
707 } else {
708 return $this->getText();
709 }
710 }
711
712 /**
713 * Get the lowest-level subpage name, i.e. the rightmost part after /
714 * @return string Subpage name
715 */
716 public function getSubpageText() {
717 global $wgNamespacesWithSubpages;
718 if( isset( $wgNamespacesWithSubpages[ $this->mNamespace ] ) && $wgNamespacesWithSubpages[ $this->mNamespace ] ) {
719 $parts = explode( '/', $this->mTextform );
720 return( $parts[ count( $parts ) - 1 ] );
721 } else {
722 return( $this->mTextform );
723 }
724 }
725
726 /**
727 * Get a URL-encoded form of the subpage text
728 * @return string URL-encoded subpage name
729 */
730 public function getSubpageUrlForm() {
731 $text = $this->getSubpageText();
732 $text = wfUrlencode( str_replace( ' ', '_', $text ) );
733 $text = str_replace( '%28', '(', str_replace( '%29', ')', $text ) ); # Clean up the URL; per below, this might not be safe
734 return( $text );
735 }
736
737 /**
738 * Get a URL-encoded title (not an actual URL) including interwiki
739 * @return string the URL-encoded form
740 */
741 public function getPrefixedURL() {
742 $s = $this->prefix( $this->mDbkeyform );
743 $s = str_replace( ' ', '_', $s );
744
745 $s = wfUrlencode ( $s ) ;
746
747 # Cleaning up URL to make it look nice -- is this safe?
748 $s = str_replace( '%28', '(', $s );
749 $s = str_replace( '%29', ')', $s );
750
751 return $s;
752 }
753
754 /**
755 * Get a real URL referring to this title, with interwiki link and
756 * fragment
757 *
758 * @param string $query an optional query string, not used
759 * for interwiki links
760 * @param string $variant language variant of url (for sr, zh..)
761 * @return string the URL
762 */
763 public function getFullURL( $query = '', $variant = false ) {
764 global $wgContLang, $wgServer, $wgRequest;
765
766 if ( '' == $this->mInterwiki ) {
767 $url = $this->getLocalUrl( $query, $variant );
768
769 // Ugly quick hack to avoid duplicate prefixes (bug 4571 etc)
770 // Correct fix would be to move the prepending elsewhere.
771 if ($wgRequest->getVal('action') != 'render') {
772 $url = $wgServer . $url;
773 }
774 } else {
775 $baseUrl = $this->getInterwikiLink( $this->mInterwiki );
776
777 $namespace = wfUrlencode( $this->getNsText() );
778 if ( '' != $namespace ) {
779 # Can this actually happen? Interwikis shouldn't be parsed.
780 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
781 $namespace .= ':';
782 }
783 $url = str_replace( '$1', $namespace . $this->mUrlform, $baseUrl );
784 $url = wfAppendQuery( $url, $query );
785 }
786
787 # Finally, add the fragment.
788 $url .= $this->getFragmentForURL();
789
790 wfRunHooks( 'GetFullURL', array( &$this, &$url, $query ) );
791 return $url;
792 }
793
794 /**
795 * Get a URL with no fragment or server name. If this page is generated
796 * with action=render, $wgServer is prepended.
797 * @param string $query an optional query string; if not specified,
798 * $wgArticlePath will be used.
799 * @param string $variant language variant of url (for sr, zh..)
800 * @return string the URL
801 */
802 public function getLocalURL( $query = '', $variant = false ) {
803 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
804 global $wgVariantArticlePath, $wgContLang, $wgUser;
805
806 // internal links should point to same variant as current page (only anonymous users)
807 if($variant == false && $wgContLang->hasVariants() && !$wgUser->isLoggedIn()){
808 $pref = $wgContLang->getPreferredVariant(false);
809 if($pref != $wgContLang->getCode())
810 $variant = $pref;
811 }
812
813 if ( $this->isExternal() ) {
814 $url = $this->getFullURL();
815 if ( $query ) {
816 // This is currently only used for edit section links in the
817 // context of interwiki transclusion. In theory we should
818 // append the query to the end of any existing query string,
819 // but interwiki transclusion is already broken in that case.
820 $url .= "?$query";
821 }
822 } else {
823 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
824 if ( $query == '' ) {
825 if( $variant != false && $wgContLang->hasVariants() ) {
826 if( $wgVariantArticlePath == false ) {
827 $variantArticlePath = "$wgScript?title=$1&variant=$2"; // default
828 } else {
829 $variantArticlePath = $wgVariantArticlePath;
830 }
831 $url = str_replace( '$2', urlencode( $variant ), $variantArticlePath );
832 $url = str_replace( '$1', $dbkey, $url );
833 } else {
834 $url = str_replace( '$1', $dbkey, $wgArticlePath );
835 }
836 } else {
837 global $wgActionPaths;
838 $url = false;
839 $matches = array();
840 if( !empty( $wgActionPaths ) &&
841 preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches ) )
842 {
843 $action = urldecode( $matches[2] );
844 if( isset( $wgActionPaths[$action] ) ) {
845 $query = $matches[1];
846 if( isset( $matches[4] ) ) $query .= $matches[4];
847 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
848 if( $query != '' ) $url .= '?' . $query;
849 }
850 }
851 if ( $url === false ) {
852 if ( $query == '-' ) {
853 $query = '';
854 }
855 $url = "{$wgScript}?title={$dbkey}&{$query}";
856 }
857 }
858
859 // FIXME: this causes breakage in various places when we
860 // actually expected a local URL and end up with dupe prefixes.
861 if ($wgRequest->getVal('action') == 'render') {
862 $url = $wgServer . $url;
863 }
864 }
865 wfRunHooks( 'GetLocalURL', array( &$this, &$url, $query ) );
866 return $url;
867 }
868
869 /**
870 * Get an HTML-escaped version of the URL form, suitable for
871 * using in a link, without a server name or fragment
872 * @param string $query an optional query string
873 * @return string the URL
874 */
875 public function escapeLocalURL( $query = '' ) {
876 return htmlspecialchars( $this->getLocalURL( $query ) );
877 }
878
879 /**
880 * Get an HTML-escaped version of the URL form, suitable for
881 * using in a link, including the server name and fragment
882 *
883 * @return string the URL
884 * @param string $query an optional query string
885 */
886 public function escapeFullURL( $query = '' ) {
887 return htmlspecialchars( $this->getFullURL( $query ) );
888 }
889
890 /**
891 * Get the URL form for an internal link.
892 * - Used in various Squid-related code, in case we have a different
893 * internal hostname for the server from the exposed one.
894 *
895 * @param string $query an optional query string
896 * @param string $variant language variant of url (for sr, zh..)
897 * @return string the URL
898 */
899 public function getInternalURL( $query = '', $variant = false ) {
900 global $wgInternalServer;
901 $url = $wgInternalServer . $this->getLocalURL( $query, $variant );
902 wfRunHooks( 'GetInternalURL', array( &$this, &$url, $query ) );
903 return $url;
904 }
905
906 /**
907 * Get the edit URL for this Title
908 * @return string the URL, or a null string if this is an
909 * interwiki link
910 */
911 public function getEditURL() {
912 if ( '' != $this->mInterwiki ) { return ''; }
913 $s = $this->getLocalURL( 'action=edit' );
914
915 return $s;
916 }
917
918 /**
919 * Get the HTML-escaped displayable text form.
920 * Used for the title field in <a> tags.
921 * @return string the text, including any prefixes
922 */
923 public function getEscapedText() {
924 return htmlspecialchars( $this->getPrefixedText() );
925 }
926
927 /**
928 * Is this Title interwiki?
929 * @return boolean
930 */
931 public function isExternal() { return ( '' != $this->mInterwiki ); }
932
933 /**
934 * Is this page "semi-protected" - the *only* protection is autoconfirm?
935 *
936 * @param string Action to check (default: edit)
937 * @return bool
938 */
939 public function isSemiProtected( $action = 'edit' ) {
940 if( $this->exists() ) {
941 $restrictions = $this->getRestrictions( $action );
942 if( count( $restrictions ) > 0 ) {
943 foreach( $restrictions as $restriction ) {
944 if( strtolower( $restriction ) != 'autoconfirmed' )
945 return false;
946 }
947 } else {
948 # Not protected
949 return false;
950 }
951 return true;
952 } else {
953 # If it doesn't exist, it can't be protected
954 return false;
955 }
956 }
957
958 /**
959 * Does the title correspond to a protected article?
960 * @param string $what the action the page is protected from,
961 * by default checks move and edit
962 * @return boolean
963 */
964 public function isProtected( $action = '' ) {
965 global $wgRestrictionLevels, $wgRestrictionTypes;
966
967 # Special pages have inherent protection
968 if( $this->getNamespace() == NS_SPECIAL )
969 return true;
970
971 # Check regular protection levels
972 foreach( $wgRestrictionTypes as $type ){
973 if( $action == $type || $action == '' ) {
974 $r = $this->getRestrictions( $type );
975 foreach( $wgRestrictionLevels as $level ) {
976 if( in_array( $level, $r ) && $level != '' ) {
977 return true;
978 }
979 }
980 }
981 }
982
983 return false;
984 }
985
986 /**
987 * Is $wgUser watching this page?
988 * @return boolean
989 */
990 public function userIsWatching() {
991 global $wgUser;
992
993 if ( is_null( $this->mWatched ) ) {
994 if ( NS_SPECIAL == $this->mNamespace || !$wgUser->isLoggedIn()) {
995 $this->mWatched = false;
996 } else {
997 $this->mWatched = $wgUser->isWatched( $this );
998 }
999 }
1000 return $this->mWatched;
1001 }
1002
1003 /**
1004 * Can $wgUser perform $action on this page?
1005 * This skips potentially expensive cascading permission checks.
1006 *
1007 * Suitable for use for nonessential UI controls in common cases, but
1008 * _not_ for functional access control.
1009 *
1010 * May provide false positives, but should never provide a false negative.
1011 *
1012 * @param string $action action that permission needs to be checked for
1013 * @return boolean
1014 */
1015 public function quickUserCan( $action ) {
1016 return $this->userCan( $action, false );
1017 }
1018
1019 /**
1020 * Determines if $wgUser is unable to edit this page because it has been protected
1021 * by $wgNamespaceProtection.
1022 *
1023 * @return boolean
1024 */
1025 public function isNamespaceProtected() {
1026 global $wgNamespaceProtection, $wgUser;
1027 if( isset( $wgNamespaceProtection[ $this->mNamespace ] ) ) {
1028 foreach( (array)$wgNamespaceProtection[ $this->mNamespace ] as $right ) {
1029 if( $right != '' && !$wgUser->isAllowed( $right ) )
1030 return true;
1031 }
1032 }
1033 return false;
1034 }
1035
1036 /**
1037 * Can $wgUser perform $action on this page?
1038 * @param string $action action that permission needs to be checked for
1039 * @param bool $doExpensiveQueries Set this to false to avoid doing unnecessary queries.
1040 * @return boolean
1041 */
1042 public function userCan( $action, $doExpensiveQueries = true ) {
1043 global $wgUser;
1044 return ( $this->getUserPermissionsErrorsInternal( $action, $wgUser, $doExpensiveQueries ) === array());
1045 }
1046
1047 /**
1048 * Can $user perform $action on this page?
1049 *
1050 * FIXME: This *does not* check throttles (User::pingLimiter()).
1051 *
1052 * @param string $action action that permission needs to be checked for
1053 * @param User $user user to check
1054 * @param bool $doExpensiveQueries Set this to false to avoid doing unnecessary queries.
1055 * @return array Array of arrays of the arguments to wfMsg to explain permissions problems.
1056 */
1057 public function getUserPermissionsErrors( $action, $user, $doExpensiveQueries = true ) {
1058 $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries );
1059
1060 global $wgContLang;
1061 global $wgLang;
1062 global $wgEmailConfirmToEdit;
1063
1064 if ( $wgEmailConfirmToEdit && !$user->isEmailConfirmed() ) {
1065 $errors[] = array( 'confirmedittext' );
1066 }
1067
1068 if ( $user->isBlockedFrom( $this ) ) {
1069 $block = $user->mBlock;
1070
1071 // This is from OutputPage::blockedPage
1072 // Copied at r23888 by werdna
1073
1074 $id = $user->blockedBy();
1075 $reason = $user->blockedFor();
1076 if( $reason == '' ) {
1077 $reason = wfMsg( 'blockednoreason' );
1078 }
1079 $ip = wfGetIP();
1080
1081 if ( is_numeric( $id ) ) {
1082 $name = User::whoIs( $id );
1083 } else {
1084 $name = $id;
1085 }
1086
1087 $link = '[[' . $wgContLang->getNsText( NS_USER ) . ":{$name}|{$name}]]";
1088 $blockid = $block->mId;
1089 $blockExpiry = $user->mBlock->mExpiry;
1090 $blockTimestamp = $wgLang->timeanddate( wfTimestamp( TS_MW, $user->mBlock->mTimestamp ), true );
1091
1092 if ( $blockExpiry == 'infinity' ) {
1093 // Entry in database (table ipblocks) is 'infinity' but 'ipboptions' uses 'infinite' or 'indefinite'
1094 $scBlockExpiryOptions = wfMsg( 'ipboptions' );
1095
1096 foreach ( explode( ',', $scBlockExpiryOptions ) as $option ) {
1097 if ( strpos( $option, ':' ) == false )
1098 continue;
1099
1100 list ($show, $value) = explode( ":", $option );
1101
1102 if ( $value == 'infinite' || $value == 'indefinite' ) {
1103 $blockExpiry = $show;
1104 break;
1105 }
1106 }
1107 } else {
1108 $blockExpiry = $wgLang->timeanddate( wfTimestamp( TS_MW, $blockExpiry ), true );
1109 }
1110
1111 $intended = $user->mBlock->mAddress;
1112
1113 $errors[] = array( ($block->mAuto ? 'autoblockedtext' : 'blockedtext'), $link, $reason, $ip, $name,
1114 $blockid, $blockExpiry, $intended, $blockTimestamp );
1115 }
1116
1117 return $errors;
1118 }
1119
1120 /**
1121 * Can $user perform $action on this page? This is an internal function,
1122 * which checks ONLY that previously checked by userCan (i.e. it leaves out
1123 * checks on wfReadOnly() and blocks)
1124 *
1125 * @param string $action action that permission needs to be checked for
1126 * @param User $user user to check
1127 * @param bool $doExpensiveQueries Set this to false to avoid doing unnecessary queries.
1128 * @return array Array of arrays of the arguments to wfMsg to explain permissions problems.
1129 */
1130 private function getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries = true ) {
1131 wfProfileIn( __METHOD__ );
1132
1133 $errors = array();
1134
1135 // Use getUserPermissionsErrors instead
1136 if ( !wfRunHooks( 'userCan', array( &$this, &$user, $action, &$result ) ) ) {
1137 wfProfileOut( __METHOD__ );
1138 return $result ? array() : array( array( 'badaccess-group0' ) );
1139 }
1140
1141 if (!wfRunHooks( 'getUserPermissionsErrors', array( &$this, &$user, $action, &$result ) ) ) {
1142 if ($result != array() && is_array($result) && !is_array($result[0]))
1143 $errors[] = $result; # A single array representing an error
1144 else if (is_array($result) && is_array($result[0]))
1145 $errors = array_merge( $errors, $result ); # A nested array representing multiple errors
1146 else if ($result != '' && $result != null && $result !== true && $result !== false)
1147 $errors[] = array($result); # A string representing a message-id
1148 else if ($result === false )
1149 $errors[] = array('badaccess-group0'); # a generic "We don't want them to do that"
1150 }
1151 if ($doExpensiveQueries && !wfRunHooks( 'getUserPermissionsErrorsExpensive', array( &$this, &$user, $action, &$result ) ) ) {
1152 if ($result != array() && is_array($result) && !is_array($result[0]))
1153 $errors[] = $result; # A single array representing an error
1154 else if (is_array($result) && is_array($result[0]))
1155 $errors = array_merge( $errors, $result ); # A nested array representing multiple errors
1156 else if ($result != '' && $result != null && $result !== true && $result !== false)
1157 $errors[] = array($result); # A string representing a message-id
1158 else if ($result === false )
1159 $errors[] = array('badaccess-group0'); # a generic "We don't want them to do that"
1160 }
1161
1162 if( NS_SPECIAL == $this->mNamespace ) {
1163 $errors[] = array('ns-specialprotected');
1164 }
1165
1166 if ( $this->isNamespaceProtected() ) {
1167 $ns = $this->getNamespace() == NS_MAIN
1168 ? wfMsg( 'nstab-main' )
1169 : $this->getNsText();
1170 $errors[] = (NS_MEDIAWIKI == $this->mNamespace
1171 ? array('protectedinterface')
1172 : array( 'namespaceprotected', $ns ) );
1173 }
1174
1175 if( $this->mDbkeyform == '_' ) {
1176 # FIXME: Is this necessary? Shouldn't be allowed anyway...
1177 $errors[] = array('badaccess-group0');
1178 }
1179
1180 # protect css/js subpages of user pages
1181 # XXX: this might be better using restrictions
1182 # XXX: Find a way to work around the php bug that prevents using $this->userCanEditCssJsSubpage() from working
1183 if( $this->isCssJsSubpage()
1184 && !$user->isAllowed('editusercssjs')
1185 && !preg_match('/^'.preg_quote($user->getName(), '/').'\//', $this->mTextform) ) {
1186 $errors[] = array('customcssjsprotected');
1187 }
1188
1189 if ( $doExpensiveQueries && !$this->isCssJsSubpage() ) {
1190 # We /could/ use the protection level on the source page, but it's fairly ugly
1191 # as we have to establish a precedence hierarchy for pages included by multiple
1192 # cascade-protected pages. So just restrict it to people with 'protect' permission,
1193 # as they could remove the protection anyway.
1194 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
1195 # Cascading protection depends on more than this page...
1196 # Several cascading protected pages may include this page...
1197 # Check each cascading level
1198 # This is only for protection restrictions, not for all actions
1199 if( $cascadingSources > 0 && isset($restrictions[$action]) ) {
1200 foreach( $restrictions[$action] as $right ) {
1201 $right = ( $right == 'sysop' ) ? 'protect' : $right;
1202 if( '' != $right && !$user->isAllowed( $right ) ) {
1203 $pages = '';
1204 foreach( $cascadingSources as $page )
1205 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
1206 $errors[] = array( 'cascadeprotected', count( $cascadingSources ), $pages );
1207 }
1208 }
1209 }
1210 }
1211
1212 foreach( $this->getRestrictions($action) as $right ) {
1213 // Backwards compatibility, rewrite sysop -> protect
1214 if ( $right == 'sysop' ) {
1215 $right = 'protect';
1216 }
1217 if( '' != $right && !$user->isAllowed( $right ) ) {
1218 //Users with 'editprotected' permission can edit protected pages
1219 if( $action=='edit' && $user->isAllowed( 'editprotected' ) ) {
1220 //Users with 'editprotected' permission cannot edit protected pages
1221 //with cascading option turned on.
1222 if($this->mCascadeRestriction) {
1223 $errors[] = array( 'protectedpagetext', $right );
1224 } else {
1225 //Nothing, user can edit!
1226 }
1227 } else {
1228 $errors[] = array( 'protectedpagetext', $right );
1229 }
1230 }
1231 }
1232
1233 if ($action == 'protect') {
1234 if ($this->getUserPermissionsErrors('edit', $user) != array()) {
1235 $errors[] = array( 'protect-cantedit' ); // If they can't edit, they shouldn't protect.
1236 }
1237 }
1238
1239 if ($action == 'create') {
1240 $title_protection = $this->getTitleProtection();
1241
1242 if (is_array($title_protection)) {
1243 extract($title_protection);
1244
1245 if ($pt_create_perm == 'sysop')
1246 $pt_create_perm = 'protect';
1247
1248 if ($pt_create_perm == '' || !$user->isAllowed($pt_create_perm)) {
1249 $errors[] = array ( 'titleprotected', User::whoIs($pt_user), $pt_reason );
1250 }
1251 }
1252
1253 if( ( $this->isTalkPage() && !$user->isAllowed( 'createtalk' ) ) ||
1254 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage' ) ) ) {
1255 $errors[] = $user->isAnon() ? array ('nocreatetext') : array ('nocreate-loggedin');
1256 }
1257 } elseif( $action == 'move' && !( $this->isMovable() && $user->isAllowed( 'move' ) ) ) {
1258 $errors[] = $user->isAnon() ? array ( 'movenologintext' ) : array ('movenotallowed');
1259 } elseif ( !$user->isAllowed( $action ) ) {
1260 $return = null;
1261 $groups = array();
1262 global $wgGroupPermissions;
1263 foreach( $wgGroupPermissions as $key => $value ) {
1264 if( isset( $value[$action] ) && $value[$action] == true ) {
1265 $groupName = User::getGroupName( $key );
1266 $groupPage = User::getGroupPage( $key );
1267 if( $groupPage ) {
1268 $groups[] = '[['.$groupPage->getPrefixedText().'|'.$groupName.']]';
1269 } else {
1270 $groups[] = $groupName;
1271 }
1272 }
1273 }
1274 $n = count( $groups );
1275 $groups = implode( ', ', $groups );
1276 switch( $n ) {
1277 case 0:
1278 case 1:
1279 case 2:
1280 $return = array( "badaccess-group$n", $groups );
1281 break;
1282 default:
1283 $return = array( 'badaccess-groups', $groups );
1284 }
1285 $errors[] = $return;
1286 }
1287
1288 wfProfileOut( __METHOD__ );
1289 return $errors;
1290 }
1291
1292 /**
1293 * Is this title subject to title protection?
1294 * @return mixed An associative array representing any existent title
1295 * protection, or false if there's none.
1296 */
1297 private function getTitleProtection() {
1298 // Can't protect pages in special namespaces
1299 if ( $this->getNamespace() < 0 ) {
1300 return false;
1301 }
1302
1303 $dbr = wfGetDB( DB_SLAVE );
1304 $res = $dbr->select( 'protected_titles', '*',
1305 array ('pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey()) );
1306
1307 if ($row = $dbr->fetchRow( $res )) {
1308 return $row;
1309 } else {
1310 return false;
1311 }
1312 }
1313
1314 public function updateTitleProtection( $create_perm, $reason, $expiry ) {
1315 global $wgGroupPermissions,$wgUser,$wgContLang;
1316
1317 if ($create_perm == implode(',',$this->getRestrictions('create'))
1318 && $expiry == $this->mRestrictionsExpiry) {
1319 // No change
1320 return true;
1321 }
1322
1323 list ($namespace, $title) = array( $this->getNamespace(), $this->getDBkey() );
1324
1325 $dbw = wfGetDB( DB_MASTER );
1326
1327 $encodedExpiry = Block::encodeExpiry($expiry, $dbw );
1328
1329 $expiry_description = '';
1330 if ( $encodedExpiry != 'infinity' ) {
1331 $expiry_description = ' (' . wfMsgForContent( 'protect-expiring', $wgContLang->timeanddate( $expiry ) ).')';
1332 }
1333
1334 # Update protection table
1335 if ($create_perm != '' ) {
1336 $dbw->replace( 'protected_titles', array(array('pt_namespace', 'pt_title')),
1337 array( 'pt_namespace' => $namespace, 'pt_title' => $title
1338 , 'pt_create_perm' => $create_perm
1339 , 'pt_timestamp' => Block::encodeExpiry(wfTimestampNow(), $dbw)
1340 , 'pt_expiry' => $encodedExpiry
1341 , 'pt_user' => $wgUser->getId(), 'pt_reason' => $reason ), __METHOD__ );
1342 } else {
1343 $dbw->delete( 'protected_titles', array( 'pt_namespace' => $namespace,
1344 'pt_title' => $title ), __METHOD__ );
1345 }
1346 # Update the protection log
1347 $log = new LogPage( 'protect' );
1348
1349 if( $create_perm ) {
1350 $log->addEntry( $this->mRestrictions['create'] ? 'modify' : 'protect', $this, trim( $reason . " [create=$create_perm] $expiry_description" ) );
1351 } else {
1352 $log->addEntry( 'unprotect', $this, $reason );
1353 }
1354
1355 return true;
1356 }
1357
1358 /**
1359 * Remove any title protection (due to page existing
1360 */
1361 public function deleteTitleProtection() {
1362 $dbw = wfGetDB( DB_MASTER );
1363
1364 $dbw->delete( 'protected_titles',
1365 array ('pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey()), __METHOD__ );
1366 }
1367
1368 /**
1369 * Can $wgUser edit this page?
1370 * @return boolean
1371 * @deprecated use userCan('edit')
1372 */
1373 public function userCanEdit( $doExpensiveQueries = true ) {
1374 return $this->userCan( 'edit', $doExpensiveQueries );
1375 }
1376
1377 /**
1378 * Can $wgUser create this page?
1379 * @return boolean
1380 * @deprecated use userCan('create')
1381 */
1382 public function userCanCreate( $doExpensiveQueries = true ) {
1383 return $this->userCan( 'create', $doExpensiveQueries );
1384 }
1385
1386 /**
1387 * Can $wgUser move this page?
1388 * @return boolean
1389 * @deprecated use userCan('move')
1390 */
1391 public function userCanMove( $doExpensiveQueries = true ) {
1392 return $this->userCan( 'move', $doExpensiveQueries );
1393 }
1394
1395 /**
1396 * Would anybody with sufficient privileges be able to move this page?
1397 * Some pages just aren't movable.
1398 *
1399 * @return boolean
1400 */
1401 public function isMovable() {
1402 return MWNamespace::isMovable( $this->getNamespace() )
1403 && $this->getInterwiki() == '';
1404 }
1405
1406 /**
1407 * Can $wgUser read this page?
1408 * @return boolean
1409 * @todo fold these checks into userCan()
1410 */
1411 public function userCanRead() {
1412 global $wgUser, $wgGroupPermissions;
1413
1414 $result = null;
1415 wfRunHooks( 'userCan', array( &$this, &$wgUser, 'read', &$result ) );
1416 if ( $result !== null ) {
1417 return $result;
1418 }
1419
1420 # Shortcut for public wikis, allows skipping quite a bit of code
1421 if ($wgGroupPermissions['*']['read'])
1422 return true;
1423
1424 if( $wgUser->isAllowed( 'read' ) ) {
1425 return true;
1426 } else {
1427 global $wgWhitelistRead;
1428
1429 /**
1430 * Always grant access to the login page.
1431 * Even anons need to be able to log in.
1432 */
1433 if( $this->isSpecial( 'Userlogin' ) || $this->isSpecial( 'Resetpass' ) ) {
1434 return true;
1435 }
1436
1437 /**
1438 * Bail out if there isn't whitelist
1439 */
1440 if( !is_array($wgWhitelistRead) ) {
1441 return false;
1442 }
1443
1444 /**
1445 * Check for explicit whitelisting
1446 */
1447 $name = $this->getPrefixedText();
1448 $dbName = $this->getPrefixedDBKey();
1449 // Check with and without underscores
1450 if( in_array($name,$wgWhitelistRead,true) || in_array($dbName,$wgWhitelistRead,true) )
1451 return true;
1452
1453 /**
1454 * Old settings might have the title prefixed with
1455 * a colon for main-namespace pages
1456 */
1457 if( $this->getNamespace() == NS_MAIN ) {
1458 if( in_array( ':' . $name, $wgWhitelistRead ) )
1459 return true;
1460 }
1461
1462 /**
1463 * If it's a special page, ditch the subpage bit
1464 * and check again
1465 */
1466 if( $this->getNamespace() == NS_SPECIAL ) {
1467 $name = $this->getDBkey();
1468 list( $name, /* $subpage */) = SpecialPage::resolveAliasWithSubpage( $name );
1469 if ( $name === false ) {
1470 # Invalid special page, but we show standard login required message
1471 return false;
1472 }
1473
1474 $pure = SpecialPage::getTitleFor( $name )->getPrefixedText();
1475 if( in_array( $pure, $wgWhitelistRead, true ) )
1476 return true;
1477 }
1478
1479 }
1480 return false;
1481 }
1482
1483 /**
1484 * Is this a talk page of some sort?
1485 * @return bool
1486 */
1487 public function isTalkPage() {
1488 return MWNamespace::isTalk( $this->getNamespace() );
1489 }
1490
1491 /**
1492 * Is this a subpage?
1493 * @return bool
1494 */
1495 public function isSubpage() {
1496 global $wgNamespacesWithSubpages;
1497
1498 if( isset( $wgNamespacesWithSubpages[ $this->mNamespace ] ) ) {
1499 return ( strpos( $this->getText(), '/' ) !== false && $wgNamespacesWithSubpages[ $this->mNamespace ] == true );
1500 } else {
1501 return false;
1502 }
1503 }
1504
1505 /**
1506 * Could this page contain custom CSS or JavaScript, based
1507 * on the title?
1508 *
1509 * @return bool
1510 */
1511 public function isCssOrJsPage() {
1512 return $this->mNamespace == NS_MEDIAWIKI
1513 && preg_match( '!\.(?:css|js)$!u', $this->mTextform ) > 0;
1514 }
1515
1516 /**
1517 * Is this a .css or .js subpage of a user page?
1518 * @return bool
1519 */
1520 public function isCssJsSubpage() {
1521 return ( NS_USER == $this->mNamespace and preg_match("/\\/.*\\.(?:css|js)$/", $this->mTextform ) );
1522 }
1523 /**
1524 * Is this a *valid* .css or .js subpage of a user page?
1525 * Check that the corresponding skin exists
1526 */
1527 public function isValidCssJsSubpage() {
1528 if ( $this->isCssJsSubpage() ) {
1529 $skinNames = Skin::getSkinNames();
1530 return array_key_exists( $this->getSkinFromCssJsSubpage(), $skinNames );
1531 } else {
1532 return false;
1533 }
1534 }
1535 /**
1536 * Trim down a .css or .js subpage title to get the corresponding skin name
1537 */
1538 public function getSkinFromCssJsSubpage() {
1539 $subpage = explode( '/', $this->mTextform );
1540 $subpage = $subpage[ count( $subpage ) - 1 ];
1541 return( str_replace( array( '.css', '.js' ), array( '', '' ), $subpage ) );
1542 }
1543 /**
1544 * Is this a .css subpage of a user page?
1545 * @return bool
1546 */
1547 public function isCssSubpage() {
1548 return ( NS_USER == $this->mNamespace && preg_match("/\\/.*\\.css$/", $this->mTextform ) );
1549 }
1550 /**
1551 * Is this a .js subpage of a user page?
1552 * @return bool
1553 */
1554 public function isJsSubpage() {
1555 return ( NS_USER == $this->mNamespace && preg_match("/\\/.*\\.js$/", $this->mTextform ) );
1556 }
1557 /**
1558 * Protect css/js subpages of user pages: can $wgUser edit
1559 * this page?
1560 *
1561 * @return boolean
1562 * @todo XXX: this might be better using restrictions
1563 */
1564 public function userCanEditCssJsSubpage() {
1565 global $wgUser;
1566 return ( $wgUser->isAllowed('editusercssjs') || preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform) );
1567 }
1568
1569 /**
1570 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
1571 *
1572 * @return bool If the page is subject to cascading restrictions.
1573 */
1574 public function isCascadeProtected() {
1575 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
1576 return ( $sources > 0 );
1577 }
1578
1579 /**
1580 * Cascading protection: Get the source of any cascading restrictions on this page.
1581 *
1582 * @param $get_pages bool Whether or not to retrieve the actual pages that the restrictions have come from.
1583 * @return array( mixed title array, restriction array)
1584 * 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.
1585 * The restriction array is an array of each type, each of which contains an array of unique groups
1586 */
1587 public function getCascadeProtectionSources( $get_pages = true ) {
1588 global $wgEnableCascadingProtection, $wgRestrictionTypes;
1589
1590 # Define our dimension of restrictions types
1591 $pagerestrictions = array();
1592 foreach( $wgRestrictionTypes as $action )
1593 $pagerestrictions[$action] = array();
1594
1595 if (!$wgEnableCascadingProtection)
1596 return array( false, $pagerestrictions );
1597
1598 if ( isset( $this->mCascadeSources ) && $get_pages ) {
1599 return array( $this->mCascadeSources, $this->mCascadingRestrictions );
1600 } else if ( isset( $this->mHasCascadingRestrictions ) && !$get_pages ) {
1601 return array( $this->mHasCascadingRestrictions, $pagerestrictions );
1602 }
1603
1604 wfProfileIn( __METHOD__ );
1605
1606 $dbr = wfGetDb( DB_SLAVE );
1607
1608 if ( $this->getNamespace() == NS_IMAGE ) {
1609 $tables = array ('imagelinks', 'page_restrictions');
1610 $where_clauses = array(
1611 'il_to' => $this->getDBkey(),
1612 'il_from=pr_page',
1613 'pr_cascade' => 1 );
1614 } else {
1615 $tables = array ('templatelinks', 'page_restrictions');
1616 $where_clauses = array(
1617 'tl_namespace' => $this->getNamespace(),
1618 'tl_title' => $this->getDBkey(),
1619 'tl_from=pr_page',
1620 'pr_cascade' => 1 );
1621 }
1622
1623 if ( $get_pages ) {
1624 $cols = array('pr_page', 'page_namespace', 'page_title', 'pr_expiry', 'pr_type', 'pr_level' );
1625 $where_clauses[] = 'page_id=pr_page';
1626 $tables[] = 'page';
1627 } else {
1628 $cols = array( 'pr_expiry' );
1629 }
1630
1631 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__ );
1632
1633 $sources = $get_pages ? array() : false;
1634 $now = wfTimestampNow();
1635 $purgeExpired = false;
1636
1637 while( $row = $dbr->fetchObject( $res ) ) {
1638 $expiry = Block::decodeExpiry( $row->pr_expiry );
1639 if( $expiry > $now ) {
1640 if ($get_pages) {
1641 $page_id = $row->pr_page;
1642 $page_ns = $row->page_namespace;
1643 $page_title = $row->page_title;
1644 $sources[$page_id] = Title::makeTitle($page_ns, $page_title);
1645 # Add groups needed for each restriction type if its not already there
1646 # Make sure this restriction type still exists
1647 if ( isset($pagerestrictions[$row->pr_type]) && !in_array($row->pr_level, $pagerestrictions[$row->pr_type]) ) {
1648 $pagerestrictions[$row->pr_type][]=$row->pr_level;
1649 }
1650 } else {
1651 $sources = true;
1652 }
1653 } else {
1654 // Trigger lazy purge of expired restrictions from the db
1655 $purgeExpired = true;
1656 }
1657 }
1658 if( $purgeExpired ) {
1659 Title::purgeExpiredRestrictions();
1660 }
1661
1662 wfProfileOut( __METHOD__ );
1663
1664 if ( $get_pages ) {
1665 $this->mCascadeSources = $sources;
1666 $this->mCascadingRestrictions = $pagerestrictions;
1667 } else {
1668 $this->mHasCascadingRestrictions = $sources;
1669 }
1670
1671 return array( $sources, $pagerestrictions );
1672 }
1673
1674 function areRestrictionsCascading() {
1675 if (!$this->mRestrictionsLoaded) {
1676 $this->loadRestrictions();
1677 }
1678
1679 return $this->mCascadeRestriction;
1680 }
1681
1682 /**
1683 * Loads a string into mRestrictions array
1684 * @param resource $res restrictions as an SQL result.
1685 */
1686 private function loadRestrictionsFromRow( $res, $oldFashionedRestrictions = NULL ) {
1687 global $wgRestrictionTypes;
1688 $dbr = wfGetDB( DB_SLAVE );
1689
1690 foreach( $wgRestrictionTypes as $type ){
1691 $this->mRestrictions[$type] = array();
1692 }
1693
1694 $this->mCascadeRestriction = false;
1695 $this->mRestrictionsExpiry = Block::decodeExpiry('');
1696
1697 # Backwards-compatibility: also load the restrictions from the page record (old format).
1698
1699 if ( $oldFashionedRestrictions === NULL ) {
1700 $oldFashionedRestrictions = $dbr->selectField( 'page', 'page_restrictions', array( 'page_id' => $this->getArticleId() ), __METHOD__ );
1701 }
1702
1703 if ($oldFashionedRestrictions != '') {
1704
1705 foreach( explode( ':', trim( $oldFashionedRestrictions ) ) as $restrict ) {
1706 $temp = explode( '=', trim( $restrict ) );
1707 if(count($temp) == 1) {
1708 // old old format should be treated as edit/move restriction
1709 $this->mRestrictions['edit'] = explode( ',', trim( $temp[0] ) );
1710 $this->mRestrictions['move'] = explode( ',', trim( $temp[0] ) );
1711 } else {
1712 $this->mRestrictions[$temp[0]] = explode( ',', trim( $temp[1] ) );
1713 }
1714 }
1715
1716 $this->mOldRestrictions = true;
1717
1718 }
1719
1720 if( $dbr->numRows( $res ) ) {
1721 # Current system - load second to make them override.
1722 $now = wfTimestampNow();
1723 $purgeExpired = false;
1724
1725 while ($row = $dbr->fetchObject( $res ) ) {
1726 # Cycle through all the restrictions.
1727
1728 // Don't take care of restrictions types that aren't in $wgRestrictionTypes
1729 if( !in_array( $row->pr_type, $wgRestrictionTypes ) )
1730 continue;
1731
1732 // This code should be refactored, now that it's being used more generally,
1733 // But I don't really see any harm in leaving it in Block for now -werdna
1734 $expiry = Block::decodeExpiry( $row->pr_expiry );
1735
1736 // Only apply the restrictions if they haven't expired!
1737 if ( !$expiry || $expiry > $now ) {
1738 $this->mRestrictionsExpiry = $expiry;
1739 $this->mRestrictions[$row->pr_type] = explode( ',', trim( $row->pr_level ) );
1740
1741 $this->mCascadeRestriction |= $row->pr_cascade;
1742 } else {
1743 // Trigger a lazy purge of expired restrictions
1744 $purgeExpired = true;
1745 }
1746 }
1747
1748 if( $purgeExpired ) {
1749 Title::purgeExpiredRestrictions();
1750 }
1751 }
1752
1753 $this->mRestrictionsLoaded = true;
1754 }
1755
1756 public function loadRestrictions( $oldFashionedRestrictions = NULL ) {
1757 if( !$this->mRestrictionsLoaded ) {
1758 if ($this->exists()) {
1759 $dbr = wfGetDB( DB_SLAVE );
1760
1761 $res = $dbr->select( 'page_restrictions', '*',
1762 array ( 'pr_page' => $this->getArticleId() ), __METHOD__ );
1763
1764 $this->loadRestrictionsFromRow( $res, $oldFashionedRestrictions );
1765 } else {
1766 $title_protection = $this->getTitleProtection();
1767
1768 if (is_array($title_protection)) {
1769 extract($title_protection);
1770
1771 $now = wfTimestampNow();
1772 $expiry = Block::decodeExpiry($pt_expiry);
1773
1774 if (!$expiry || $expiry > $now) {
1775 // Apply the restrictions
1776 $this->mRestrictionsExpiry = $expiry;
1777 $this->mRestrictions['create'] = explode(',', trim($pt_create_perm) );
1778 } else { // Get rid of the old restrictions
1779 Title::purgeExpiredRestrictions();
1780 }
1781 }
1782 $this->mRestrictionsLoaded = true;
1783 }
1784 }
1785 }
1786
1787 /**
1788 * Purge expired restrictions from the page_restrictions table
1789 */
1790 static function purgeExpiredRestrictions() {
1791 $dbw = wfGetDB( DB_MASTER );
1792 $dbw->delete( 'page_restrictions',
1793 array( 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
1794 __METHOD__ );
1795
1796 $dbw->delete( 'protected_titles',
1797 array( 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
1798 __METHOD__ );
1799 }
1800
1801 /**
1802 * Accessor/initialisation for mRestrictions
1803 *
1804 * @param string $action action that permission needs to be checked for
1805 * @return array the array of groups allowed to edit this article
1806 */
1807 public function getRestrictions( $action ) {
1808 if( !$this->mRestrictionsLoaded ) {
1809 $this->loadRestrictions();
1810 }
1811 return isset( $this->mRestrictions[$action] )
1812 ? $this->mRestrictions[$action]
1813 : array();
1814 }
1815
1816 /**
1817 * Is there a version of this page in the deletion archive?
1818 * @return int the number of archived revisions
1819 */
1820 public function isDeleted() {
1821 $fname = 'Title::isDeleted';
1822 if ( $this->getNamespace() < 0 ) {
1823 $n = 0;
1824 } else {
1825 $dbr = wfGetDB( DB_SLAVE );
1826 $n = $dbr->selectField( 'archive', 'COUNT(*)', array( 'ar_namespace' => $this->getNamespace(),
1827 'ar_title' => $this->getDBkey() ), $fname );
1828 if( $this->getNamespace() == NS_IMAGE ) {
1829 $n += $dbr->selectField( 'filearchive', 'COUNT(*)',
1830 array( 'fa_name' => $this->getDBkey() ), $fname );
1831 }
1832 }
1833 return (int)$n;
1834 }
1835
1836 /**
1837 * Get the article ID for this Title from the link cache,
1838 * adding it if necessary
1839 * @param int $flags a bit field; may be GAID_FOR_UPDATE to select
1840 * for update
1841 * @return int the ID
1842 */
1843 public function getArticleID( $flags = 0 ) {
1844 $linkCache = LinkCache::singleton();
1845 if ( $flags & GAID_FOR_UPDATE ) {
1846 $oldUpdate = $linkCache->forUpdate( true );
1847 $this->mArticleID = $linkCache->addLinkObj( $this );
1848 $linkCache->forUpdate( $oldUpdate );
1849 } else {
1850 if ( -1 == $this->mArticleID ) {
1851 $this->mArticleID = $linkCache->addLinkObj( $this );
1852 }
1853 }
1854 return $this->mArticleID;
1855 }
1856
1857 /**
1858 * Is this an article that is a redirect page?
1859 * Uses link cache, adding it if necessary
1860 * @param int $flags a bit field; may be GAID_FOR_UPDATE to select for update
1861 * @return bool
1862 */
1863 public function isRedirect( $flags = 0 ) {
1864 if( !is_null($this->mRedirect) )
1865 return $this->mRedirect;
1866 # Zero for special pages.
1867 # Also, calling getArticleID() loads the field from cache!
1868 if( !$this->getArticleID($flags) || $this->getNamespace() == NS_SPECIAL ) {
1869 return false;
1870 }
1871 $linkCache = LinkCache::singleton();
1872 $this->mRedirect = (bool)$linkCache->getGoodLinkFieldObj( $this, 'redirect' );
1873
1874 return $this->mRedirect;
1875 }
1876
1877 /**
1878 * What is the length of this page?
1879 * Uses link cache, adding it if necessary
1880 * @param int $flags a bit field; may be GAID_FOR_UPDATE to select for update
1881 * @return bool
1882 */
1883 public function getLength( $flags = 0 ) {
1884 if( $this->mLength != -1 )
1885 return $this->mLength;
1886 # Zero for special pages.
1887 # Also, calling getArticleID() loads the field from cache!
1888 if( !$this->getArticleID($flags) || $this->getNamespace() == NS_SPECIAL ) {
1889 return 0;
1890 }
1891 $linkCache = LinkCache::singleton();
1892 $this->mLength = intval( $linkCache->getGoodLinkFieldObj( $this, 'length' ) );
1893
1894 return $this->mLength;
1895 }
1896
1897 /**
1898 * What is the page_latest field for this page?
1899 * @param int $flags a bit field; may be GAID_FOR_UPDATE to select for update
1900 * @return int
1901 */
1902 public function getLatestRevID( $flags = 0 ) {
1903 if ($this->mLatestID !== false)
1904 return $this->mLatestID;
1905
1906 $db = ($flags & GAID_FOR_UPDATE) ? wfGetDB(DB_MASTER) : wfGetDB(DB_SLAVE);
1907 return $this->mLatestID = $db->selectField( 'revision',
1908 "max(rev_id)",
1909 array('rev_page' => $this->getArticleID()),
1910 'Title::getLatestRevID' );
1911 }
1912
1913 /**
1914 * This clears some fields in this object, and clears any associated
1915 * keys in the "bad links" section of the link cache.
1916 *
1917 * - This is called from Article::insertNewArticle() to allow
1918 * loading of the new page_id. It's also called from
1919 * Article::doDeleteArticle()
1920 *
1921 * @param int $newid the new Article ID
1922 */
1923 public function resetArticleID( $newid ) {
1924 $linkCache = LinkCache::singleton();
1925 $linkCache->clearBadLink( $this->getPrefixedDBkey() );
1926
1927 if ( 0 == $newid ) { $this->mArticleID = -1; }
1928 else { $this->mArticleID = $newid; }
1929 $this->mRestrictionsLoaded = false;
1930 $this->mRestrictions = array();
1931 }
1932
1933 /**
1934 * Updates page_touched for this page; called from LinksUpdate.php
1935 * @return bool true if the update succeded
1936 */
1937 public function invalidateCache() {
1938 global $wgUseFileCache;
1939
1940 if ( wfReadOnly() ) {
1941 return;
1942 }
1943
1944 $dbw = wfGetDB( DB_MASTER );
1945 $success = $dbw->update( 'page',
1946 array( /* SET */
1947 'page_touched' => $dbw->timestamp()
1948 ), array( /* WHERE */
1949 'page_namespace' => $this->getNamespace() ,
1950 'page_title' => $this->getDBkey()
1951 ), 'Title::invalidateCache'
1952 );
1953
1954 if ($wgUseFileCache) {
1955 $cache = new HTMLFileCache($this);
1956 @unlink($cache->fileCacheName());
1957 }
1958
1959 return $success;
1960 }
1961
1962 /**
1963 * Prefix some arbitrary text with the namespace or interwiki prefix
1964 * of this object
1965 *
1966 * @param string $name the text
1967 * @return string the prefixed text
1968 * @private
1969 */
1970 /* private */ function prefix( $name ) {
1971 $p = '';
1972 if ( '' != $this->mInterwiki ) {
1973 $p = $this->mInterwiki . ':';
1974 }
1975 if ( 0 != $this->mNamespace ) {
1976 $p .= $this->getNsText() . ':';
1977 }
1978 return $p . $name;
1979 }
1980
1981 /**
1982 * Secure and split - main initialisation function for this object
1983 *
1984 * Assumes that mDbkeyform has been set, and is urldecoded
1985 * and uses underscores, but not otherwise munged. This function
1986 * removes illegal characters, splits off the interwiki and
1987 * namespace prefixes, sets the other forms, and canonicalizes
1988 * everything.
1989 * @return bool true on success
1990 */
1991 private function secureAndSplit() {
1992 global $wgContLang, $wgLocalInterwiki, $wgCapitalLinks;
1993
1994 # Initialisation
1995 static $rxTc = false;
1996 if( !$rxTc ) {
1997 # Matching titles will be held as illegal.
1998 $rxTc = '/' .
1999 # Any character not allowed is forbidden...
2000 '[^' . Title::legalChars() . ']' .
2001 # URL percent encoding sequences interfere with the ability
2002 # to round-trip titles -- you can't link to them consistently.
2003 '|%[0-9A-Fa-f]{2}' .
2004 # XML/HTML character references produce similar issues.
2005 '|&[A-Za-z0-9\x80-\xff]+;' .
2006 '|&#[0-9]+;' .
2007 '|&#x[0-9A-Fa-f]+;' .
2008 '/S';
2009 }
2010
2011 $this->mInterwiki = $this->mFragment = '';
2012 $this->mNamespace = $this->mDefaultNamespace; # Usually NS_MAIN
2013
2014 $dbkey = $this->mDbkeyform;
2015
2016 # Strip Unicode bidi override characters.
2017 # Sometimes they slip into cut-n-pasted page titles, where the
2018 # override chars get included in list displays.
2019 $dbkey = str_replace( "\xE2\x80\x8E", '', $dbkey ); // 200E LEFT-TO-RIGHT MARK
2020 $dbkey = str_replace( "\xE2\x80\x8F", '', $dbkey ); // 200F RIGHT-TO-LEFT MARK
2021
2022 # Clean up whitespace
2023 #
2024 $dbkey = preg_replace( '/[ _]+/', '_', $dbkey );
2025 $dbkey = trim( $dbkey, '_' );
2026
2027 if ( '' == $dbkey ) {
2028 return false;
2029 }
2030
2031 if( false !== strpos( $dbkey, UTF8_REPLACEMENT ) ) {
2032 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
2033 return false;
2034 }
2035
2036 $this->mDbkeyform = $dbkey;
2037
2038 # Initial colon indicates main namespace rather than specified default
2039 # but should not create invalid {ns,title} pairs such as {0,Project:Foo}
2040 if ( ':' == $dbkey{0} ) {
2041 $this->mNamespace = NS_MAIN;
2042 $dbkey = substr( $dbkey, 1 ); # remove the colon but continue processing
2043 $dbkey = trim( $dbkey, '_' ); # remove any subsequent whitespace
2044 }
2045
2046 # Namespace or interwiki prefix
2047 $firstPass = true;
2048 do {
2049 $m = array();
2050 if ( preg_match( "/^(.+?)_*:_*(.*)$/S", $dbkey, $m ) ) {
2051 $p = $m[1];
2052 if ( $ns = $wgContLang->getNsIndex( $p )) {
2053 # Ordinary namespace
2054 $dbkey = $m[2];
2055 $this->mNamespace = $ns;
2056 } elseif( $this->getInterwikiLink( $p ) ) {
2057 if( !$firstPass ) {
2058 # Can't make a local interwiki link to an interwiki link.
2059 # That's just crazy!
2060 return false;
2061 }
2062
2063 # Interwiki link
2064 $dbkey = $m[2];
2065 $this->mInterwiki = $wgContLang->lc( $p );
2066
2067 # Redundant interwiki prefix to the local wiki
2068 if ( 0 == strcasecmp( $this->mInterwiki, $wgLocalInterwiki ) ) {
2069 if( $dbkey == '' ) {
2070 # Can't have an empty self-link
2071 return false;
2072 }
2073 $this->mInterwiki = '';
2074 $firstPass = false;
2075 # Do another namespace split...
2076 continue;
2077 }
2078
2079 # If there's an initial colon after the interwiki, that also
2080 # resets the default namespace
2081 if ( $dbkey !== '' && $dbkey[0] == ':' ) {
2082 $this->mNamespace = NS_MAIN;
2083 $dbkey = substr( $dbkey, 1 );
2084 }
2085 }
2086 # If there's no recognized interwiki or namespace,
2087 # then let the colon expression be part of the title.
2088 }
2089 break;
2090 } while( true );
2091
2092 # We already know that some pages won't be in the database!
2093 #
2094 if ( '' != $this->mInterwiki || NS_SPECIAL == $this->mNamespace ) {
2095 $this->mArticleID = 0;
2096 }
2097 $fragment = strstr( $dbkey, '#' );
2098 if ( false !== $fragment ) {
2099 $this->setFragment( $fragment );
2100 $dbkey = substr( $dbkey, 0, strlen( $dbkey ) - strlen( $fragment ) );
2101 # remove whitespace again: prevents "Foo_bar_#"
2102 # becoming "Foo_bar_"
2103 $dbkey = preg_replace( '/_*$/', '', $dbkey );
2104 }
2105
2106 # Reject illegal characters.
2107 #
2108 if( preg_match( $rxTc, $dbkey ) ) {
2109 return false;
2110 }
2111
2112 /**
2113 * Pages with "/./" or "/../" appearing in the URLs will
2114 * often be unreachable due to the way web browsers deal
2115 * with 'relative' URLs. Forbid them explicitly.
2116 */
2117 if ( strpos( $dbkey, '.' ) !== false &&
2118 ( $dbkey === '.' || $dbkey === '..' ||
2119 strpos( $dbkey, './' ) === 0 ||
2120 strpos( $dbkey, '../' ) === 0 ||
2121 strpos( $dbkey, '/./' ) !== false ||
2122 strpos( $dbkey, '/../' ) !== false ||
2123 substr( $dbkey, -2 ) == '/.' ||
2124 substr( $dbkey, -3 ) == '/..' ) )
2125 {
2126 return false;
2127 }
2128
2129 /**
2130 * Magic tilde sequences? Nu-uh!
2131 */
2132 if( strpos( $dbkey, '~~~' ) !== false ) {
2133 return false;
2134 }
2135
2136 /**
2137 * Limit the size of titles to 255 bytes.
2138 * This is typically the size of the underlying database field.
2139 * We make an exception for special pages, which don't need to be stored
2140 * in the database, and may edge over 255 bytes due to subpage syntax
2141 * for long titles, e.g. [[Special:Block/Long name]]
2142 */
2143 if ( ( $this->mNamespace != NS_SPECIAL && strlen( $dbkey ) > 255 ) ||
2144 strlen( $dbkey ) > 512 )
2145 {
2146 return false;
2147 }
2148
2149 /**
2150 * Normally, all wiki links are forced to have
2151 * an initial capital letter so [[foo]] and [[Foo]]
2152 * point to the same place.
2153 *
2154 * Don't force it for interwikis, since the other
2155 * site might be case-sensitive.
2156 */
2157 $this->mUserCaseDBKey = $dbkey;
2158 if( $wgCapitalLinks && $this->mInterwiki == '') {
2159 $dbkey = $wgContLang->ucfirst( $dbkey );
2160 }
2161
2162 /**
2163 * Can't make a link to a namespace alone...
2164 * "empty" local links can only be self-links
2165 * with a fragment identifier.
2166 */
2167 if( $dbkey == '' &&
2168 $this->mInterwiki == '' &&
2169 $this->mNamespace != NS_MAIN ) {
2170 return false;
2171 }
2172 // Allow IPv6 usernames to start with '::' by canonicalizing IPv6 titles.
2173 // IP names are not allowed for accounts, and can only be referring to
2174 // edits from the IP. Given '::' abbreviations and caps/lowercaps,
2175 // there are numerous ways to present the same IP. Having sp:contribs scan
2176 // them all is silly and having some show the edits and others not is
2177 // inconsistent. Same for talk/userpages. Keep them normalized instead.
2178 $dbkey = ($this->mNamespace == NS_USER || $this->mNamespace == NS_USER_TALK) ?
2179 IP::sanitizeIP( $dbkey ) : $dbkey;
2180 // Any remaining initial :s are illegal.
2181 if ( $dbkey !== '' && ':' == $dbkey{0} ) {
2182 return false;
2183 }
2184
2185 # Fill fields
2186 $this->mDbkeyform = $dbkey;
2187 $this->mUrlform = wfUrlencode( $dbkey );
2188
2189 $this->mTextform = str_replace( '_', ' ', $dbkey );
2190
2191 return true;
2192 }
2193
2194 /**
2195 * Set the fragment for this title
2196 * This is kind of bad, since except for this rarely-used function, Title objects
2197 * are immutable. The reason this is here is because it's better than setting the
2198 * members directly, which is what Linker::formatComment was doing previously.
2199 *
2200 * @param string $fragment text
2201 * @todo clarify whether access is supposed to be public (was marked as "kind of public")
2202 */
2203 public function setFragment( $fragment ) {
2204 $this->mFragment = str_replace( '_', ' ', substr( $fragment, 1 ) );
2205 }
2206
2207 /**
2208 * Get a Title object associated with the talk page of this article
2209 * @return Title the object for the talk page
2210 */
2211 public function getTalkPage() {
2212 return Title::makeTitle( MWNamespace::getTalk( $this->getNamespace() ), $this->getDBkey() );
2213 }
2214
2215 /**
2216 * Get a title object associated with the subject page of this
2217 * talk page
2218 *
2219 * @return Title the object for the subject page
2220 */
2221 public function getSubjectPage() {
2222 return Title::makeTitle( MWNamespace::getSubject( $this->getNamespace() ), $this->getDBkey() );
2223 }
2224
2225 /**
2226 * Get an array of Title objects linking to this Title
2227 * Also stores the IDs in the link cache.
2228 *
2229 * WARNING: do not use this function on arbitrary user-supplied titles!
2230 * On heavily-used templates it will max out the memory.
2231 *
2232 * @param string $options may be FOR UPDATE
2233 * @return array the Title objects linking here
2234 */
2235 public function getLinksTo( $options = '', $table = 'pagelinks', $prefix = 'pl' ) {
2236 $linkCache = LinkCache::singleton();
2237
2238 if ( $options ) {
2239 $db = wfGetDB( DB_MASTER );
2240 } else {
2241 $db = wfGetDB( DB_SLAVE );
2242 }
2243
2244 $res = $db->select( array( 'page', $table ),
2245 array( 'page_namespace', 'page_title', 'page_id', 'page_len', 'page_is_redirect' ),
2246 array(
2247 "{$prefix}_from=page_id",
2248 "{$prefix}_namespace" => $this->getNamespace(),
2249 "{$prefix}_title" => $this->getDBkey() ),
2250 'Title::getLinksTo',
2251 $options );
2252
2253 $retVal = array();
2254 if ( $db->numRows( $res ) ) {
2255 while ( $row = $db->fetchObject( $res ) ) {
2256 if ( $titleObj = Title::makeTitle( $row->page_namespace, $row->page_title ) ) {
2257 $linkCache->addGoodLinkObj( $row->page_id, $titleObj, $row->page_len, $row->page_is_redirect );
2258 $retVal[] = $titleObj;
2259 }
2260 }
2261 }
2262 $db->freeResult( $res );
2263 return $retVal;
2264 }
2265
2266 /**
2267 * Get an array of Title objects using this Title as a template
2268 * Also stores the IDs in the link cache.
2269 *
2270 * WARNING: do not use this function on arbitrary user-supplied titles!
2271 * On heavily-used templates it will max out the memory.
2272 *
2273 * @param string $options may be FOR UPDATE
2274 * @return array the Title objects linking here
2275 */
2276 public function getTemplateLinksTo( $options = '' ) {
2277 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
2278 }
2279
2280 /**
2281 * Get an array of Title objects referring to non-existent articles linked from this page
2282 *
2283 * @todo check if needed (used only in SpecialBrokenRedirects.php, and should use redirect table in this case)
2284 * @param string $options may be FOR UPDATE
2285 * @return array the Title objects
2286 */
2287 public function getBrokenLinksFrom( $options = '' ) {
2288 if ( $this->getArticleId() == 0 ) {
2289 # All links from article ID 0 are false positives
2290 return array();
2291 }
2292
2293 if ( $options ) {
2294 $db = wfGetDB( DB_MASTER );
2295 } else {
2296 $db = wfGetDB( DB_SLAVE );
2297 }
2298
2299 $res = $db->safeQuery(
2300 "SELECT pl_namespace, pl_title
2301 FROM !
2302 LEFT JOIN !
2303 ON pl_namespace=page_namespace
2304 AND pl_title=page_title
2305 WHERE pl_from=?
2306 AND page_namespace IS NULL
2307 !",
2308 $db->tableName( 'pagelinks' ),
2309 $db->tableName( 'page' ),
2310 $this->getArticleId(),
2311 $options );
2312
2313 $retVal = array();
2314 if ( $db->numRows( $res ) ) {
2315 while ( $row = $db->fetchObject( $res ) ) {
2316 $retVal[] = Title::makeTitle( $row->pl_namespace, $row->pl_title );
2317 }
2318 }
2319 $db->freeResult( $res );
2320 return $retVal;
2321 }
2322
2323
2324 /**
2325 * Get a list of URLs to purge from the Squid cache when this
2326 * page changes
2327 *
2328 * @return array the URLs
2329 */
2330 public function getSquidURLs() {
2331 global $wgContLang;
2332
2333 $urls = array(
2334 $this->getInternalURL(),
2335 $this->getInternalURL( 'action=history' )
2336 );
2337
2338 // purge variant urls as well
2339 if($wgContLang->hasVariants()){
2340 $variants = $wgContLang->getVariants();
2341 foreach($variants as $vCode){
2342 if($vCode==$wgContLang->getCode()) continue; // we don't want default variant
2343 $urls[] = $this->getInternalURL('',$vCode);
2344 }
2345 }
2346
2347 return $urls;
2348 }
2349
2350 public function purgeSquid() {
2351 global $wgUseSquid;
2352 if ( $wgUseSquid ) {
2353 $urls = $this->getSquidURLs();
2354 $u = new SquidUpdate( $urls );
2355 $u->doUpdate();
2356 }
2357 }
2358
2359 /**
2360 * Move this page without authentication
2361 * @param Title &$nt the new page Title
2362 */
2363 public function moveNoAuth( &$nt ) {
2364 return $this->moveTo( $nt, false );
2365 }
2366
2367 /**
2368 * Check whether a given move operation would be valid.
2369 * Returns true if ok, or a message key string for an error message
2370 * if invalid. (Scarrrrry ugly interface this.)
2371 * @param Title &$nt the new title
2372 * @param bool $auth indicates whether $wgUser's permissions
2373 * should be checked
2374 * @return mixed true on success, message name on failure
2375 */
2376 public function isValidMoveOperation( &$nt, $auth = true ) {
2377 if( !$this or !$nt ) {
2378 return 'badtitletext';
2379 }
2380 if( $this->equals( $nt ) ) {
2381 return 'selfmove';
2382 }
2383 if( !$this->isMovable() || !$nt->isMovable() ) {
2384 return 'immobile_namespace';
2385 }
2386
2387 $oldid = $this->getArticleID();
2388 $newid = $nt->getArticleID();
2389
2390 if ( strlen( $nt->getDBkey() ) < 1 ) {
2391 return 'articleexists';
2392 }
2393 if ( ( '' == $this->getDBkey() ) ||
2394 ( !$oldid ) ||
2395 ( '' == $nt->getDBkey() ) ) {
2396 return 'badarticleerror';
2397 }
2398
2399 // Image-specific checks
2400 if( $this->getNamespace() == NS_IMAGE ) {
2401 $file = wfLocalFile( $this );
2402 if( $file->exists() ) {
2403 if( $nt->getNamespace() != NS_IMAGE ) {
2404 return 'imagenocrossnamespace';
2405 }
2406 if( !File::checkExtensionCompatibility( $file, $nt->getDbKey() ) ) {
2407 return 'imagetypemismatch';
2408 }
2409 }
2410 }
2411
2412 if ( $auth ) {
2413 global $wgUser;
2414 $errors = array_merge($this->getUserPermissionsErrors('move', $wgUser),
2415 $this->getUserPermissionsErrors('edit', $wgUser),
2416 $nt->getUserPermissionsErrors('move', $wgUser),
2417 $nt->getUserPermissionsErrors('edit', $wgUser));
2418 if($errors !== array())
2419 return $errors[0][0];
2420 }
2421
2422 global $wgUser;
2423 $err = null;
2424 if( !wfRunHooks( 'AbortMove', array( $this, $nt, $wgUser, &$err ) ) ) {
2425 return 'hookaborted';
2426 }
2427
2428 # The move is allowed only if (1) the target doesn't exist, or
2429 # (2) the target is a redirect to the source, and has no history
2430 # (so we can undo bad moves right after they're done).
2431
2432 if ( 0 != $newid ) { # Target exists; check for validity
2433 if ( ! $this->isValidMoveTarget( $nt ) ) {
2434 return 'articleexists';
2435 }
2436 } else {
2437 $tp = $nt->getTitleProtection();
2438 $right = ( $tp['pt_create_perm'] == 'sysop' ) ? 'protect' : $tp['pt_create_perm'];
2439 if ( $tp and !$wgUser->isAllowed( $right ) ) {
2440 return 'cantmove-titleprotected';
2441 }
2442 }
2443 return true;
2444 }
2445
2446 /**
2447 * Move a title to a new location
2448 * @param Title &$nt the new title
2449 * @param bool $auth indicates whether $wgUser's permissions
2450 * should be checked
2451 * @param string $reason The reason for the move
2452 * @param bool $createRedirect Whether to create a redirect from the old title to the new title.
2453 * Ignored if the user doesn't have the suppressredirect right.
2454 * @return mixed true on success, message name on failure
2455 */
2456 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true ) {
2457 $err = $this->isValidMoveOperation( $nt, $auth );
2458 if( is_string( $err ) ) {
2459 return $err;
2460 }
2461
2462 $pageid = $this->getArticleID();
2463 if( $nt->exists() ) {
2464 $err = $this->moveOverExistingRedirect( $nt, $reason, $createRedirect );
2465 $pageCountChange = ($createRedirect ? 0 : -1);
2466 } else { # Target didn't exist, do normal move.
2467 $err = $this->moveToNewTitle( $nt, $reason, $createRedirect );
2468 $pageCountChange = ($createRedirect ? 1 : 0);
2469 }
2470 if( is_string( $err ) ) {
2471 return $err;
2472 }
2473 $redirid = $this->getArticleID();
2474
2475 // Category memberships include a sort key which may be customized.
2476 // If it's left as the default (the page title), we need to update
2477 // the sort key to match the new title.
2478 //
2479 // Be careful to avoid resetting cl_timestamp, which may disturb
2480 // time-based lists on some sites.
2481 //
2482 // Warning -- if the sort key is *explicitly* set to the old title,
2483 // we can't actually distinguish it from a default here, and it'll
2484 // be set to the new title even though it really shouldn't.
2485 // It'll get corrected on the next edit, but resetting cl_timestamp.
2486 $dbw = wfGetDB( DB_MASTER );
2487 $dbw->update( 'categorylinks',
2488 array(
2489 'cl_sortkey' => $nt->getPrefixedText(),
2490 'cl_timestamp=cl_timestamp' ),
2491 array(
2492 'cl_from' => $pageid,
2493 'cl_sortkey' => $this->getPrefixedText() ),
2494 __METHOD__ );
2495
2496 # Update watchlists
2497
2498 $oldnamespace = $this->getNamespace() & ~1;
2499 $newnamespace = $nt->getNamespace() & ~1;
2500 $oldtitle = $this->getDBkey();
2501 $newtitle = $nt->getDBkey();
2502
2503 if( $oldnamespace != $newnamespace || $oldtitle != $newtitle ) {
2504 WatchedItem::duplicateEntries( $this, $nt );
2505 }
2506
2507 # Update search engine
2508 $u = new SearchUpdate( $pageid, $nt->getPrefixedDBkey() );
2509 $u->doUpdate();
2510 $u = new SearchUpdate( $redirid, $this->getPrefixedDBkey(), '' );
2511 $u->doUpdate();
2512
2513 # Update site_stats
2514 if( $this->isContentPage() && !$nt->isContentPage() ) {
2515 # No longer a content page
2516 # Not viewed, edited, removing
2517 $u = new SiteStatsUpdate( 0, 1, -1, $pageCountChange );
2518 } elseif( !$this->isContentPage() && $nt->isContentPage() ) {
2519 # Now a content page
2520 # Not viewed, edited, adding
2521 $u = new SiteStatsUpdate( 0, 1, +1, $pageCountChange );
2522 } elseif( $pageCountChange ) {
2523 # Redirect added
2524 $u = new SiteStatsUpdate( 0, 0, 0, 1 );
2525 } else {
2526 # Nothing special
2527 $u = false;
2528 }
2529 if( $u )
2530 $u->doUpdate();
2531 # Update message cache for interface messages
2532 if( $nt->getNamespace() == NS_MEDIAWIKI ) {
2533 global $wgMessageCache;
2534 $oldarticle = new Article( $this );
2535 $wgMessageCache->replace( $this->getDBkey(), $oldarticle->getContent() );
2536 $newarticle = new Article( $nt );
2537 $wgMessageCache->replace( $nt->getDBkey(), $newarticle->getContent() );
2538 }
2539
2540 global $wgUser;
2541 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) );
2542 return true;
2543 }
2544
2545 /**
2546 * Move page to a title which is at present a redirect to the
2547 * source page
2548 *
2549 * @param Title &$nt the page to move to, which should currently
2550 * be a redirect
2551 * @param string $reason The reason for the move
2552 * @param bool $createRedirect Whether to leave a redirect at the old title.
2553 * Ignored if the user doesn't have the suppressredirect right
2554 */
2555 private function moveOverExistingRedirect( &$nt, $reason = '', $createRedirect = true ) {
2556 global $wgUseSquid, $wgUser;
2557 $fname = 'Title::moveOverExistingRedirect';
2558 $comment = wfMsgForContent( '1movedto2_redir', $this->getPrefixedText(), $nt->getPrefixedText() );
2559
2560 if ( $reason ) {
2561 $comment .= ": $reason";
2562 }
2563
2564 $now = wfTimestampNow();
2565 $newid = $nt->getArticleID();
2566 $oldid = $this->getArticleID();
2567 $dbw = wfGetDB( DB_MASTER );
2568
2569 # Move an image if it is
2570 if( $this->getNamespace() == NS_IMAGE ) {
2571 $file = wfLocalFile( $this );
2572 if( $file->exists() ) {
2573 $status = $file->move( $nt );
2574 if( !$status->isOk() ) {
2575 return $status->getWikiText();
2576 }
2577 }
2578 }
2579
2580 # Delete the old redirect. We don't save it to history since
2581 # by definition if we've got here it's rather uninteresting.
2582 # We have to remove it so that the next step doesn't trigger
2583 # a conflict on the unique namespace+title index...
2584 $dbw->delete( 'page', array( 'page_id' => $newid ), $fname );
2585 if ( !$dbw->cascadingDeletes() ) {
2586 $dbw->delete( 'revision', array( 'rev_page' => $newid ), __METHOD__ );
2587 global $wgUseTrackbacks;
2588 if ($wgUseTrackbacks)
2589 $dbw->delete( 'trackbacks', array( 'tb_page' => $newid ), __METHOD__ );
2590 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), __METHOD__ );
2591 $dbw->delete( 'imagelinks', array( 'il_from' => $newid ), __METHOD__ );
2592 $dbw->delete( 'categorylinks', array( 'cl_from' => $newid ), __METHOD__ );
2593 $dbw->delete( 'templatelinks', array( 'tl_from' => $newid ), __METHOD__ );
2594 $dbw->delete( 'externallinks', array( 'el_from' => $newid ), __METHOD__ );
2595 $dbw->delete( 'langlinks', array( 'll_from' => $newid ), __METHOD__ );
2596 $dbw->delete( 'redirect', array( 'rd_from' => $newid ), __METHOD__ );
2597 }
2598
2599 # Save a null revision in the page's history notifying of the move
2600 $nullRevision = Revision::newNullRevision( $dbw, $oldid, $comment, true );
2601 $nullRevId = $nullRevision->insertOn( $dbw, true );
2602
2603 # Change the name of the target page:
2604 $dbw->update( 'page',
2605 /* SET */ array(
2606 'page_touched' => $dbw->timestamp($now),
2607 'page_namespace' => $nt->getNamespace(),
2608 'page_title' => $nt->getDBkey(),
2609 'page_latest' => $nullRevId,
2610 ),
2611 /* WHERE */ array( 'page_id' => $oldid ),
2612 $fname
2613 );
2614 $nt->resetArticleID( $oldid );
2615
2616 # Recreate the redirect, this time in the other direction.
2617 if($createRedirect || !$wgUser->isAllowed('suppressredirect'))
2618 {
2619 $mwRedir = MagicWord::get( 'redirect' );
2620 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
2621 $redirectArticle = new Article( $this );
2622 $newid = $redirectArticle->insertOn( $dbw );
2623 $redirectRevision = new Revision( array(
2624 'page' => $newid,
2625 'comment' => $comment,
2626 'text' => $redirectText ) );
2627 $redirectRevision->insertOn( $dbw, true );
2628 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
2629
2630 # Now, we record the link from the redirect to the new title.
2631 # It should have no other outgoing links...
2632 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), $fname );
2633 $dbw->insert( 'pagelinks',
2634 array(
2635 'pl_from' => $newid,
2636 'pl_namespace' => $nt->getNamespace(),
2637 'pl_title' => $nt->getDBkey() ),
2638 $fname );
2639 } else {
2640 $this->resetArticleID( 0 );
2641 }
2642
2643 # Log the move
2644 $log = new LogPage( 'move' );
2645 $log->addEntry( 'move_redir', $this, $reason, array( 1 => $nt->getPrefixedText() ) );
2646
2647 # Purge squid
2648 if ( $wgUseSquid ) {
2649 $urls = array_merge( $nt->getSquidURLs(), $this->getSquidURLs() );
2650 $u = new SquidUpdate( $urls );
2651 $u->doUpdate();
2652 }
2653 }
2654
2655 /**
2656 * Move page to non-existing title.
2657 * @param Title &$nt the new Title
2658 * @param string $reason The reason for the move
2659 * @param bool $createRedirect Whether to create a redirect from the old title to the new title
2660 * Ignored if the user doesn't have the suppressredirect right
2661 */
2662 private function moveToNewTitle( &$nt, $reason = '', $createRedirect = true ) {
2663 global $wgUseSquid, $wgUser;
2664 $fname = 'MovePageForm::moveToNewTitle';
2665 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
2666 if ( $reason ) {
2667 $comment .= ": $reason";
2668 }
2669
2670 $newid = $nt->getArticleID();
2671 $oldid = $this->getArticleID();
2672 $dbw = wfGetDB( DB_MASTER );
2673 $now = $dbw->timestamp();
2674
2675 # Move an image if it is
2676 if( $this->getNamespace() == NS_IMAGE ) {
2677 $file = wfLocalFile( $this );
2678 if( $file->exists() ) {
2679 $status = $file->move( $nt );
2680 if( !$status->isOk() ) {
2681 return $status->getWikiText();
2682 }
2683 }
2684 }
2685
2686 # Save a null revision in the page's history notifying of the move
2687 $nullRevision = Revision::newNullRevision( $dbw, $oldid, $comment, true );
2688 $nullRevId = $nullRevision->insertOn( $dbw, true );
2689
2690 # Rename page entry
2691 $dbw->update( 'page',
2692 /* SET */ array(
2693 'page_touched' => $now,
2694 'page_namespace' => $nt->getNamespace(),
2695 'page_title' => $nt->getDBkey(),
2696 'page_latest' => $nullRevId,
2697 ),
2698 /* WHERE */ array( 'page_id' => $oldid ),
2699 $fname
2700 );
2701 $nt->resetArticleID( $oldid );
2702
2703 if($createRedirect || !$wgUser->isAllowed('suppressredirect'))
2704 {
2705 # Insert redirect
2706 $mwRedir = MagicWord::get( 'redirect' );
2707 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
2708 $redirectArticle = new Article( $this );
2709 $newid = $redirectArticle->insertOn( $dbw );
2710 $redirectRevision = new Revision( array(
2711 'page' => $newid,
2712 'comment' => $comment,
2713 'text' => $redirectText ) );
2714 $redirectRevision->insertOn( $dbw, true );
2715 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
2716
2717 # Record the just-created redirect's linking to the page
2718 $dbw->insert( 'pagelinks',
2719 array(
2720 'pl_from' => $newid,
2721 'pl_namespace' => $nt->getNamespace(),
2722 'pl_title' => $nt->getDBkey() ),
2723 $fname );
2724 } else {
2725 $this->resetArticleID( 0 );
2726 }
2727
2728 # Log the move
2729 $log = new LogPage( 'move' );
2730 $log->addEntry( 'move', $this, $reason, array( 1 => $nt->getPrefixedText()) );
2731
2732 # Purge caches as per article creation
2733 Article::onArticleCreate( $nt );
2734
2735 # Purge old title from squid
2736 # The new title, and links to the new title, are purged in Article::onArticleCreate()
2737 $this->purgeSquid();
2738 }
2739
2740 /**
2741 * Checks if $this can be moved to a given Title
2742 * - Selects for update, so don't call it unless you mean business
2743 *
2744 * @param Title &$nt the new title to check
2745 */
2746 public function isValidMoveTarget( $nt ) {
2747
2748 $fname = 'Title::isValidMoveTarget';
2749 $dbw = wfGetDB( DB_MASTER );
2750
2751 # Is it an existsing file?
2752 if( $nt->getNamespace() == NS_IMAGE ) {
2753 $file = wfLocalFile( $nt );
2754 if( $file->exists() ) {
2755 wfDebug( __METHOD__ . ": file exists\n" );
2756 return false;
2757 }
2758 }
2759
2760 # Is it a redirect?
2761 $id = $nt->getArticleID();
2762 $obj = $dbw->selectRow( array( 'page', 'revision', 'text'),
2763 array( 'page_is_redirect','old_text','old_flags' ),
2764 array( 'page_id' => $id, 'page_latest=rev_id', 'rev_text_id=old_id' ),
2765 $fname, 'FOR UPDATE' );
2766
2767 if ( !$obj || 0 == $obj->page_is_redirect ) {
2768 # Not a redirect
2769 wfDebug( __METHOD__ . ": not a redirect\n" );
2770 return false;
2771 }
2772 $text = Revision::getRevisionText( $obj );
2773
2774 # Does the redirect point to the source?
2775 # Or is it a broken self-redirect, usually caused by namespace collisions?
2776 $m = array();
2777 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $text, $m ) ) {
2778 $redirTitle = Title::newFromText( $m[1] );
2779 if( !is_object( $redirTitle ) ||
2780 ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
2781 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) ) {
2782 wfDebug( __METHOD__ . ": redirect points to other page\n" );
2783 return false;
2784 }
2785 } else {
2786 # Fail safe
2787 wfDebug( __METHOD__ . ": failsafe\n" );
2788 return false;
2789 }
2790
2791 # Does the article have a history?
2792 $row = $dbw->selectRow( array( 'page', 'revision'),
2793 array( 'rev_id' ),
2794 array( 'page_namespace' => $nt->getNamespace(),
2795 'page_title' => $nt->getDBkey(),
2796 'page_id=rev_page AND page_latest != rev_id'
2797 ), $fname, 'FOR UPDATE'
2798 );
2799
2800 # Return true if there was no history
2801 return $row === false;
2802 }
2803
2804 /**
2805 * Can this title be added to a user's watchlist?
2806 *
2807 * @return bool
2808 */
2809 public function isWatchable() {
2810 return !$this->isExternal()
2811 && MWNamespace::isWatchable( $this->getNamespace() );
2812 }
2813
2814 /**
2815 * Get categories to which this Title belongs and return an array of
2816 * categories' names.
2817 *
2818 * @return array an array of parents in the form:
2819 * $parent => $currentarticle
2820 */
2821 public function getParentCategories() {
2822 global $wgContLang;
2823
2824 $titlekey = $this->getArticleId();
2825 $dbr = wfGetDB( DB_SLAVE );
2826 $categorylinks = $dbr->tableName( 'categorylinks' );
2827
2828 # NEW SQL
2829 $sql = "SELECT * FROM $categorylinks"
2830 ." WHERE cl_from='$titlekey'"
2831 ." AND cl_from <> '0'"
2832 ." ORDER BY cl_sortkey";
2833
2834 $res = $dbr->query ( $sql ) ;
2835
2836 if($dbr->numRows($res) > 0) {
2837 while ( $x = $dbr->fetchObject ( $res ) )
2838 //$data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$x->cl_to);
2839 $data[$wgContLang->getNSText ( NS_CATEGORY ).':'.$x->cl_to] = $this->getFullText();
2840 $dbr->freeResult ( $res ) ;
2841 } else {
2842 $data = array();
2843 }
2844 return $data;
2845 }
2846
2847 /**
2848 * Get a tree of parent categories
2849 * @param array $children an array with the children in the keys, to check for circular refs
2850 * @return array
2851 */
2852 public function getParentCategoryTree( $children = array() ) {
2853 $stack = array();
2854 $parents = $this->getParentCategories();
2855
2856 if($parents != '') {
2857 foreach($parents as $parent => $current) {
2858 if ( array_key_exists( $parent, $children ) ) {
2859 # Circular reference
2860 $stack[$parent] = array();
2861 } else {
2862 $nt = Title::newFromText($parent);
2863 if ( $nt ) {
2864 $stack[$parent] = $nt->getParentCategoryTree( $children + array($parent => 1) );
2865 }
2866 }
2867 }
2868 return $stack;
2869 } else {
2870 return array();
2871 }
2872 }
2873
2874
2875 /**
2876 * Get an associative array for selecting this title from
2877 * the "page" table
2878 *
2879 * @return array
2880 */
2881 public function pageCond() {
2882 return array( 'page_namespace' => $this->mNamespace, 'page_title' => $this->mDbkeyform );
2883 }
2884
2885 /**
2886 * Get the revision ID of the previous revision
2887 *
2888 * @param integer $revision Revision ID. Get the revision that was before this one.
2889 * @param integer $flags, GAID_FOR_UPDATE
2890 * @return integer $oldrevision|false
2891 */
2892 public function getPreviousRevisionID( $revision, $flags=0 ) {
2893 $db = ($flags & GAID_FOR_UPDATE) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
2894 return $db->selectField( 'revision', 'rev_id',
2895 'rev_page=' . intval( $this->getArticleId() ) .
2896 ' AND rev_id<' . intval( $revision ) . ' ORDER BY rev_id DESC' );
2897 }
2898
2899 /**
2900 * Get the revision ID of the next revision
2901 *
2902 * @param integer $revision Revision ID. Get the revision that was after this one.
2903 * @param integer $flags, GAID_FOR_UPDATE
2904 * @return integer $oldrevision|false
2905 */
2906 public function getNextRevisionID( $revision, $flags=0 ) {
2907 $db = ($flags & GAID_FOR_UPDATE) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
2908 return $db->selectField( 'revision', 'rev_id',
2909 'rev_page=' . intval( $this->getArticleId() ) .
2910 ' AND rev_id>' . intval( $revision ) . ' ORDER BY rev_id' );
2911 }
2912
2913 /**
2914 * Get the number of revisions between the given revision IDs.
2915 * Used for diffs and other things that really need it.
2916 *
2917 * @param integer $old Revision ID.
2918 * @param integer $new Revision ID.
2919 * @return integer Number of revisions between these IDs.
2920 */
2921 public function countRevisionsBetween( $old, $new ) {
2922 $dbr = wfGetDB( DB_SLAVE );
2923 return $dbr->selectField( 'revision', 'count(*)',
2924 'rev_page = ' . intval( $this->getArticleId() ) .
2925 ' AND rev_id > ' . intval( $old ) .
2926 ' AND rev_id < ' . intval( $new ),
2927 __METHOD__,
2928 array( 'USE INDEX' => 'PRIMARY' ) );
2929 }
2930
2931 /**
2932 * Compare with another title.
2933 *
2934 * @param Title $title
2935 * @return bool
2936 */
2937 public function equals( $title ) {
2938 // Note: === is necessary for proper matching of number-like titles.
2939 return $this->getInterwiki() === $title->getInterwiki()
2940 && $this->getNamespace() == $title->getNamespace()
2941 && $this->getDBkey() === $title->getDBkey();
2942 }
2943
2944 /**
2945 * Callback for usort() to do title sorts by (namespace, title)
2946 */
2947 static function compare( $a, $b ) {
2948 if( $a->getNamespace() == $b->getNamespace() ) {
2949 return strcmp( $a->getText(), $b->getText() );
2950 } else {
2951 return $a->getNamespace() - $b->getNamespace();
2952 }
2953 }
2954
2955 /**
2956 * Return a string representation of this title
2957 *
2958 * @return string
2959 */
2960 public function __toString() {
2961 return $this->getPrefixedText();
2962 }
2963
2964 /**
2965 * Check if page exists
2966 * @return bool
2967 */
2968 public function exists() {
2969 return $this->getArticleId() != 0;
2970 }
2971
2972 /**
2973 * Do we know that this title definitely exists, or should we otherwise
2974 * consider that it exists?
2975 *
2976 * @return bool
2977 */
2978 public function isAlwaysKnown() {
2979 // If the page is form Mediawiki:message/lang, calling wfMsgWeirdKey causes
2980 // the full l10n of that language to be loaded. That takes much memory and
2981 // isn't needed. So we strip the language part away.
2982 // Also, extension messages which are not loaded, are shown as red, because
2983 // we don't call MessageCache::loadAllMessages.
2984 list( $basename, /* rest */ ) = explode( '/', $this->mDbkeyform, 2 );
2985 return $this->isExternal()
2986 || ( $this->mNamespace == NS_MAIN && $this->mDbkeyform == '' )
2987 || ( $this->mNamespace == NS_MEDIAWIKI && wfMsgWeirdKey( $basename ) );
2988 }
2989
2990 /**
2991 * Update page_touched timestamps and send squid purge messages for
2992 * pages linking to this title. May be sent to the job queue depending
2993 * on the number of links. Typically called on create and delete.
2994 */
2995 public function touchLinks() {
2996 $u = new HTMLCacheUpdate( $this, 'pagelinks' );
2997 $u->doUpdate();
2998
2999 if ( $this->getNamespace() == NS_CATEGORY ) {
3000 $u = new HTMLCacheUpdate( $this, 'categorylinks' );
3001 $u->doUpdate();
3002 }
3003 }
3004
3005 /**
3006 * Get the last touched timestamp
3007 */
3008 public function getTouched() {
3009 $dbr = wfGetDB( DB_SLAVE );
3010 $touched = $dbr->selectField( 'page', 'page_touched',
3011 array(
3012 'page_namespace' => $this->getNamespace(),
3013 'page_title' => $this->getDBkey()
3014 ), __METHOD__
3015 );
3016 return $touched;
3017 }
3018
3019 public function trackbackURL() {
3020 global $wgTitle, $wgScriptPath, $wgServer;
3021
3022 return "$wgServer$wgScriptPath/trackback.php?article="
3023 . htmlspecialchars(urlencode($wgTitle->getPrefixedDBkey()));
3024 }
3025
3026 public function trackbackRDF() {
3027 $url = htmlspecialchars($this->getFullURL());
3028 $title = htmlspecialchars($this->getText());
3029 $tburl = $this->trackbackURL();
3030
3031 // Autodiscovery RDF is placed in comments so HTML validator
3032 // won't barf. This is a rather icky workaround, but seems
3033 // frequently used by this kind of RDF thingy.
3034 //
3035 // Spec: http://www.sixapart.com/pronet/docs/trackback_spec
3036 return "<!--
3037 <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"
3038 xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
3039 xmlns:trackback=\"http://madskills.com/public/xml/rss/module/trackback/\">
3040 <rdf:Description
3041 rdf:about=\"$url\"
3042 dc:identifier=\"$url\"
3043 dc:title=\"$title\"
3044 trackback:ping=\"$tburl\" />
3045 </rdf:RDF>
3046 -->";
3047 }
3048
3049 /**
3050 * Generate strings used for xml 'id' names in monobook tabs
3051 * @return string
3052 */
3053 public function getNamespaceKey() {
3054 global $wgContLang;
3055 switch ($this->getNamespace()) {
3056 case NS_MAIN:
3057 case NS_TALK:
3058 return 'nstab-main';
3059 case NS_USER:
3060 case NS_USER_TALK:
3061 return 'nstab-user';
3062 case NS_MEDIA:
3063 return 'nstab-media';
3064 case NS_SPECIAL:
3065 return 'nstab-special';
3066 case NS_PROJECT:
3067 case NS_PROJECT_TALK:
3068 return 'nstab-project';
3069 case NS_IMAGE:
3070 case NS_IMAGE_TALK:
3071 return 'nstab-image';
3072 case NS_MEDIAWIKI:
3073 case NS_MEDIAWIKI_TALK:
3074 return 'nstab-mediawiki';
3075 case NS_TEMPLATE:
3076 case NS_TEMPLATE_TALK:
3077 return 'nstab-template';
3078 case NS_HELP:
3079 case NS_HELP_TALK:
3080 return 'nstab-help';
3081 case NS_CATEGORY:
3082 case NS_CATEGORY_TALK:
3083 return 'nstab-category';
3084 default:
3085 return 'nstab-' . $wgContLang->lc( $this->getSubjectNsText() );
3086 }
3087 }
3088
3089 /**
3090 * Returns true if this title resolves to the named special page
3091 * @param string $name The special page name
3092 */
3093 public function isSpecial( $name ) {
3094 if ( $this->getNamespace() == NS_SPECIAL ) {
3095 list( $thisName, /* $subpage */ ) = SpecialPage::resolveAliasWithSubpage( $this->getDBkey() );
3096 if ( $name == $thisName ) {
3097 return true;
3098 }
3099 }
3100 return false;
3101 }
3102
3103 /**
3104 * If the Title refers to a special page alias which is not the local default,
3105 * returns a new Title which points to the local default. Otherwise, returns $this.
3106 */
3107 public function fixSpecialName() {
3108 if ( $this->getNamespace() == NS_SPECIAL ) {
3109 $canonicalName = SpecialPage::resolveAlias( $this->mDbkeyform );
3110 if ( $canonicalName ) {
3111 $localName = SpecialPage::getLocalNameFor( $canonicalName );
3112 if ( $localName != $this->mDbkeyform ) {
3113 return Title::makeTitle( NS_SPECIAL, $localName );
3114 }
3115 }
3116 }
3117 return $this;
3118 }
3119
3120 /**
3121 * Is this Title in a namespace which contains content?
3122 * In other words, is this a content page, for the purposes of calculating
3123 * statistics, etc?
3124 *
3125 * @return bool
3126 */
3127 public function isContentPage() {
3128 return MWNamespace::isContent( $this->getNamespace() );
3129 }
3130
3131 public function getRedirectsHere( $ns = null ) {
3132 $redirs = array();
3133
3134 $dbr = wfGetDB( DB_SLAVE );
3135 $where = array(
3136 'rd_namespace' => $this->getNamespace(),
3137 'rd_title' => $this->getDBkey(),
3138 'rd_from = page_id'
3139 );
3140 if ( !is_null($ns) ) $where['page_namespace'] = $ns;
3141
3142 $result = $dbr->select(
3143 array( 'redirect', 'page' ),
3144 array( 'page_namespace', 'page_title' ),
3145 $where,
3146 __METHOD__
3147 );
3148
3149
3150 while( $row = $dbr->fetchObject( $result ) ) {
3151 $redirs[] = self::newFromRow( $row );
3152 }
3153 return $redirs;
3154 }
3155 }