9348d34e2c84f72c7ab6d8d5edf6c1c51e492625
[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 if ( $this->getNamespace() < 0 ) {
1076 $n = 0;
1077 } else {
1078 $dbr =& wfGetDB( DB_SLAVE );
1079 $n = $dbr->selectField( 'archive', 'COUNT(*)', array( 'ar_namespace' => $this->getNamespace(),
1080 'ar_title' => $this->getDBkey() ), $fname );
1081 }
1082 return (int)$n;
1083 }
1084
1085 /**
1086 * Get the article ID for this Title from the link cache,
1087 * adding it if necessary
1088 * @param int $flags a bit field; may be GAID_FOR_UPDATE to select
1089 * for update
1090 * @return int the ID
1091 * @access public
1092 */
1093 function getArticleID( $flags = 0 ) {
1094 global $wgLinkCache;
1095
1096 if ( $flags & GAID_FOR_UPDATE ) {
1097 $oldUpdate = $wgLinkCache->forUpdate( true );
1098 $this->mArticleID = $wgLinkCache->addLinkObj( $this );
1099 $wgLinkCache->forUpdate( $oldUpdate );
1100 } else {
1101 if ( -1 == $this->mArticleID ) {
1102 $this->mArticleID = $wgLinkCache->addLinkObj( $this );
1103 }
1104 }
1105 return $this->mArticleID;
1106 }
1107
1108 /**
1109 * This clears some fields in this object, and clears any associated
1110 * keys in the "bad links" section of $wgLinkCache.
1111 *
1112 * - This is called from Article::insertNewArticle() to allow
1113 * loading of the new page_id. It's also called from
1114 * Article::doDeleteArticle()
1115 *
1116 * @param int $newid the new Article ID
1117 * @access public
1118 */
1119 function resetArticleID( $newid ) {
1120 global $wgLinkCache;
1121 $wgLinkCache->clearBadLink( $this->getPrefixedDBkey() );
1122
1123 if ( 0 == $newid ) { $this->mArticleID = -1; }
1124 else { $this->mArticleID = $newid; }
1125 $this->mRestrictionsLoaded = false;
1126 $this->mRestrictions = array();
1127 }
1128
1129 /**
1130 * Updates page_touched for this page; called from LinksUpdate.php
1131 * @return bool true if the update succeded
1132 * @access public
1133 */
1134 function invalidateCache() {
1135 if ( wfReadOnly() ) {
1136 return;
1137 }
1138
1139 $now = wfTimestampNow();
1140 $dbw =& wfGetDB( DB_MASTER );
1141 $success = $dbw->update( 'page',
1142 array( /* SET */
1143 'page_touched' => $dbw->timestamp()
1144 ), array( /* WHERE */
1145 'page_namespace' => $this->getNamespace() ,
1146 'page_title' => $this->getDBkey()
1147 ), 'Title::invalidateCache'
1148 );
1149 return $success;
1150 }
1151
1152 /**
1153 * Prefix some arbitrary text with the namespace or interwiki prefix
1154 * of this object
1155 *
1156 * @param string $name the text
1157 * @return string the prefixed text
1158 * @access private
1159 */
1160 /* private */ function prefix( $name ) {
1161 global $wgContLang;
1162
1163 $p = '';
1164 if ( '' != $this->mInterwiki ) {
1165 $p = $this->mInterwiki . ':';
1166 }
1167 if ( 0 != $this->mNamespace ) {
1168 $p .= $wgContLang->getNsText( $this->mNamespace ) . ':';
1169 }
1170 return $p . $name;
1171 }
1172
1173 /**
1174 * Secure and split - main initialisation function for this object
1175 *
1176 * Assumes that mDbkeyform has been set, and is urldecoded
1177 * and uses underscores, but not otherwise munged. This function
1178 * removes illegal characters, splits off the interwiki and
1179 * namespace prefixes, sets the other forms, and canonicalizes
1180 * everything.
1181 * @return bool true on success
1182 * @access private
1183 */
1184 /* private */ function secureAndSplit() {
1185 global $wgContLang, $wgLocalInterwiki, $wgCapitalLinks;
1186 $fname = 'Title::secureAndSplit';
1187 wfProfileIn( $fname );
1188
1189 # Initialisation
1190 static $rxTc = false;
1191 if( !$rxTc ) {
1192 # % is needed as well
1193 $rxTc = '/[^' . Title::legalChars() . ']|%[0-9A-Fa-f]{2}/S';
1194 }
1195
1196 $this->mInterwiki = $this->mFragment = '';
1197 $this->mNamespace = $this->mDefaultNamespace; # Usually NS_MAIN
1198
1199 # Clean up whitespace
1200 #
1201 $t = preg_replace( '/[ _]+/', '_', $this->mDbkeyform );
1202 $t = trim( $t, '_' );
1203
1204 if ( '' == $t ) {
1205 wfProfileOut( $fname );
1206 return false;
1207 }
1208
1209 if( false !== strpos( $t, UTF8_REPLACEMENT ) ) {
1210 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
1211 wfProfileOut( $fname );
1212 return false;
1213 }
1214
1215 $this->mDbkeyform = $t;
1216
1217 # Initial colon indicating main namespace
1218 if ( ':' == $t{0} ) {
1219 $r = substr( $t, 1 );
1220 $this->mNamespace = NS_MAIN;
1221 } else {
1222 # Namespace or interwiki prefix
1223 $firstPass = true;
1224 do {
1225 if ( preg_match( "/^(.+?)_*:_*(.*)$/S", $t, $m ) ) {
1226 $p = $m[1];
1227 $lowerNs = strtolower( $p );
1228 if ( $ns = Namespace::getCanonicalIndex( $lowerNs ) ) {
1229 # Canonical namespace
1230 $t = $m[2];
1231 $this->mNamespace = $ns;
1232 } elseif ( $ns = $wgContLang->getNsIndex( $lowerNs )) {
1233 # Ordinary namespace
1234 $t = $m[2];
1235 $this->mNamespace = $ns;
1236 } elseif( $this->getInterwikiLink( $p ) ) {
1237 if( !$firstPass ) {
1238 # Can't make a local interwiki link to an interwiki link.
1239 # That's just crazy!
1240 wfProfileOut( $fname );
1241 return false;
1242 }
1243
1244 # Interwiki link
1245 $t = $m[2];
1246 $this->mInterwiki = $p;
1247
1248 # Redundant interwiki prefix to the local wiki
1249 if ( 0 == strcasecmp( $this->mInterwiki, $wgLocalInterwiki ) ) {
1250 if( $t == '' ) {
1251 # Can't have an empty self-link
1252 wfProfileOut( $fname );
1253 return false;
1254 }
1255 $this->mInterwiki = '';
1256 $firstPass = false;
1257 # Do another namespace split...
1258 continue;
1259 }
1260 }
1261 # If there's no recognized interwiki or namespace,
1262 # then let the colon expression be part of the title.
1263 }
1264 break;
1265 } while( true );
1266 $r = $t;
1267 }
1268
1269 # We already know that some pages won't be in the database!
1270 #
1271 if ( '' != $this->mInterwiki || -1 == $this->mNamespace ) {
1272 $this->mArticleID = 0;
1273 }
1274 $f = strstr( $r, '#' );
1275 if ( false !== $f ) {
1276 $this->mFragment = substr( $f, 1 );
1277 $r = substr( $r, 0, strlen( $r ) - strlen( $f ) );
1278 # remove whitespace again: prevents "Foo_bar_#"
1279 # becoming "Foo_bar_"
1280 $r = preg_replace( '/_*$/', '', $r );
1281 }
1282
1283 # Reject illegal characters.
1284 #
1285 if( preg_match( $rxTc, $r ) ) {
1286 wfProfileOut( $fname );
1287 return false;
1288 }
1289
1290 /**
1291 * Pages with "/./" or "/../" appearing in the URLs will
1292 * often be unreachable due to the way web browsers deal
1293 * with 'relative' URLs. Forbid them explicitly.
1294 */
1295 if ( strpos( $r, '.' ) !== false &&
1296 ( $r === '.' || $r === '..' ||
1297 strpos( $r, './' ) === 0 ||
1298 strpos( $r, '../' ) === 0 ||
1299 strpos( $r, '/./' ) !== false ||
1300 strpos( $r, '/../' ) !== false ) )
1301 {
1302 wfProfileOut( $fname );
1303 return false;
1304 }
1305
1306 # We shouldn't need to query the DB for the size.
1307 #$maxSize = $dbr->textFieldSize( 'page', 'page_title' );
1308 if ( strlen( $r ) > 255 ) {
1309 wfProfileOut( $fname );
1310 return false;
1311 }
1312
1313 /**
1314 * Normally, all wiki links are forced to have
1315 * an initial capital letter so [[foo]] and [[Foo]]
1316 * point to the same place.
1317 *
1318 * Don't force it for interwikis, since the other
1319 * site might be case-sensitive.
1320 */
1321 if( $wgCapitalLinks && $this->mInterwiki == '') {
1322 $t = $wgContLang->ucfirst( $r );
1323 } else {
1324 $t = $r;
1325 }
1326
1327 /**
1328 * Can't make a link to a namespace alone...
1329 * "empty" local links can only be self-links
1330 * with a fragment identifier.
1331 */
1332 if( $t == '' &&
1333 $this->mInterwiki == '' &&
1334 $this->mNamespace != NS_MAIN ) {
1335 wfProfileOut( $fname );
1336 return false;
1337 }
1338
1339 # Fill fields
1340 $this->mDbkeyform = $t;
1341 $this->mUrlform = wfUrlencode( $t );
1342
1343 $this->mTextform = str_replace( '_', ' ', $t );
1344
1345 wfProfileOut( $fname );
1346 return true;
1347 }
1348
1349 /**
1350 * Get a Title object associated with the talk page of this article
1351 * @return Title the object for the talk page
1352 * @access public
1353 */
1354 function getTalkPage() {
1355 return Title::makeTitle( Namespace::getTalk( $this->getNamespace() ), $this->getDBkey() );
1356 }
1357
1358 /**
1359 * Get a title object associated with the subject page of this
1360 * talk page
1361 *
1362 * @return Title the object for the subject page
1363 * @access public
1364 */
1365 function getSubjectPage() {
1366 return Title::makeTitle( Namespace::getSubject( $this->getNamespace() ), $this->getDBkey() );
1367 }
1368
1369 /**
1370 * Get an array of Title objects linking to this Title
1371 * Also stores the IDs in the link cache.
1372 *
1373 * @param string $options may be FOR UPDATE
1374 * @return array the Title objects linking here
1375 * @access public
1376 */
1377 function getLinksTo( $options = '' ) {
1378 global $wgLinkCache;
1379 $id = $this->getArticleID();
1380
1381 if ( $options ) {
1382 $db =& wfGetDB( DB_MASTER );
1383 } else {
1384 $db =& wfGetDB( DB_SLAVE );
1385 }
1386
1387 $res = $db->select( array( 'page', 'pagelinks' ),
1388 array( 'page_namespace', 'page_title', 'page_id' ),
1389 array(
1390 'pl_from=page_id',
1391 'pl_namespace' => $this->getNamespace(),
1392 'pl_title' => $this->getDbKey() ),
1393 'Title::getLinksTo',
1394 $options );
1395
1396 $retVal = array();
1397 if ( $db->numRows( $res ) ) {
1398 while ( $row = $db->fetchObject( $res ) ) {
1399 if ( $titleObj = Title::makeTitle( $row->page_namespace, $row->page_title ) ) {
1400 $wgLinkCache->addGoodLinkObj( $row->page_id, $titleObj );
1401 $retVal[] = $titleObj;
1402 }
1403 }
1404 }
1405 $db->freeResult( $res );
1406 return $retVal;
1407 }
1408
1409 /**
1410 * Get an array of Title objects referring to non-existent articles linked from this page
1411 *
1412 * @param string $options may be FOR UPDATE
1413 * @return array the Title objects
1414 * @access public
1415 */
1416 function getBrokenLinksFrom( $options = '' ) {
1417 global $wgLinkCache;
1418
1419 if ( $options ) {
1420 $db =& wfGetDB( DB_MASTER );
1421 } else {
1422 $db =& wfGetDB( DB_SLAVE );
1423 }
1424
1425 $res = $db->safeQuery(
1426 "SELECT pl_namespace, pl_title
1427 FROM !
1428 LEFT JOIN !
1429 ON pl_namespace=page_namespace
1430 AND pl_title=page_title
1431 WHERE pl_from=?
1432 AND page_namespace IS NULL
1433 !",
1434 $db->tableName( 'pagelinks' ),
1435 $db->tableName( 'page' ),
1436 $this->getArticleId(),
1437 $options );
1438
1439 $retVal = array();
1440 if ( $db->numRows( $res ) ) {
1441 while ( $row = $db->fetchObject( $res ) ) {
1442 $retVal[] = Title::makeTitle( $row->pl_namespace, $row->pl_title );
1443 }
1444 }
1445 $db->freeResult( $res );
1446 return $retVal;
1447 }
1448
1449
1450 /**
1451 * Get a list of URLs to purge from the Squid cache when this
1452 * page changes
1453 *
1454 * @return array the URLs
1455 * @access public
1456 */
1457 function getSquidURLs() {
1458 return array(
1459 $this->getInternalURL(),
1460 $this->getInternalURL( 'action=history' )
1461 );
1462 }
1463
1464 /**
1465 * Move this page without authentication
1466 * @param Title &$nt the new page Title
1467 * @access public
1468 */
1469 function moveNoAuth( &$nt ) {
1470 return $this->moveTo( $nt, false );
1471 }
1472
1473 /**
1474 * Check whether a given move operation would be valid.
1475 * Returns true if ok, or a message key string for an error message
1476 * if invalid. (Scarrrrry ugly interface this.)
1477 * @param Title &$nt the new title
1478 * @param bool $auth indicates whether $wgUser's permissions
1479 * should be checked
1480 * @return mixed true on success, message name on failure
1481 * @access public
1482 */
1483 function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
1484 global $wgUser;
1485 if( !$this or !$nt ) {
1486 return 'badtitletext';
1487 }
1488 if( $this->equals( $nt ) ) {
1489 return 'selfmove';
1490 }
1491 if( !$this->isMovable() || !$nt->isMovable() ) {
1492 return 'immobile_namespace';
1493 }
1494
1495 $fname = 'Title::move';
1496 $oldid = $this->getArticleID();
1497 $newid = $nt->getArticleID();
1498
1499 if ( strlen( $nt->getDBkey() ) < 1 ) {
1500 return 'articleexists';
1501 }
1502 if ( ( '' == $this->getDBkey() ) ||
1503 ( !$oldid ) ||
1504 ( '' == $nt->getDBkey() ) ) {
1505 return 'badarticleerror';
1506 }
1507
1508 if ( $auth && (
1509 !$this->userCanEdit() || !$nt->userCanEdit() ||
1510 !$this->userCanMove() || !$nt->userCanMove() ) ) {
1511 return 'protectedpage';
1512 }
1513
1514 # The move is allowed only if (1) the target doesn't exist, or
1515 # (2) the target is a redirect to the source, and has no history
1516 # (so we can undo bad moves right after they're done).
1517
1518 if ( 0 != $newid ) { # Target exists; check for validity
1519 if ( ! $this->isValidMoveTarget( $nt ) ) {
1520 return 'articleexists';
1521 }
1522 }
1523 return true;
1524 }
1525
1526 /**
1527 * Move a title to a new location
1528 * @param Title &$nt the new title
1529 * @param bool $auth indicates whether $wgUser's permissions
1530 * should be checked
1531 * @return mixed true on success, message name on failure
1532 * @access public
1533 */
1534 function moveTo( &$nt, $auth = true, $reason = '' ) {
1535 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
1536 if( is_string( $err ) ) {
1537 return $err;
1538 }
1539
1540 $pageid = $this->getArticleID();
1541 if( $nt->exists() ) {
1542 $this->moveOverExistingRedirect( $nt, $reason );
1543 $pageCountChange = 0;
1544 } else { # Target didn't exist, do normal move.
1545 $this->moveToNewTitle( $nt, $newid, $reason );
1546 $pageCountChange = 1;
1547 }
1548 $redirid = $this->getArticleID();
1549
1550 # Fixing category links (those without piped 'alternate' names) to be sorted under the new title
1551 $dbw =& wfGetDB( DB_MASTER );
1552 $categorylinks = $dbw->tableName( 'categorylinks' );
1553 $sql = "UPDATE $categorylinks SET cl_sortkey=" . $dbw->addQuotes( $nt->getPrefixedText() ) .
1554 " WHERE cl_from=" . $dbw->addQuotes( $pageid ) .
1555 " AND cl_sortkey=" . $dbw->addQuotes( $this->getPrefixedText() );
1556 $dbw->query( $sql, 'SpecialMovepage::doSubmit' );
1557
1558 # Update watchlists
1559
1560 $oldnamespace = $this->getNamespace() & ~1;
1561 $newnamespace = $nt->getNamespace() & ~1;
1562 $oldtitle = $this->getDBkey();
1563 $newtitle = $nt->getDBkey();
1564
1565 if( $oldnamespace != $newnamespace || $oldtitle != $newtitle ) {
1566 WatchedItem::duplicateEntries( $this, $nt );
1567 }
1568
1569 # Update search engine
1570 $u = new SearchUpdate( $pageid, $nt->getPrefixedDBkey() );
1571 $u->doUpdate();
1572 $u = new SearchUpdate( $redirid, $this->getPrefixedDBkey(), '' );
1573 $u->doUpdate();
1574
1575 # Update site_stats
1576 if ( $this->getNamespace() == NS_MAIN and $nt->getNamespace() != NS_MAIN ) {
1577 # Moved out of main namespace
1578 # not viewed, edited, removing
1579 $u = new SiteStatsUpdate( 0, 1, -1, $pageCountChange);
1580 } elseif ( $this->getNamespace() != NS_MAIN and $nt->getNamespace() == NS_MAIN ) {
1581 # Moved into main namespace
1582 # not viewed, edited, adding
1583 $u = new SiteStatsUpdate( 0, 1, +1, $pageCountChange );
1584 } elseif ( $pageCountChange ) {
1585 # Added redirect
1586 $u = new SiteStatsUpdate( 0, 0, 0, 1 );
1587 } else{
1588 $u = false;
1589 }
1590 if ( $u ) {
1591 $u->doUpdate();
1592 }
1593
1594 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) );
1595 return true;
1596 }
1597
1598 /**
1599 * Move page to a title which is at present a redirect to the
1600 * source page
1601 *
1602 * @param Title &$nt the page to move to, which should currently
1603 * be a redirect
1604 * @access private
1605 */
1606 function moveOverExistingRedirect( &$nt, $reason = '' ) {
1607 global $wgUser, $wgLinkCache, $wgUseSquid, $wgMwRedir;
1608 $fname = 'Title::moveOverExistingRedirect';
1609 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
1610
1611 if ( $reason ) {
1612 $comment .= ": $reason";
1613 }
1614
1615 $now = wfTimestampNow();
1616 $rand = wfRandom();
1617 $newid = $nt->getArticleID();
1618 $oldid = $this->getArticleID();
1619 $dbw =& wfGetDB( DB_MASTER );
1620 $links = $dbw->tableName( 'links' );
1621
1622 # Delete the old redirect. We don't save it to history since
1623 # by definition if we've got here it's rather uninteresting.
1624 # We have to remove it so that the next step doesn't trigger
1625 # a conflict on the unique namespace+title index...
1626 $dbw->delete( 'page', array( 'page_id' => $newid ), $fname );
1627
1628 # Save a null revision in the page's history notifying of the move
1629 $nullRevision = Revision::newNullRevision( $dbw, $oldid,
1630 wfMsg( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() ),
1631 true );
1632 $nullRevId = $nullRevision->insertOn( $dbw );
1633
1634 # Change the name of the target page:
1635 $dbw->update( 'page',
1636 /* SET */ array(
1637 'page_touched' => $dbw->timestamp($now),
1638 'page_namespace' => $nt->getNamespace(),
1639 'page_title' => $nt->getDBkey(),
1640 'page_latest' => $nullRevId,
1641 ),
1642 /* WHERE */ array( 'page_id' => $oldid ),
1643 $fname
1644 );
1645 $wgLinkCache->clearLink( $nt->getPrefixedDBkey() );
1646
1647 # Recreate the redirect, this time in the other direction.
1648 $redirectText = $wgMwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
1649 $redirectArticle = new Article( $this );
1650 $newid = $redirectArticle->insertOn( $dbw );
1651 $redirectRevision = new Revision( array(
1652 'page' => $newid,
1653 'comment' => $comment,
1654 'text' => $redirectText ) );
1655 $revid = $redirectRevision->insertOn( $dbw );
1656 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
1657 $wgLinkCache->clearLink( $this->getPrefixedDBkey() );
1658
1659 # Log the move
1660 $log = new LogPage( 'move' );
1661 $log->addEntry( 'move_redir', $this, $reason, array( 1 => $nt->getPrefixedText() ) );
1662
1663 # Now, we record the link from the redirect to the new title.
1664 # It should have no other outgoing links...
1665 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), $fname );
1666 $dbw->insert( 'pagelinks',
1667 array(
1668 'pl_from' => $newid,
1669 'pl_namespace' => $nt->getNamespace(),
1670 'pl_title' => $nt->getDbKey() ),
1671 $fname );
1672
1673 # Purge squid
1674 if ( $wgUseSquid ) {
1675 $urls = array_merge( $nt->getSquidURLs(), $this->getSquidURLs() );
1676 $u = new SquidUpdate( $urls );
1677 $u->doUpdate();
1678 }
1679 }
1680
1681 /**
1682 * Move page to non-existing title.
1683 * @param Title &$nt the new Title
1684 * @param int &$newid set to be the new article ID
1685 * @access private
1686 */
1687 function moveToNewTitle( &$nt, &$newid, $reason = '' ) {
1688 global $wgUser, $wgLinkCache, $wgUseSquid;
1689 global $wgMwRedir;
1690 $fname = 'MovePageForm::moveToNewTitle';
1691 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
1692 if ( $reason ) {
1693 $comment .= ": $reason";
1694 }
1695
1696 $newid = $nt->getArticleID();
1697 $oldid = $this->getArticleID();
1698 $dbw =& wfGetDB( DB_MASTER );
1699 $now = $dbw->timestamp();
1700 wfSeedRandom();
1701 $rand = wfRandom();
1702
1703 # Save a null revision in the page's history notifying of the move
1704 $nullRevision = Revision::newNullRevision( $dbw, $oldid,
1705 wfMsg( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() ),
1706 true );
1707 $nullRevId = $nullRevision->insertOn( $dbw );
1708
1709 # Rename cur entry
1710 $dbw->update( 'page',
1711 /* SET */ array(
1712 'page_touched' => $now,
1713 'page_namespace' => $nt->getNamespace(),
1714 'page_title' => $nt->getDBkey(),
1715 'page_latest' => $nullRevId,
1716 ),
1717 /* WHERE */ array( 'page_id' => $oldid ),
1718 $fname
1719 );
1720
1721 $wgLinkCache->clearLink( $nt->getPrefixedDBkey() );
1722
1723 # Insert redirect
1724 $redirectText = $wgMwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
1725 $redirectArticle = new Article( $this );
1726 $newid = $redirectArticle->insertOn( $dbw );
1727 $redirectRevision = new Revision( array(
1728 'page' => $newid,
1729 'comment' => $comment,
1730 'text' => $redirectText ) );
1731 $revid = $redirectRevision->insertOn( $dbw );
1732 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
1733 $wgLinkCache->clearLink( $this->getPrefixedDBkey() );
1734
1735 # Log the move
1736 $log = new LogPage( 'move' );
1737 $log->addEntry( 'move', $this, $reason, array( 1 => $nt->getPrefixedText()) );
1738
1739 # Purge caches as per article creation
1740 Article::onArticleCreate( $nt );
1741
1742 # Record the just-created redirect's linking to the page
1743 $dbw->insert( 'pagelinks',
1744 array(
1745 'pl_from' => $newid,
1746 'pl_namespace' => $nt->getNamespace(),
1747 'pl_title' => $nt->getDBkey() ),
1748 $fname );
1749
1750 # Non-existent target may have had broken links to it; these must
1751 # now be touched to update link coloring.
1752 $nt->touchLinks();
1753
1754 # Purge old title from squid
1755 # The new title, and links to the new title, are purged in Article::onArticleCreate()
1756 $titles = $nt->getLinksTo();
1757 if ( $wgUseSquid ) {
1758 $urls = $this->getSquidURLs();
1759 foreach ( $titles as $linkTitle ) {
1760 $urls[] = $linkTitle->getInternalURL();
1761 }
1762 $u = new SquidUpdate( $urls );
1763 $u->doUpdate();
1764 }
1765 }
1766
1767 /**
1768 * Checks if $this can be moved to a given Title
1769 * - Selects for update, so don't call it unless you mean business
1770 *
1771 * @param Title &$nt the new title to check
1772 * @access public
1773 */
1774 function isValidMoveTarget( $nt ) {
1775
1776 $fname = 'Title::isValidMoveTarget';
1777 $dbw =& wfGetDB( DB_MASTER );
1778
1779 # Is it a redirect?
1780 $id = $nt->getArticleID();
1781 $obj = $dbw->selectRow( array( 'page', 'revision', 'text'),
1782 array( 'page_is_redirect','old_text' ),
1783 array( 'page_id' => $id, 'page_latest=rev_id', 'rev_text_id=old_id' ),
1784 $fname, 'FOR UPDATE' );
1785
1786 if ( !$obj || 0 == $obj->page_is_redirect ) {
1787 # Not a redirect
1788 return false;
1789 }
1790
1791 # Does the redirect point to the source?
1792 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $obj->old_text, $m ) ) {
1793 $redirTitle = Title::newFromText( $m[1] );
1794 if( !is_object( $redirTitle ) ||
1795 $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() ) {
1796 return false;
1797 }
1798 }
1799
1800 # Does the article have a history?
1801 $row = $dbw->selectRow( array( 'page', 'revision'),
1802 array( 'rev_id' ),
1803 array( 'page_namespace' => $nt->getNamespace(),
1804 'page_title' => $nt->getDBkey(),
1805 'page_id=rev_page AND page_latest != rev_id'
1806 ), $fname, 'FOR UPDATE'
1807 );
1808
1809 # Return true if there was no history
1810 return $row === false;
1811 }
1812
1813 /**
1814 * Create a redirect; fails if the title already exists; does
1815 * not notify RC
1816 *
1817 * @param Title $dest the destination of the redirect
1818 * @param string $comment the comment string describing the move
1819 * @return bool true on success
1820 * @access public
1821 */
1822 function createRedirect( $dest, $comment ) {
1823 global $wgUser;
1824 if ( $this->getArticleID() ) {
1825 return false;
1826 }
1827
1828 $fname = 'Title::createRedirect';
1829 $dbw =& wfGetDB( DB_MASTER );
1830
1831 $article = new Article( $this );
1832 $newid = $article->insertOn( $dbw );
1833 $revision = new Revision( array(
1834 'page' => $newid,
1835 'comment' => $comment,
1836 'text' => "#REDIRECT [[" . $dest->getPrefixedText() . "]]\n",
1837 ) );
1838 $revisionId = $revision->insertOn( $dbw );
1839 $article->updateRevisionOn( $dbw, $revision, 0 );
1840
1841 # Link table
1842 $dbw->insert( 'pagelinks',
1843 array(
1844 'pl_from' => $newid,
1845 'pl_namespace' => $dest->getNamespace(),
1846 'pl_title' => $dest->getDbKey()
1847 ), $fname
1848 );
1849
1850 Article::onArticleCreate( $this );
1851 return true;
1852 }
1853
1854 /**
1855 * Get categories to which this Title belongs and return an array of
1856 * categories' names.
1857 *
1858 * @return array an array of parents in the form:
1859 * $parent => $currentarticle
1860 * @access public
1861 */
1862 function getParentCategories() {
1863 global $wgContLang,$wgUser;
1864
1865 $titlekey = $this->getArticleId();
1866 $sk =& $wgUser->getSkin();
1867 $parents = array();
1868 $dbr =& wfGetDB( DB_SLAVE );
1869 $categorylinks = $dbr->tableName( 'categorylinks' );
1870
1871 # NEW SQL
1872 $sql = "SELECT * FROM $categorylinks"
1873 ." WHERE cl_from='$titlekey'"
1874 ." AND cl_from <> '0'"
1875 ." ORDER BY cl_sortkey";
1876
1877 $res = $dbr->query ( $sql ) ;
1878
1879 if($dbr->numRows($res) > 0) {
1880 while ( $x = $dbr->fetchObject ( $res ) )
1881 //$data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$x->cl_to);
1882 $data[$wgContLang->getNSText ( NS_CATEGORY ).':'.$x->cl_to] = $this->getFullText();
1883 $dbr->freeResult ( $res ) ;
1884 } else {
1885 $data = '';
1886 }
1887 return $data;
1888 }
1889
1890 /**
1891 * Get a tree of parent categories
1892 * @param array $children an array with the children in the keys, to check for circular refs
1893 * @return array
1894 * @access public
1895 */
1896 function getParentCategoryTree( $children = array() ) {
1897 $parents = $this->getParentCategories();
1898
1899 if($parents != '') {
1900 foreach($parents as $parent => $current)
1901 {
1902 if ( array_key_exists( $parent, $children ) ) {
1903 # Circular reference
1904 $stack[$parent] = array();
1905 } else {
1906 $nt = Title::newFromText($parent);
1907 $stack[$parent] = $nt->getParentCategoryTree( $children + array($parent => 1) );
1908 }
1909 }
1910 return $stack;
1911 } else {
1912 return array();
1913 }
1914 }
1915
1916
1917 /**
1918 * Get an associative array for selecting this title from
1919 * the "cur" table
1920 *
1921 * @return array
1922 * @access public
1923 */
1924 function curCond() {
1925 wfDebugDieBacktrace( 'curCond called' );
1926 return array( 'cur_namespace' => $this->mNamespace, 'cur_title' => $this->mDbkeyform );
1927 }
1928
1929 /**
1930 * Get an associative array for selecting this title from the
1931 * "old" table
1932 *
1933 * @return array
1934 * @access public
1935 */
1936 function oldCond() {
1937 wfDebugDieBacktrace( 'oldCond called' );
1938 return array( 'old_namespace' => $this->mNamespace, 'old_title' => $this->mDbkeyform );
1939 }
1940
1941 /**
1942 * Get the revision ID of the previous revision
1943 *
1944 * @param integer $revision Revision ID. Get the revision that was before this one.
1945 * @return interger $oldrevision|false
1946 */
1947 function getPreviousRevisionID( $revision ) {
1948 $dbr =& wfGetDB( DB_SLAVE );
1949 return $dbr->selectField( 'revision', 'rev_id',
1950 'rev_page=' . IntVal( $this->getArticleId() ) .
1951 ' AND rev_id<' . IntVal( $revision ) . ' ORDER BY rev_id DESC' );
1952 }
1953
1954 /**
1955 * Get the revision ID of the next revision
1956 *
1957 * @param integer $revision Revision ID. Get the revision that was after this one.
1958 * @return interger $oldrevision|false
1959 */
1960 function getNextRevisionID( $revision ) {
1961 $dbr =& wfGetDB( DB_SLAVE );
1962 return $dbr->selectField( 'revision', 'rev_id',
1963 'rev_page=' . IntVal( $this->getArticleId() ) .
1964 ' AND rev_id>' . IntVal( $revision ) . ' ORDER BY rev_id' );
1965 }
1966
1967 /**
1968 * Compare with another title.
1969 *
1970 * @param Title $title
1971 * @return bool
1972 */
1973 function equals( &$title ) {
1974 return $this->getInterwiki() == $title->getInterwiki()
1975 && $this->getNamespace() == $title->getNamespace()
1976 && $this->getDbkey() == $title->getDbkey();
1977 }
1978
1979 /**
1980 * Check if page exists
1981 * @return bool
1982 */
1983 function exists() {
1984 return $this->getArticleId() != 0;
1985 }
1986
1987 /**
1988 * Should a link should be displayed as a known link, just based on its title?
1989 *
1990 * Currently, a self-link with a fragment, special pages and image pages are in
1991 * this category. Special pages never exist in the database. Some images do not
1992 * have description pages in the database, but the description page contains
1993 * useful history information that the user may want to link to.
1994 *
1995 */
1996 function isAlwaysKnown() {
1997 return $this->isExternal() || ( 0 == $this->mNamespace && "" == $this->mDbkeyform )
1998 || NS_SPECIAL == $this->mNamespace || NS_IMAGE == $this->mNamespace;
1999 }
2000
2001 /**
2002 * Update page_touched timestamps on pages linking to this title.
2003 * In principal, this could be backgrounded and could also do squid
2004 * purging.
2005 */
2006 function touchLinks() {
2007 $fname = 'Title::touchLinks';
2008
2009 $dbw =& wfGetDB( DB_MASTER );
2010
2011 $res = $dbw->select( 'pagelinks',
2012 array( 'pl_from' ),
2013 array(
2014 'pl_namespace' => $this->getNamespace(),
2015 'pl_title' => $this->getDbKey() ),
2016 $fname );
2017 if ( 0 == $dbw->numRows( $res ) ) {
2018 return;
2019 }
2020
2021 $arr = array();
2022 $toucharr = array();
2023 while( $row = $dbw->fetchObject( $res ) ) {
2024 $toucharr[] = $row->pl_from;
2025 }
2026
2027 $dbw->update( 'page', /* SET */ array( 'page_touched' => $dbw->timestamp() ),
2028 /* WHERE */ array( 'page_id' => $toucharr ),$fname);
2029 }
2030 }
2031 ?>