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