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