* Replace wfMungeToUtf8 and do_html_entity_decode with a single function
[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 if( preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches ) ) {
724 global $wgActionPaths;
725 $action = urldecode( $matches[2] );
726 if( isset( $wgActionPaths[$action] ) ) {
727 $query = $matches[1];
728 if( isset( $matches[4] ) ) $query .= $matches[4];
729 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
730 if( $query != '' ) $url .= '?' . $query;
731 return $url;
732 }
733 }
734 if ( $query == '-' ) {
735 $query = '';
736 }
737 $url = "{$wgScript}?title={$dbkey}&{$query}";
738 }
739 return $url;
740 }
741
742 /**
743 * Get an HTML-escaped version of the URL form, suitable for
744 * using in a link, without a server name or fragment
745 * @param string $query an optional query string
746 * @return string the URL
747 * @access public
748 */
749 function escapeLocalURL( $query = '' ) {
750 return htmlspecialchars( $this->getLocalURL( $query ) );
751 }
752
753 /**
754 * Get an HTML-escaped version of the URL form, suitable for
755 * using in a link, including the server name and fragment
756 *
757 * @return string the URL
758 * @param string $query an optional query string
759 * @access public
760 */
761 function escapeFullURL( $query = '' ) {
762 return htmlspecialchars( $this->getFullURL( $query ) );
763 }
764
765 /**
766 * Get the URL form for an internal link.
767 * - Used in various Squid-related code, in case we have a different
768 * internal hostname for the server from the exposed one.
769 *
770 * @param string $query an optional query string
771 * @return string the URL
772 * @access public
773 */
774 function getInternalURL( $query = '' ) {
775 global $wgInternalServer;
776 return $wgInternalServer . $this->getLocalURL( $query );
777 }
778
779 /**
780 * Get the edit URL for this Title
781 * @return string the URL, or a null string if this is an
782 * interwiki link
783 * @access public
784 */
785 function getEditURL() {
786 global $wgServer, $wgScript;
787
788 if ( '' != $this->mInterwiki ) { return ''; }
789 $s = $this->getLocalURL( 'action=edit' );
790
791 return $s;
792 }
793
794 /**
795 * Get the HTML-escaped displayable text form.
796 * Used for the title field in <a> tags.
797 * @return string the text, including any prefixes
798 * @access public
799 */
800 function getEscapedText() {
801 return htmlspecialchars( $this->getPrefixedText() );
802 }
803
804 /**
805 * Is this Title interwiki?
806 * @return boolean
807 * @access public
808 */
809 function isExternal() { return ( '' != $this->mInterwiki ); }
810
811 /**
812 * Does the title correspond to a protected article?
813 * @param string $what the action the page is protected from,
814 * by default checks move and edit
815 * @return boolean
816 * @access public
817 */
818 function isProtected($action = '') {
819 if ( -1 == $this->mNamespace ) { return true; }
820 if($action == 'edit' || $action == '') {
821 $a = $this->getRestrictions("edit");
822 if ( in_array( 'sysop', $a ) ) { return true; }
823 }
824 if($action == 'move' || $action == '') {
825 $a = $this->getRestrictions("move");
826 if ( in_array( 'sysop', $a ) ) { return true; }
827 }
828 return false;
829 }
830
831 /**
832 * Is $wgUser is watching this page?
833 * @return boolean
834 * @access public
835 */
836 function userIsWatching() {
837 global $wgUser;
838
839 if ( is_null( $this->mWatched ) ) {
840 if ( -1 == $this->mNamespace || 0 == $wgUser->getID()) {
841 $this->mWatched = false;
842 } else {
843 $this->mWatched = $wgUser->isWatched( $this );
844 }
845 }
846 return $this->mWatched;
847 }
848
849 /**
850 * Is $wgUser perform $action this page?
851 * @param string $action action that permission needs to be checked for
852 * @return boolean
853 * @access private
854 */
855 function userCan($action) {
856 $fname = 'Title::userCanEdit';
857 wfProfileIn( $fname );
858
859 global $wgUser;
860 if( NS_SPECIAL == $this->mNamespace ) {
861 wfProfileOut( $fname );
862 return false;
863 }
864 if( NS_MEDIAWIKI == $this->mNamespace &&
865 !$wgUser->isAllowed('editinterface') ) {
866 wfProfileOut( $fname );
867 return false;
868 }
869 if( $this->mDbkeyform == '_' ) {
870 # FIXME: Is this necessary? Shouldn't be allowed anyway...
871 wfProfileOut( $fname );
872 return false;
873 }
874
875 # protect global styles and js
876 if ( NS_MEDIAWIKI == $this->mNamespace
877 && preg_match("/\\.(css|js)$/", $this->mTextform )
878 && !$wgUser->isAllowed('editinterface') ) {
879 wfProfileOut( $fname );
880 return false;
881 }
882
883 # protect css/js subpages of user pages
884 # XXX: this might be better using restrictions
885 # XXX: Find a way to work around the php bug that prevents using $this->userCanEditCssJsSubpage() from working
886 if( NS_USER == $this->mNamespace
887 && preg_match("/\\.(css|js)$/", $this->mTextform )
888 && !$wgUser->isAllowed('editinterface')
889 && !preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform) ) {
890 wfProfileOut( $fname );
891 return false;
892 }
893
894 foreach( $this->getRestrictions($action) as $right ) {
895 // Backwards compatibility, rewrite sysop -> protect
896 if ( $right == 'sysop' ) {
897 $right = 'protect';
898 }
899 if( '' != $right && !$wgUser->isAllowed( $right ) ) {
900 wfProfileOut( $fname );
901 return false;
902 }
903 }
904
905 if( $action == 'move' && !$this->isMovable() ) {
906 wfProfileOut( $fname );
907 return false;
908 }
909
910 wfProfileOut( $fname );
911 return true;
912 }
913
914 /**
915 * Can $wgUser edit this page?
916 * @return boolean
917 * @access public
918 */
919 function userCanEdit() {
920 return $this->userCan('edit');
921 }
922
923 /**
924 * Can $wgUser move this page?
925 * @return boolean
926 * @access public
927 */
928 function userCanMove() {
929 return $this->userCan('move');
930 }
931
932 /**
933 * Would anybody with sufficient privileges be able to move this page?
934 * Some pages just aren't movable.
935 *
936 * @return boolean
937 * @access public
938 */
939 function isMovable() {
940 return Namespace::isMovable( $this->getNamespace() )
941 && $this->getInterwiki() == '';
942 }
943
944 /**
945 * Can $wgUser read this page?
946 * @return boolean
947 * @access public
948 */
949 function userCanRead() {
950 global $wgUser;
951
952 if( $wgUser->isAllowed('read') ) {
953 return true;
954 } else {
955 global $wgWhitelistRead;
956
957 /** If anon users can create an account,
958 they need to reach the login page first! */
959 if( $wgUser->isAllowed( 'createaccount' )
960 && $this->mId == NS_SPECIAL
961 && $this->getText() == 'Userlogin' ) {
962 return true;
963 }
964
965 /** some pages are explicitly allowed */
966 $name = $this->getPrefixedText();
967 if( $wgWhitelistRead && in_array( $name, $wgWhitelistRead ) ) {
968 return true;
969 }
970
971 # Compatibility with old settings
972 if( $wgWhitelistRead && $this->getNamespace() == NS_MAIN ) {
973 if( in_array( ':' . $name, $wgWhitelistRead ) ) {
974 return true;
975 }
976 }
977 }
978 return false;
979 }
980
981 /**
982 * Is this a talk page of some sort?
983 * @return bool
984 * @access public
985 */
986 function isTalkPage() {
987 return Namespace::isTalk( $this->getNamespace() );
988 }
989
990 /**
991 * Is this a .css or .js subpage of a user page?
992 * @return bool
993 * @access public
994 */
995 function isCssJsSubpage() {
996 return ( NS_USER == $this->mNamespace and preg_match("/\\.(css|js)$/", $this->mTextform ) );
997 }
998 /**
999 * Is this a .css subpage of a user page?
1000 * @return bool
1001 * @access public
1002 */
1003 function isCssSubpage() {
1004 return ( NS_USER == $this->mNamespace and preg_match("/\\.css$/", $this->mTextform ) );
1005 }
1006 /**
1007 * Is this a .js subpage of a user page?
1008 * @return bool
1009 * @access public
1010 */
1011 function isJsSubpage() {
1012 return ( NS_USER == $this->mNamespace and preg_match("/\\.js$/", $this->mTextform ) );
1013 }
1014 /**
1015 * Protect css/js subpages of user pages: can $wgUser edit
1016 * this page?
1017 *
1018 * @return boolean
1019 * @todo XXX: this might be better using restrictions
1020 * @access public
1021 */
1022 function userCanEditCssJsSubpage() {
1023 global $wgUser;
1024 return ( $wgUser->isAllowed('editinterface') or preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform) );
1025 }
1026
1027 /**
1028 * Loads a string into mRestrictions array
1029 * @param string $res restrictions in string format
1030 * @access public
1031 */
1032 function loadRestrictions( $res ) {
1033 foreach( explode( ':', trim( $res ) ) as $restrict ) {
1034 $temp = explode( '=', trim( $restrict ) );
1035 if(count($temp) == 1) {
1036 // old format should be treated as edit/move restriction
1037 $this->mRestrictions["edit"] = explode( ',', trim( $temp[0] ) );
1038 $this->mRestrictions["move"] = explode( ',', trim( $temp[0] ) );
1039 } else {
1040 $this->mRestrictions[$temp[0]] = explode( ',', trim( $temp[1] ) );
1041 }
1042 }
1043 $this->mRestrictionsLoaded = true;
1044 }
1045
1046 /**
1047 * Accessor/initialisation for mRestrictions
1048 * @param string $action action that permission needs to be checked for
1049 * @return array the array of groups allowed to edit this article
1050 * @access public
1051 */
1052 function getRestrictions($action) {
1053 $id = $this->getArticleID();
1054 if ( 0 == $id ) { return array(); }
1055
1056 if ( ! $this->mRestrictionsLoaded ) {
1057 $dbr =& wfGetDB( DB_SLAVE );
1058 $res = $dbr->selectField( 'page', 'page_restrictions', 'page_id='.$id );
1059 $this->loadRestrictions( $res );
1060 }
1061 if( isset( $this->mRestrictions[$action] ) ) {
1062 return $this->mRestrictions[$action];
1063 }
1064 return array();
1065 }
1066
1067 /**
1068 * Is there a version of this page in the deletion archive?
1069 * @return int the number of archived revisions
1070 * @access public
1071 */
1072 function isDeleted() {
1073 $fname = 'Title::isDeleted';
1074 $dbr =& wfGetDB( DB_SLAVE );
1075 $n = $dbr->selectField( 'archive', 'COUNT(*)', array( 'ar_namespace' => $this->getNamespace(),
1076 'ar_title' => $this->getDBkey() ), $fname );
1077 return (int)$n;
1078 }
1079
1080 /**
1081 * Get the article ID for this Title from the link cache,
1082 * adding it if necessary
1083 * @param int $flags a bit field; may be GAID_FOR_UPDATE to select
1084 * for update
1085 * @return int the ID
1086 * @access public
1087 */
1088 function getArticleID( $flags = 0 ) {
1089 global $wgLinkCache;
1090
1091 if ( $flags & GAID_FOR_UPDATE ) {
1092 $oldUpdate = $wgLinkCache->forUpdate( true );
1093 $this->mArticleID = $wgLinkCache->addLinkObj( $this );
1094 $wgLinkCache->forUpdate( $oldUpdate );
1095 } else {
1096 if ( -1 == $this->mArticleID ) {
1097 $this->mArticleID = $wgLinkCache->addLinkObj( $this );
1098 }
1099 }
1100 return $this->mArticleID;
1101 }
1102
1103 /**
1104 * This clears some fields in this object, and clears any associated
1105 * keys in the "bad links" section of $wgLinkCache.
1106 *
1107 * - This is called from Article::insertNewArticle() to allow
1108 * loading of the new page_id. It's also called from
1109 * Article::doDeleteArticle()
1110 *
1111 * @param int $newid the new Article ID
1112 * @access public
1113 */
1114 function resetArticleID( $newid ) {
1115 global $wgLinkCache;
1116 $wgLinkCache->clearBadLink( $this->getPrefixedDBkey() );
1117
1118 if ( 0 == $newid ) { $this->mArticleID = -1; }
1119 else { $this->mArticleID = $newid; }
1120 $this->mRestrictionsLoaded = false;
1121 $this->mRestrictions = array();
1122 }
1123
1124 /**
1125 * Updates page_touched for this page; called from LinksUpdate.php
1126 * @return bool true if the update succeded
1127 * @access public
1128 */
1129 function invalidateCache() {
1130 if ( wfReadOnly() ) {
1131 return;
1132 }
1133
1134 $now = wfTimestampNow();
1135 $dbw =& wfGetDB( DB_MASTER );
1136 $success = $dbw->update( 'page',
1137 array( /* SET */
1138 'page_touched' => $dbw->timestamp()
1139 ), array( /* WHERE */
1140 'page_namespace' => $this->getNamespace() ,
1141 'page_title' => $this->getDBkey()
1142 ), 'Title::invalidateCache'
1143 );
1144 return $success;
1145 }
1146
1147 /**
1148 * Prefix some arbitrary text with the namespace or interwiki prefix
1149 * of this object
1150 *
1151 * @param string $name the text
1152 * @return string the prefixed text
1153 * @access private
1154 */
1155 /* private */ function prefix( $name ) {
1156 global $wgContLang;
1157
1158 $p = '';
1159 if ( '' != $this->mInterwiki ) {
1160 $p = $this->mInterwiki . ':';
1161 }
1162 if ( 0 != $this->mNamespace ) {
1163 $p .= $wgContLang->getNsText( $this->mNamespace ) . ':';
1164 }
1165 return $p . $name;
1166 }
1167
1168 /**
1169 * Secure and split - main initialisation function for this object
1170 *
1171 * Assumes that mDbkeyform has been set, and is urldecoded
1172 * and uses underscores, but not otherwise munged. This function
1173 * removes illegal characters, splits off the interwiki and
1174 * namespace prefixes, sets the other forms, and canonicalizes
1175 * everything.
1176 * @return bool true on success
1177 * @access private
1178 */
1179 /* private */ function secureAndSplit() {
1180 global $wgContLang, $wgLocalInterwiki, $wgCapitalLinks;
1181 $fname = 'Title::secureAndSplit';
1182 wfProfileIn( $fname );
1183
1184 # Initialisation
1185 static $rxTc = false;
1186 if( !$rxTc ) {
1187 # % is needed as well
1188 $rxTc = '/[^' . Title::legalChars() . ']|%[0-9A-Fa-f]{2}/S';
1189 }
1190
1191 $this->mInterwiki = $this->mFragment = '';
1192 $this->mNamespace = $this->mDefaultNamespace; # Usually NS_MAIN
1193
1194 # Clean up whitespace
1195 #
1196 $t = preg_replace( '/[ _]+/', '_', $this->mDbkeyform );
1197 $t = trim( $t, '_' );
1198
1199 if ( '' == $t ) {
1200 wfProfileOut( $fname );
1201 return false;
1202 }
1203
1204 if( false !== strpos( $t, UTF8_REPLACEMENT ) ) {
1205 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
1206 wfProfileOut( $fname );
1207 return false;
1208 }
1209
1210 $this->mDbkeyform = $t;
1211
1212 # Initial colon indicating main namespace
1213 if ( ':' == $t{0} ) {
1214 $r = substr( $t, 1 );
1215 $this->mNamespace = NS_MAIN;
1216 } else {
1217 # Namespace or interwiki prefix
1218 $firstPass = true;
1219 do {
1220 if ( preg_match( "/^(.+?)_*:_*(.*)$/S", $t, $m ) ) {
1221 $p = $m[1];
1222 $lowerNs = strtolower( $p );
1223 if ( $ns = Namespace::getCanonicalIndex( $lowerNs ) ) {
1224 # Canonical namespace
1225 $t = $m[2];
1226 $this->mNamespace = $ns;
1227 } elseif ( $ns = $wgContLang->getNsIndex( $lowerNs )) {
1228 # Ordinary namespace
1229 $t = $m[2];
1230 $this->mNamespace = $ns;
1231 } elseif( $this->getInterwikiLink( $p ) ) {
1232 if( !$firstPass ) {
1233 # Can't make a local interwiki link to an interwiki link.
1234 # That's just crazy!
1235 wfProfileOut( $fname );
1236 return false;
1237 }
1238
1239 # Interwiki link
1240 $t = $m[2];
1241 $this->mInterwiki = $p;
1242
1243 # Redundant interwiki prefix to the local wiki
1244 if ( 0 == strcasecmp( $this->mInterwiki, $wgLocalInterwiki ) ) {
1245 if( $t == '' ) {
1246 # Can't have an empty self-link
1247 wfProfileOut( $fname );
1248 return false;
1249 }
1250 $this->mInterwiki = '';
1251 $firstPass = false;
1252 # Do another namespace split...
1253 continue;
1254 }
1255 }
1256 # If there's no recognized interwiki or namespace,
1257 # then let the colon expression be part of the title.
1258 }
1259 break;
1260 } while( true );
1261 $r = $t;
1262 }
1263
1264 # We already know that some pages won't be in the database!
1265 #
1266 if ( '' != $this->mInterwiki || -1 == $this->mNamespace ) {
1267 $this->mArticleID = 0;
1268 }
1269 $f = strstr( $r, '#' );
1270 if ( false !== $f ) {
1271 $this->mFragment = substr( $f, 1 );
1272 $r = substr( $r, 0, strlen( $r ) - strlen( $f ) );
1273 # remove whitespace again: prevents "Foo_bar_#"
1274 # becoming "Foo_bar_"
1275 $r = preg_replace( '/_*$/', '', $r );
1276 }
1277
1278 # Reject illegal characters.
1279 #
1280 if( preg_match( $rxTc, $r ) ) {
1281 wfProfileOut( $fname );
1282 return false;
1283 }
1284
1285 /**
1286 * Pages with "/./" or "/../" appearing in the URLs will
1287 * often be unreachable due to the way web browsers deal
1288 * with 'relative' URLs. Forbid them explicitly.
1289 */
1290 if ( strpos( $r, '.' ) !== false &&
1291 ( $r === '.' || $r === '..' ||
1292 strpos( $r, './' ) === 0 ||
1293 strpos( $r, '../' ) === 0 ||
1294 strpos( $r, '/./' ) !== false ||
1295 strpos( $r, '/../' ) !== false ) )
1296 {
1297 wfProfileOut( $fname );
1298 return false;
1299 }
1300
1301 # We shouldn't need to query the DB for the size.
1302 #$maxSize = $dbr->textFieldSize( 'page', 'page_title' );
1303 if ( strlen( $r ) > 255 ) {
1304 wfProfileOut( $fname );
1305 return false;
1306 }
1307
1308 /**
1309 * Normally, all wiki links are forced to have
1310 * an initial capital letter so [[foo]] and [[Foo]]
1311 * point to the same place.
1312 *
1313 * Don't force it for interwikis, since the other
1314 * site might be case-sensitive.
1315 */
1316 if( $wgCapitalLinks && $this->mInterwiki == '') {
1317 $t = $wgContLang->ucfirst( $r );
1318 } else {
1319 $t = $r;
1320 }
1321
1322 /**
1323 * Can't make a link to a namespace alone...
1324 * "empty" local links can only be self-links
1325 * with a fragment identifier.
1326 */
1327 if( $t == '' &&
1328 $this->mInterwiki == '' &&
1329 $this->mNamespace != NS_MAIN ) {
1330 wfProfileOut( $fname );
1331 return false;
1332 }
1333
1334 # Fill fields
1335 $this->mDbkeyform = $t;
1336 $this->mUrlform = wfUrlencode( $t );
1337
1338 $this->mTextform = str_replace( '_', ' ', $t );
1339
1340 wfProfileOut( $fname );
1341 return true;
1342 }
1343
1344 /**
1345 * Get a Title object associated with the talk page of this article
1346 * @return Title the object for the talk page
1347 * @access public
1348 */
1349 function getTalkPage() {
1350 return Title::makeTitle( Namespace::getTalk( $this->getNamespace() ), $this->getDBkey() );
1351 }
1352
1353 /**
1354 * Get a title object associated with the subject page of this
1355 * talk page
1356 *
1357 * @return Title the object for the subject page
1358 * @access public
1359 */
1360 function getSubjectPage() {
1361 return Title::makeTitle( Namespace::getSubject( $this->getNamespace() ), $this->getDBkey() );
1362 }
1363
1364 /**
1365 * Get an array of Title objects linking to this Title
1366 * Also stores the IDs in the link cache.
1367 *
1368 * @param string $options may be FOR UPDATE
1369 * @return array the Title objects linking here
1370 * @access public
1371 */
1372 function getLinksTo( $options = '' ) {
1373 global $wgLinkCache;
1374 $id = $this->getArticleID();
1375
1376 if ( $options ) {
1377 $db =& wfGetDB( DB_MASTER );
1378 } else {
1379 $db =& wfGetDB( DB_SLAVE );
1380 }
1381
1382 $res = $db->select( array( 'page', 'pagelinks' ),
1383 array( 'page_namespace', 'page_title', 'page_id' ),
1384 array(
1385 'pl_from=page_id',
1386 'pl_namespace' => $this->getNamespace(),
1387 'pl_title' => $this->getDbKey() ),
1388 'Title::getLinksTo',
1389 $options );
1390
1391 $retVal = array();
1392 if ( $db->numRows( $res ) ) {
1393 while ( $row = $db->fetchObject( $res ) ) {
1394 if ( $titleObj = Title::makeTitle( $row->page_namespace, $row->page_title ) ) {
1395 $wgLinkCache->addGoodLinkObj( $row->page_id, $titleObj );
1396 $retVal[] = $titleObj;
1397 }
1398 }
1399 }
1400 $db->freeResult( $res );
1401 return $retVal;
1402 }
1403
1404 /**
1405 * Get an array of Title objects referring to non-existent articles linked from this page
1406 *
1407 * @param string $options may be FOR UPDATE
1408 * @return array the Title objects
1409 * @access public
1410 */
1411 function getBrokenLinksFrom( $options = '' ) {
1412 global $wgLinkCache;
1413
1414 if ( $options ) {
1415 $db =& wfGetDB( DB_MASTER );
1416 } else {
1417 $db =& wfGetDB( DB_SLAVE );
1418 }
1419
1420 $res = $db->safeQuery(
1421 "SELECT pl_namespace, pl_title
1422 FROM !
1423 LEFT JOIN !
1424 ON pl_namespace=page_namespace
1425 AND pl_title=page_title
1426 WHERE pl_from=?
1427 AND page_namespace IS NULL
1428 !",
1429 $db->tableName( 'pagelinks' ),
1430 $db->tableName( 'page' ),
1431 $this->getArticleId(),
1432 $options );
1433
1434 $retVal = array();
1435 if ( $db->numRows( $res ) ) {
1436 while ( $row = $db->fetchObject( $res ) ) {
1437 $retVal[] = Title::makeTitle( $row->pl_namespace, $row->pl_title );
1438 }
1439 }
1440 $db->freeResult( $res );
1441 return $retVal;
1442 }
1443
1444
1445 /**
1446 * Get a list of URLs to purge from the Squid cache when this
1447 * page changes
1448 *
1449 * @return array the URLs
1450 * @access public
1451 */
1452 function getSquidURLs() {
1453 return array(
1454 $this->getInternalURL(),
1455 $this->getInternalURL( 'action=history' )
1456 );
1457 }
1458
1459 /**
1460 * Move this page without authentication
1461 * @param Title &$nt the new page Title
1462 * @access public
1463 */
1464 function moveNoAuth( &$nt ) {
1465 return $this->moveTo( $nt, false );
1466 }
1467
1468 /**
1469 * Check whether a given move operation would be valid.
1470 * Returns true if ok, or a message key string for an error message
1471 * if invalid. (Scarrrrry ugly interface this.)
1472 * @param Title &$nt the new title
1473 * @param bool $auth indicates whether $wgUser's permissions
1474 * should be checked
1475 * @return mixed true on success, message name on failure
1476 * @access public
1477 */
1478 function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
1479 global $wgUser;
1480 if( !$this or !$nt ) {
1481 return 'badtitletext';
1482 }
1483 if( $this->equals( $nt ) ) {
1484 return 'selfmove';
1485 }
1486 if( !$this->isMovable() || !$nt->isMovable() ) {
1487 return 'immobile_namespace';
1488 }
1489
1490 $fname = 'Title::move';
1491 $oldid = $this->getArticleID();
1492 $newid = $nt->getArticleID();
1493
1494 if ( strlen( $nt->getDBkey() ) < 1 ) {
1495 return 'articleexists';
1496 }
1497 if ( ( '' == $this->getDBkey() ) ||
1498 ( !$oldid ) ||
1499 ( '' == $nt->getDBkey() ) ) {
1500 return 'badarticleerror';
1501 }
1502
1503 if ( $auth && (
1504 !$this->userCanEdit() || !$nt->userCanEdit() ||
1505 !$this->userCanMove() || !$nt->userCanMove() ) ) {
1506 return 'protectedpage';
1507 }
1508
1509 # The move is allowed only if (1) the target doesn't exist, or
1510 # (2) the target is a redirect to the source, and has no history
1511 # (so we can undo bad moves right after they're done).
1512
1513 if ( 0 != $newid ) { # Target exists; check for validity
1514 if ( ! $this->isValidMoveTarget( $nt ) ) {
1515 return 'articleexists';
1516 }
1517 }
1518 return true;
1519 }
1520
1521 /**
1522 * Move a title to a new location
1523 * @param Title &$nt the new title
1524 * @param bool $auth indicates whether $wgUser's permissions
1525 * should be checked
1526 * @return mixed true on success, message name on failure
1527 * @access public
1528 */
1529 function moveTo( &$nt, $auth = true, $reason = '' ) {
1530 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
1531 if( is_string( $err ) ) {
1532 return $err;
1533 }
1534 if( $nt->exists() ) {
1535 $this->moveOverExistingRedirect( $nt, $reason );
1536 } else { # Target didn't exist, do normal move.
1537 $this->moveToNewTitle( $nt, $newid, $reason );
1538 }
1539
1540 # Fixing category links (those without piped 'alternate' names) to be sorted under the new title
1541
1542 $dbw =& wfGetDB( DB_MASTER );
1543 $categorylinks = $dbw->tableName( 'categorylinks' );
1544 $sql = "UPDATE $categorylinks SET cl_sortkey=" . $dbw->addQuotes( $nt->getPrefixedText() ) .
1545 " WHERE cl_from=" . $dbw->addQuotes( $this->getArticleID() ) .
1546 " AND cl_sortkey=" . $dbw->addQuotes( $this->getPrefixedText() );
1547 $dbw->query( $sql, 'SpecialMovepage::doSubmit' );
1548
1549 # Update watchlists
1550
1551 $oldnamespace = $this->getNamespace() & ~1;
1552 $newnamespace = $nt->getNamespace() & ~1;
1553 $oldtitle = $this->getDBkey();
1554 $newtitle = $nt->getDBkey();
1555
1556 if( $oldnamespace != $newnamespace || $oldtitle != $newtitle ) {
1557 WatchedItem::duplicateEntries( $this, $nt );
1558 }
1559
1560 # Update search engine
1561 $u = new SearchUpdate( $oldid, $nt->getPrefixedDBkey() );
1562 $u->doUpdate();
1563 $u = new SearchUpdate( $newid, $this->getPrefixedDBkey(), '' );
1564 $u->doUpdate();
1565
1566 wfRunHooks( 'TitleMoveComplete', array(&$this, &$nt, &$wgUser, $oldid, $newid) );
1567 return true;
1568 }
1569
1570 /**
1571 * Move page to a title which is at present a redirect to the
1572 * source page
1573 *
1574 * @param Title &$nt the page to move to, which should currently
1575 * be a redirect
1576 * @access private
1577 */
1578 function moveOverExistingRedirect( &$nt, $reason = '' ) {
1579 global $wgUser, $wgLinkCache, $wgUseSquid, $wgMwRedir;
1580 $fname = 'Title::moveOverExistingRedirect';
1581 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
1582
1583 if ( $reason ) {
1584 $comment .= ": $reason";
1585 }
1586
1587 $now = wfTimestampNow();
1588 $rand = wfRandom();
1589 $newid = $nt->getArticleID();
1590 $oldid = $this->getArticleID();
1591 $dbw =& wfGetDB( DB_MASTER );
1592 $links = $dbw->tableName( 'links' );
1593
1594 # Delete the old redirect. We don't save it to history since
1595 # by definition if we've got here it's rather uninteresting.
1596 # We have to remove it so that the next step doesn't trigger
1597 # a conflict on the unique namespace+title index...
1598 $dbw->delete( 'page', array( 'page_id' => $newid ), $fname );
1599
1600 # Save a null revision in the page's history notifying of the move
1601 $nullRevision = Revision::newNullRevision( $dbw, $oldid,
1602 wfMsg( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() ),
1603 true );
1604 $nullRevId = $nullRevision->insertOn( $dbw );
1605
1606 # Change the name of the target page:
1607 $dbw->update( 'page',
1608 /* SET */ array(
1609 'page_touched' => $dbw->timestamp($now),
1610 'page_namespace' => $nt->getNamespace(),
1611 'page_title' => $nt->getDBkey(),
1612 'page_latest' => $nullRevId,
1613 ),
1614 /* WHERE */ array( 'page_id' => $oldid ),
1615 $fname
1616 );
1617 $wgLinkCache->clearLink( $nt->getPrefixedDBkey() );
1618
1619 # Recreate the redirect, this time in the other direction.
1620 $redirectText = $wgMwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
1621 $redirectArticle = new Article( $this );
1622 $newid = $redirectArticle->insertOn( $dbw );
1623 $redirectRevision = new Revision( array(
1624 'page' => $newid,
1625 'comment' => $comment,
1626 'text' => $redirectText ) );
1627 $revid = $redirectRevision->insertOn( $dbw );
1628 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
1629 $wgLinkCache->clearLink( $this->getPrefixedDBkey() );
1630
1631 # Log the move
1632 $log = new LogPage( 'move' );
1633 $log->addEntry( 'move_redir', $this, $reason, array( 1 => $nt->getPrefixedText() ) );
1634
1635 # Now, we record the link from the redirect to the new title.
1636 # It should have no other outgoing links...
1637 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), $fname );
1638 $dbw->insert( 'pagelinks',
1639 array(
1640 'pl_from' => $newid,
1641 'pl_namespace' => $this->getNamespace(),
1642 'pl_title' => $this->getDbKey() ),
1643 $fname );
1644
1645 # Purge squid
1646 if ( $wgUseSquid ) {
1647 $urls = array_merge( $nt->getSquidURLs(), $this->getSquidURLs() );
1648 $u = new SquidUpdate( $urls );
1649 $u->doUpdate();
1650 }
1651 }
1652
1653 /**
1654 * Move page to non-existing title.
1655 * @param Title &$nt the new Title
1656 * @param int &$newid set to be the new article ID
1657 * @access private
1658 */
1659 function moveToNewTitle( &$nt, &$newid, $reason = '' ) {
1660 global $wgUser, $wgLinkCache, $wgUseSquid;
1661 global $wgMwRedir;
1662 $fname = 'MovePageForm::moveToNewTitle';
1663 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
1664 if ( $reason ) {
1665 $comment .= ": $reason";
1666 }
1667
1668 $newid = $nt->getArticleID();
1669 $oldid = $this->getArticleID();
1670 $dbw =& wfGetDB( DB_MASTER );
1671 $now = $dbw->timestamp();
1672 wfSeedRandom();
1673 $rand = wfRandom();
1674
1675 # Save a null revision in the page's history notifying of the move
1676 $nullRevision = Revision::newNullRevision( $dbw, $oldid,
1677 wfMsg( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() ),
1678 true );
1679 $nullRevId = $nullRevision->insertOn( $dbw );
1680
1681 # Rename cur entry
1682 $dbw->update( 'page',
1683 /* SET */ array(
1684 'page_touched' => $now,
1685 'page_namespace' => $nt->getNamespace(),
1686 'page_title' => $nt->getDBkey(),
1687 'page_latest' => $nullRevId,
1688 ),
1689 /* WHERE */ array( 'page_id' => $oldid ),
1690 $fname
1691 );
1692
1693 $wgLinkCache->clearLink( $nt->getPrefixedDBkey() );
1694
1695 # Insert redirect
1696 $redirectText = $wgMwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
1697 $redirectArticle = new Article( $this );
1698 $newid = $redirectArticle->insertOn( $dbw );
1699 $redirectRevision = new Revision( array(
1700 'page' => $newid,
1701 'comment' => $comment,
1702 'text' => $redirectText ) );
1703 $revid = $redirectRevision->insertOn( $dbw );
1704 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
1705 $wgLinkCache->clearLink( $this->getPrefixedDBkey() );
1706
1707 # Log the move
1708 $log = new LogPage( 'move' );
1709 $log->addEntry( 'move', $this, $reason, array( 1 => $nt->getPrefixedText()) );
1710
1711 # Purge caches as per article creation
1712 Article::onArticleCreate( $nt );
1713
1714 # Record the just-created redirect's linking to the page
1715 $dbw->insert( 'pagelinks',
1716 array(
1717 'pl_from' => $newid,
1718 'pl_namespace' => $this->getNamespace(),
1719 'pl_title' => $this->getDBkey() ),
1720 $fname );
1721
1722 # Non-existent target may have had broken links to it; these must
1723 # now be touched to update link coloring.
1724 $nt->touchLinks();
1725
1726 # Purge old title from squid
1727 # The new title, and links to the new title, are purged in Article::onArticleCreate()
1728 $titles = $nt->getLinksTo();
1729 if ( $wgUseSquid ) {
1730 $urls = $this->getSquidURLs();
1731 foreach ( $titles as $linkTitle ) {
1732 $urls[] = $linkTitle->getInternalURL();
1733 }
1734 $u = new SquidUpdate( $urls );
1735 $u->doUpdate();
1736 }
1737 }
1738
1739 /**
1740 * Checks if $this can be moved to a given Title
1741 * - Selects for update, so don't call it unless you mean business
1742 *
1743 * @param Title &$nt the new title to check
1744 * @access public
1745 */
1746 function isValidMoveTarget( $nt ) {
1747
1748 $fname = 'Title::isValidMoveTarget';
1749 $dbw =& wfGetDB( DB_MASTER );
1750
1751 # Is it a redirect?
1752 $id = $nt->getArticleID();
1753 $obj = $dbw->selectRow( array( 'page', 'revision', 'text'),
1754 array( 'page_is_redirect','old_text' ),
1755 array( 'page_id' => $id, 'page_latest=rev_id', 'rev_text_id=old_id' ),
1756 $fname, 'FOR UPDATE' );
1757
1758 if ( !$obj || 0 == $obj->page_is_redirect ) {
1759 # Not a redirect
1760 return false;
1761 }
1762
1763 # Does the redirect point to the source?
1764 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $obj->old_text, $m ) ) {
1765 $redirTitle = Title::newFromText( $m[1] );
1766 if( !is_object( $redirTitle ) ||
1767 $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() ) {
1768 return false;
1769 }
1770 }
1771
1772 # Does the article have a history?
1773 $row = $dbw->selectRow( array( 'page', 'revision'),
1774 array( 'rev_id' ),
1775 array( 'page_namespace' => $nt->getNamespace(),
1776 'page_title' => $nt->getDBkey(),
1777 'page_id=rev_page AND page_latest != rev_id'
1778 ), $fname, 'FOR UPDATE'
1779 );
1780
1781 # Return true if there was no history
1782 return $row === false;
1783 }
1784
1785 /**
1786 * Create a redirect; fails if the title already exists; does
1787 * not notify RC
1788 *
1789 * @param Title $dest the destination of the redirect
1790 * @param string $comment the comment string describing the move
1791 * @return bool true on success
1792 * @access public
1793 */
1794 function createRedirect( $dest, $comment ) {
1795 global $wgUser;
1796 if ( $this->getArticleID() ) {
1797 return false;
1798 }
1799
1800 $fname = 'Title::createRedirect';
1801 $dbw =& wfGetDB( DB_MASTER );
1802
1803 $article = new Article( $this );
1804 $newid = $article->insertOn( $dbw );
1805 $revision = new Revision( array(
1806 'page' => $newid,
1807 'comment' => $comment,
1808 'text' => "#REDIRECT [[" . $dest->getPrefixedText() . "]]\n",
1809 ) );
1810 $revisionId = $revision->insertOn( $dbw );
1811 $article->updateRevisionOn( $dbw, $revision, 0 );
1812
1813 # Link table
1814 $dbw->insert( 'pagelinks',
1815 array(
1816 'pl_from' => $newid,
1817 'pl_namespace' => $dest->getNamespace(),
1818 'pl_title' => $dest->getDbKey()
1819 ), $fname
1820 );
1821
1822 Article::onArticleCreate( $this );
1823 return true;
1824 }
1825
1826 /**
1827 * Get categories to which this Title belongs and return an array of
1828 * categories' names.
1829 *
1830 * @return array an array of parents in the form:
1831 * $parent => $currentarticle
1832 * @access public
1833 */
1834 function getParentCategories() {
1835 global $wgContLang,$wgUser;
1836
1837 $titlekey = $this->getArticleId();
1838 $sk =& $wgUser->getSkin();
1839 $parents = array();
1840 $dbr =& wfGetDB( DB_SLAVE );
1841 $categorylinks = $dbr->tableName( 'categorylinks' );
1842
1843 # NEW SQL
1844 $sql = "SELECT * FROM $categorylinks"
1845 ." WHERE cl_from='$titlekey'"
1846 ." AND cl_from <> '0'"
1847 ." ORDER BY cl_sortkey";
1848
1849 $res = $dbr->query ( $sql ) ;
1850
1851 if($dbr->numRows($res) > 0) {
1852 while ( $x = $dbr->fetchObject ( $res ) )
1853 //$data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$x->cl_to);
1854 $data[$wgContLang->getNSText ( NS_CATEGORY ).':'.$x->cl_to] = $this->getFullText();
1855 $dbr->freeResult ( $res ) ;
1856 } else {
1857 $data = '';
1858 }
1859 return $data;
1860 }
1861
1862 /**
1863 * Get a tree of parent categories
1864 * @param array $children an array with the children in the keys, to check for circular refs
1865 * @return array
1866 * @access public
1867 */
1868 function getParentCategoryTree( $children = array() ) {
1869 $parents = $this->getParentCategories();
1870
1871 if($parents != '') {
1872 foreach($parents as $parent => $current)
1873 {
1874 if ( array_key_exists( $parent, $children ) ) {
1875 # Circular reference
1876 $stack[$parent] = array();
1877 } else {
1878 $nt = Title::newFromText($parent);
1879 $stack[$parent] = $nt->getParentCategoryTree( $children + array($parent => 1) );
1880 }
1881 }
1882 return $stack;
1883 } else {
1884 return array();
1885 }
1886 }
1887
1888
1889 /**
1890 * Get an associative array for selecting this title from
1891 * the "cur" table
1892 *
1893 * @return array
1894 * @access public
1895 */
1896 function curCond() {
1897 wfDebugDieBacktrace( 'curCond called' );
1898 return array( 'cur_namespace' => $this->mNamespace, 'cur_title' => $this->mDbkeyform );
1899 }
1900
1901 /**
1902 * Get an associative array for selecting this title from the
1903 * "old" table
1904 *
1905 * @return array
1906 * @access public
1907 */
1908 function oldCond() {
1909 wfDebugDieBacktrace( 'oldCond called' );
1910 return array( 'old_namespace' => $this->mNamespace, 'old_title' => $this->mDbkeyform );
1911 }
1912
1913 /**
1914 * Get the revision ID of the previous revision
1915 *
1916 * @param integer $revision Revision ID. Get the revision that was before this one.
1917 * @return interger $oldrevision|false
1918 */
1919 function getPreviousRevisionID( $revision ) {
1920 $dbr =& wfGetDB( DB_SLAVE );
1921 return $dbr->selectField( 'revision', 'rev_id',
1922 'rev_page=' . IntVal( $this->getArticleId() ) .
1923 ' AND rev_id<' . IntVal( $revision ) . ' ORDER BY rev_id DESC' );
1924 }
1925
1926 /**
1927 * Get the revision ID of the next revision
1928 *
1929 * @param integer $revision Revision ID. Get the revision that was after this one.
1930 * @return interger $oldrevision|false
1931 */
1932 function getNextRevisionID( $revision ) {
1933 $dbr =& wfGetDB( DB_SLAVE );
1934 return $dbr->selectField( 'revision', 'rev_id',
1935 'rev_page=' . IntVal( $this->getArticleId() ) .
1936 ' AND rev_id>' . IntVal( $revision ) . ' ORDER BY rev_id' );
1937 }
1938
1939 /**
1940 * Compare with another title.
1941 *
1942 * @param Title $title
1943 * @return bool
1944 */
1945 function equals( &$title ) {
1946 return $this->getInterwiki() == $title->getInterwiki()
1947 && $this->getNamespace() == $title->getNamespace()
1948 && $this->getDbkey() == $title->getDbkey();
1949 }
1950
1951 /**
1952 * Check if page exists
1953 * @return bool
1954 */
1955 function exists() {
1956 return $this->getArticleId() != 0;
1957 }
1958
1959 /**
1960 * Should a link should be displayed as a known link, just based on its title?
1961 *
1962 * Currently, a self-link with a fragment, special pages and image pages are in
1963 * this category. Special pages never exist in the database. Some images do not
1964 * have description pages in the database, but the description page contains
1965 * useful history information that the user may want to link to.
1966 *
1967 */
1968 function isAlwaysKnown() {
1969 return ( 0 == $this->mNamespace && "" == $this->mDbkeyform )
1970 || NS_SPECIAL == $this->mNamespace || NS_IMAGE == $this->mNamespace;
1971 }
1972
1973 /**
1974 * Update page_touched timestamps on pages linking to this title.
1975 * In principal, this could be backgrounded and could also do squid
1976 * purging.
1977 */
1978 function touchLinks() {
1979 $fname = 'Title::touchLinks';
1980
1981 $dbw =& wfGetDB( DB_MASTER );
1982
1983 $res = $dbw->select( 'pagelinks',
1984 array( 'pl_from' ),
1985 array(
1986 'pl_namespace' => $this->getNamespace(),
1987 'pl_title' => $this->getDbKey() ),
1988 $fname );
1989 if ( 0 == $dbw->numRows( $res ) ) {
1990 return;
1991 }
1992
1993 $arr = array();
1994 $toucharr = array();
1995 while( $row = $dbw->fetchObject( $res ) ) {
1996 $toucharr[] = $row->pl_from;
1997 }
1998
1999 $dbw->update( 'page', /* SET */ array( 'page_touched' => $dbw->timestamp() ),
2000 /* WHERE */ array( 'page_id' => $toucharr ),$fname);
2001 }
2002 }
2003 ?>