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