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