a4dc83f04a19f7a42c58907389b884e34ac42f53
[lhc/web/wiklou.git] / includes / Title.php
1 <?php
2 /**
3 * See title.txt
4 *
5 * @package MediaWiki
6 */
7
8 /** */
9 require_once( 'normal/UtfNormal.php' );
10
11 $wgTitleInterwikiCache = array();
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 /**
22 * Title class
23 * - Represents a title, which may contain an interwiki designation or namespace
24 * - Can fetch various kinds of data from the database, albeit inefficiently.
25 *
26 * @package MediaWiki
27 */
28 class Title {
29 /**
30 * All member variables should be considered private
31 * Please use the accessor functions
32 */
33
34 /**#@+
35 * @access private
36 */
37
38 var $mTextform; # Text form (spaces not underscores) of the main part
39 var $mUrlform; # URL-encoded form of the main part
40 var $mDbkeyform; # Main part with underscores
41 var $mNamespace; # Namespace index, i.e. one of the NS_xxxx constants
42 var $mInterwiki; # Interwiki prefix (or null string)
43 var $mFragment; # Title fragment (i.e. the bit after the #)
44 var $mArticleID; # Article ID, fetched from the link cache on demand
45 var $mLatestID; # ID of most recent revision
46 var $mRestrictions; # Array of groups allowed to edit this article
47 # Only null or "sysop" are supported
48 var $mRestrictionsLoaded; # Boolean for initialisation on demand
49 var $mPrefixedText; # Text form including namespace/interwiki, initialised on demand
50 var $mDefaultNamespace; # Namespace index when there is no namespace
51 # Zero except in {{transclusion}} tags
52 var $mWatched; # Is $wgUser watching this page? NULL if unfilled, accessed through userIsWatching()
53 /**#@-*/
54
55
56 /**
57 * Constructor
58 * @access private
59 */
60 /* private */ function Title() {
61 $this->mInterwiki = $this->mUrlform =
62 $this->mTextform = $this->mDbkeyform = '';
63 $this->mArticleID = -1;
64 $this->mNamespace = NS_MAIN;
65 $this->mRestrictionsLoaded = false;
66 $this->mRestrictions = array();
67 # Dont change the following, NS_MAIN is hardcoded in several place
68 # See bug #696
69 $this->mDefaultNamespace = NS_MAIN;
70 $this->mWatched = NULL;
71 $this->mLatestID = false;
72 }
73
74 /**
75 * Create a new Title from a prefixed DB key
76 * @param string $key The database key, which has underscores
77 * instead of spaces, possibly including namespace and
78 * interwiki prefixes
79 * @return Title the new object, or NULL on an error
80 * @static
81 * @access public
82 */
83 /* static */ function newFromDBkey( $key ) {
84 $t = new Title();
85 $t->mDbkeyform = $key;
86 if( $t->secureAndSplit() )
87 return $t;
88 else
89 return NULL;
90 }
91
92 /**
93 * Create a new Title from text, such as what one would
94 * find in a link. Decodes any HTML entities in the text.
95 *
96 * @param string $text the link text; spaces, prefixes,
97 * and an initial ':' indicating the main namespace
98 * are accepted
99 * @param int $defaultNamespace the namespace to use if
100 * none is specified by a prefix
101 * @return Title the new object, or NULL on an error
102 * @static
103 * @access public
104 */
105 function newFromText( $text, $defaultNamespace = NS_MAIN ) {
106 $fname = 'Title::newFromText';
107 wfProfileIn( $fname );
108
109 if( is_object( $text ) ) {
110 wfDebugDieBacktrace( 'Title::newFromText given an object' );
111 }
112
113 /**
114 * Wiki pages often contain multiple links to the same page.
115 * Title normalization and parsing can become expensive on
116 * pages with many links, so we can save a little time by
117 * caching them.
118 *
119 * In theory these are value objects and won't get changed...
120 */
121 static $titleCache = array();
122 if( $defaultNamespace == NS_MAIN && isset( $titleCache[$text] ) ) {
123 wfProfileOut( $fname );
124 return $titleCache[$text];
125 }
126
127 /**
128 * Convert things like &eacute; &#257; or &#x3017; into real text...
129 */
130 $filteredText = Sanitizer::decodeCharReferences( $text );
131
132 $t =& new Title();
133 $t->mDbkeyform = str_replace( ' ', '_', $filteredText );
134 $t->mDefaultNamespace = $defaultNamespace;
135
136 if( $t->secureAndSplit() ) {
137 if( $defaultNamespace == NS_MAIN ) {
138 if( count( $titleCache ) >= MW_TITLECACHE_MAX ) {
139 # Avoid memory leaks on mass operations...
140 $titleCache = array();
141 }
142 $titleCache[$text] =& $t;
143 }
144 wfProfileOut( $fname );
145 return $t;
146 } else {
147 wfProfileOut( $fname );
148 $ret = NULL;
149 return $ret;
150 }
151 }
152
153 /**
154 * Create a new Title from URL-encoded text. Ensures that
155 * the given title's length does not exceed the maximum.
156 * @param string $url the title, as might be taken from a URL
157 * @return Title the new object, or NULL on an error
158 * @static
159 * @access public
160 */
161 function newFromURL( $url ) {
162 global $wgLang, $wgServer;
163 $t = new Title();
164
165 # For compatibility with old buggy URLs. "+" is not valid in titles,
166 # but some URLs used it as a space replacement and they still come
167 # from some external search tools.
168 $s = str_replace( '+', ' ', $url );
169
170 $t->mDbkeyform = str_replace( ' ', '_', $s );
171 if( $t->secureAndSplit() ) {
172 return $t;
173 } else {
174 return NULL;
175 }
176 }
177
178 /**
179 * Create a new Title from an article ID
180 *
181 * @todo This is inefficiently implemented, the page row is requested
182 * but not used for anything else
183 *
184 * @param int $id the page_id corresponding to the Title to create
185 * @return Title the new object, or NULL on an error
186 * @access public
187 * @static
188 */
189 function newFromID( $id ) {
190 $fname = 'Title::newFromID';
191 $dbr =& wfGetDB( DB_SLAVE );
192 $row = $dbr->selectRow( 'page', array( 'page_namespace', 'page_title' ),
193 array( 'page_id' => $id ), $fname );
194 if ( $row !== false ) {
195 $title = Title::makeTitle( $row->page_namespace, $row->page_title );
196 } else {
197 $title = NULL;
198 }
199 return $title;
200 }
201
202 /**
203 * Create a new Title from a namespace index and a DB key.
204 * It's assumed that $ns and $title are *valid*, for instance when
205 * they came directly from the database or a special page name.
206 * For convenience, spaces are converted to underscores so that
207 * eg user_text fields can be used directly.
208 *
209 * @param int $ns the namespace of the article
210 * @param string $title the unprefixed database key form
211 * @return Title the new object
212 * @static
213 * @access public
214 */
215 function &makeTitle( $ns, $title ) {
216 $t =& new Title();
217 $t->mInterwiki = '';
218 $t->mFragment = '';
219 $t->mNamespace = intval( $ns );
220 $t->mDbkeyform = str_replace( ' ', '_', $title );
221 $t->mArticleID = ( $ns >= 0 ) ? -1 : 0;
222 $t->mUrlform = wfUrlencode( $t->mDbkeyform );
223 $t->mTextform = str_replace( '_', ' ', $title );
224 return $t;
225 }
226
227 /**
228 * Create a new Title frrom a namespace index and a DB key.
229 * The parameters will be checked for validity, which is a bit slower
230 * than makeTitle() but safer for user-provided data.
231 *
232 * @param int $ns the namespace of the article
233 * @param string $title the database key form
234 * @return Title the new object, or NULL on an error
235 * @static
236 * @access public
237 */
238 function makeTitleSafe( $ns, $title ) {
239 $t = new Title();
240 $t->mDbkeyform = Title::makeName( $ns, $title );
241 if( $t->secureAndSplit() ) {
242 return $t;
243 } else {
244 return NULL;
245 }
246 }
247
248 /**
249 * Create a new Title for the Main Page
250 *
251 * @static
252 * @return Title the new object
253 * @access public
254 */
255 function newMainPage() {
256 return Title::newFromText( wfMsgForContent( 'mainpage' ) );
257 }
258
259 /**
260 * Create a new Title for a redirect
261 * @param string $text the redirect title text
262 * @return Title the new object, or NULL if the text is not a
263 * valid redirect
264 * @static
265 * @access public
266 */
267 function newFromRedirect( $text ) {
268 global $wgMwRedir;
269 $rt = NULL;
270 if ( $wgMwRedir->matchStart( $text ) ) {
271 if ( preg_match( '/\[{2}(.*?)(?:\||\]{2})/', $text, $m ) ) {
272 # categories are escaped using : for example one can enter:
273 # #REDIRECT [[:Category:Music]]. Need to remove it.
274 if ( substr($m[1],0,1) == ':') {
275 # We don't want to keep the ':'
276 $m[1] = substr( $m[1], 1 );
277 }
278
279 $rt = Title::newFromText( $m[1] );
280 # Disallow redirects to Special:Userlogout
281 if ( !is_null($rt) && $rt->getNamespace() == NS_SPECIAL && preg_match( '/^Userlogout/i', $rt->getText() ) ) {
282 $rt = NULL;
283 }
284 }
285 }
286 return $rt;
287 }
288
289 #----------------------------------------------------------------------------
290 # Static functions
291 #----------------------------------------------------------------------------
292
293 /**
294 * Get the prefixed DB key associated with an ID
295 * @param int $id the page_id of the article
296 * @return Title an object representing the article, or NULL
297 * if no such article was found
298 * @static
299 * @access public
300 */
301 function nameOf( $id ) {
302 $fname = 'Title::nameOf';
303 $dbr =& wfGetDB( DB_SLAVE );
304
305 $s = $dbr->selectRow( 'page', array( 'page_namespace','page_title' ), array( 'page_id' => $id ), $fname );
306 if ( $s === false ) { return NULL; }
307
308 $n = Title::makeName( $s->page_namespace, $s->page_title );
309 return $n;
310 }
311
312 /**
313 * Get a regex character class describing the legal characters in a link
314 * @return string the list of characters, not delimited
315 * @static
316 * @access public
317 */
318 function legalChars() {
319 global $wgLegalTitleChars;
320 return $wgLegalTitleChars;
321 }
322
323 /**
324 * Get a string representation of a title suitable for
325 * including in a search index
326 *
327 * @param int $ns a namespace index
328 * @param string $title text-form main part
329 * @return string a stripped-down title string ready for the
330 * search index
331 */
332 /* static */ function indexTitle( $ns, $title ) {
333 global $wgDBminWordLen, $wgContLang;
334 require_once( 'SearchEngine.php' );
335
336 $lc = SearchEngine::legalSearchChars() . '&#;';
337 $t = $wgContLang->stripForSearch( $title );
338 $t = preg_replace( "/[^{$lc}]+/", ' ', $t );
339 $t = strtolower( $t );
340
341 # Handle 's, s'
342 $t = preg_replace( "/([{$lc}]+)'s( |$)/", "\\1 \\1's ", $t );
343 $t = preg_replace( "/([{$lc}]+)s'( |$)/", "\\1s ", $t );
344
345 $t = preg_replace( "/\\s+/", ' ', $t );
346
347 if ( $ns == NS_IMAGE ) {
348 $t = preg_replace( "/ (png|gif|jpg|jpeg|ogg)$/", "", $t );
349 }
350 return trim( $t );
351 }
352
353 /*
354 * Make a prefixed DB key from a DB key and a namespace index
355 * @param int $ns numerical representation of the namespace
356 * @param string $title the DB key form the title
357 * @return string the prefixed form of the title
358 */
359 /* static */ function makeName( $ns, $title ) {
360 global $wgContLang;
361
362 $n = $wgContLang->getNsText( $ns );
363 return $n == '' ? $title : "$n:$title";
364 }
365
366 /**
367 * Returns the URL associated with an interwiki prefix
368 * @param string $key the interwiki prefix (e.g. "MeatBall")
369 * @return the associated URL, containing "$1", which should be
370 * replaced by an article title
371 * @static (arguably)
372 * @access public
373 */
374 function getInterwikiLink( $key, $transludeonly = false ) {
375 global $wgMemc, $wgDBname, $wgInterwikiExpiry, $wgTitleInterwikiCache;
376 $fname = 'Title::getInterwikiLink';
377
378 wfProfileIn( $fname );
379
380 $key = strtolower( $key );
381
382 $k = $wgDBname.':interwiki:'.$key;
383 if( array_key_exists( $k, $wgTitleInterwikiCache ) ) {
384 wfProfileOut( $fname );
385 return $wgTitleInterwikiCache[$k]->iw_url;
386 }
387
388 $s = $wgMemc->get( $k );
389 # Ignore old keys with no iw_local
390 if( $s && isset( $s->iw_local ) && isset($s->iw_trans)) {
391 $wgTitleInterwikiCache[$k] = $s;
392 wfProfileOut( $fname );
393 return $s->iw_url;
394 }
395
396 $dbr =& wfGetDB( DB_SLAVE );
397 $res = $dbr->select( 'interwiki',
398 array( 'iw_url', 'iw_local', 'iw_trans' ),
399 array( 'iw_prefix' => $key ), $fname );
400 if( !$res ) {
401 wfProfileOut( $fname );
402 return '';
403 }
404
405 $s = $dbr->fetchObject( $res );
406 if( !$s ) {
407 # Cache non-existence: create a blank object and save it to memcached
408 $s = (object)false;
409 $s->iw_url = '';
410 $s->iw_local = 0;
411 $s->iw_trans = 0;
412 }
413 $wgMemc->set( $k, $s, $wgInterwikiExpiry );
414 $wgTitleInterwikiCache[$k] = $s;
415
416 wfProfileOut( $fname );
417 return $s->iw_url;
418 }
419
420 /**
421 * Determine whether the object refers to a page within
422 * this project.
423 *
424 * @return bool TRUE if this is an in-project interwiki link
425 * or a wikilink, FALSE otherwise
426 * @access public
427 */
428 function isLocal() {
429 global $wgTitleInterwikiCache, $wgDBname;
430
431 if ( $this->mInterwiki != '' ) {
432 # Make sure key is loaded into cache
433 $this->getInterwikiLink( $this->mInterwiki );
434 $k = $wgDBname.':interwiki:' . $this->mInterwiki;
435 return (bool)($wgTitleInterwikiCache[$k]->iw_local);
436 } else {
437 return true;
438 }
439 }
440
441 /**
442 * Determine whether the object refers to a page within
443 * this project and is transcludable.
444 *
445 * @return bool TRUE if this is transcludable
446 * @access public
447 */
448 function isTrans() {
449 global $wgTitleInterwikiCache, $wgDBname;
450
451 if ($this->mInterwiki == '' || !$this->isLocal())
452 return false;
453 # Make sure key is loaded into cache
454 $this->getInterwikiLink( $this->mInterwiki );
455 $k = $wgDBname.':interwiki:' . $this->mInterwiki;
456 return (bool)($wgTitleInterwikiCache[$k]->iw_trans);
457 }
458
459 /**
460 * Update the page_touched field for an array of title objects
461 * @todo Inefficient unless the IDs are already loaded into the
462 * link cache
463 * @param array $titles an array of Title objects to be touched
464 * @param string $timestamp the timestamp to use instead of the
465 * default current time
466 * @static
467 * @access public
468 */
469 function touchArray( $titles, $timestamp = '' ) {
470 global $wgUseFileCache;
471
472 if ( count( $titles ) == 0 ) {
473 return;
474 }
475 $dbw =& wfGetDB( DB_MASTER );
476 if ( $timestamp == '' ) {
477 $timestamp = $dbw->timestamp();
478 }
479 $page = $dbw->tableName( 'page' );
480 /*
481 $sql = "UPDATE $page SET page_touched='{$timestamp}' WHERE page_id IN (";
482 $first = true;
483
484 foreach ( $titles as $title ) {
485 if ( $wgUseFileCache ) {
486 $cm = new CacheManager($title);
487 @unlink($cm->fileCacheName());
488 }
489
490 if ( ! $first ) {
491 $sql .= ',';
492 }
493 $first = false;
494 $sql .= $title->getArticleID();
495 }
496 $sql .= ')';
497 if ( ! $first ) {
498 $dbw->query( $sql, 'Title::touchArray' );
499 }
500 */
501 // hack hack hack -- brion 2005-07-11. this was unfriendly to db.
502 // do them in small chunks:
503 $fname = 'Title::touchArray';
504 foreach( $titles as $title ) {
505 $dbw->update( 'page',
506 array( 'page_touched' => $timestamp ),
507 array(
508 'page_namespace' => $title->getNamespace(),
509 'page_title' => $title->getDBkey() ),
510 $fname );
511 }
512 }
513
514 #----------------------------------------------------------------------------
515 # Other stuff
516 #----------------------------------------------------------------------------
517
518 /** Simple accessors */
519 /**
520 * Get the text form (spaces not underscores) of the main part
521 * @return string
522 * @access public
523 */
524 function getText() { return $this->mTextform; }
525 /**
526 * Get the URL-encoded form of the main part
527 * @return string
528 * @access public
529 */
530 function getPartialURL() { return $this->mUrlform; }
531 /**
532 * Get the main part with underscores
533 * @return string
534 * @access public
535 */
536 function getDBkey() { return $this->mDbkeyform; }
537 /**
538 * Get the namespace index, i.e. one of the NS_xxxx constants
539 * @return int
540 * @access public
541 */
542 function getNamespace() { return $this->mNamespace; }
543 /**
544 * Get the namespace text
545 * @return string
546 * @access public
547 */
548 function getNsText() {
549 global $wgContLang;
550 return $wgContLang->getNsText( $this->mNamespace );
551 }
552 /**
553 * Get the namespace text of the subject (rather than talk) page
554 * @return string
555 * @access public
556 */
557 function getSubjectNsText() {
558 global $wgContLang;
559 return $wgContLang->getNsText( Namespace::getSubject( $this->mNamespace ) );
560 }
561
562 /**
563 * Get the interwiki prefix (or null string)
564 * @return string
565 * @access public
566 */
567 function getInterwiki() { return $this->mInterwiki; }
568 /**
569 * Get the Title fragment (i.e. the bit after the #)
570 * @return string
571 * @access public
572 */
573 function getFragment() { return $this->mFragment; }
574 /**
575 * Get the default namespace index, for when there is no namespace
576 * @return int
577 * @access public
578 */
579 function getDefaultNamespace() { return $this->mDefaultNamespace; }
580
581 /**
582 * Get title for search index
583 * @return string a stripped-down title string ready for the
584 * search index
585 */
586 function getIndexTitle() {
587 return Title::indexTitle( $this->mNamespace, $this->mTextform );
588 }
589
590 /**
591 * Get the prefixed database key form
592 * @return string the prefixed title, with underscores and
593 * any interwiki and namespace prefixes
594 * @access public
595 */
596 function getPrefixedDBkey() {
597 $s = $this->prefix( $this->mDbkeyform );
598 $s = str_replace( ' ', '_', $s );
599 return $s;
600 }
601
602 /**
603 * Get the prefixed title with spaces.
604 * This is the form usually used for display
605 * @return string the prefixed title, with spaces
606 * @access public
607 */
608 function getPrefixedText() {
609 global $wgContLang;
610 if ( empty( $this->mPrefixedText ) ) {
611 $s = $this->prefix( $this->mTextform );
612 $s = str_replace( '_', ' ', $s );
613 $this->mPrefixedText = $s;
614 }
615 return $this->mPrefixedText;
616 }
617
618 /**
619 * Get the prefixed title with spaces, plus any fragment
620 * (part beginning with '#')
621 * @return string the prefixed title, with spaces and
622 * the fragment, including '#'
623 * @access public
624 */
625 function getFullText() {
626 global $wgContLang;
627 $text = $this->getPrefixedText();
628 if( '' != $this->mFragment ) {
629 $text .= '#' . $this->mFragment;
630 }
631 return $text;
632 }
633
634 /**
635 * Get a URL-encoded title (not an actual URL) including interwiki
636 * @return string the URL-encoded form
637 * @access public
638 */
639 function getPrefixedURL() {
640 $s = $this->prefix( $this->mDbkeyform );
641 $s = str_replace( ' ', '_', $s );
642
643 $s = wfUrlencode ( $s ) ;
644
645 # Cleaning up URL to make it look nice -- is this safe?
646 $s = str_replace( '%28', '(', $s );
647 $s = str_replace( '%29', ')', $s );
648
649 return $s;
650 }
651
652 /**
653 * Get a real URL referring to this title, with interwiki link and
654 * fragment
655 *
656 * @param string $query an optional query string, not used
657 * for interwiki links
658 * @return string the URL
659 * @access public
660 */
661 function getFullURL( $query = '' ) {
662 global $wgContLang, $wgServer, $wgScript, $wgMakeDumpLinks, $wgArticlePath;
663
664 if ( '' == $this->mInterwiki ) {
665 return $wgServer . $this->getLocalUrl( $query );
666 } elseif ( $wgMakeDumpLinks && $wgContLang->getLanguageName( $this->mInterwiki ) ) {
667 $baseUrl = str_replace( '$1', "../../{$this->mInterwiki}/$1", $wgArticlePath );
668 $baseUrl = str_replace( '$1', $this->getHashedDirectory() . '/$1', $baseUrl );
669 } else {
670 $baseUrl = $this->getInterwikiLink( $this->mInterwiki );
671 }
672
673 $namespace = $wgContLang->getNsText( $this->mNamespace );
674 if ( '' != $namespace ) {
675 # Can this actually happen? Interwikis shouldn't be parsed.
676 $namespace .= ':';
677 }
678 $url = str_replace( '$1', $namespace . $this->mUrlform, $baseUrl );
679 if( $query != '' ) {
680 if( false === strpos( $url, '?' ) ) {
681 $url .= '?';
682 } else {
683 $url .= '&';
684 }
685 $url .= $query;
686 }
687 if ( '' != $this->mFragment ) {
688 $url .= '#' . $this->mFragment;
689 }
690 return $url;
691 }
692
693 /**
694 * Get a relative directory for putting an HTML version of this article into
695 */
696 function getHashedDirectory() {
697 global $wgMakeDumpLinks, $wgInputEncoding;
698 $dbkey = $this->getDBkey();
699
700 # Split into characters
701 if ( $wgInputEncoding == 'UTF-8' ) {
702 preg_match_all( '/./us', $dbkey, $m );
703 } else {
704 preg_match_all( '/./s', $dbkey, $m );
705 }
706 $chars = $m[0];
707 $length = count( $chars );
708 $dir = '';
709
710 for ( $i = 0; $i < $wgMakeDumpLinks; $i++ ) {
711 if ( $i ) {
712 $dir .= '/';
713 }
714 if ( $i >= $length ) {
715 $dir .= '_';
716 } elseif ( ord( $chars[$i] ) > 32 ) {
717 $dir .= strtolower( $chars[$i] );
718 } else {
719 $dir .= sprintf( "%02X", ord( $chars[$i] ) );
720 }
721 }
722 return $dir;
723 }
724
725 function getHashedFilename() {
726 $dbkey = $this->getPrefixedDBkey();
727 $mainPage = Title::newMainPage();
728 if ( $mainPage->getPrefixedDBkey() == $dbkey ) {
729 return 'index.html';
730 }
731
732 $dir = $this->getHashedDirectory();
733
734 # Replace illegal charcters for Windows paths with underscores
735 $friendlyName = strtr( $dbkey, '/\\*?"<>|~', '_________' );
736
737 # Work out lower case form. We assume we're on a system with case-insensitive
738 # filenames, so unless the case is of a special form, we have to disambiguate
739 $lowerCase = $this->prefix( ucfirst( strtolower( $this->getDBkey() ) ) );
740
741 # Make it mostly unique
742 if ( $lowerCase != $friendlyName ) {
743 $friendlyName .= '_' . substr(md5( $dbkey ), 0, 4);
744 }
745 # Handle colon specially by replacing it with tilde
746 # Thus we reduce the number of paths with hashes appended
747 $friendlyName = str_replace( ':', '~', $friendlyName );
748 return "$dir/$friendlyName.html";
749 }
750
751 /**
752 * Get a URL with no fragment or server name. If this page is generated
753 * with action=render, $wgServer is prepended.
754 * @param string $query an optional query string; if not specified,
755 * $wgArticlePath will be used.
756 * @return string the URL
757 * @access public
758 */
759 function getLocalURL( $query = '' ) {
760 global $wgLang, $wgArticlePath, $wgScript, $wgMakeDumpLinks, $wgServer, $action;
761
762 if ( $this->isExternal() ) {
763 return $this->getFullURL();
764 }
765
766 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
767 if ( $wgMakeDumpLinks ) {
768 $url = str_replace( '$1', wfUrlencode( $this->getHashedFilename() ), $wgArticlePath );
769 } elseif ( $query == '' ) {
770 $url = str_replace( '$1', $dbkey, $wgArticlePath );
771 } else {
772 global $wgActionPaths;
773 if( !empty( $wgActionPaths ) &&
774 preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches ) ) {
775 $action = urldecode( $matches[2] );
776 if( isset( $wgActionPaths[$action] ) ) {
777 $query = $matches[1];
778 if( isset( $matches[4] ) ) $query .= $matches[4];
779 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
780 if( $query != '' ) $url .= '?' . $query;
781 return $url;
782 }
783 }
784 if ( $query == '-' ) {
785 $query = '';
786 }
787 $url = "{$wgScript}?title={$dbkey}&{$query}";
788 }
789
790 if ($action == 'render')
791 return $wgServer . $url;
792 else
793 return $url;
794 }
795
796 /**
797 * Get an HTML-escaped version of the URL form, suitable for
798 * using in a link, without a server name or fragment
799 * @param string $query an optional query string
800 * @return string the URL
801 * @access public
802 */
803 function escapeLocalURL( $query = '' ) {
804 return htmlspecialchars( $this->getLocalURL( $query ) );
805 }
806
807 /**
808 * Get an HTML-escaped version of the URL form, suitable for
809 * using in a link, including the server name and fragment
810 *
811 * @return string the URL
812 * @param string $query an optional query string
813 * @access public
814 */
815 function escapeFullURL( $query = '' ) {
816 return htmlspecialchars( $this->getFullURL( $query ) );
817 }
818
819 /**
820 * Get the URL form for an internal link.
821 * - Used in various Squid-related code, in case we have a different
822 * internal hostname for the server from the exposed one.
823 *
824 * @param string $query an optional query string
825 * @return string the URL
826 * @access public
827 */
828 function getInternalURL( $query = '' ) {
829 global $wgInternalServer;
830 return $wgInternalServer . $this->getLocalURL( $query );
831 }
832
833 /**
834 * Get the edit URL for this Title
835 * @return string the URL, or a null string if this is an
836 * interwiki link
837 * @access public
838 */
839 function getEditURL() {
840 global $wgServer, $wgScript;
841
842 if ( '' != $this->mInterwiki ) { return ''; }
843 $s = $this->getLocalURL( 'action=edit' );
844
845 return $s;
846 }
847
848 /**
849 * Get the HTML-escaped displayable text form.
850 * Used for the title field in <a> tags.
851 * @return string the text, including any prefixes
852 * @access public
853 */
854 function getEscapedText() {
855 return htmlspecialchars( $this->getPrefixedText() );
856 }
857
858 /**
859 * Is this Title interwiki?
860 * @return boolean
861 * @access public
862 */
863 function isExternal() { return ( '' != $this->mInterwiki ); }
864
865 /**
866 * Does the title correspond to a protected article?
867 * @param string $what the action the page is protected from,
868 * by default checks move and edit
869 * @return boolean
870 * @access public
871 */
872 function isProtected($action = '') {
873 if ( -1 == $this->mNamespace ) { return true; }
874 if($action == 'edit' || $action == '') {
875 $a = $this->getRestrictions("edit");
876 if ( in_array( 'sysop', $a ) ) { return true; }
877 }
878 if($action == 'move' || $action == '') {
879 $a = $this->getRestrictions("move");
880 if ( in_array( 'sysop', $a ) ) { return true; }
881 }
882 return false;
883 }
884
885 /**
886 * Is $wgUser is watching this page?
887 * @return boolean
888 * @access public
889 */
890 function userIsWatching() {
891 global $wgUser;
892
893 if ( is_null( $this->mWatched ) ) {
894 if ( -1 == $this->mNamespace || 0 == $wgUser->getID()) {
895 $this->mWatched = false;
896 } else {
897 $this->mWatched = $wgUser->isWatched( $this );
898 }
899 }
900 return $this->mWatched;
901 }
902
903 /**
904 * Is $wgUser perform $action this page?
905 * @param string $action action that permission needs to be checked for
906 * @return boolean
907 * @access private
908 */
909 function userCan($action) {
910 $fname = 'Title::userCanEdit';
911 wfProfileIn( $fname );
912
913 global $wgUser;
914 if( NS_SPECIAL == $this->mNamespace ) {
915 wfProfileOut( $fname );
916 return false;
917 }
918 if( NS_MEDIAWIKI == $this->mNamespace &&
919 !$wgUser->isAllowed('editinterface') ) {
920 wfProfileOut( $fname );
921 return false;
922 }
923 if( $this->mDbkeyform == '_' ) {
924 # FIXME: Is this necessary? Shouldn't be allowed anyway...
925 wfProfileOut( $fname );
926 return false;
927 }
928
929 # protect global styles and js
930 if ( NS_MEDIAWIKI == $this->mNamespace
931 && preg_match("/\\.(css|js)$/", $this->mTextform )
932 && !$wgUser->isAllowed('editinterface') ) {
933 wfProfileOut( $fname );
934 return false;
935 }
936
937 # protect css/js subpages of user pages
938 # XXX: this might be better using restrictions
939 # XXX: Find a way to work around the php bug that prevents using $this->userCanEditCssJsSubpage() from working
940 if( NS_USER == $this->mNamespace
941 && preg_match("/\\.(css|js)$/", $this->mTextform )
942 && !$wgUser->isAllowed('editinterface')
943 && !preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform) ) {
944 wfProfileOut( $fname );
945 return false;
946 }
947
948 foreach( $this->getRestrictions($action) as $right ) {
949 // Backwards compatibility, rewrite sysop -> protect
950 if ( $right == 'sysop' ) {
951 $right = 'protect';
952 }
953 if( '' != $right && !$wgUser->isAllowed( $right ) ) {
954 wfProfileOut( $fname );
955 return false;
956 }
957 }
958
959 if( $action == 'move' &&
960 !( $this->isMovable() && $wgUser->isAllowed( 'move' ) ) ) {
961 wfProfileOut( $fname );
962 return false;
963 }
964
965 wfProfileOut( $fname );
966 return true;
967 }
968
969 /**
970 * Can $wgUser edit this page?
971 * @return boolean
972 * @access public
973 */
974 function userCanEdit() {
975 return $this->userCan('edit');
976 }
977
978 /**
979 * Can $wgUser move this page?
980 * @return boolean
981 * @access public
982 */
983 function userCanMove() {
984 return $this->userCan('move');
985 }
986
987 /**
988 * Would anybody with sufficient privileges be able to move this page?
989 * Some pages just aren't movable.
990 *
991 * @return boolean
992 * @access public
993 */
994 function isMovable() {
995 return Namespace::isMovable( $this->getNamespace() )
996 && $this->getInterwiki() == '';
997 }
998
999 /**
1000 * Can $wgUser read this page?
1001 * @return boolean
1002 * @access public
1003 */
1004 function userCanRead() {
1005 global $wgUser;
1006
1007 if( $wgUser->isAllowed('read') ) {
1008 return true;
1009 } else {
1010 global $wgWhitelistRead;
1011
1012 /** If anon users can create an account,
1013 they need to reach the login page first! */
1014 if( $wgUser->isAllowed( 'createaccount' )
1015 && $this->getNamespace() == NS_SPECIAL
1016 && $this->getText() == 'Userlogin' ) {
1017 return true;
1018 }
1019
1020 /** some pages are explicitly allowed */
1021 $name = $this->getPrefixedText();
1022 if( $wgWhitelistRead && in_array( $name, $wgWhitelistRead ) ) {
1023 return true;
1024 }
1025
1026 # Compatibility with old settings
1027 if( $wgWhitelistRead && $this->getNamespace() == NS_MAIN ) {
1028 if( in_array( ':' . $name, $wgWhitelistRead ) ) {
1029 return true;
1030 }
1031 }
1032 }
1033 return false;
1034 }
1035
1036 /**
1037 * Is this a talk page of some sort?
1038 * @return bool
1039 * @access public
1040 */
1041 function isTalkPage() {
1042 return Namespace::isTalk( $this->getNamespace() );
1043 }
1044
1045 /**
1046 * Is this a .css or .js subpage of a user page?
1047 * @return bool
1048 * @access public
1049 */
1050 function isCssJsSubpage() {
1051 return ( NS_USER == $this->mNamespace and preg_match("/\\.(css|js)$/", $this->mTextform ) );
1052 }
1053 /**
1054 * Is this a .css subpage of a user page?
1055 * @return bool
1056 * @access public
1057 */
1058 function isCssSubpage() {
1059 return ( NS_USER == $this->mNamespace and preg_match("/\\.css$/", $this->mTextform ) );
1060 }
1061 /**
1062 * Is this a .js subpage of a user page?
1063 * @return bool
1064 * @access public
1065 */
1066 function isJsSubpage() {
1067 return ( NS_USER == $this->mNamespace and preg_match("/\\.js$/", $this->mTextform ) );
1068 }
1069 /**
1070 * Protect css/js subpages of user pages: can $wgUser edit
1071 * this page?
1072 *
1073 * @return boolean
1074 * @todo XXX: this might be better using restrictions
1075 * @access public
1076 */
1077 function userCanEditCssJsSubpage() {
1078 global $wgUser;
1079 return ( $wgUser->isAllowed('editinterface') or preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform) );
1080 }
1081
1082 /**
1083 * Loads a string into mRestrictions array
1084 * @param string $res restrictions in string format
1085 * @access public
1086 */
1087 function loadRestrictions( $res ) {
1088 foreach( explode( ':', trim( $res ) ) as $restrict ) {
1089 $temp = explode( '=', trim( $restrict ) );
1090 if(count($temp) == 1) {
1091 // old format should be treated as edit/move restriction
1092 $this->mRestrictions["edit"] = explode( ',', trim( $temp[0] ) );
1093 $this->mRestrictions["move"] = explode( ',', trim( $temp[0] ) );
1094 } else {
1095 $this->mRestrictions[$temp[0]] = explode( ',', trim( $temp[1] ) );
1096 }
1097 }
1098 $this->mRestrictionsLoaded = true;
1099 }
1100
1101 /**
1102 * Accessor/initialisation for mRestrictions
1103 * @param string $action action that permission needs to be checked for
1104 * @return array the array of groups allowed to edit this article
1105 * @access public
1106 */
1107 function getRestrictions($action) {
1108 $id = $this->getArticleID();
1109 if ( 0 == $id ) { return array(); }
1110
1111 if ( ! $this->mRestrictionsLoaded ) {
1112 $dbr =& wfGetDB( DB_SLAVE );
1113 $res = $dbr->selectField( 'page', 'page_restrictions', 'page_id='.$id );
1114 $this->loadRestrictions( $res );
1115 }
1116 if( isset( $this->mRestrictions[$action] ) ) {
1117 return $this->mRestrictions[$action];
1118 }
1119 return array();
1120 }
1121
1122 /**
1123 * Is there a version of this page in the deletion archive?
1124 * @return int the number of archived revisions
1125 * @access public
1126 */
1127 function isDeleted() {
1128 $fname = 'Title::isDeleted';
1129 if ( $this->getNamespace() < 0 ) {
1130 $n = 0;
1131 } else {
1132 $dbr =& wfGetDB( DB_SLAVE );
1133 $n = $dbr->selectField( 'archive', 'COUNT(*)', array( 'ar_namespace' => $this->getNamespace(),
1134 'ar_title' => $this->getDBkey() ), $fname );
1135 }
1136 return (int)$n;
1137 }
1138
1139 /**
1140 * Get the article ID for this Title from the link cache,
1141 * adding it if necessary
1142 * @param int $flags a bit field; may be GAID_FOR_UPDATE to select
1143 * for update
1144 * @return int the ID
1145 * @access public
1146 */
1147 function getArticleID( $flags = 0 ) {
1148 global $wgLinkCache;
1149 if ( $flags & GAID_FOR_UPDATE ) {
1150 $oldUpdate = $wgLinkCache->forUpdate( true );
1151 $this->mArticleID = $wgLinkCache->addLinkObj( $this );
1152 $wgLinkCache->forUpdate( $oldUpdate );
1153 } else {
1154 if ( -1 == $this->mArticleID ) {
1155 $this->mArticleID = $wgLinkCache->addLinkObj( $this );
1156 }
1157 }
1158 return $this->mArticleID;
1159 }
1160
1161 function getLatestRevID() {
1162 if ($this->mLatestID !== false)
1163 return $this->mLatestID;
1164
1165 $db =& wfGetDB(DB_SLAVE);
1166 return $this->mLatestID = $db->selectField( 'revision',
1167 "max(rev_id)",
1168 array('rev_page' => $this->getArticleID()),
1169 'Title::getLatestRevID' );
1170 }
1171
1172 /**
1173 * This clears some fields in this object, and clears any associated
1174 * keys in the "bad links" section of $wgLinkCache.
1175 *
1176 * - This is called from Article::insertNewArticle() to allow
1177 * loading of the new page_id. It's also called from
1178 * Article::doDeleteArticle()
1179 *
1180 * @param int $newid the new Article ID
1181 * @access public
1182 */
1183 function resetArticleID( $newid ) {
1184 global $wgLinkCache;
1185 $wgLinkCache->clearBadLink( $this->getPrefixedDBkey() );
1186
1187 if ( 0 == $newid ) { $this->mArticleID = -1; }
1188 else { $this->mArticleID = $newid; }
1189 $this->mRestrictionsLoaded = false;
1190 $this->mRestrictions = array();
1191 }
1192
1193 /**
1194 * Updates page_touched for this page; called from LinksUpdate.php
1195 * @return bool true if the update succeded
1196 * @access public
1197 */
1198 function invalidateCache() {
1199 global $wgUseFileCache;
1200
1201 if ( wfReadOnly() ) {
1202 return;
1203 }
1204
1205 $now = wfTimestampNow();
1206 $dbw =& wfGetDB( DB_MASTER );
1207 $success = $dbw->update( 'page',
1208 array( /* SET */
1209 'page_touched' => $dbw->timestamp()
1210 ), array( /* WHERE */
1211 'page_namespace' => $this->getNamespace() ,
1212 'page_title' => $this->getDBkey()
1213 ), 'Title::invalidateCache'
1214 );
1215
1216 if ($wgUseFileCache) {
1217 $cache = new CacheManager($this);
1218 @unlink($cache->fileCacheName());
1219 }
1220
1221 return $success;
1222 }
1223
1224 /**
1225 * Prefix some arbitrary text with the namespace or interwiki prefix
1226 * of this object
1227 *
1228 * @param string $name the text
1229 * @return string the prefixed text
1230 * @access private
1231 */
1232 /* private */ function prefix( $name ) {
1233 global $wgContLang;
1234
1235 $p = '';
1236 if ( '' != $this->mInterwiki ) {
1237 $p = $this->mInterwiki . ':';
1238 }
1239 if ( 0 != $this->mNamespace ) {
1240 $p .= $wgContLang->getNsText( $this->mNamespace ) . ':';
1241 }
1242 return $p . $name;
1243 }
1244
1245 /**
1246 * Secure and split - main initialisation function for this object
1247 *
1248 * Assumes that mDbkeyform has been set, and is urldecoded
1249 * and uses underscores, but not otherwise munged. This function
1250 * removes illegal characters, splits off the interwiki and
1251 * namespace prefixes, sets the other forms, and canonicalizes
1252 * everything.
1253 * @return bool true on success
1254 * @access private
1255 */
1256 /* private */ function secureAndSplit() {
1257 global $wgContLang, $wgLocalInterwiki, $wgCapitalLinks;
1258 $fname = 'Title::secureAndSplit';
1259 wfProfileIn( $fname );
1260
1261 # Initialisation
1262 static $rxTc = false;
1263 if( !$rxTc ) {
1264 # % is needed as well
1265 $rxTc = '/[^' . Title::legalChars() . ']|%[0-9A-Fa-f]{2}/S';
1266 }
1267
1268 $this->mInterwiki = $this->mFragment = '';
1269 $this->mNamespace = $this->mDefaultNamespace; # Usually NS_MAIN
1270
1271 # Clean up whitespace
1272 #
1273 $t = preg_replace( '/[ _]+/', '_', $this->mDbkeyform );
1274 $t = trim( $t, '_' );
1275
1276 if ( '' == $t ) {
1277 wfProfileOut( $fname );
1278 return false;
1279 }
1280
1281 if( false !== strpos( $t, UTF8_REPLACEMENT ) ) {
1282 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
1283 wfProfileOut( $fname );
1284 return false;
1285 }
1286
1287 $this->mDbkeyform = $t;
1288
1289 # Initial colon indicates main namespace rather than specified default
1290 # but should not create invalid {ns,title} pairs such as {0,Project:Foo}
1291 if ( ':' == $t{0} ) {
1292 $this->mNamespace = NS_MAIN;
1293 $t = substr( $t, 1 ); # remove the colon but continue processing
1294 }
1295
1296 # Namespace or interwiki prefix
1297 $firstPass = true;
1298 do {
1299 if ( preg_match( "/^(.+?)_*:_*(.*)$/S", $t, $m ) ) {
1300 $p = $m[1];
1301 $lowerNs = strtolower( $p );
1302 if ( $ns = Namespace::getCanonicalIndex( $lowerNs ) ) {
1303 # Canonical namespace
1304 $t = $m[2];
1305 $this->mNamespace = $ns;
1306 } elseif ( $ns = $wgContLang->getNsIndex( $lowerNs )) {
1307 # Ordinary namespace
1308 $t = $m[2];
1309 $this->mNamespace = $ns;
1310 } elseif( $this->getInterwikiLink( $p ) ) {
1311 if( !$firstPass ) {
1312 # Can't make a local interwiki link to an interwiki link.
1313 # That's just crazy!
1314 wfProfileOut( $fname );
1315 return false;
1316 }
1317
1318 # Interwiki link
1319 $t = $m[2];
1320 $this->mInterwiki = strtolower( $p );
1321
1322 # Redundant interwiki prefix to the local wiki
1323 if ( 0 == strcasecmp( $this->mInterwiki, $wgLocalInterwiki ) ) {
1324 if( $t == '' ) {
1325 # Can't have an empty self-link
1326 wfProfileOut( $fname );
1327 return false;
1328 }
1329 $this->mInterwiki = '';
1330 $firstPass = false;
1331 # Do another namespace split...
1332 continue;
1333 }
1334 }
1335 # If there's no recognized interwiki or namespace,
1336 # then let the colon expression be part of the title.
1337 }
1338 break;
1339 } while( true );
1340 $r = $t;
1341
1342 # We already know that some pages won't be in the database!
1343 #
1344 if ( '' != $this->mInterwiki || -1 == $this->mNamespace ) {
1345 $this->mArticleID = 0;
1346 }
1347 $f = strstr( $r, '#' );
1348 if ( false !== $f ) {
1349 $this->mFragment = substr( $f, 1 );
1350 $r = substr( $r, 0, strlen( $r ) - strlen( $f ) );
1351 # remove whitespace again: prevents "Foo_bar_#"
1352 # becoming "Foo_bar_"
1353 $r = preg_replace( '/_*$/', '', $r );
1354 }
1355
1356 # Reject illegal characters.
1357 #
1358 if( preg_match( $rxTc, $r ) ) {
1359 wfProfileOut( $fname );
1360 return false;
1361 }
1362
1363 /**
1364 * Pages with "/./" or "/../" appearing in the URLs will
1365 * often be unreachable due to the way web browsers deal
1366 * with 'relative' URLs. Forbid them explicitly.
1367 */
1368 if ( strpos( $r, '.' ) !== false &&
1369 ( $r === '.' || $r === '..' ||
1370 strpos( $r, './' ) === 0 ||
1371 strpos( $r, '../' ) === 0 ||
1372 strpos( $r, '/./' ) !== false ||
1373 strpos( $r, '/../' ) !== false ) )
1374 {
1375 wfProfileOut( $fname );
1376 return false;
1377 }
1378
1379 # We shouldn't need to query the DB for the size.
1380 #$maxSize = $dbr->textFieldSize( 'page', 'page_title' );
1381 if ( strlen( $r ) > 255 ) {
1382 wfProfileOut( $fname );
1383 return false;
1384 }
1385
1386 /**
1387 * Normally, all wiki links are forced to have
1388 * an initial capital letter so [[foo]] and [[Foo]]
1389 * point to the same place.
1390 *
1391 * Don't force it for interwikis, since the other
1392 * site might be case-sensitive.
1393 */
1394 if( $wgCapitalLinks && $this->mInterwiki == '') {
1395 $t = $wgContLang->ucfirst( $r );
1396 } else {
1397 $t = $r;
1398 }
1399
1400 /**
1401 * Can't make a link to a namespace alone...
1402 * "empty" local links can only be self-links
1403 * with a fragment identifier.
1404 */
1405 if( $t == '' &&
1406 $this->mInterwiki == '' &&
1407 $this->mNamespace != NS_MAIN ) {
1408 wfProfileOut( $fname );
1409 return false;
1410 }
1411
1412 # Fill fields
1413 $this->mDbkeyform = $t;
1414 $this->mUrlform = wfUrlencode( $t );
1415
1416 $this->mTextform = str_replace( '_', ' ', $t );
1417
1418 wfProfileOut( $fname );
1419 return true;
1420 }
1421
1422 /**
1423 * Get a Title object associated with the talk page of this article
1424 * @return Title the object for the talk page
1425 * @access public
1426 */
1427 function getTalkPage() {
1428 return Title::makeTitle( Namespace::getTalk( $this->getNamespace() ), $this->getDBkey() );
1429 }
1430
1431 /**
1432 * Get a title object associated with the subject page of this
1433 * talk page
1434 *
1435 * @return Title the object for the subject page
1436 * @access public
1437 */
1438 function getSubjectPage() {
1439 return Title::makeTitle( Namespace::getSubject( $this->getNamespace() ), $this->getDBkey() );
1440 }
1441
1442 /**
1443 * Get an array of Title objects linking to this Title
1444 * Also stores the IDs in the link cache.
1445 *
1446 * @param string $options may be FOR UPDATE
1447 * @return array the Title objects linking here
1448 * @access public
1449 */
1450 function getLinksTo( $options = '' ) {
1451 global $wgLinkCache;
1452 $id = $this->getArticleID();
1453
1454 if ( $options ) {
1455 $db =& wfGetDB( DB_MASTER );
1456 } else {
1457 $db =& wfGetDB( DB_SLAVE );
1458 }
1459
1460 $res = $db->select( array( 'page', 'pagelinks' ),
1461 array( 'page_namespace', 'page_title', 'page_id' ),
1462 array(
1463 'pl_from=page_id',
1464 'pl_namespace' => $this->getNamespace(),
1465 'pl_title' => $this->getDbKey() ),
1466 'Title::getLinksTo',
1467 $options );
1468
1469 $retVal = array();
1470 if ( $db->numRows( $res ) ) {
1471 while ( $row = $db->fetchObject( $res ) ) {
1472 if ( $titleObj = Title::makeTitle( $row->page_namespace, $row->page_title ) ) {
1473 $wgLinkCache->addGoodLinkObj( $row->page_id, $titleObj );
1474 $retVal[] = $titleObj;
1475 }
1476 }
1477 }
1478 $db->freeResult( $res );
1479 return $retVal;
1480 }
1481
1482 /**
1483 * Get an array of Title objects referring to non-existent articles linked from this page
1484 *
1485 * @param string $options may be FOR UPDATE
1486 * @return array the Title objects
1487 * @access public
1488 */
1489 function getBrokenLinksFrom( $options = '' ) {
1490 global $wgLinkCache;
1491
1492 if ( $options ) {
1493 $db =& wfGetDB( DB_MASTER );
1494 } else {
1495 $db =& wfGetDB( DB_SLAVE );
1496 }
1497
1498 $res = $db->safeQuery(
1499 "SELECT pl_namespace, pl_title
1500 FROM !
1501 LEFT JOIN !
1502 ON pl_namespace=page_namespace
1503 AND pl_title=page_title
1504 WHERE pl_from=?
1505 AND page_namespace IS NULL
1506 !",
1507 $db->tableName( 'pagelinks' ),
1508 $db->tableName( 'page' ),
1509 $this->getArticleId(),
1510 $options );
1511
1512 $retVal = array();
1513 if ( $db->numRows( $res ) ) {
1514 while ( $row = $db->fetchObject( $res ) ) {
1515 $retVal[] = Title::makeTitle( $row->pl_namespace, $row->pl_title );
1516 }
1517 }
1518 $db->freeResult( $res );
1519 return $retVal;
1520 }
1521
1522
1523 /**
1524 * Get a list of URLs to purge from the Squid cache when this
1525 * page changes
1526 *
1527 * @return array the URLs
1528 * @access public
1529 */
1530 function getSquidURLs() {
1531 return array(
1532 $this->getInternalURL(),
1533 $this->getInternalURL( 'action=history' )
1534 );
1535 }
1536
1537 /**
1538 * Move this page without authentication
1539 * @param Title &$nt the new page Title
1540 * @access public
1541 */
1542 function moveNoAuth( &$nt ) {
1543 return $this->moveTo( $nt, false );
1544 }
1545
1546 /**
1547 * Check whether a given move operation would be valid.
1548 * Returns true if ok, or a message key string for an error message
1549 * if invalid. (Scarrrrry ugly interface this.)
1550 * @param Title &$nt the new title
1551 * @param bool $auth indicates whether $wgUser's permissions
1552 * should be checked
1553 * @return mixed true on success, message name on failure
1554 * @access public
1555 */
1556 function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
1557 global $wgUser;
1558 if( !$this or !$nt ) {
1559 return 'badtitletext';
1560 }
1561 if( $this->equals( $nt ) ) {
1562 return 'selfmove';
1563 }
1564 if( !$this->isMovable() || !$nt->isMovable() ) {
1565 return 'immobile_namespace';
1566 }
1567
1568 $fname = 'Title::move';
1569 $oldid = $this->getArticleID();
1570 $newid = $nt->getArticleID();
1571
1572 if ( strlen( $nt->getDBkey() ) < 1 ) {
1573 return 'articleexists';
1574 }
1575 if ( ( '' == $this->getDBkey() ) ||
1576 ( !$oldid ) ||
1577 ( '' == $nt->getDBkey() ) ) {
1578 return 'badarticleerror';
1579 }
1580
1581 if ( $auth && (
1582 !$this->userCanEdit() || !$nt->userCanEdit() ||
1583 !$this->userCanMove() || !$nt->userCanMove() ) ) {
1584 return 'protectedpage';
1585 }
1586
1587 # The move is allowed only if (1) the target doesn't exist, or
1588 # (2) the target is a redirect to the source, and has no history
1589 # (so we can undo bad moves right after they're done).
1590
1591 if ( 0 != $newid ) { # Target exists; check for validity
1592 if ( ! $this->isValidMoveTarget( $nt ) ) {
1593 return 'articleexists';
1594 }
1595 }
1596 return true;
1597 }
1598
1599 /**
1600 * Move a title to a new location
1601 * @param Title &$nt the new title
1602 * @param bool $auth indicates whether $wgUser's permissions
1603 * should be checked
1604 * @return mixed true on success, message name on failure
1605 * @access public
1606 */
1607 function moveTo( &$nt, $auth = true, $reason = '' ) {
1608 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
1609 if( is_string( $err ) ) {
1610 return $err;
1611 }
1612
1613 $pageid = $this->getArticleID();
1614 if( $nt->exists() ) {
1615 $this->moveOverExistingRedirect( $nt, $reason );
1616 $pageCountChange = 0;
1617 } else { # Target didn't exist, do normal move.
1618 $this->moveToNewTitle( $nt, $newid, $reason );
1619 $pageCountChange = 1;
1620 }
1621 $redirid = $this->getArticleID();
1622
1623 # Fixing category links (those without piped 'alternate' names) to be sorted under the new title
1624 $dbw =& wfGetDB( DB_MASTER );
1625 $categorylinks = $dbw->tableName( 'categorylinks' );
1626 $sql = "UPDATE $categorylinks SET cl_sortkey=" . $dbw->addQuotes( $nt->getPrefixedText() ) .
1627 " WHERE cl_from=" . $dbw->addQuotes( $pageid ) .
1628 " AND cl_sortkey=" . $dbw->addQuotes( $this->getPrefixedText() );
1629 $dbw->query( $sql, 'SpecialMovepage::doSubmit' );
1630
1631 # Update watchlists
1632
1633 $oldnamespace = $this->getNamespace() & ~1;
1634 $newnamespace = $nt->getNamespace() & ~1;
1635 $oldtitle = $this->getDBkey();
1636 $newtitle = $nt->getDBkey();
1637
1638 if( $oldnamespace != $newnamespace || $oldtitle != $newtitle ) {
1639 WatchedItem::duplicateEntries( $this, $nt );
1640 }
1641
1642 # Update search engine
1643 $u = new SearchUpdate( $pageid, $nt->getPrefixedDBkey() );
1644 $u->doUpdate();
1645 $u = new SearchUpdate( $redirid, $this->getPrefixedDBkey(), '' );
1646 $u->doUpdate();
1647
1648 # Update site_stats
1649 if ( $this->getNamespace() == NS_MAIN and $nt->getNamespace() != NS_MAIN ) {
1650 # Moved out of main namespace
1651 # not viewed, edited, removing
1652 $u = new SiteStatsUpdate( 0, 1, -1, $pageCountChange);
1653 } elseif ( $this->getNamespace() != NS_MAIN and $nt->getNamespace() == NS_MAIN ) {
1654 # Moved into main namespace
1655 # not viewed, edited, adding
1656 $u = new SiteStatsUpdate( 0, 1, +1, $pageCountChange );
1657 } elseif ( $pageCountChange ) {
1658 # Added redirect
1659 $u = new SiteStatsUpdate( 0, 0, 0, 1 );
1660 } else{
1661 $u = false;
1662 }
1663 if ( $u ) {
1664 $u->doUpdate();
1665 }
1666
1667 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) );
1668 return true;
1669 }
1670
1671 /**
1672 * Move page to a title which is at present a redirect to the
1673 * source page
1674 *
1675 * @param Title &$nt the page to move to, which should currently
1676 * be a redirect
1677 * @access private
1678 */
1679 function moveOverExistingRedirect( &$nt, $reason = '' ) {
1680 global $wgUser, $wgLinkCache, $wgUseSquid, $wgMwRedir;
1681 $fname = 'Title::moveOverExistingRedirect';
1682 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
1683
1684 if ( $reason ) {
1685 $comment .= ": $reason";
1686 }
1687
1688 $now = wfTimestampNow();
1689 $rand = wfRandom();
1690 $newid = $nt->getArticleID();
1691 $oldid = $this->getArticleID();
1692 $dbw =& wfGetDB( DB_MASTER );
1693 $links = $dbw->tableName( 'links' );
1694
1695 # Delete the old redirect. We don't save it to history since
1696 # by definition if we've got here it's rather uninteresting.
1697 # We have to remove it so that the next step doesn't trigger
1698 # a conflict on the unique namespace+title index...
1699 $dbw->delete( 'page', array( 'page_id' => $newid ), $fname );
1700
1701 # Save a null revision in the page's history notifying of the move
1702 $nullRevision = Revision::newNullRevision( $dbw, $oldid,
1703 wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() ),
1704 true );
1705 $nullRevId = $nullRevision->insertOn( $dbw );
1706
1707 # Change the name of the target page:
1708 $dbw->update( 'page',
1709 /* SET */ array(
1710 'page_touched' => $dbw->timestamp($now),
1711 'page_namespace' => $nt->getNamespace(),
1712 'page_title' => $nt->getDBkey(),
1713 'page_latest' => $nullRevId,
1714 ),
1715 /* WHERE */ array( 'page_id' => $oldid ),
1716 $fname
1717 );
1718 $wgLinkCache->clearLink( $nt->getPrefixedDBkey() );
1719
1720 # Recreate the redirect, this time in the other direction.
1721 $redirectText = $wgMwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
1722 $redirectArticle = new Article( $this );
1723 $newid = $redirectArticle->insertOn( $dbw );
1724 $redirectRevision = new Revision( array(
1725 'page' => $newid,
1726 'comment' => $comment,
1727 'text' => $redirectText ) );
1728 $revid = $redirectRevision->insertOn( $dbw );
1729 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
1730 $wgLinkCache->clearLink( $this->getPrefixedDBkey() );
1731
1732 # Log the move
1733 $log = new LogPage( 'move' );
1734 $log->addEntry( 'move_redir', $this, $reason, array( 1 => $nt->getPrefixedText() ) );
1735
1736 # Now, we record the link from the redirect to the new title.
1737 # It should have no other outgoing links...
1738 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), $fname );
1739 $dbw->insert( 'pagelinks',
1740 array(
1741 'pl_from' => $newid,
1742 'pl_namespace' => $nt->getNamespace(),
1743 'pl_title' => $nt->getDbKey() ),
1744 $fname );
1745
1746 # Purge squid
1747 if ( $wgUseSquid ) {
1748 $urls = array_merge( $nt->getSquidURLs(), $this->getSquidURLs() );
1749 $u = new SquidUpdate( $urls );
1750 $u->doUpdate();
1751 }
1752 }
1753
1754 /**
1755 * Move page to non-existing title.
1756 * @param Title &$nt the new Title
1757 * @param int &$newid set to be the new article ID
1758 * @access private
1759 */
1760 function moveToNewTitle( &$nt, &$newid, $reason = '' ) {
1761 global $wgUser, $wgLinkCache, $wgUseSquid;
1762 global $wgMwRedir;
1763 $fname = 'MovePageForm::moveToNewTitle';
1764 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
1765 if ( $reason ) {
1766 $comment .= ": $reason";
1767 }
1768
1769 $newid = $nt->getArticleID();
1770 $oldid = $this->getArticleID();
1771 $dbw =& wfGetDB( DB_MASTER );
1772 $now = $dbw->timestamp();
1773 wfSeedRandom();
1774 $rand = wfRandom();
1775
1776 # Save a null revision in the page's history notifying of the move
1777 $nullRevision = Revision::newNullRevision( $dbw, $oldid,
1778 wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() ),
1779 true );
1780 $nullRevId = $nullRevision->insertOn( $dbw );
1781
1782 # Rename cur entry
1783 $dbw->update( 'page',
1784 /* SET */ array(
1785 'page_touched' => $now,
1786 'page_namespace' => $nt->getNamespace(),
1787 'page_title' => $nt->getDBkey(),
1788 'page_latest' => $nullRevId,
1789 ),
1790 /* WHERE */ array( 'page_id' => $oldid ),
1791 $fname
1792 );
1793
1794 $wgLinkCache->clearLink( $nt->getPrefixedDBkey() );
1795
1796 # Insert redirect
1797 $redirectText = $wgMwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
1798 $redirectArticle = new Article( $this );
1799 $newid = $redirectArticle->insertOn( $dbw );
1800 $redirectRevision = new Revision( array(
1801 'page' => $newid,
1802 'comment' => $comment,
1803 'text' => $redirectText ) );
1804 $revid = $redirectRevision->insertOn( $dbw );
1805 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
1806 $wgLinkCache->clearLink( $this->getPrefixedDBkey() );
1807
1808 # Log the move
1809 $log = new LogPage( 'move' );
1810 $log->addEntry( 'move', $this, $reason, array( 1 => $nt->getPrefixedText()) );
1811
1812 # Purge caches as per article creation
1813 Article::onArticleCreate( $nt );
1814
1815 # Record the just-created redirect's linking to the page
1816 $dbw->insert( 'pagelinks',
1817 array(
1818 'pl_from' => $newid,
1819 'pl_namespace' => $nt->getNamespace(),
1820 'pl_title' => $nt->getDBkey() ),
1821 $fname );
1822
1823 # Non-existent target may have had broken links to it; these must
1824 # now be touched to update link coloring.
1825 $nt->touchLinks();
1826
1827 # Purge old title from squid
1828 # The new title, and links to the new title, are purged in Article::onArticleCreate()
1829 $titles = $nt->getLinksTo();
1830 if ( $wgUseSquid ) {
1831 $urls = $this->getSquidURLs();
1832 foreach ( $titles as $linkTitle ) {
1833 $urls[] = $linkTitle->getInternalURL();
1834 }
1835 $u = new SquidUpdate( $urls );
1836 $u->doUpdate();
1837 }
1838 }
1839
1840 /**
1841 * Checks if $this can be moved to a given Title
1842 * - Selects for update, so don't call it unless you mean business
1843 *
1844 * @param Title &$nt the new title to check
1845 * @access public
1846 */
1847 function isValidMoveTarget( $nt ) {
1848
1849 $fname = 'Title::isValidMoveTarget';
1850 $dbw =& wfGetDB( DB_MASTER );
1851
1852 # Is it a redirect?
1853 $id = $nt->getArticleID();
1854 $obj = $dbw->selectRow( array( 'page', 'revision', 'text'),
1855 array( 'page_is_redirect','old_text','old_flags' ),
1856 array( 'page_id' => $id, 'page_latest=rev_id', 'rev_text_id=old_id' ),
1857 $fname, 'FOR UPDATE' );
1858
1859 if ( !$obj || 0 == $obj->page_is_redirect ) {
1860 # Not a redirect
1861 return false;
1862 }
1863 $text = Revision::getRevisionText( $obj );
1864
1865 # Does the redirect point to the source?
1866 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $text, $m ) ) {
1867 $redirTitle = Title::newFromText( $m[1] );
1868 if( !is_object( $redirTitle ) ||
1869 $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() ) {
1870 return false;
1871 }
1872 } else {
1873 # Fail safe
1874 return false;
1875 }
1876
1877 # Does the article have a history?
1878 $row = $dbw->selectRow( array( 'page', 'revision'),
1879 array( 'rev_id' ),
1880 array( 'page_namespace' => $nt->getNamespace(),
1881 'page_title' => $nt->getDBkey(),
1882 'page_id=rev_page AND page_latest != rev_id'
1883 ), $fname, 'FOR UPDATE'
1884 );
1885
1886 # Return true if there was no history
1887 return $row === false;
1888 }
1889
1890 /**
1891 * Create a redirect; fails if the title already exists; does
1892 * not notify RC
1893 *
1894 * @param Title $dest the destination of the redirect
1895 * @param string $comment the comment string describing the move
1896 * @return bool true on success
1897 * @access public
1898 */
1899 function createRedirect( $dest, $comment ) {
1900 global $wgUser;
1901 if ( $this->getArticleID() ) {
1902 return false;
1903 }
1904
1905 $fname = 'Title::createRedirect';
1906 $dbw =& wfGetDB( DB_MASTER );
1907
1908 $article = new Article( $this );
1909 $newid = $article->insertOn( $dbw );
1910 $revision = new Revision( array(
1911 'page' => $newid,
1912 'comment' => $comment,
1913 'text' => "#REDIRECT [[" . $dest->getPrefixedText() . "]]\n",
1914 ) );
1915 $revisionId = $revision->insertOn( $dbw );
1916 $article->updateRevisionOn( $dbw, $revision, 0 );
1917
1918 # Link table
1919 $dbw->insert( 'pagelinks',
1920 array(
1921 'pl_from' => $newid,
1922 'pl_namespace' => $dest->getNamespace(),
1923 'pl_title' => $dest->getDbKey()
1924 ), $fname
1925 );
1926
1927 Article::onArticleCreate( $this );
1928 return true;
1929 }
1930
1931 /**
1932 * Get categories to which this Title belongs and return an array of
1933 * categories' names.
1934 *
1935 * @return array an array of parents in the form:
1936 * $parent => $currentarticle
1937 * @access public
1938 */
1939 function getParentCategories() {
1940 global $wgContLang,$wgUser;
1941
1942 $titlekey = $this->getArticleId();
1943 $sk =& $wgUser->getSkin();
1944 $parents = array();
1945 $dbr =& wfGetDB( DB_SLAVE );
1946 $categorylinks = $dbr->tableName( 'categorylinks' );
1947
1948 # NEW SQL
1949 $sql = "SELECT * FROM $categorylinks"
1950 ." WHERE cl_from='$titlekey'"
1951 ." AND cl_from <> '0'"
1952 ." ORDER BY cl_sortkey";
1953
1954 $res = $dbr->query ( $sql ) ;
1955
1956 if($dbr->numRows($res) > 0) {
1957 while ( $x = $dbr->fetchObject ( $res ) )
1958 //$data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$x->cl_to);
1959 $data[$wgContLang->getNSText ( NS_CATEGORY ).':'.$x->cl_to] = $this->getFullText();
1960 $dbr->freeResult ( $res ) ;
1961 } else {
1962 $data = '';
1963 }
1964 return $data;
1965 }
1966
1967 /**
1968 * Get a tree of parent categories
1969 * @param array $children an array with the children in the keys, to check for circular refs
1970 * @return array
1971 * @access public
1972 */
1973 function getParentCategoryTree( $children = array() ) {
1974 $parents = $this->getParentCategories();
1975
1976 if($parents != '') {
1977 foreach($parents as $parent => $current)
1978 {
1979 if ( array_key_exists( $parent, $children ) ) {
1980 # Circular reference
1981 $stack[$parent] = array();
1982 } else {
1983 $nt = Title::newFromText($parent);
1984 $stack[$parent] = $nt->getParentCategoryTree( $children + array($parent => 1) );
1985 }
1986 }
1987 return $stack;
1988 } else {
1989 return array();
1990 }
1991 }
1992
1993
1994 /**
1995 * Get an associative array for selecting this title from
1996 * the "cur" table
1997 *
1998 * @return array
1999 * @access public
2000 */
2001 function curCond() {
2002 wfDebugDieBacktrace( 'curCond called' );
2003 return array( 'cur_namespace' => $this->mNamespace, 'cur_title' => $this->mDbkeyform );
2004 }
2005
2006 /**
2007 * Get an associative array for selecting this title from the
2008 * "old" table
2009 *
2010 * @return array
2011 * @access public
2012 */
2013 function oldCond() {
2014 wfDebugDieBacktrace( 'oldCond called' );
2015 return array( 'old_namespace' => $this->mNamespace, 'old_title' => $this->mDbkeyform );
2016 }
2017
2018 /**
2019 * Get the revision ID of the previous revision
2020 *
2021 * @param integer $revision Revision ID. Get the revision that was before this one.
2022 * @return interger $oldrevision|false
2023 */
2024 function getPreviousRevisionID( $revision ) {
2025 $dbr =& wfGetDB( DB_SLAVE );
2026 return $dbr->selectField( 'revision', 'rev_id',
2027 'rev_page=' . intval( $this->getArticleId() ) .
2028 ' AND rev_id<' . intval( $revision ) . ' ORDER BY rev_id DESC' );
2029 }
2030
2031 /**
2032 * Get the revision ID of the next revision
2033 *
2034 * @param integer $revision Revision ID. Get the revision that was after this one.
2035 * @return interger $oldrevision|false
2036 */
2037 function getNextRevisionID( $revision ) {
2038 $dbr =& wfGetDB( DB_SLAVE );
2039 return $dbr->selectField( 'revision', 'rev_id',
2040 'rev_page=' . intval( $this->getArticleId() ) .
2041 ' AND rev_id>' . intval( $revision ) . ' ORDER BY rev_id' );
2042 }
2043
2044 /**
2045 * Compare with another title.
2046 *
2047 * @param Title $title
2048 * @return bool
2049 */
2050 function equals( &$title ) {
2051 return $this->getInterwiki() == $title->getInterwiki()
2052 && $this->getNamespace() == $title->getNamespace()
2053 && $this->getDbkey() == $title->getDbkey();
2054 }
2055
2056 /**
2057 * Check if page exists
2058 * @return bool
2059 */
2060 function exists() {
2061 return $this->getArticleId() != 0;
2062 }
2063
2064 /**
2065 * Should a link should be displayed as a known link, just based on its title?
2066 *
2067 * Currently, a self-link with a fragment, special pages and image pages are in
2068 * this category. Special pages never exist in the database. Some images do not
2069 * have description pages in the database, but the description page contains
2070 * useful history information that the user may want to link to.
2071 */
2072 function isAlwaysKnown() {
2073 return $this->isExternal() || ( 0 == $this->mNamespace && "" == $this->mDbkeyform )
2074 || NS_SPECIAL == $this->mNamespace || NS_IMAGE == $this->mNamespace;
2075 }
2076
2077 /**
2078 * Update page_touched timestamps on pages linking to this title.
2079 * In principal, this could be backgrounded and could also do squid
2080 * purging.
2081 */
2082 function touchLinks() {
2083 $fname = 'Title::touchLinks';
2084
2085 $dbw =& wfGetDB( DB_MASTER );
2086
2087 $res = $dbw->select( 'pagelinks',
2088 array( 'pl_from' ),
2089 array(
2090 'pl_namespace' => $this->getNamespace(),
2091 'pl_title' => $this->getDbKey() ),
2092 $fname );
2093 if ( 0 == $dbw->numRows( $res ) ) {
2094 return;
2095 }
2096
2097 $arr = array();
2098 $toucharr = array();
2099 while( $row = $dbw->fetchObject( $res ) ) {
2100 $toucharr[] = $row->pl_from;
2101 }
2102 if (!count($toucharr))
2103 return;
2104 $dbw->update( 'page', /* SET */ array( 'page_touched' => $dbw->timestamp() ),
2105 /* WHERE */ array( 'page_id' => $toucharr ),$fname);
2106 }
2107
2108 function trackbackURL() {
2109 global $wgTitle, $wgScriptPath, $wgServer;
2110
2111 return "$wgServer$wgScriptPath/trackback.php?article="
2112 . htmlspecialchars(urlencode($wgTitle->getPrefixedDBkey()));
2113 }
2114
2115 function trackbackRDF() {
2116 $url = htmlspecialchars($this->getFullURL());
2117 $title = htmlspecialchars($this->getText());
2118 $tburl = $this->trackbackURL();
2119
2120 return "
2121 <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"
2122 xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
2123 xmlns:trackback=\"http://madskills.com/public/xml/rss/module/trackback/\">
2124 <rdf:Description
2125 rdf:about=\"$url\"
2126 dc:identifier=\"$url\"
2127 dc:title=\"$title\"
2128 trackback:ping=\"$tburl\" />
2129 </rdf:RDF>";
2130 }
2131 }
2132 ?>