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